greader.php 40 KB

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