greader.php 41 KB

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