greader.php 44 KB

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