greader.php 48 KB

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