greader.php 43 KB

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