greader.php 48 KB

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