4
0

greader.php 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  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. $salt = FreshRSS_Context::systemConf()->salt;
  305. $faviconsUrl = Minz_Url::display('/f.php?', '', true);
  306. $faviconsUrl = str_replace('/api/greader.php/reader/api/0/subscription', '', $faviconsUrl); //Security if base_url is not set properly
  307. $subscriptions = [];
  308. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  309. foreach ($categoryDAO->listCategories(prePopulateFeeds: true, details: true) as $cat) {
  310. foreach ($cat->feeds() as $feed) {
  311. $subscriptions[] = [
  312. 'id' => 'feed/' . $feed->id(),
  313. 'title' => escapeToUnicodeAlternative($feed->name(), true),
  314. 'categories' => [
  315. [
  316. 'id' => 'user/-/label/' . htmlspecialchars_decode($cat->name(), ENT_QUOTES),
  317. 'label' => htmlspecialchars_decode($cat->name(), ENT_QUOTES),
  318. ],
  319. ],
  320. //'sortid' => $feed->name(),
  321. //'firstitemmsec' => 0,
  322. 'url' => htmlspecialchars_decode($feed->url(), ENT_QUOTES),
  323. 'htmlUrl' => htmlspecialchars_decode($feed->website(), ENT_QUOTES),
  324. 'iconUrl' => $faviconsUrl . hash('crc32b', $salt . $feed->url()),
  325. ];
  326. }
  327. }
  328. echo json_encode(['subscriptions' => $subscriptions], JSON_OPTIONS), "\n";
  329. exit();
  330. }
  331. /**
  332. * @param list<string> $streamNames StreamId(s) to operate on. The parameter may be repeated to edit multiple subscriptions at once
  333. * @param list<string> $titles Title(s) to use for the subscription(s). Each title is associated with the corresponding streamName
  334. * @param string $action 'subscribe'|'unsubscribe'|'edit'
  335. * @param string $add StreamId to add the subscription(s) to (generally a category)
  336. * @param string $remove StreamId to remove the subscription(s) from (generally a category)
  337. */
  338. private static function subscriptionEdit(array $streamNames, array $titles, string $action, string $add = '', string $remove = ''): never {
  339. // https://github.com/mihaip/google-reader-api/blob/master/wiki/ApiSubscriptionEdit.wiki
  340. if (count($streamNames) < 1) {
  341. self::badRequest();
  342. }
  343. switch ($action) {
  344. case 'subscribe':
  345. case 'unsubscribe':
  346. case 'edit':
  347. break;
  348. default:
  349. self::badRequest();
  350. }
  351. $addCatId = 0;
  352. if (str_starts_with($add, 'user/')) { // user/-/label/Example ; user/username/label/Example
  353. if (str_starts_with($add, 'user/-/label/')) {
  354. $c_name = substr($add, 13);
  355. } else {
  356. $prefix = 'user/' . Minz_User::name() . '/label/';
  357. if (str_starts_with($add, $prefix)) {
  358. $c_name = substr($add, strlen($prefix));
  359. } else {
  360. $c_name = '';
  361. }
  362. }
  363. $c_name = htmlspecialchars($c_name, ENT_COMPAT, 'UTF-8');
  364. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  365. $cat = $categoryDAO->searchByName($c_name);
  366. $addCatId = $cat === null ? 0 : $cat->id();
  367. if ($addCatId === 0) {
  368. $addCatId = $categoryDAO->addCategory(['name' => $c_name]) ?: FreshRSS_CategoryDAO::DEFAULTCATEGORYID;
  369. }
  370. } elseif (str_starts_with($remove, 'user/-/label/')) {
  371. $addCatId = FreshRSS_CategoryDAO::DEFAULTCATEGORYID;
  372. }
  373. $feedDAO = FreshRSS_Factory::createFeedDao();
  374. for ($i = count($streamNames) - 1; $i >= 0; $i--) {
  375. $streamUrl = $streamNames[$i]; //feed/http://example.net/sample.xml ; feed/338
  376. if (str_starts_with($streamUrl, 'feed/')) {
  377. $streamUrl = '' . preg_replace('%^(feed/)+%', '', $streamUrl);
  378. $feedId = 0;
  379. if (is_numeric($streamUrl)) {
  380. if ($action === 'subscribe') {
  381. continue;
  382. }
  383. $feedId = (int)$streamUrl;
  384. } else {
  385. $streamUrl = htmlspecialchars($streamUrl, ENT_COMPAT, 'UTF-8');
  386. $feed = $feedDAO->searchByUrl($streamUrl);
  387. $feedId = $feed == null ? -1 : $feed->id();
  388. }
  389. $title = $titles[$i] ?? '';
  390. $title = htmlspecialchars($title, ENT_COMPAT, 'UTF-8');
  391. switch ($action) {
  392. case 'subscribe':
  393. if ($feedId <= 0) {
  394. $http_auth = '';
  395. try {
  396. FreshRSS_feed_Controller::addFeed($streamUrl, $title, $addCatId, '', $http_auth);
  397. continue 2;
  398. } catch (Exception $e) {
  399. Minz_Log::error('subscriptionEdit error subscribe: ' . $e->getMessage(), API_LOG);
  400. }
  401. }
  402. self::badRequest();
  403. // Always exits
  404. case 'unsubscribe':
  405. if (!($feedId > 0 && FreshRSS_feed_Controller::deleteFeed($feedId))) {
  406. self::badRequest();
  407. }
  408. break;
  409. case 'edit':
  410. if ($feedId > 0) {
  411. if ($addCatId > 0) {
  412. FreshRSS_feed_Controller::moveFeed($feedId, $addCatId);
  413. }
  414. if ($title != '') {
  415. FreshRSS_feed_Controller::renameFeed($feedId, $title);
  416. }
  417. } else {
  418. self::badRequest();
  419. }
  420. break;
  421. }
  422. }
  423. }
  424. exit('OK');
  425. }
  426. private static function quickadd(string $url): never {
  427. try {
  428. $url = htmlspecialchars($url, ENT_COMPAT, 'UTF-8');
  429. if (str_starts_with($url, 'feed/')) {
  430. $url = substr($url, 5);
  431. }
  432. $feed = FreshRSS_feed_Controller::addFeed($url);
  433. exit(json_encode([
  434. 'numResults' => 1,
  435. 'query' => $feed->url(),
  436. 'streamId' => 'feed/' . $feed->id(),
  437. 'streamName' => $feed->name(),
  438. ], JSON_OPTIONS));
  439. } catch (Exception $e) {
  440. Minz_Log::error('quickadd error: ' . $e->getMessage(), API_LOG);
  441. die(json_encode([
  442. 'numResults' => 0,
  443. 'error' => $e->getMessage(),
  444. ], JSON_OPTIONS));
  445. }
  446. }
  447. private static function unreadCount(): never {
  448. // https://web.archive.org/web/20210126115837/https://blog.martindoms.com/2009/10/16/using-the-google-reader-api-part-2#unread-count
  449. header('Content-Type: application/json; charset=UTF-8');
  450. $totalUnreads = 0;
  451. $totalLastUpdate = 0;
  452. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  453. $feedDAO = FreshRSS_Factory::createFeedDao();
  454. $feedsNewestItemUsec = $feedDAO->listFeedsNewestItemUsec();
  455. $unreadcounts = [];
  456. foreach ($categoryDAO->listCategories(prePopulateFeeds: true, details: true) as $cat) {
  457. $catLastUpdate = 0;
  458. foreach ($cat->feeds() as $feed) {
  459. $lastUpdate = $feedsNewestItemUsec['f_' . $feed->id()] ?? 0;
  460. $unreadcounts[] = [
  461. 'id' => 'feed/' . $feed->id(),
  462. 'count' => $feed->nbNotRead(),
  463. 'newestItemTimestampUsec' => '' . $lastUpdate,
  464. ];
  465. if ($catLastUpdate < $lastUpdate) {
  466. $catLastUpdate = $lastUpdate;
  467. }
  468. }
  469. $unreadcounts[] = [
  470. 'id' => 'user/-/label/' . htmlspecialchars_decode($cat->name(), ENT_QUOTES),
  471. 'count' => $cat->nbNotRead(),
  472. 'newestItemTimestampUsec' => '' . $catLastUpdate,
  473. ];
  474. $totalUnreads += $cat->nbNotRead();
  475. if ($totalLastUpdate < $catLastUpdate) {
  476. $totalLastUpdate = $catLastUpdate;
  477. }
  478. }
  479. $tagDAO = FreshRSS_Factory::createTagDao();
  480. $tagsNewestItemUsec = $tagDAO->listTagsNewestItemUsec();
  481. foreach ($tagDAO->listTags(precounts: true) as $label) {
  482. $lastUpdate = $tagsNewestItemUsec['t_' . $label->id()] ?? 0;
  483. $unreadcounts[] = [
  484. 'id' => 'user/-/label/' . htmlspecialchars_decode($label->name(), ENT_QUOTES),
  485. 'count' => $label->nbUnread(),
  486. 'newestItemTimestampUsec' => '' . $lastUpdate,
  487. ];
  488. }
  489. $unreadcounts[] = [
  490. 'id' => 'user/-/state/com.google/reading-list',
  491. 'count' => $totalUnreads,
  492. 'newestItemTimestampUsec' => '' . $totalLastUpdate,
  493. ];
  494. echo json_encode([
  495. 'max' => $totalUnreads,
  496. 'unreadcounts' => $unreadcounts,
  497. ], JSON_OPTIONS), "\n";
  498. exit();
  499. }
  500. /**
  501. * @param list<FreshRSS_Entry> $entries
  502. * @return list<array<string,mixed>>
  503. */
  504. private static function entriesToArray(array $entries): array {
  505. if (empty($entries)) {
  506. return [];
  507. }
  508. $catDAO = FreshRSS_Factory::createCategoryDao();
  509. $categories = $catDAO->listCategories(prePopulateFeeds: true);
  510. $tagDAO = FreshRSS_Factory::createTagDao();
  511. $entryIdsTagNames = $tagDAO->getEntryIdsTagNames($entries);
  512. $items = [];
  513. foreach ($entries as $item) {
  514. /** @var FreshRSS_Entry|null $entry */
  515. $entry = Minz_ExtensionManager::callHook('entry_before_display', $item);
  516. if ($entry === null) {
  517. continue;
  518. }
  519. $feed = FreshRSS_Category::findFeed($categories, $entry->feedId());
  520. if ($feed === null) {
  521. continue;
  522. }
  523. $entry->_feed($feed);
  524. $items[] = $entry->toGReader('compat', $entryIdsTagNames['e_' . $entry->id()] ?? []);
  525. }
  526. return $items;
  527. }
  528. /**
  529. * @param 'A'|'c'|'f'|'s' $type
  530. * @return array{'A'|'c'|'f'|'s'|'t',int,int,FreshRSS_BooleanSearch}
  531. */
  532. private static function streamContentsFilters(string $type, int|string $streamId,
  533. string $filter_target, string $exclude_target, int $start_time, int $stop_time): array {
  534. switch ($type) {
  535. case 'f': //feed
  536. if ($streamId != '' && is_string($streamId) && !is_numeric($streamId)) {
  537. $feedDAO = FreshRSS_Factory::createFeedDao();
  538. $streamId = htmlspecialchars($streamId, ENT_COMPAT, 'UTF-8');
  539. $feed = $feedDAO->searchByUrl($streamId);
  540. $streamId = $feed === null ? -1 : $feed->id();
  541. }
  542. break;
  543. case 'c': //category or label
  544. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  545. $streamId = htmlspecialchars((string)$streamId, ENT_COMPAT, 'UTF-8');
  546. $cat = $categoryDAO->searchByName($streamId);
  547. if ($cat !== null) {
  548. $streamId = $cat->id();
  549. } else {
  550. $tagDAO = FreshRSS_Factory::createTagDao();
  551. $tag = $tagDAO->searchByName($streamId);
  552. if ($tag !== null) {
  553. $type = 't';
  554. $streamId = $tag->id();
  555. } else {
  556. $streamId = -1;
  557. }
  558. }
  559. break;
  560. }
  561. $streamId = (int)$streamId;
  562. $state = match ($filter_target) {
  563. 'user/-/state/com.google/read' => FreshRSS_Entry::STATE_READ,
  564. 'user/-/state/com.google/unread' => FreshRSS_Entry::STATE_NOT_READ,
  565. 'user/-/state/com.google/starred' => FreshRSS_Entry::STATE_FAVORITE,
  566. default => FreshRSS_Entry::STATE_ALL,
  567. };
  568. switch ($exclude_target) {
  569. case 'user/-/state/com.google/read':
  570. $state &= FreshRSS_Entry::STATE_NOT_READ;
  571. break;
  572. case 'user/-/state/com.google/unread':
  573. $state &= FreshRSS_Entry::STATE_READ;
  574. break;
  575. case 'user/-/state/com.google/starred':
  576. $state &= FreshRSS_Entry::STATE_NOT_FAVORITE;
  577. break;
  578. }
  579. $searches = new FreshRSS_BooleanSearch('');
  580. if ($start_time !== 0) {
  581. $search = new FreshRSS_Search('');
  582. $search->setMinDate($start_time);
  583. $searches->add($search);
  584. }
  585. if ($stop_time !== 0) {
  586. $search = new FreshRSS_Search('');
  587. $search->setMaxDate($stop_time);
  588. $searches->add($search);
  589. }
  590. return [$type, $streamId, $state, $searches];
  591. }
  592. /**
  593. * @param numeric-string $continuation
  594. */
  595. private static function streamContents(string $path, string $include_target, int $start_time, int $stop_time, int $count,
  596. string $order, string $filter_target, string $exclude_target, string $continuation): never {
  597. // https://code.google.com/archive/p/pyrfeed/wikis/GoogleReaderAPI.wiki
  598. // https://web.archive.org/web/20210126115837/https://blog.martindoms.com/2009/10/16/using-the-google-reader-api-part-2#feed
  599. header('Content-Type: application/json; charset=UTF-8');
  600. $type = match ($path) {
  601. 'starred' => 's',
  602. 'feed' => 'f',
  603. 'label' => 'c',
  604. 'reading-list' => 'A',
  605. default => 'A',
  606. };
  607. [$type, $include_target, $state, $searches] =
  608. self::streamContentsFilters($type, $include_target, $filter_target, $exclude_target, $start_time, $stop_time);
  609. if ($continuation !== '0') {
  610. $count++; //Shift by one element
  611. }
  612. $entryDAO = FreshRSS_Factory::createEntryDao();
  613. $entries = $entryDAO->listWhere($type, $include_target, $state, $searches,
  614. order: $order === 'o' ? 'ASC' : 'DESC',
  615. continuation_id: $continuation,
  616. limit: $count);
  617. $entries = array_values(iterator_to_array($entries)); //TODO: Improve
  618. $items = self::entriesToArray($entries);
  619. if ($continuation !== '0') {
  620. array_shift($items); //Discard first element that was already sent in the previous response
  621. $count--;
  622. }
  623. $response = [
  624. 'id' => 'user/-/state/com.google/reading-list',
  625. 'updated' => time(),
  626. 'items' => $items,
  627. ];
  628. if (count($entries) >= $count) {
  629. $entry = end($entries);
  630. if ($entry != false) {
  631. $response['continuation'] = '' . $entry->id();
  632. }
  633. }
  634. unset($entries, $entryDAO, $items);
  635. gc_collect_cycles();
  636. echoJson($response, 2); // $optimisationDepth=2 as we are interested in being memory efficient for {"items":[...]}
  637. exit();
  638. }
  639. /**
  640. * @param numeric-string $continuation
  641. */
  642. private static function streamContentsItemsIds(string $streamId, int $start_time, int $stop_time, int $count,
  643. string $order, string $filter_target, string $exclude_target, string $continuation): never {
  644. // https://github.com/mihaip/google-reader-api/blob/master/wiki/ApiStreamItemsIds.wiki
  645. // https://code.google.com/archive/p/pyrfeed/wikis/GoogleReaderAPI.wiki
  646. // https://web.archive.org/web/20210126115837/https://blog.martindoms.com/2009/10/16/using-the-google-reader-api-part-2#feed
  647. $type = 'A';
  648. if ($streamId === 'user/-/state/com.google/reading-list') {
  649. $type = 'A';
  650. } elseif ($streamId === 'user/-/state/com.google/starred') {
  651. $type = 's';
  652. } elseif (str_starts_with($streamId, 'feed/')) {
  653. $type = 'f';
  654. $streamId = substr($streamId, 5);
  655. } elseif (str_starts_with($streamId, 'user/-/label/')) {
  656. $type = 'c';
  657. $streamId = substr($streamId, 13);
  658. }
  659. [$type, $id, $state, $searches] = self::streamContentsFilters($type, $streamId, $filter_target, $exclude_target, $start_time, $stop_time);
  660. if ($continuation !== '0') {
  661. $count++; //Shift by one element
  662. }
  663. $entryDAO = FreshRSS_Factory::createEntryDao();
  664. $ids = $entryDAO->listIdsWhere($type, $id, $state, $searches,
  665. order: $order === 'o' ? 'ASC' : 'DESC',
  666. continuation_id: $continuation,
  667. limit: $count);
  668. if ($ids === null) {
  669. self::internalServerError();
  670. }
  671. if ($continuation !== '0') {
  672. array_shift($ids); //Discard first element that was already sent in the previous response
  673. $count--;
  674. }
  675. if (empty($ids) && isset($_GET['client']) && $_GET['client'] === 'newsplus') {
  676. $ids = [ 0 ]; //For News+ bug https://github.com/noinnion/newsplus/issues/84#issuecomment-57834632
  677. }
  678. $itemRefs = [];
  679. foreach ($ids as $entryId) {
  680. $itemRefs[] = [
  681. 'id' => '' . $entryId, //64-bit decimal
  682. ];
  683. }
  684. $response = [
  685. 'itemRefs' => $itemRefs,
  686. ];
  687. if (count($ids) >= $count) {
  688. $entryId = end($ids);
  689. if ($entryId != false) {
  690. $response['continuation'] = '' . $entryId;
  691. }
  692. }
  693. echo json_encode($response, JSON_OPTIONS), "\n";
  694. exit();
  695. }
  696. /**
  697. * @param list<string> $e_ids
  698. */
  699. private static function streamContentsItems(array $e_ids, string $order): never {
  700. header('Content-Type: application/json; charset=UTF-8');
  701. foreach ($e_ids as $i => $e_id) {
  702. // https://feedhq.readthedocs.io/en/latest/api/terminology.html#items
  703. if (!ctype_digit($e_id) || $e_id[0] === '0') {
  704. $e_ids[$i] = hex2dec(basename($e_id)); //Strip prefix 'tag:google.com,2005:reader/item/'
  705. }
  706. }
  707. /** @var list<numeric-string> $e_ids */
  708. $entryDAO = FreshRSS_Factory::createEntryDao();
  709. $entries = $entryDAO->listByIds($e_ids, order: $order === 'o' ? 'ASC' : 'DESC');
  710. $entries = array_values(iterator_to_array($entries)); //TODO: Improve
  711. $items = self::entriesToArray($entries);
  712. $response = [
  713. 'id' => 'user/-/state/com.google/reading-list',
  714. 'updated' => time(),
  715. 'items' => $items,
  716. ];
  717. unset($entries, $entryDAO, $items);
  718. gc_collect_cycles();
  719. echoJson($response, 2); // $optimisationDepth=2 as we are interested in being memory efficient for {"items":[...]}
  720. exit();
  721. }
  722. /**
  723. * @param list<string> $e_ids IDs of the items to edit
  724. * @param list<string> $as tags to add to all the listed items
  725. * @param list<string> $rs tags to remove from all the listed items
  726. */
  727. private static function editTag(array $e_ids, array $as, array $rs): never {
  728. foreach ($e_ids as $i => $e_id) {
  729. if (!ctype_digit($e_id) || $e_id[0] === '0') {
  730. $e_ids[$i] = hex2dec(basename($e_id)); //Strip prefix 'tag:google.com,2005:reader/item/'
  731. }
  732. }
  733. /** @var list<numeric-string> $e_ids */
  734. $entryDAO = FreshRSS_Factory::createEntryDao();
  735. $tagDAO = FreshRSS_Factory::createTagDao();
  736. foreach ($as as $a) {
  737. switch ($a) {
  738. case 'user/-/state/com.google/read':
  739. $entryDAO->markRead($e_ids, true);
  740. break;
  741. case 'user/-/state/com.google/starred':
  742. $entryDAO->markFavorite($e_ids, true);
  743. break;
  744. case 'user/-/state/com.google/broadcast':
  745. case 'user/-/state/com.google/like':
  746. case 'user/-/state/com.google/tracking-kept-unread':
  747. // Not supported
  748. break;
  749. default:
  750. $tagName = '';
  751. if (str_starts_with($a, 'user/-/label/')) {
  752. $tagName = substr($a, 13);
  753. } else {
  754. $user = Minz_User::name() ?? '';
  755. $prefix = 'user/' . $user . '/label/';
  756. if (str_starts_with($a, $prefix)) {
  757. $tagName = substr($a, strlen($prefix));
  758. }
  759. }
  760. if ($tagName !== '') {
  761. $tagName = htmlspecialchars($tagName, ENT_COMPAT, 'UTF-8');
  762. $tag = $tagDAO->searchByName($tagName);
  763. if ($tag === null) {
  764. $tagDAO->addTag(['name' => $tagName]);
  765. $tag = $tagDAO->searchByName($tagName);
  766. }
  767. if ($tag !== null) {
  768. foreach ($e_ids as $e_id) {
  769. $tagDAO->tagEntry($tag->id(), $e_id, true);
  770. }
  771. }
  772. }
  773. break;
  774. }
  775. }
  776. foreach ($rs as $r) {
  777. switch ($r) {
  778. case 'user/-/state/com.google/read':
  779. $entryDAO->markRead($e_ids, false);
  780. break;
  781. case 'user/-/state/com.google/starred':
  782. $entryDAO->markFavorite($e_ids, false);
  783. break;
  784. case 'user/-/state/com.google/broadcast':
  785. case 'user/-/state/com.google/like':
  786. case 'user/-/state/com.google/tracking-kept-unread':
  787. // Not supported
  788. break;
  789. default:
  790. if (str_starts_with($r, 'user/-/label/')) {
  791. $tagName = substr($r, 13);
  792. $tagName = htmlspecialchars($tagName, ENT_COMPAT, 'UTF-8');
  793. $tag = $tagDAO->searchByName($tagName);
  794. if ($tag !== null) {
  795. foreach ($e_ids as $e_id) {
  796. $tagDAO->tagEntry($tag->id(), $e_id, false);
  797. }
  798. }
  799. }
  800. break;
  801. }
  802. }
  803. exit('OK');
  804. }
  805. private static function renameTag(string $s, string $dest): never {
  806. if (str_starts_with($s, 'user/-/label/') && str_starts_with($dest, 'user/-/label/')) {
  807. $s = substr($s, 13);
  808. $s = htmlspecialchars($s, ENT_COMPAT, 'UTF-8');
  809. $dest = substr($dest, 13);
  810. $dest = htmlspecialchars($dest, ENT_COMPAT, 'UTF-8');
  811. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  812. $cat = $categoryDAO->searchByName($s);
  813. if ($cat != null) {
  814. $categoryDAO->updateCategory($cat->id(), [
  815. 'name' => $dest, 'kind' => $cat->kind(), 'attributes' => $cat->attributes()
  816. ]);
  817. exit('OK');
  818. } else {
  819. $tagDAO = FreshRSS_Factory::createTagDao();
  820. $tag = $tagDAO->searchByName($s);
  821. if ($tag != null) {
  822. $tagDAO->updateTagName($tag->id(), $dest);
  823. exit('OK');
  824. }
  825. }
  826. }
  827. self::badRequest();
  828. }
  829. private static function disableTag(string $s): never {
  830. if (str_starts_with($s, 'user/-/label/')) {
  831. $s = substr($s, 13);
  832. $s = htmlspecialchars($s, ENT_COMPAT, 'UTF-8');
  833. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  834. $cat = $categoryDAO->searchByName($s);
  835. if ($cat != null) {
  836. $feedDAO = FreshRSS_Factory::createFeedDao();
  837. $feedDAO->changeCategory($cat->id(), 0);
  838. if ($cat->id() > 1) {
  839. $categoryDAO->deleteCategory($cat->id());
  840. }
  841. exit('OK');
  842. } else {
  843. $tagDAO = FreshRSS_Factory::createTagDao();
  844. $tag = $tagDAO->searchByName($s);
  845. if ($tag != null) {
  846. $tagDAO->deleteTag($tag->id());
  847. exit('OK');
  848. }
  849. }
  850. }
  851. self::badRequest();
  852. }
  853. /**
  854. * @param numeric-string $olderThanId
  855. */
  856. private static function markAllAsRead(string $streamId, string $olderThanId): never {
  857. $entryDAO = FreshRSS_Factory::createEntryDao();
  858. if (str_starts_with($streamId, 'feed/')) {
  859. $f_id = basename($streamId);
  860. if (!is_numeric($f_id)) {
  861. self::badRequest();
  862. }
  863. $f_id = (int)$f_id;
  864. $entryDAO->markReadFeed($f_id, $olderThanId);
  865. } elseif (str_starts_with($streamId, 'user/-/label/')) {
  866. $c_name = substr($streamId, 13);
  867. $c_name = htmlspecialchars($c_name, ENT_COMPAT, 'UTF-8');
  868. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  869. $cat = $categoryDAO->searchByName($c_name);
  870. if ($cat != null) {
  871. $entryDAO->markReadCat($cat->id(), $olderThanId);
  872. } else {
  873. $tagDAO = FreshRSS_Factory::createTagDao();
  874. $tag = $tagDAO->searchByName($c_name);
  875. if ($tag != null) {
  876. $entryDAO->markReadTag($tag->id(), $olderThanId);
  877. } else {
  878. self::badRequest();
  879. }
  880. }
  881. } elseif ($streamId === 'user/-/state/com.google/reading-list') {
  882. $entryDAO->markReadEntries($olderThanId, false);
  883. } else {
  884. self::badRequest();
  885. }
  886. exit('OK');
  887. }
  888. public static function parse(): never {
  889. header('Access-Control-Allow-Headers: Authorization');
  890. header('Access-Control-Allow-Methods: GET, POST');
  891. header('Access-Control-Allow-Origin: *');
  892. header('Access-Control-Max-Age: 600');
  893. if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') {
  894. self::noContent();
  895. }
  896. $pathInfo = '';
  897. if (empty($_SERVER['PATH_INFO']) || !is_string($_SERVER['PATH_INFO'])) {
  898. if (!empty($_SERVER['ORIG_PATH_INFO']) && is_string($_SERVER['ORIG_PATH_INFO'])) {
  899. // Compatibility https://php.net/reserved.variables.server
  900. $pathInfo = $_SERVER['ORIG_PATH_INFO'];
  901. }
  902. } else {
  903. $pathInfo = $_SERVER['PATH_INFO'];
  904. }
  905. $pathInfo = rawurldecode($pathInfo);
  906. $pathInfo = '' . preg_replace('%^(/api)?(/greader\.php)?%', '', $pathInfo); //Discard common errors
  907. if ($pathInfo == '' && empty($_SERVER['QUERY_STRING'])) {
  908. exit('OK');
  909. }
  910. $pathInfos = explode('/', $pathInfo);
  911. if (count($pathInfos) < 3) {
  912. self::badRequest();
  913. }
  914. FreshRSS_Context::initSystem();
  915. //Minz_Log::debug('----------------------------------------------------------------', API_LOG);
  916. //Minz_Log::debug(self::debugInfo(), API_LOG);
  917. if (!FreshRSS_Context::hasSystemConf() || !FreshRSS_Context::systemConf()->api_enabled) {
  918. self::serviceUnavailable();
  919. } elseif ($pathInfos[1] === 'check' && $pathInfos[2] === 'compatibility') {
  920. self::checkCompatibility();
  921. }
  922. Minz_Session::init('FreshRSS', true);
  923. if ($pathInfos[1] !== 'accounts') {
  924. self::authorizationToUser();
  925. }
  926. if (FreshRSS_Context::hasUserConf()) {
  927. Minz_Translate::init(FreshRSS_Context::userConf()->language);
  928. Minz_ExtensionManager::init();
  929. Minz_ExtensionManager::enableByList(FreshRSS_Context::userConf()->extensions_enabled, 'user');
  930. } else {
  931. Minz_Translate::init();
  932. }
  933. self::$ORIGINAL_INPUT = file_get_contents('php://input', false, null, 0, 1048576) ?: '';
  934. if ($pathInfos[1] === 'accounts') {
  935. if (($pathInfos[2] === 'ClientLogin') && is_string($_REQUEST['Email'] ?? null) && is_string($_REQUEST['Passwd'] ?? null)) {
  936. self::clientLogin($_REQUEST['Email'], $_REQUEST['Passwd']);
  937. }
  938. } elseif (isset($pathInfos[3], $pathInfos[4]) && $pathInfos[1] === 'reader' && $pathInfos[2] === 'api' && $pathInfos[3] === '0') {
  939. if (Minz_User::name() === null) {
  940. self::unauthorized();
  941. }
  942. // ck=[unix timestamp]: Use the current Unix time here, helps Google with caching
  943. $timestamp = is_numeric($_GET['ck'] ?? null) ? (int)$_GET['ck'] : 0;
  944. switch ($pathInfos[4]) {
  945. case 'stream':
  946. /**
  947. * xt=[exclude target]: Used to exclude certain items from the feed.
  948. * For example, using xt=user/-/state/com.google/read will exclude items
  949. * that the current user has marked as read, or xt=feed/[feedurl] will
  950. * exclude items from a particular feed (obviously not useful in this request,
  951. * but xt appears in other listing requests).
  952. */
  953. $exclude_target = is_string($_GET['xt'] ?? null) ? $_GET['xt'] : '';
  954. $filter_target = is_string($_GET['it'] ?? null) ? $_GET['it'] : '';
  955. //n=[integer] : The maximum number of results to return.
  956. $count = is_numeric($_GET['n'] ?? null) ? (int)$_GET['n'] : 20;
  957. //r=[d|n|o] : Sort order of item results. d or n gives items in descending date order, o in ascending order.
  958. $order = is_string($_GET['r'] ?? null) ? $_GET['r'] : 'd';
  959. /**
  960. * ot=[unix timestamp] : The time from which you want to retrieve items.
  961. * Only items that have been crawled by Google Reader after this time will be returned.
  962. */
  963. $start_time = is_numeric($_GET['ot'] ?? null) ? (int)$_GET['ot'] : 0;
  964. $stop_time = is_numeric($_GET['nt'] ?? null) ? (int)$_GET['nt'] : 0;
  965. /**
  966. * Continuation token. If a StreamContents response does not represent
  967. * all items in a timestamp range, it will have a continuation attribute.
  968. * The same request can be re-issued with the value of that attribute put
  969. * in this parameter to get more items
  970. */
  971. $continuation = is_string($_GET['c'] ?? null) ? trim($_GET['c']) : '';
  972. if (!ctype_digit($continuation)) {
  973. $continuation = '0';
  974. }
  975. if (isset($pathInfos[5]) && $pathInfos[5] === 'contents') {
  976. if (!isset($pathInfos[6]) && is_string($_GET['s'] ?? null)) {
  977. // Compatibility BazQux API https://github.com/bazqux/bazqux-api#fetching-streams
  978. $streamIdInfos = explode('/', $_GET['s']);
  979. foreach ($streamIdInfos as $streamIdInfo) {
  980. $pathInfos[] = $streamIdInfo;
  981. }
  982. }
  983. if (isset($pathInfos[6], $pathInfos[7])) {
  984. if ($pathInfos[6] === 'feed') {
  985. $include_target = $pathInfos[7];
  986. if ($include_target !== '' && !is_numeric($include_target)) {
  987. $include_target = empty($_SERVER['REQUEST_URI']) || !is_string($_SERVER['REQUEST_URI']) ? '' : $_SERVER['REQUEST_URI'];
  988. if (preg_match('#/reader/api/0/stream/contents/feed/([A-Za-z0-9\'!*()%$_.~+-]+)#', $include_target, $matches) === 1) {
  989. $include_target = urldecode($matches[1]);
  990. } else {
  991. $include_target = '';
  992. }
  993. }
  994. self::streamContents($pathInfos[6], $include_target, $start_time, $stop_time,
  995. $count, $order, $filter_target, $exclude_target, $continuation);
  996. } elseif (isset($pathInfos[8], $pathInfos[9]) && $pathInfos[6] === 'user') {
  997. if ($pathInfos[8] === 'state') {
  998. if ($pathInfos[9] === 'com.google' && isset($pathInfos[10])) {
  999. if ($pathInfos[10] === 'reading-list' || $pathInfos[10] === 'starred') {
  1000. $include_target = '';
  1001. self::streamContents($pathInfos[10], $include_target, $start_time, $stop_time, $count, $order,
  1002. $filter_target, $exclude_target, $continuation);
  1003. }
  1004. }
  1005. } elseif ($pathInfos[8] === 'label') {
  1006. $include_target = empty($_SERVER['REQUEST_URI']) || !is_string($_SERVER['REQUEST_URI']) ? '' : $_SERVER['REQUEST_URI'];
  1007. if (preg_match('#/reader/api/0/stream/contents/user/[^/+]/label/([A-Za-z0-9\'!*()%$_.~+-]+)#', $include_target, $matches)) {
  1008. $include_target = urldecode($matches[1]);
  1009. } else {
  1010. $include_target = $pathInfos[9];
  1011. }
  1012. self::streamContents($pathInfos[8], $include_target, $start_time, $stop_time,
  1013. $count, $order, $filter_target, $exclude_target, $continuation);
  1014. }
  1015. }
  1016. } else { //EasyRSS, FeedMe
  1017. $include_target = '';
  1018. self::streamContents('reading-list', $include_target, $start_time, $stop_time,
  1019. $count, $order, $filter_target, $exclude_target, $continuation);
  1020. }
  1021. } elseif ($pathInfos[5] === 'items') {
  1022. if ($pathInfos[6] === 'ids' && is_string($_GET['s'] ?? null)) {
  1023. // StreamId for which to fetch the item IDs.
  1024. // TODO: support multiple streams
  1025. $streamId = $_GET['s'];
  1026. self::streamContentsItemsIds($streamId, $start_time, $stop_time, $count, $order, $filter_target, $exclude_target, $continuation);
  1027. } elseif ($pathInfos[6] === 'contents' && isset($_POST['i'])) { //FeedMe
  1028. $e_ids = self::multiplePosts('i'); //item IDs
  1029. self::streamContentsItems($e_ids, $order);
  1030. }
  1031. }
  1032. break;
  1033. case 'tag':
  1034. if (isset($pathInfos[5]) && $pathInfos[5] === 'list') {
  1035. $output = $_GET['output'] ?? '';
  1036. if ($output !== 'json') self::notImplemented();
  1037. self::tagList();
  1038. }
  1039. break;
  1040. case 'subscription':
  1041. if (isset($pathInfos[5])) {
  1042. switch ($pathInfos[5]) {
  1043. case 'export':
  1044. self::subscriptionExport();
  1045. // Always exits
  1046. case 'import':
  1047. if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' && self::$ORIGINAL_INPUT != '') {
  1048. self::subscriptionImport(self::$ORIGINAL_INPUT);
  1049. }
  1050. break;
  1051. case 'list':
  1052. $output = $_GET['output'] ?? '';
  1053. if ($output !== 'json') self::notImplemented();
  1054. self::subscriptionList();
  1055. // Always exits
  1056. case 'edit':
  1057. if (isset($_REQUEST['s'], $_REQUEST['ac'])) {
  1058. // StreamId to operate on. The parameter may be repeated to edit multiple subscriptions at once
  1059. $streamNames = empty($_POST['s']) && is_string($_GET['s'] ?? null) ? [$_GET['s']] : self::multiplePosts('s');
  1060. /* Title to use for the subscription. For the `subscribe` action,
  1061. * if not specified then the feed’s current title will be used. Can
  1062. * be used with the `edit` action to rename a subscription */
  1063. $titles = empty($_POST['t']) && is_string($_GET['t'] ?? null) ? [$_GET['t']] : self::multiplePosts('t');
  1064. // Action to perform on the given StreamId. Possible values are `subscribe`, `unsubscribe` and `edit`
  1065. $action = is_string($_REQUEST['ac'] ?? null) ? $_REQUEST['ac'] : '';
  1066. // StreamId to add the subscription to (generally a user label)
  1067. // (in FreshRSS, we do not support repeated values since a feed can only be in one category)
  1068. $add = is_string($_REQUEST['a'] ?? null) ? $_REQUEST['a'] : '';
  1069. // StreamId to remove the subscription from (generally a user label) (in FreshRSS, we do not support repeated values)
  1070. $remove = is_string($_REQUEST['r'] ?? null) ? $_REQUEST['r'] : '';
  1071. self::subscriptionEdit($streamNames, $titles, $action, $add, $remove);
  1072. }
  1073. break;
  1074. case 'quickadd': //https://github.com/theoldreader/api
  1075. if (is_string($_REQUEST['quickadd'] ?? null)) {
  1076. self::quickadd($_REQUEST['quickadd']);
  1077. }
  1078. break;
  1079. }
  1080. }
  1081. break;
  1082. case 'unread-count':
  1083. $output = $_GET['output'] ?? '';
  1084. if ($output !== 'json') self::notImplemented();
  1085. self::unreadCount();
  1086. // Always exits
  1087. case 'edit-tag': // https://web.archive.org/web/20200616071132/https://blog.martindoms.com/2010/01/20/using-the-google-reader-api-part-3
  1088. $token = is_string($_POST['T'] ?? null) ? trim($_POST['T']) : '';
  1089. self::checkToken(FreshRSS_Context::userConf(), $token);
  1090. // Add (Can be repeated to add multiple tags at once): user/-/state/com.google/read user/-/state/com.google/starred
  1091. $as = self::multiplePosts('a');
  1092. // Remove (Can be repeated to remove multiple tags at once): user/-/state/com.google/read user/-/state/com.google/starred
  1093. $rs = self::multiplePosts('r');
  1094. $e_ids = self::multiplePosts('i'); //item IDs
  1095. self::editTag($e_ids, $as, $rs);
  1096. // Always exits
  1097. case 'rename-tag': //https://github.com/theoldreader/api
  1098. $token = is_string($_POST['T'] ?? null) ? trim($_POST['T']) : '';
  1099. self::checkToken(FreshRSS_Context::userConf(), $token);
  1100. $s = is_string($_POST['s'] ?? null) ? trim($_POST['s']) : ''; //user/-/label/Folder
  1101. $dest = is_string($_POST['dest'] ?? null) ? trim($_POST['dest']) : ''; //user/-/label/NewFolder
  1102. self::renameTag($s, $dest);
  1103. // Always exits
  1104. case 'disable-tag': //https://github.com/theoldreader/api
  1105. $token = is_string($_POST['T'] ?? null) ? trim($_POST['T']) : '';
  1106. self::checkToken(FreshRSS_Context::userConf(), $token);
  1107. $s_s = self::multiplePosts('s');
  1108. foreach ($s_s as $s) {
  1109. self::disableTag($s); //user/-/label/Folder
  1110. }
  1111. // Always exits
  1112. case 'mark-all-as-read':
  1113. $token = is_string($_POST['T'] ?? null) ? trim($_POST['T']) : '';
  1114. self::checkToken(FreshRSS_Context::userConf(), $token);
  1115. $streamId = is_string($_POST['s'] ?? null) ? trim($_POST['s']) : '';
  1116. $ts = is_string($_POST['ts'] ?? null) ? trim($_POST['ts']) : '0'; //Older than timestamp in nanoseconds
  1117. if (!ctype_digit($ts)) {
  1118. self::badRequest();
  1119. }
  1120. self::markAllAsRead($streamId, $ts);
  1121. // Always exits
  1122. case 'token':
  1123. self::token(FreshRSS_Context::userConf());
  1124. // Always exits
  1125. case 'user-info':
  1126. self::userInfo();
  1127. // Always exits
  1128. }
  1129. }
  1130. self::badRequest();
  1131. }
  1132. }
  1133. GReaderAPI::parse();