greader.php 42 KB

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