greader.php 41 KB

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