greader.php 40 KB

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