4
0

greader.php 48 KB

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