4
0

greader.php 44 KB

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