greader.php 40 KB

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