greader.php 44 KB

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