greader.php 41 KB

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