greader.php 41 KB

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