greader.php 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. == Description ==
  5. Server-side API compatible with Google Reader API layer 2
  6. for the FreshRSS project https://freshrss.org
  7. FreshRSS-specific information is prefixed with 'frss:'
  8. == Credits ==
  9. * 2014-03: Released by Alexandre Alapetite https://alexandre.alapetite.fr
  10. under GNU AGPL 3 license http://www.gnu.org/licenses/agpl-3.0.html
  11. == Documentation ==
  12. * https://code.google.com/archive/p/pyrfeed/wikis/GoogleReaderAPI.wiki
  13. * https://web.archive.org/web/20130718025427/http://undoc.in/
  14. * http://ranchero.com/downloads/GoogleReaderAPI-2009.pdf
  15. * https://github.com/mihaip/google-reader-api
  16. * https://web.archive.org/web/20210126113527/https://blog.martindoms.com/2009/08/15/using-the-google-reader-api-part-1
  17. * https://github.com/noinnion/newsplus/blob/master/extensions/GoogleReaderCloneExtension/src/com/noinnion/android/newsplus/extension/google_reader/GoogleReaderClient.java
  18. * https://github.com/ericmann/gReader-Library/blob/master/greader.class.php
  19. * https://github.com/devongovett/reader
  20. * https://github.com/theoldreader/api
  21. * https://www.inoreader.com/developers/
  22. * https://feedhq.readthedocs.io/en/latest/api/index.html
  23. * https://github.com/bazqux/bazqux-api
  24. */
  25. require dirname(__DIR__, 2) . '/constants.php';
  26. require LIB_PATH . '/lib_rss.php'; //Includes class autoloader
  27. header("Content-Security-Policy: default-src 'none'; frame-ancestors 'none'; sandbox");
  28. header('X-Content-Type-Options: nosniff');
  29. if (PHP_INT_SIZE < 8) { //32-bit
  30. /** @return numeric-string */
  31. function hex2dec(string $hex): string {
  32. if (!ctype_xdigit($hex)) return '0';
  33. $result = gmp_strval(gmp_init($hex, 16), 10);
  34. /** @var numeric-string $result */
  35. return $result;
  36. }
  37. } else { //64-bit
  38. /** @return numeric-string */
  39. function hex2dec(string $hex): string {
  40. if (!ctype_xdigit($hex)) {
  41. return '0';
  42. }
  43. return '' . hexdec($hex);
  44. }
  45. }
  46. const JSON_OPTIONS = JSON_THROW_ON_ERROR | JSON_INVALID_UTF8_SUBSTITUTE | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
  47. function headerVariable(string $headerName, string $varName): string {
  48. $header = '';
  49. $upName = 'HTTP_' . strtoupper($headerName);
  50. if (is_string($_SERVER[$upName] ?? null)) {
  51. $header = '' . $_SERVER[$upName];
  52. } elseif (is_string($_SERVER['REDIRECT_' . $upName] ?? null)) {
  53. $header = '' . $_SERVER['REDIRECT_' . $upName];
  54. } elseif (function_exists('getallheaders')) {
  55. $ALL_HEADERS = getallheaders();
  56. if (is_string($ALL_HEADERS[$headerName] ?? null)) {
  57. $header = '' . $ALL_HEADERS[$headerName];
  58. }
  59. }
  60. parse_str($header, $pairs);
  61. if (empty($pairs[$varName])) {
  62. return '';
  63. }
  64. return is_string($pairs[$varName]) ? $pairs[$varName] : '';
  65. }
  66. final class GReaderAPI {
  67. private static string $ORIGINAL_INPUT = '';
  68. /** @return list<string> */
  69. private static function multiplePosts(string $name): array {
  70. //https://bugs.php.net/bug.php?id=51633
  71. $inputs = explode('&', self::$ORIGINAL_INPUT);
  72. $result = [];
  73. $prefix = $name . '=';
  74. $prefixLength = strlen($prefix);
  75. foreach ($inputs as $input) {
  76. if (str_starts_with($input, $prefix)) {
  77. $result[] = urldecode(substr($input, $prefixLength));
  78. }
  79. }
  80. return $result;
  81. }
  82. private static function debugInfo(): string {
  83. if (function_exists('getallheaders')) {
  84. $ALL_HEADERS = getallheaders();
  85. } else { //nginx http://php.net/getallheaders#84262
  86. $ALL_HEADERS = [];
  87. foreach ($_SERVER as $name => $value) {
  88. if (is_string($name) && str_starts_with($name, 'HTTP_')) {
  89. $ALL_HEADERS[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
  90. }
  91. }
  92. }
  93. $log = sensitive_log([
  94. 'date' => date('c'),
  95. 'headers' => $ALL_HEADERS,
  96. '_SERVER' => $_SERVER,
  97. '_GET' => $_GET,
  98. '_POST' => $_POST,
  99. '_COOKIE' => $_COOKIE,
  100. 'INPUT' => self::$ORIGINAL_INPUT,
  101. ]);
  102. return print_r($log, true);
  103. }
  104. private static function noContent(): never {
  105. header('HTTP/1.1 204 No Content');
  106. exit();
  107. }
  108. private static function badRequest(): never {
  109. Minz_Log::warning(__METHOD__, API_LOG);
  110. Minz_Log::debug(__METHOD__ . ' ' . self::debugInfo(), API_LOG);
  111. header('HTTP/1.1 400 Bad Request');
  112. header('Content-Type: text/plain; charset=UTF-8');
  113. die('Bad Request!');
  114. }
  115. private static function unauthorized(): never {
  116. Minz_Log::warning(__METHOD__, API_LOG);
  117. Minz_Log::debug(__METHOD__ . ' ' . self::debugInfo(), API_LOG);
  118. header('HTTP/1.1 401 Unauthorized');
  119. header('Content-Type: text/plain; charset=UTF-8');
  120. header('Google-Bad-Token: true');
  121. die('Unauthorized!');
  122. }
  123. private static function internalServerError(): never {
  124. Minz_Log::warning(__METHOD__, API_LOG);
  125. Minz_Log::debug(__METHOD__ . ' ' . self::debugInfo(), API_LOG);
  126. header('HTTP/1.1 500 Internal Server Error');
  127. header('Content-Type: text/plain; charset=UTF-8');
  128. die('Internal Server Error!');
  129. }
  130. private static function notImplemented(): never {
  131. Minz_Log::warning(__METHOD__, API_LOG);
  132. Minz_Log::debug(__METHOD__ . ' ' . self::debugInfo(), API_LOG);
  133. header('HTTP/1.1 501 Not Implemented');
  134. header('Content-Type: text/plain; charset=UTF-8');
  135. die('Not Implemented!');
  136. }
  137. private static function serviceUnavailable(): never {
  138. Minz_Log::warning(__METHOD__, API_LOG);
  139. Minz_Log::debug(__METHOD__ . ' ' . self::debugInfo(), API_LOG);
  140. header('HTTP/1.1 503 Service Unavailable');
  141. header('Content-Type: text/plain; charset=UTF-8');
  142. die('Service Unavailable!');
  143. }
  144. private static function checkCompatibility(): never {
  145. Minz_Log::warning(__METHOD__, API_LOG);
  146. Minz_Log::debug(__METHOD__ . ' ' . self::debugInfo(), API_LOG);
  147. header('Content-Type: text/plain; charset=UTF-8');
  148. if (PHP_INT_SIZE < 8 && !function_exists('gmp_init')) {
  149. die('FAIL 64-bit or GMP extension! Wrong PHP configuration.');
  150. }
  151. $headerAuth = headerVariable('Authorization', 'GoogleLogin_auth');
  152. if ($headerAuth == '') {
  153. die('FAIL get HTTP Authorization header! Wrong Web server configuration.');
  154. }
  155. echo 'PASS';
  156. exit();
  157. }
  158. private static function authorizationToUser(): string {
  159. //Input is 'GoogleLogin auth', but PHP replaces spaces by '_' http://php.net/language.variables.external
  160. $headerAuth = headerVariable('Authorization', 'GoogleLogin_auth');
  161. if ($headerAuth != '') {
  162. $headerAuthX = explode('/', $headerAuth, 2);
  163. if (count($headerAuthX) === 2) {
  164. $user = $headerAuthX[0];
  165. if (FreshRSS_user_Controller::checkUsername($user)) {
  166. FreshRSS_Context::initUser($user);
  167. if (!FreshRSS_Context::hasUserConf() || !FreshRSS_Context::hasSystemConf()) {
  168. Minz_Log::warning('Invalid API user ' . $user . ': configuration cannot be found.');
  169. self::unauthorized();
  170. }
  171. if (!FreshRSS_Context::userConf()->enabled) {
  172. Minz_Log::warning('Invalid API user ' . $user . ': configuration cannot be found.');
  173. self::unauthorized();
  174. }
  175. if ($headerAuthX[1] === sha1(FreshRSS_Context::systemConf()->salt . $user . FreshRSS_Context::userConf()->apiPasswordHash)) {
  176. return $user;
  177. } else {
  178. Minz_Log::warning('Invalid API authorisation for user ' . $user);
  179. self::unauthorized();
  180. }
  181. } else {
  182. self::badRequest();
  183. }
  184. }
  185. }
  186. return '';
  187. }
  188. private static function clientLogin(string $email, string $pass): never {
  189. //https://web.archive.org/web/20130604091042/http://undoc.in/clientLogin.html
  190. if (FreshRSS_user_Controller::checkUsername($email)) {
  191. FreshRSS_Context::initUser($email);
  192. if (!FreshRSS_Context::hasUserConf() || !FreshRSS_Context::hasSystemConf()) {
  193. Minz_Log::warning('Invalid API user ' . $email . ': configuration cannot be found.');
  194. self::unauthorized();
  195. }
  196. if (FreshRSS_Context::userConf()->apiPasswordHash != '' && password_verify($pass, FreshRSS_Context::userConf()->apiPasswordHash)) {
  197. header('Content-Type: text/plain; charset=UTF-8');
  198. $auth = $email . '/' . sha1(FreshRSS_Context::systemConf()->salt . $email . FreshRSS_Context::userConf()->apiPasswordHash);
  199. echo 'SID=', $auth, "\n",
  200. 'LSID=null', "\n", //Vienna RSS
  201. 'Auth=', $auth, "\n";
  202. exit();
  203. } else {
  204. Minz_Log::warning('Password API mismatch for user ' . $email);
  205. self::unauthorized();
  206. }
  207. } else {
  208. self::badRequest();
  209. }
  210. }
  211. private static function token(?FreshRSS_UserConfiguration $conf): never {
  212. // https://web.archive.org/web/20210126113527/https://blog.martindoms.com/2009/08/15/using-the-google-reader-api-part-1
  213. // https://github.com/ericmann/gReader-Library/blob/master/greader.class.php
  214. $user = Minz_User::name();
  215. if ($user === null || $conf === null || !FreshRSS_Context::hasSystemConf()) {
  216. self::unauthorized();
  217. }
  218. //Minz_Log::debug('token('. $user . ')', API_LOG); //TODO: Implement real token that expires
  219. $token = str_pad(sha1(FreshRSS_Context::systemConf()->salt . $user . $conf->apiPasswordHash), 57, 'Z'); //Must have 57 characters
  220. echo $token, "\n";
  221. exit();
  222. }
  223. private static function checkToken(?FreshRSS_UserConfiguration $conf, string $token): bool {
  224. // https://github.com/mihaip/google-reader-api/blob/master/wiki/ActionToken.wiki
  225. $user = Minz_User::name();
  226. if ($user === null || $conf === null || !FreshRSS_Context::hasSystemConf()) {
  227. self::unauthorized();
  228. }
  229. if ($user !== Minz_User::INTERNAL_USER && ( //TODO: Check security consequences
  230. $token === '' || //FeedMe
  231. $token === 'x')) { //Reeder
  232. return true;
  233. }
  234. if (hash_equals(str_pad(sha1(FreshRSS_Context::systemConf()->salt . $user . $conf->apiPasswordHash), 57, 'Z'), $token)) {
  235. return true;
  236. }
  237. Minz_Log::warning('Invalid POST token: ' . $token, API_LOG);
  238. self::unauthorized();
  239. }
  240. private static function userInfo(): never {
  241. //https://github.com/theoldreader/api#user-info
  242. if (!FreshRSS_Context::hasUserConf()) {
  243. self::unauthorized();
  244. }
  245. $user = Minz_User::name();
  246. exit(json_encode([
  247. 'userId' => $user,
  248. 'userName' => $user,
  249. 'userProfileId' => $user,
  250. 'userEmail' => FreshRSS_Context::userConf()->mail_login,
  251. ], JSON_OPTIONS));
  252. }
  253. private static function tagList(): never {
  254. header('Content-Type: application/json; charset=UTF-8');
  255. $tags = [
  256. ['id' => 'user/-/state/com.google/starred'],
  257. // ['id' => 'user/-/state/com.google/broadcast', 'sortid' => '2']
  258. ['id' => 'user/-/state/com.google/reading-list'],
  259. ['id' => 'user/-/state/org.freshrss/main'],
  260. ['id' => 'user/-/state/org.freshrss/important'],
  261. // ['id' => 'user/-/state/org.freshrss/hidden'],
  262. ];
  263. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  264. $categories = $categoryDAO->listCategories(prePopulateFeeds: false, details: false);
  265. foreach ($categories as $cat) {
  266. $tags[] = [
  267. 'id' => 'user/-/label/' . htmlspecialchars_decode($cat->name(), ENT_QUOTES),
  268. //'sortid' => $cat->name(),
  269. 'type' => 'folder', //Inoreader
  270. ];
  271. }
  272. $tagDAO = FreshRSS_Factory::createTagDao();
  273. $labels = $tagDAO->listTags(precounts: true);
  274. foreach ($labels as $label) {
  275. $tags[] = [
  276. 'id' => 'user/-/label/' . htmlspecialchars_decode($label->name(), ENT_QUOTES),
  277. //'sortid' => $label->name(),
  278. 'type' => 'tag', //Inoreader
  279. 'unread_count' => $label->nbUnread(), //Inoreader
  280. ];
  281. }
  282. echo json_encode(['tags' => $tags], JSON_OPTIONS), "\n";
  283. exit();
  284. }
  285. private static function subscriptionExport(): never {
  286. $user = Minz_User::name() ?? Minz_User::INTERNAL_USER;
  287. $export_service = new FreshRSS_Export_Service($user);
  288. [$filename, $content] = $export_service->generateOpml();
  289. header('Content-Type: application/xml; charset=UTF-8');
  290. header('Content-disposition: attachment; filename="' . $filename . '"');
  291. echo $content;
  292. exit();
  293. }
  294. private static function subscriptionImport(string $opml): never {
  295. $user = Minz_User::name() ?? Minz_User::INTERNAL_USER;
  296. $importService = new FreshRSS_Import_Service($user);
  297. $importService->importOpml($opml);
  298. if ($importService->lastStatus()) {
  299. FreshRSS_feed_Controller::actualizeFeedsAndCommit();
  300. invalidateHttpCache($user);
  301. exit('OK');
  302. } else {
  303. self::badRequest();
  304. }
  305. }
  306. private static function subscriptionList(): never {
  307. if (!FreshRSS_Context::hasSystemConf()) {
  308. self::internalServerError();
  309. }
  310. header('Content-Type: application/json; charset=UTF-8');
  311. $subscriptions = [];
  312. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  313. foreach ($categoryDAO->listCategories(prePopulateFeeds: true, details: true) as $cat) {
  314. foreach ($cat->feeds() as $feed) {
  315. if ($feed->priority() <= FreshRSS_Feed::PRIORITY_HIDDEN) {
  316. continue;
  317. }
  318. $subscriptions[] = [
  319. 'id' => 'feed/' . $feed->id(),
  320. 'title' => escapeToUnicodeAlternative($feed->name(), true),
  321. 'categories' => [
  322. [
  323. 'id' => 'user/-/label/' . htmlspecialchars_decode($cat->name(), ENT_QUOTES),
  324. 'label' => htmlspecialchars_decode($cat->name(), ENT_QUOTES),
  325. ],
  326. ],
  327. //'sortid' => $feed->name(),
  328. //'firstitemmsec' => 0,
  329. 'url' => htmlspecialchars_decode($feed->url(), ENT_QUOTES),
  330. 'htmlUrl' => htmlspecialchars_decode($feed->website(), ENT_QUOTES),
  331. 'iconUrl' => str_replace(
  332. '/api/greader.php/reader/api/0/subscription', '', // Security if base_url is not set properly
  333. $feed->favicon(absolute: true)),
  334. 'frss:priority' => match ($feed->priority()) {
  335. FreshRSS_Feed::PRIORITY_IMPORTANT => FreshRSS_Export_Service::PRIORITY_IMPORTANT,
  336. FreshRSS_Feed::PRIORITY_MAIN_STREAM => FreshRSS_Export_Service::PRIORITY_MAIN_STREAM,
  337. FreshRSS_Feed::PRIORITY_CATEGORY => FreshRSS_Export_Service::PRIORITY_CATEGORY,
  338. FreshRSS_Feed::PRIORITY_FEED => FreshRSS_Export_Service::PRIORITY_FEED,
  339. // FreshRSS_Feed::PRIORITY_HIDDEN => FreshRSS_Export_Service::PRIORITY_HIDDEN, // Not returned by the API
  340. default => FreshRSS_Export_Service::PRIORITY_MAIN_STREAM,
  341. },
  342. ];
  343. }
  344. }
  345. echo json_encode(['subscriptions' => $subscriptions], JSON_OPTIONS), "\n";
  346. exit();
  347. }
  348. /**
  349. * @param list<string> $streamNames StreamId(s) to operate on. The parameter may be repeated to edit multiple subscriptions at once
  350. * @param list<string> $titles Title(s) to use for the subscription(s). Each title is associated with the corresponding streamName
  351. * @param string $action 'subscribe'|'unsubscribe'|'edit'
  352. * @param string $add StreamId to add the subscription(s) to (generally a category)
  353. * @param string $remove StreamId to remove the subscription(s) from (generally a category)
  354. */
  355. private static function subscriptionEdit(array $streamNames, array $titles, string $action, string $add = '', string $remove = ''): never {
  356. // https://github.com/mihaip/google-reader-api/blob/master/wiki/ApiSubscriptionEdit.wiki
  357. if (count($streamNames) < 1) {
  358. self::badRequest();
  359. }
  360. switch ($action) {
  361. case 'subscribe':
  362. case 'unsubscribe':
  363. case 'edit':
  364. break;
  365. default:
  366. self::badRequest();
  367. }
  368. $addCatId = 0;
  369. if (str_starts_with($add, 'user/')) { // user/-/label/Example ; user/username/label/Example
  370. if (str_starts_with($add, 'user/-/label/')) {
  371. $c_name = substr($add, 13);
  372. } else {
  373. $prefix = 'user/' . Minz_User::name() . '/label/';
  374. if (str_starts_with($add, $prefix)) {
  375. $c_name = substr($add, strlen($prefix));
  376. } else {
  377. $c_name = '';
  378. }
  379. }
  380. $c_name = htmlspecialchars($c_name, ENT_COMPAT, 'UTF-8');
  381. if (in_array($c_name, ['', FreshRSS_CategoryDAO::DEFAULT_CATEGORY_NAME, _t('gen.short.default_category')], true)) {
  382. $addCatId = FreshRSS_CategoryDAO::DEFAULTCATEGORYID;
  383. } else {
  384. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  385. $cat = $categoryDAO->searchByName($c_name);
  386. $addCatId = $cat === null ? 0 : $cat->id();
  387. if ($addCatId === 0) {
  388. $addCatId = $categoryDAO->addCategory(['name' => $c_name]) ?: FreshRSS_CategoryDAO::DEFAULTCATEGORYID;
  389. }
  390. }
  391. } elseif (str_starts_with($remove, 'user/-/label/')) {
  392. $addCatId = FreshRSS_CategoryDAO::DEFAULTCATEGORYID;
  393. }
  394. $feedDAO = FreshRSS_Factory::createFeedDao();
  395. for ($i = count($streamNames) - 1; $i >= 0; $i--) {
  396. $streamUrl = $streamNames[$i]; //feed/http://example.net/sample.xml ; feed/338
  397. if (str_starts_with($streamUrl, 'feed/')) {
  398. $streamUrl = '' . preg_replace('%^(feed/)+%', '', $streamUrl);
  399. $feedId = 0;
  400. if (is_numeric($streamUrl)) {
  401. if ($action === 'subscribe') {
  402. continue;
  403. }
  404. $feedId = (int)$streamUrl;
  405. } else {
  406. $streamUrl = htmlspecialchars($streamUrl, ENT_COMPAT, 'UTF-8');
  407. $feed = $feedDAO->searchByUrl($streamUrl);
  408. $feedId = $feed == null ? -1 : $feed->id();
  409. }
  410. $title = $titles[$i] ?? '';
  411. $title = htmlspecialchars($title, ENT_COMPAT, 'UTF-8');
  412. switch ($action) {
  413. case 'subscribe':
  414. if ($feedId <= 0) {
  415. $http_auth = '';
  416. try {
  417. $kind = self::detectFeedKind($streamUrl);
  418. FreshRSS_feed_Controller::addFeed($streamUrl, $title, $addCatId, '', $http_auth, [], $kind);
  419. continue 2;
  420. } catch (Exception $e) {
  421. Minz_Log::error('subscriptionEdit error subscribe: ' . $e->getMessage(), API_LOG);
  422. }
  423. }
  424. self::badRequest();
  425. // Always exits
  426. case 'unsubscribe':
  427. if (!($feedId > 0 && FreshRSS_feed_Controller::deleteFeed($feedId))) {
  428. self::badRequest();
  429. }
  430. break;
  431. case 'edit':
  432. if ($feedId > 0) {
  433. if ($addCatId > 0) {
  434. FreshRSS_feed_Controller::moveFeed($feedId, $addCatId);
  435. }
  436. if ($title != '') {
  437. FreshRSS_feed_Controller::renameFeed($feedId, $title);
  438. }
  439. } else {
  440. self::badRequest();
  441. }
  442. break;
  443. }
  444. }
  445. }
  446. exit('OK');
  447. }
  448. /**
  449. * Guess the kind of feed (RSS/ATOM vs. JSON) based on URL.
  450. * The Google Reader API does not provide any way for the client to specify the feed format.
  451. */
  452. private static function detectFeedKind(string $url): int {
  453. return preg_match('/(?:\b|_)json(?:\b|_)/i', $url) === 1
  454. ? FreshRSS_Feed::KIND_JSONFEED
  455. : FreshRSS_Feed::KIND_RSS;
  456. }
  457. private static function quickadd(string $url): never {
  458. try {
  459. $url = htmlspecialchars($url, ENT_COMPAT, 'UTF-8');
  460. if (str_starts_with($url, 'feed/')) {
  461. $url = substr($url, 5);
  462. }
  463. $feed = FreshRSS_feed_Controller::addFeed($url, kind: self::detectFeedKind($url));
  464. exit(json_encode([
  465. 'numResults' => 1,
  466. 'query' => $feed->url(),
  467. 'streamId' => 'feed/' . $feed->id(),
  468. 'streamName' => $feed->name(),
  469. ], JSON_OPTIONS));
  470. } catch (Exception $e) {
  471. Minz_Log::error('quickadd error: ' . $e->getMessage(), API_LOG);
  472. die(json_encode([
  473. 'numResults' => 0,
  474. 'error' => $e->getMessage(),
  475. ], JSON_OPTIONS));
  476. }
  477. }
  478. private static function unreadCount(): never {
  479. // https://web.archive.org/web/20210126115837/https://blog.martindoms.com/2009/10/16/using-the-google-reader-api-part-2#unread-count
  480. header('Content-Type: application/json; charset=UTF-8');
  481. $totalUnreads = 0;
  482. $totalLastUpdate = 0;
  483. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  484. $feedDAO = FreshRSS_Factory::createFeedDao();
  485. $feedsNewestItemUsec = $feedDAO->listFeedsNewestItemUsec();
  486. $unreadcounts = [];
  487. foreach ($categoryDAO->listCategories(prePopulateFeeds: true, details: true) as $cat) {
  488. $catLastUpdate = 0;
  489. foreach ($cat->feeds() as $feed) {
  490. if ($feed->priority() <= FreshRSS_Feed::PRIORITY_HIDDEN) {
  491. continue;
  492. }
  493. $lastUpdate = $feedsNewestItemUsec['f_' . $feed->id()] ?? 0;
  494. $unreadcounts[] = [
  495. 'id' => 'feed/' . $feed->id(),
  496. 'count' => $feed->nbNotRead(),
  497. 'newestItemTimestampUsec' => '' . $lastUpdate,
  498. ];
  499. if ($catLastUpdate < $lastUpdate) {
  500. $catLastUpdate = $lastUpdate;
  501. }
  502. }
  503. $unreadcounts[] = [
  504. 'id' => 'user/-/label/' . htmlspecialchars_decode($cat->name(), ENT_QUOTES),
  505. 'count' => $cat->nbNotRead(),
  506. 'newestItemTimestampUsec' => '' . $catLastUpdate,
  507. ];
  508. $totalUnreads += $cat->nbNotRead();
  509. if ($totalLastUpdate < $catLastUpdate) {
  510. $totalLastUpdate = $catLastUpdate;
  511. }
  512. }
  513. $tagDAO = FreshRSS_Factory::createTagDao();
  514. $tagsNewestItemUsec = $tagDAO->listTagsNewestItemUsec();
  515. foreach ($tagDAO->listTags(precounts: true) as $label) {
  516. $lastUpdate = $tagsNewestItemUsec['t_' . $label->id()] ?? 0;
  517. $unreadcounts[] = [
  518. 'id' => 'user/-/label/' . htmlspecialchars_decode($label->name(), ENT_QUOTES),
  519. 'count' => $label->nbUnread(),
  520. 'newestItemTimestampUsec' => '' . $lastUpdate,
  521. ];
  522. }
  523. $unreadcounts[] = [
  524. 'id' => 'user/-/state/com.google/reading-list',
  525. 'count' => $totalUnreads,
  526. 'newestItemTimestampUsec' => '' . $totalLastUpdate,
  527. ];
  528. echo json_encode([
  529. 'max' => $totalUnreads,
  530. 'unreadcounts' => $unreadcounts,
  531. ], JSON_OPTIONS), "\n";
  532. exit();
  533. }
  534. /**
  535. * @param iterable<FreshRSS_Entry> $entries
  536. * @param list<numeric-string>|null $e_ids List of entry IDs if known, for performance
  537. * @return Generator<int,array<string,mixed>>
  538. */
  539. private static function entriesToArray(iterable $entries, ?array $e_ids = null): Generator {
  540. $catDAO = FreshRSS_Factory::createCategoryDao();
  541. $categories = $catDAO->listCategories(prePopulateFeeds: true);
  542. $tagDAO = FreshRSS_Factory::createTagDao();
  543. if (is_array($e_ids)) {
  544. $entryIdsTagNames = $tagDAO->getEntryIdsTagNames($e_ids);
  545. } else {
  546. // If we do not have the list of entry IDs, we first need to iterate through all entries
  547. //TODO: Improve: avoid iterator_to_array. Type test only for PHP < 8.2
  548. $entries = array_values(is_array($entries) ? $entries : iterator_to_array($entries));
  549. $entryIdsTagNames = $tagDAO->getEntryIdsTagNames($entries);
  550. }
  551. foreach ($entries as $item) {
  552. /** @var FreshRSS_Entry|null $entry */
  553. $entry = Minz_ExtensionManager::callHook(Minz_HookType::EntryBeforeDisplay, $item);
  554. if ($entry === null) {
  555. continue;
  556. }
  557. $feed = FreshRSS_Category::findFeed($categories, $entry->feedId());
  558. if ($feed === null) {
  559. continue;
  560. }
  561. $entry->_feed($feed);
  562. yield $entry->toGReader('compat', $entryIdsTagNames['e_' . $entry->id()] ?? []);
  563. }
  564. }
  565. /**
  566. * @param 'A'|'a'|'c'|'f'|'i'|'s' $type
  567. * @return array{'A'|'a'|'c'|'f'|'i'|'s'|'t',int,int,FreshRSS_BooleanSearch}
  568. */
  569. private static function streamContentsFilters(string $type, int|string $streamId,
  570. string $filter_target, string $exclude_target, int $start_time, int $stop_time): array {
  571. switch ($type) {
  572. case 'f': //feed
  573. if ($streamId != '' && is_string($streamId) && !is_numeric($streamId)) {
  574. $feedDAO = FreshRSS_Factory::createFeedDao();
  575. $streamId = htmlspecialchars($streamId, ENT_COMPAT, 'UTF-8');
  576. $feed = $feedDAO->searchByUrl($streamId);
  577. $streamId = $feed === null ? -1 : $feed->id();
  578. }
  579. break;
  580. case 'c': //category or label
  581. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  582. $streamId = htmlspecialchars((string)$streamId, ENT_COMPAT, 'UTF-8');
  583. $cat = $categoryDAO->searchByName($streamId);
  584. if ($cat !== null) {
  585. $streamId = $cat->id();
  586. } else {
  587. $tagDAO = FreshRSS_Factory::createTagDao();
  588. $tag = $tagDAO->searchByName($streamId);
  589. if ($tag !== null) {
  590. $type = 't';
  591. $streamId = $tag->id();
  592. } else {
  593. $streamId = -1;
  594. }
  595. }
  596. break;
  597. }
  598. $streamId = is_numeric($streamId) ? (int)$streamId : 0;
  599. $state = match ($filter_target) {
  600. 'user/-/state/com.google/read' => FreshRSS_Entry::STATE_READ,
  601. 'user/-/state/com.google/unread' => FreshRSS_Entry::STATE_NOT_READ,
  602. 'user/-/state/com.google/starred' => FreshRSS_Entry::STATE_FAVORITE,
  603. default => FreshRSS_Entry::STATE_ALL,
  604. };
  605. switch ($exclude_target) {
  606. case 'user/-/state/com.google/read':
  607. $state &= FreshRSS_Entry::STATE_NOT_READ;
  608. break;
  609. case 'user/-/state/com.google/unread':
  610. $state &= FreshRSS_Entry::STATE_READ;
  611. break;
  612. case 'user/-/state/com.google/starred':
  613. $state &= FreshRSS_Entry::STATE_NOT_FAVORITE;
  614. break;
  615. }
  616. $searches = new FreshRSS_BooleanSearch('');
  617. if ($start_time !== 0) {
  618. $search = new FreshRSS_Search('');
  619. $search->setMinDate($start_time);
  620. $searches->add($search);
  621. // OR
  622. $search = new FreshRSS_Search('');
  623. $search->setMinModifiedDate($start_time);
  624. $searches->add($search);
  625. }
  626. if ($stop_time !== 0) {
  627. $search = new FreshRSS_Search('');
  628. $search->setMaxDate($stop_time);
  629. // AND
  630. $search->setMaxModifiedDate($stop_time);
  631. $searches->add($search);
  632. }
  633. return [$type, $streamId, $state, $searches];
  634. }
  635. /**
  636. * @param numeric-string $continuation
  637. */
  638. private static function streamContents(string $path, string $include_target, int $start_time, int $stop_time, int $count,
  639. string $order, string $filter_target, string $exclude_target, string $continuation): never {
  640. // https://code.google.com/archive/p/pyrfeed/wikis/GoogleReaderAPI.wiki
  641. // https://web.archive.org/web/20210126115837/https://blog.martindoms.com/2009/10/16/using-the-google-reader-api-part-2#feed
  642. header('Content-Type: application/json; charset=UTF-8');
  643. $type = match ($path) {
  644. 'starred' => 's',
  645. 'feed' => 'f',
  646. 'label' => 'c',
  647. 'reading-list' => 'A', // All except PRIORITY_HIDDEN
  648. 'main' => 'a',
  649. 'important' => 'i',
  650. default => 'A',
  651. };
  652. [$type, $include_target, $state, $searches] =
  653. self::streamContentsFilters($type, $include_target, $filter_target, $exclude_target, $start_time, $stop_time);
  654. if ($continuation !== '0') {
  655. $count++; //Shift by one element
  656. }
  657. $entryDAO = FreshRSS_Factory::createEntryDao();
  658. $entries = $entryDAO->listWhere($type, $include_target, $state, $searches,
  659. order: $order === 'o' ? 'ASC' : 'DESC',
  660. continuation_id: $continuation,
  661. limit: $count);
  662. $items = self::entriesToArray($entries);
  663. if ($continuation !== '0') {
  664. //Discard first element that was already sent in the previous response
  665. $items = new LimitIterator($items, offset: 1);
  666. $count--;
  667. }
  668. $time = time();
  669. $nbItems = 0;
  670. $lastEntryId = 0;
  671. // Note: This section must be streamed to avoid memory issues with large responses
  672. echo <<<TXT
  673. {
  674. "id": "user/-/state/com.google/reading-list",
  675. "updated": $time,
  676. "items": [
  677. TXT;
  678. foreach ($items as $item) {
  679. if (!is_array($item) || empty($item)) {
  680. continue;
  681. }
  682. if ($nbItems > 0) {
  683. echo ",\n";
  684. }
  685. $lastEntryId = is_numeric($item['frss:id'] ?? null) ? (int)$item['frss:id'] : 0;
  686. unset($item['frss:id']);
  687. echo json_encode($item, JSON_OPTIONS);
  688. $nbItems++;
  689. }
  690. echo <<<'TXT'
  691. ]
  692. TXT;
  693. if ($nbItems >= $count && $lastEntryId > 0) {
  694. echo <<<TXT
  695. ,
  696. "continuation": "$lastEntryId"
  697. TXT;
  698. }
  699. echo <<<'TXT'
  700. }
  701. TXT;
  702. exit();
  703. }
  704. /**
  705. * @param numeric-string $continuation
  706. */
  707. private static function streamContentsItemsIds(string $streamId, int $start_time, int $stop_time, int $count,
  708. string $order, string $filter_target, string $exclude_target, string $continuation): never {
  709. // https://github.com/mihaip/google-reader-api/blob/master/wiki/ApiStreamItemsIds.wiki
  710. // https://code.google.com/archive/p/pyrfeed/wikis/GoogleReaderAPI.wiki
  711. // https://web.archive.org/web/20210126115837/https://blog.martindoms.com/2009/10/16/using-the-google-reader-api-part-2#feed
  712. $type = 'A';
  713. if ($streamId === 'user/-/state/com.google/reading-list') {
  714. $type = 'A';
  715. $streamId = '';
  716. } elseif ($streamId === 'user/-/state/com.google/starred') {
  717. $type = 's';
  718. $streamId = '';
  719. } elseif ($streamId === 'user/-/state/org.freshrss/main') {
  720. $type = 'a';
  721. $streamId = '';
  722. } elseif ($streamId === 'user/-/state/org.freshrss/important') {
  723. $type = 'i';
  724. $streamId = '';
  725. } elseif ($streamId === 'user/-/state/com.google/read') {
  726. $filter_target = $streamId;
  727. $type = 'A';
  728. $streamId = '';
  729. } elseif ($streamId === 'user/-/state/com.google/unread') {
  730. $filter_target = $streamId;
  731. $type = 'A';
  732. $streamId = '';
  733. } elseif (str_starts_with($streamId, 'feed/')) {
  734. $type = 'f';
  735. $streamId = substr($streamId, 5);
  736. } elseif (str_starts_with($streamId, 'user/-/label/')) {
  737. $type = 'c';
  738. $streamId = substr($streamId, 13);
  739. }
  740. [$type, $id, $state, $searches] = self::streamContentsFilters($type, $streamId, $filter_target, $exclude_target, $start_time, $stop_time);
  741. if ($continuation !== '0') {
  742. $count++; //Shift by one element
  743. }
  744. $entryDAO = FreshRSS_Factory::createEntryDao();
  745. $ids = $entryDAO->listIdsWhere($type, $id, $state, $searches,
  746. order: $order === 'o' ? 'ASC' : 'DESC',
  747. continuation_id: $continuation,
  748. limit: $count);
  749. if ($ids === null) {
  750. self::internalServerError();
  751. }
  752. if ($continuation !== '0') {
  753. array_shift($ids); //Discard first element that was already sent in the previous response
  754. $count--;
  755. }
  756. if (empty($ids) && isset($_GET['client']) && $_GET['client'] === 'newsplus') {
  757. $ids = [ 0 ]; //For News+ bug https://github.com/noinnion/newsplus/issues/84#issuecomment-57834632
  758. }
  759. $itemRefs = [];
  760. foreach ($ids as $entryId) {
  761. $itemRefs[] = [
  762. 'id' => '' . $entryId, //64-bit decimal
  763. ];
  764. }
  765. $response = [
  766. 'itemRefs' => $itemRefs,
  767. ];
  768. if (count($ids) >= $count) {
  769. $entryId = end($ids);
  770. if ($entryId != false) {
  771. $response['continuation'] = '' . $entryId;
  772. }
  773. }
  774. echo json_encode($response, JSON_OPTIONS), "\n";
  775. exit();
  776. }
  777. /**
  778. * @param list<string> $e_ids
  779. */
  780. private static function streamContentsItems(array $e_ids, string $order): never {
  781. header('Content-Type: application/json; charset=UTF-8');
  782. foreach ($e_ids as $i => $e_id) {
  783. // https://feedhq.readthedocs.io/en/latest/api/terminology.html#items
  784. if (!ctype_digit($e_id) || $e_id[0] === '0') {
  785. $e_ids[$i] = hex2dec(basename($e_id)); //Strip prefix 'tag:google.com,2005:reader/item/'
  786. }
  787. }
  788. /** @var list<numeric-string> $e_ids */
  789. $entryDAO = FreshRSS_Factory::createEntryDao();
  790. $entries = $entryDAO->listByIds($e_ids, order: $order === 'o' ? 'ASC' : 'DESC');
  791. $items = self::entriesToArray($entries, $e_ids);
  792. $time = time();
  793. $nbItems = 0;
  794. // Note: This section must be streamed to avoid memory issues with large responses
  795. echo <<<TXT
  796. {
  797. "id": "user/-/state/com.google/reading-list",
  798. "updated": $time,
  799. "items": [
  800. TXT;
  801. foreach ($items as $item) {
  802. if (!is_array($item) || empty($item)) {
  803. continue;
  804. }
  805. if ($nbItems > 0) {
  806. echo ",\n";
  807. }
  808. unset($item['frss:id']);
  809. echo json_encode($item, JSON_OPTIONS);
  810. $nbItems++;
  811. }
  812. echo <<<'TXT'
  813. ]
  814. }
  815. TXT;
  816. exit();
  817. }
  818. /**
  819. * @param list<string> $e_ids IDs of the items to edit
  820. * @param list<string> $as tags to add to all the listed items
  821. * @param list<string> $rs tags to remove from all the listed items
  822. */
  823. private static function editTag(array $e_ids, array $as, array $rs): never {
  824. foreach ($e_ids as $i => $e_id) {
  825. if (!ctype_digit($e_id) || $e_id[0] === '0') {
  826. $e_ids[$i] = hex2dec(basename($e_id)); //Strip prefix 'tag:google.com,2005:reader/item/'
  827. }
  828. }
  829. /** @var list<numeric-string> $e_ids */
  830. $entryDAO = FreshRSS_Factory::createEntryDao();
  831. $tagDAO = FreshRSS_Factory::createTagDao();
  832. foreach ($as as $a) {
  833. switch ($a) {
  834. case 'user/-/state/com.google/read':
  835. $entryDAO->markRead($e_ids, true);
  836. break;
  837. case 'user/-/state/com.google/starred':
  838. $entryDAO->markFavorite($e_ids, true);
  839. break;
  840. case 'user/-/state/com.google/broadcast':
  841. case 'user/-/state/com.google/like':
  842. case 'user/-/state/com.google/tracking-kept-unread':
  843. // Not supported
  844. break;
  845. default:
  846. $tagName = '';
  847. if (str_starts_with($a, 'user/-/label/')) {
  848. $tagName = substr($a, 13);
  849. } else {
  850. $user = Minz_User::name() ?? '';
  851. $prefix = 'user/' . $user . '/label/';
  852. if (str_starts_with($a, $prefix)) {
  853. $tagName = substr($a, strlen($prefix));
  854. }
  855. }
  856. if ($tagName !== '') {
  857. $tagName = htmlspecialchars($tagName, ENT_COMPAT, 'UTF-8');
  858. $tag = $tagDAO->searchByName($tagName);
  859. if ($tag === null) {
  860. $tagDAO->addTag(['name' => $tagName]);
  861. $tag = $tagDAO->searchByName($tagName);
  862. }
  863. if ($tag !== null) {
  864. foreach ($e_ids as $e_id) {
  865. $tagDAO->tagEntry($tag->id(), $e_id, true);
  866. }
  867. }
  868. }
  869. break;
  870. }
  871. }
  872. foreach ($rs as $r) {
  873. switch ($r) {
  874. case 'user/-/state/com.google/read':
  875. $entryDAO->markRead($e_ids, false);
  876. break;
  877. case 'user/-/state/com.google/starred':
  878. $entryDAO->markFavorite($e_ids, false);
  879. break;
  880. case 'user/-/state/com.google/broadcast':
  881. case 'user/-/state/com.google/like':
  882. case 'user/-/state/com.google/tracking-kept-unread':
  883. // Not supported
  884. break;
  885. default:
  886. if (str_starts_with($r, 'user/-/label/')) {
  887. $tagName = substr($r, 13);
  888. $tagName = htmlspecialchars($tagName, ENT_COMPAT, 'UTF-8');
  889. $tag = $tagDAO->searchByName($tagName);
  890. if ($tag !== null) {
  891. foreach ($e_ids as $e_id) {
  892. $tagDAO->tagEntry($tag->id(), $e_id, false);
  893. }
  894. }
  895. }
  896. break;
  897. }
  898. }
  899. exit('OK');
  900. }
  901. private static function renameTag(string $s, string $dest): never {
  902. if (str_starts_with($s, 'user/-/label/') && str_starts_with($dest, 'user/-/label/')) {
  903. $s = substr($s, 13);
  904. $s = htmlspecialchars($s, ENT_COMPAT, 'UTF-8');
  905. $dest = substr($dest, 13);
  906. $dest = htmlspecialchars($dest, ENT_COMPAT, 'UTF-8');
  907. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  908. $cat = $categoryDAO->searchByName($s);
  909. if ($cat != null) {
  910. $categoryDAO->updateCategory($cat->id(), [
  911. 'name' => $dest, 'kind' => $cat->kind(), 'attributes' => $cat->attributes()
  912. ]);
  913. exit('OK');
  914. } else {
  915. $tagDAO = FreshRSS_Factory::createTagDao();
  916. $tag = $tagDAO->searchByName($s);
  917. if ($tag != null) {
  918. $tagDAO->updateTagName($tag->id(), $dest);
  919. exit('OK');
  920. }
  921. }
  922. }
  923. self::badRequest();
  924. }
  925. private static function disableTag(string $s): never {
  926. if (str_starts_with($s, 'user/-/label/')) {
  927. $s = substr($s, 13);
  928. $s = htmlspecialchars($s, ENT_COMPAT, 'UTF-8');
  929. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  930. $cat = $categoryDAO->searchByName($s);
  931. if ($cat != null) {
  932. $feedDAO = FreshRSS_Factory::createFeedDao();
  933. $feedDAO->changeCategory($cat->id(), 0);
  934. if ($cat->id() > FreshRSS_CategoryDAO::DEFAULTCATEGORYID) {
  935. $categoryDAO->deleteCategory($cat->id());
  936. }
  937. exit('OK');
  938. } else {
  939. $tagDAO = FreshRSS_Factory::createTagDao();
  940. $tag = $tagDAO->searchByName($s);
  941. if ($tag != null) {
  942. $tagDAO->deleteTag($tag->id());
  943. exit('OK');
  944. }
  945. }
  946. }
  947. self::badRequest();
  948. }
  949. /**
  950. * @param numeric-string $olderThanId
  951. */
  952. private static function markAllAsRead(string $streamId, string $olderThanId): never {
  953. $entryDAO = FreshRSS_Factory::createEntryDao();
  954. if (str_starts_with($streamId, 'feed/')) {
  955. $f_id = basename($streamId);
  956. if (!is_numeric($f_id)) {
  957. self::badRequest();
  958. }
  959. $f_id = (int)$f_id;
  960. $entryDAO->markReadFeed($f_id, $olderThanId);
  961. } elseif (str_starts_with($streamId, 'user/-/label/')) {
  962. $c_name = substr($streamId, 13);
  963. $c_name = htmlspecialchars($c_name, ENT_COMPAT, 'UTF-8');
  964. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  965. $cat = $categoryDAO->searchByName($c_name);
  966. if ($cat != null) {
  967. $entryDAO->markReadCat($cat->id(), $olderThanId);
  968. } else {
  969. $tagDAO = FreshRSS_Factory::createTagDao();
  970. $tag = $tagDAO->searchByName($c_name);
  971. if ($tag != null) {
  972. $entryDAO->markReadTag($tag->id(), $olderThanId);
  973. } else {
  974. self::badRequest();
  975. }
  976. }
  977. } elseif ($streamId === 'user/-/state/com.google/reading-list') {
  978. $entryDAO->markReadEntries($olderThanId, priorityMin: FreshRSS_Feed::PRIORITY_HIDDEN + 1);
  979. } elseif ($streamId === 'user/-/state/com.google/starred') {
  980. $entryDAO->markReadEntries($olderThanId, onlyFavorites: true, priorityMin: FreshRSS_Feed::PRIORITY_HIDDEN + 1);
  981. } elseif ($streamId === 'user/-/state/org.freshrss/main') {
  982. $entryDAO->markReadEntries($olderThanId, priorityMin: FreshRSS_Feed::PRIORITY_MAIN_STREAM);
  983. } elseif ($streamId === 'user/-/state/org.freshrss/important') {
  984. $entryDAO->markReadEntries($olderThanId, priorityMin: FreshRSS_Feed::PRIORITY_IMPORTANT);
  985. } elseif ($streamId === 'user/-/state/com.google/read') {
  986. $entryDAO->markReadEntries($olderThanId, state: FreshRSS_Entry::STATE_READ);
  987. } elseif ($streamId === 'user/-/state/com.google/unread') {
  988. $entryDAO->markReadEntries($olderThanId, state: FreshRSS_Entry::STATE_NOT_READ, priorityMin: FreshRSS_Feed::PRIORITY_HIDDEN + 1);
  989. } else {
  990. self::badRequest();
  991. }
  992. exit('OK');
  993. }
  994. public static function parse(): never {
  995. header('Access-Control-Allow-Headers: Authorization');
  996. header('Access-Control-Allow-Methods: GET, POST');
  997. header('Access-Control-Allow-Origin: *');
  998. header('Access-Control-Max-Age: 600');
  999. if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') {
  1000. self::noContent();
  1001. }
  1002. $pathInfo = '';
  1003. if (empty($_SERVER['PATH_INFO']) || !is_string($_SERVER['PATH_INFO'])) {
  1004. if (!empty($_SERVER['ORIG_PATH_INFO']) && is_string($_SERVER['ORIG_PATH_INFO'])) {
  1005. // Compatibility https://php.net/reserved.variables.server
  1006. $pathInfo = $_SERVER['ORIG_PATH_INFO'];
  1007. }
  1008. } else {
  1009. $pathInfo = $_SERVER['PATH_INFO'];
  1010. }
  1011. $pathInfo = rawurldecode($pathInfo);
  1012. $pathInfo = '' . preg_replace('%^(/api)?(/greader\.php)?%', '', $pathInfo); //Discard common errors
  1013. if ($pathInfo == '' && empty($_SERVER['QUERY_STRING'])) {
  1014. exit('OK');
  1015. }
  1016. $pathInfos = explode('/', $pathInfo);
  1017. if (count($pathInfos) < 3) {
  1018. self::badRequest();
  1019. }
  1020. FreshRSS_Context::initSystem();
  1021. //Minz_Log::debug('----------------------------------------------------------------', API_LOG);
  1022. //Minz_Log::debug(self::debugInfo(), API_LOG);
  1023. if (!FreshRSS_Context::hasSystemConf() || !FreshRSS_Context::systemConf()->api_enabled) {
  1024. self::serviceUnavailable();
  1025. } elseif ($pathInfos[1] === 'check' && $pathInfos[2] === 'compatibility') {
  1026. self::checkCompatibility();
  1027. }
  1028. Minz_Session::init('FreshRSS', true);
  1029. if ($pathInfos[1] !== 'accounts') {
  1030. self::authorizationToUser();
  1031. }
  1032. if (FreshRSS_Context::hasUserConf()) {
  1033. Minz_Translate::init(FreshRSS_Context::userConf()->language);
  1034. Minz_ExtensionManager::init();
  1035. Minz_ExtensionManager::enableByList(FreshRSS_Context::userConf()->extensions_enabled, 'user');
  1036. } else {
  1037. Minz_Translate::init();
  1038. }
  1039. self::$ORIGINAL_INPUT = file_get_contents('php://input', false, null, 0, 1048576) ?: '';
  1040. if ($pathInfos[1] === 'accounts') {
  1041. if ($pathInfos[2] === 'ClientLogin') {
  1042. $email = $_POST['Email'] ?? $_GET['Email'] ?? null;
  1043. $passwd = $_POST['Passwd'] ?? $_GET['Passwd'] ?? null;
  1044. if (is_string($email) && is_string($passwd)) {
  1045. if (isset($_GET['Email']) || isset($_GET['Passwd'])) {
  1046. $user_agent = is_string($_SERVER['HTTP_USER_AGENT'] ?? null) ? $_SERVER['HTTP_USER_AGENT'] : '';
  1047. $warning_message = 'ClientLogin using GET method is deprecated: password may appear in logs. Use POST instead. User-Agent: ' . $user_agent;
  1048. Minz_Log::warning($warning_message, API_LOG);
  1049. }
  1050. self::clientLogin($email, $passwd);
  1051. }
  1052. }
  1053. } elseif (isset($pathInfos[3], $pathInfos[4]) && $pathInfos[1] === 'reader' && $pathInfos[2] === 'api' && $pathInfos[3] === '0') {
  1054. if (Minz_User::name() === null) {
  1055. self::unauthorized();
  1056. }
  1057. // ck=[unix timestamp]: Use the current Unix time here, helps Google with caching
  1058. $timestamp = is_numeric($_GET['ck'] ?? null) ? (int)$_GET['ck'] : 0;
  1059. switch ($pathInfos[4]) {
  1060. case 'stream':
  1061. /**
  1062. * xt=[exclude target]: Used to exclude certain items from the feed.
  1063. * For example, using xt=user/-/state/com.google/read will exclude items
  1064. * that the current user has marked as read, or xt=feed/[feedurl] will
  1065. * exclude items from a particular feed (obviously not useful in this request,
  1066. * but xt appears in other listing requests).
  1067. */
  1068. $exclude_target = is_string($_GET['xt'] ?? null) ? $_GET['xt'] : '';
  1069. $filter_target = is_string($_GET['it'] ?? null) ? $_GET['it'] : '';
  1070. //n=[integer] : The maximum number of results to return.
  1071. $count = is_numeric($_GET['n'] ?? null) ? (int)$_GET['n'] : 20;
  1072. //r=[d|n|o] : Sort order of item results. d or n gives items in descending date order, o in ascending order.
  1073. $order = is_string($_GET['r'] ?? null) ? $_GET['r'] : 'd';
  1074. /**
  1075. * ot=[unix timestamp] : The time from which you want to retrieve items.
  1076. * Only items that have been crawled by Google Reader after this time will be returned.
  1077. */
  1078. $start_time = is_numeric($_GET['ot'] ?? null) ? (int)$_GET['ot'] : 0;
  1079. $stop_time = is_numeric($_GET['nt'] ?? null) ? (int)$_GET['nt'] : 0;
  1080. /**
  1081. * Continuation token. If a StreamContents response does not represent
  1082. * all items in a timestamp range, it will have a continuation attribute.
  1083. * The same request can be re-issued with the value of that attribute put
  1084. * in this parameter to get more items
  1085. */
  1086. $continuation = is_string($_GET['c'] ?? null) ? trim($_GET['c']) : '';
  1087. if (!ctype_digit($continuation)) {
  1088. $continuation = '0';
  1089. }
  1090. if (isset($pathInfos[5]) && $pathInfos[5] === 'contents') {
  1091. if (!isset($pathInfos[6]) && is_string($_GET['s'] ?? null)) {
  1092. // Compatibility BazQux API https://github.com/bazqux/bazqux-api#fetching-streams
  1093. $streamIdInfos = explode('/', $_GET['s']);
  1094. foreach ($streamIdInfos as $streamIdInfo) {
  1095. $pathInfos[] = $streamIdInfo;
  1096. }
  1097. }
  1098. if (isset($pathInfos[6], $pathInfos[7])) {
  1099. if ($pathInfos[6] === 'feed') {
  1100. $include_target = $pathInfos[7];
  1101. if ($include_target !== '' && !is_numeric($include_target)) {
  1102. $include_target = empty($_SERVER['REQUEST_URI']) || !is_string($_SERVER['REQUEST_URI']) ? '' : $_SERVER['REQUEST_URI'];
  1103. if (preg_match('#/reader/api/0/stream/contents/feed/([A-Za-z0-9\'!*()%$_.~+-]+)#', $include_target, $matches) === 1) {
  1104. $include_target = urldecode($matches[1]);
  1105. } else {
  1106. $include_target = '';
  1107. }
  1108. }
  1109. self::streamContents($pathInfos[6], $include_target, $start_time, $stop_time,
  1110. $count, $order, $filter_target, $exclude_target, $continuation);
  1111. } elseif (isset($pathInfos[8], $pathInfos[9]) && $pathInfos[6] === 'user') {
  1112. if ($pathInfos[8] === 'state') {
  1113. if (in_array($pathInfos[9], ['com.google', 'org.freshrss'], true) && isset($pathInfos[10])) {
  1114. if (in_array($pathInfos[10], ['reading-list', 'starred', 'main', 'important'], true)) {
  1115. $include_target = '';
  1116. self::streamContents($pathInfos[10], $include_target, $start_time, $stop_time, $count, $order,
  1117. $filter_target, $exclude_target, $continuation);
  1118. }
  1119. }
  1120. } elseif ($pathInfos[8] === 'label') {
  1121. $include_target = empty($_SERVER['REQUEST_URI']) || !is_string($_SERVER['REQUEST_URI']) ? '' : $_SERVER['REQUEST_URI'];
  1122. if (preg_match('#/reader/api/0/stream/contents/user/[^/+]/label/([A-Za-z0-9\'!*()%$_.~+-]+)#', $include_target, $matches)) {
  1123. $include_target = urldecode($matches[1]);
  1124. } else {
  1125. $include_target = $pathInfos[9];
  1126. }
  1127. self::streamContents($pathInfos[8], $include_target, $start_time, $stop_time,
  1128. $count, $order, $filter_target, $exclude_target, $continuation);
  1129. }
  1130. }
  1131. } else { //EasyRSS, FeedMe
  1132. $include_target = '';
  1133. self::streamContents('reading-list', $include_target, $start_time, $stop_time,
  1134. $count, $order, $filter_target, $exclude_target, $continuation);
  1135. }
  1136. } elseif ($pathInfos[5] === 'items') {
  1137. if ($pathInfos[6] === 'ids' && is_string($_GET['s'] ?? null)) {
  1138. // StreamId for which to fetch the item IDs.
  1139. // TODO: support multiple streams
  1140. $streamId = $_GET['s'];
  1141. self::streamContentsItemsIds($streamId, $start_time, $stop_time, $count, $order, $filter_target, $exclude_target, $continuation);
  1142. } elseif ($pathInfos[6] === 'contents' && isset($_POST['i'])) { //FeedMe
  1143. $e_ids = self::multiplePosts('i'); //item IDs
  1144. self::streamContentsItems($e_ids, $order);
  1145. }
  1146. }
  1147. break;
  1148. case 'tag':
  1149. if (isset($pathInfos[5]) && $pathInfos[5] === 'list') {
  1150. $output = $_GET['output'] ?? '';
  1151. if ($output !== 'json') self::notImplemented();
  1152. self::tagList();
  1153. }
  1154. break;
  1155. case 'subscription':
  1156. if (isset($pathInfos[5])) {
  1157. switch ($pathInfos[5]) {
  1158. case 'export':
  1159. self::subscriptionExport();
  1160. // Always exits
  1161. case 'import':
  1162. if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' && self::$ORIGINAL_INPUT != '') {
  1163. self::subscriptionImport(self::$ORIGINAL_INPUT);
  1164. }
  1165. break;
  1166. case 'list':
  1167. $output = $_GET['output'] ?? '';
  1168. if ($output !== 'json') self::notImplemented();
  1169. self::subscriptionList();
  1170. // Always exits
  1171. case 'edit':
  1172. if (isset($_REQUEST['s'], $_REQUEST['ac'])) {
  1173. // StreamId to operate on. The parameter may be repeated to edit multiple subscriptions at once
  1174. $streamNames = empty($_POST['s']) && is_string($_GET['s'] ?? null) ? [$_GET['s']] : self::multiplePosts('s');
  1175. /* Title to use for the subscription. For the `subscribe` action,
  1176. * if not specified then the feed’s current title will be used. Can
  1177. * be used with the `edit` action to rename a subscription */
  1178. $titles = empty($_POST['t']) && is_string($_GET['t'] ?? null) ? [$_GET['t']] : self::multiplePosts('t');
  1179. // Action to perform on the given StreamId. Possible values are `subscribe`, `unsubscribe` and `edit`
  1180. $action = is_string($_REQUEST['ac'] ?? null) ? $_REQUEST['ac'] : '';
  1181. // StreamId to add the subscription to (generally a user label)
  1182. // (in FreshRSS, we do not support repeated values since a feed can only be in one category)
  1183. $add = is_string($_REQUEST['a'] ?? null) ? $_REQUEST['a'] : '';
  1184. // StreamId to remove the subscription from (generally a user label) (in FreshRSS, we do not support repeated values)
  1185. $remove = is_string($_REQUEST['r'] ?? null) ? $_REQUEST['r'] : '';
  1186. self::subscriptionEdit($streamNames, $titles, $action, $add, $remove);
  1187. }
  1188. break;
  1189. case 'quickadd': //https://github.com/theoldreader/api
  1190. if (is_string($_REQUEST['quickadd'] ?? null)) {
  1191. self::quickadd($_REQUEST['quickadd']);
  1192. }
  1193. break;
  1194. }
  1195. }
  1196. break;
  1197. case 'unread-count':
  1198. $output = $_GET['output'] ?? '';
  1199. if ($output !== 'json') self::notImplemented();
  1200. self::unreadCount();
  1201. // Always exits
  1202. case 'edit-tag': // https://web.archive.org/web/20200616071132/https://blog.martindoms.com/2010/01/20/using-the-google-reader-api-part-3
  1203. $token = is_string($_POST['T'] ?? null) ? trim($_POST['T']) : '';
  1204. self::checkToken(FreshRSS_Context::userConf(), $token);
  1205. // Add (Can be repeated to add multiple tags at once): user/-/state/com.google/read user/-/state/com.google/starred
  1206. $as = self::multiplePosts('a');
  1207. // Remove (Can be repeated to remove multiple tags at once): user/-/state/com.google/read user/-/state/com.google/starred
  1208. $rs = self::multiplePosts('r');
  1209. $e_ids = self::multiplePosts('i'); //item IDs
  1210. self::editTag($e_ids, $as, $rs);
  1211. // Always exits
  1212. case 'rename-tag': //https://github.com/theoldreader/api
  1213. $token = is_string($_POST['T'] ?? null) ? trim($_POST['T']) : '';
  1214. self::checkToken(FreshRSS_Context::userConf(), $token);
  1215. $s = is_string($_POST['s'] ?? null) ? trim($_POST['s']) : ''; //user/-/label/Folder
  1216. $dest = is_string($_POST['dest'] ?? null) ? trim($_POST['dest']) : ''; //user/-/label/NewFolder
  1217. self::renameTag($s, $dest);
  1218. // Always exits
  1219. case 'disable-tag': //https://github.com/theoldreader/api
  1220. $token = is_string($_POST['T'] ?? null) ? trim($_POST['T']) : '';
  1221. self::checkToken(FreshRSS_Context::userConf(), $token);
  1222. $s_s = self::multiplePosts('s');
  1223. foreach ($s_s as $s) {
  1224. self::disableTag($s); //user/-/label/Folder
  1225. }
  1226. // Always exits
  1227. case 'mark-all-as-read':
  1228. $token = is_string($_POST['T'] ?? null) ? trim($_POST['T']) : '';
  1229. self::checkToken(FreshRSS_Context::userConf(), $token);
  1230. $streamId = is_string($_POST['s'] ?? null) ? trim($_POST['s']) : '';
  1231. $ts = is_string($_POST['ts'] ?? null) ? trim($_POST['ts']) : '0'; //Older than timestamp in nanoseconds
  1232. if (!ctype_digit($ts)) {
  1233. self::badRequest();
  1234. }
  1235. self::markAllAsRead($streamId, $ts);
  1236. // Always exits
  1237. case 'token':
  1238. self::token(FreshRSS_Context::userConf());
  1239. // Always exits
  1240. case 'user-info':
  1241. self::userInfo();
  1242. // Always exits
  1243. }
  1244. }
  1245. self::badRequest();
  1246. }
  1247. }
  1248. GReaderAPI::parse();