4
0

greader.php 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360
  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. $type = 'A';
  721. if ($streamId === 'user/-/state/com.google/reading-list') {
  722. $type = 'A';
  723. $streamId = '';
  724. } elseif ($streamId === 'user/-/state/com.google/starred') {
  725. $type = 's';
  726. $streamId = '';
  727. } elseif ($streamId === 'user/-/state/org.freshrss/main') {
  728. $type = 'a';
  729. $streamId = '';
  730. } elseif ($streamId === 'user/-/state/org.freshrss/important') {
  731. $type = 'i';
  732. $streamId = '';
  733. } elseif ($streamId === 'user/-/state/com.google/read') {
  734. $filter_target = $streamId;
  735. $type = 'A';
  736. $streamId = '';
  737. } elseif ($streamId === 'user/-/state/com.google/unread') {
  738. $filter_target = $streamId;
  739. $type = 'A';
  740. $streamId = '';
  741. } elseif (str_starts_with($streamId, 'feed/')) {
  742. $type = 'f';
  743. $streamId = substr($streamId, 5);
  744. } elseif (str_starts_with($streamId, 'user/-/label/')) {
  745. $type = 'c';
  746. $streamId = substr($streamId, 13);
  747. }
  748. [$type, $id, $state, $searches] = self::streamContentsFilters($type, $streamId, $filter_target, $exclude_target, $start_time, $stop_time);
  749. if ($continuation !== '0') {
  750. $count++; //Shift by one element
  751. }
  752. $entryDAO = FreshRSS_Factory::createEntryDao();
  753. $ids = $entryDAO->listIdsWhere($type, $id, $state, $searches,
  754. order: $order === 'o' ? 'ASC' : 'DESC',
  755. continuation_id: $continuation,
  756. limit: $count);
  757. if ($ids === null) {
  758. self::internalServerError();
  759. }
  760. if ($continuation !== '0') {
  761. array_shift($ids); //Discard first element that was already sent in the previous response
  762. $count--;
  763. }
  764. if (empty($ids) && isset($_GET['client']) && $_GET['client'] === 'newsplus') {
  765. $ids = [ 0 ]; //For News+ bug https://github.com/noinnion/newsplus/issues/84#issuecomment-57834632
  766. }
  767. $itemRefs = [];
  768. foreach ($ids as $entryId) {
  769. $itemRefs[] = [
  770. 'id' => '' . $entryId, //64-bit decimal
  771. ];
  772. }
  773. $response = [
  774. 'itemRefs' => $itemRefs,
  775. ];
  776. if (count($ids) >= $count) {
  777. $entryId = end($ids);
  778. if ($entryId != false) {
  779. $response['continuation'] = '' . $entryId;
  780. }
  781. }
  782. echo json_encode($response, JSON_OPTIONS), "\n";
  783. exit();
  784. }
  785. /**
  786. * @param list<string> $e_ids
  787. */
  788. private static function streamContentsItems(array $e_ids, string $order): never {
  789. header('Content-Type: application/json; charset=UTF-8');
  790. foreach ($e_ids as $i => $e_id) {
  791. // https://feedhq.readthedocs.io/en/latest/api/terminology.html#items
  792. if (!ctype_digit($e_id) || $e_id[0] === '0') {
  793. $e_ids[$i] = hex2dec(basename($e_id)); //Strip prefix 'tag:google.com,2005:reader/item/'
  794. }
  795. }
  796. /** @var list<numeric-string> $e_ids */
  797. $entryDAO = FreshRSS_Factory::createEntryDao();
  798. $entries = $entryDAO->listByIds($e_ids, order: $order === 'o' ? 'ASC' : 'DESC');
  799. $items = self::entriesToArray($entries, $e_ids);
  800. $time = time();
  801. $nbItems = 0;
  802. // Note: This section must be streamed to avoid memory issues with large responses
  803. echo <<<TXT
  804. {
  805. "id": "user/-/state/com.google/reading-list",
  806. "updated": $time,
  807. "items": [
  808. TXT;
  809. foreach ($items as $item) {
  810. if (!is_array($item) || empty($item)) {
  811. continue;
  812. }
  813. if ($nbItems > 0) {
  814. echo ",\n";
  815. }
  816. unset($item['frss:id']);
  817. echo json_encode($item, JSON_OPTIONS);
  818. $nbItems++;
  819. }
  820. echo <<<'TXT'
  821. ]
  822. }
  823. TXT;
  824. exit();
  825. }
  826. /**
  827. * @param list<string> $e_ids IDs of the items to edit
  828. * @param list<string> $as tags to add to all the listed items
  829. * @param list<string> $rs tags to remove from all the listed items
  830. */
  831. private static function editTag(array $e_ids, array $as, array $rs): never {
  832. foreach ($e_ids as $i => $e_id) {
  833. if (!ctype_digit($e_id) || $e_id[0] === '0') {
  834. $e_ids[$i] = hex2dec(basename($e_id)); //Strip prefix 'tag:google.com,2005:reader/item/'
  835. }
  836. }
  837. /** @var list<numeric-string> $e_ids */
  838. $entryDAO = FreshRSS_Factory::createEntryDao();
  839. $tagDAO = FreshRSS_Factory::createTagDao();
  840. foreach ($as as $a) {
  841. switch ($a) {
  842. case 'user/-/state/com.google/read':
  843. $entryDAO->markRead($e_ids, true);
  844. break;
  845. case 'user/-/state/com.google/starred':
  846. $entryDAO->markFavorite($e_ids, true);
  847. break;
  848. case 'user/-/state/com.google/broadcast':
  849. case 'user/-/state/com.google/like':
  850. case 'user/-/state/com.google/tracking-kept-unread':
  851. // Not supported
  852. break;
  853. default:
  854. $tagName = '';
  855. if (str_starts_with($a, 'user/-/label/')) {
  856. $tagName = substr($a, 13);
  857. } else {
  858. $user = Minz_User::name() ?? '';
  859. $prefix = 'user/' . $user . '/label/';
  860. if (str_starts_with($a, $prefix)) {
  861. $tagName = substr($a, strlen($prefix));
  862. }
  863. }
  864. if ($tagName !== '') {
  865. $tagName = htmlspecialchars($tagName, ENT_COMPAT, 'UTF-8');
  866. $tag = $tagDAO->searchByName($tagName);
  867. if ($tag === null) {
  868. $tagDAO->addTag(['name' => $tagName]);
  869. $tag = $tagDAO->searchByName($tagName);
  870. }
  871. if ($tag !== null) {
  872. foreach ($e_ids as $e_id) {
  873. $tagDAO->tagEntry($tag->id(), $e_id, true);
  874. }
  875. }
  876. }
  877. break;
  878. }
  879. }
  880. foreach ($rs as $r) {
  881. switch ($r) {
  882. case 'user/-/state/com.google/read':
  883. $entryDAO->markRead($e_ids, false);
  884. break;
  885. case 'user/-/state/com.google/starred':
  886. $entryDAO->markFavorite($e_ids, false);
  887. break;
  888. case 'user/-/state/com.google/broadcast':
  889. case 'user/-/state/com.google/like':
  890. case 'user/-/state/com.google/tracking-kept-unread':
  891. // Not supported
  892. break;
  893. default:
  894. if (str_starts_with($r, 'user/-/label/')) {
  895. $tagName = substr($r, 13);
  896. $tagName = htmlspecialchars($tagName, ENT_COMPAT, 'UTF-8');
  897. $tag = $tagDAO->searchByName($tagName);
  898. if ($tag !== null) {
  899. foreach ($e_ids as $e_id) {
  900. $tagDAO->tagEntry($tag->id(), $e_id, false);
  901. }
  902. }
  903. }
  904. break;
  905. }
  906. }
  907. exit('OK');
  908. }
  909. private static function renameTag(string $s, string $dest): never {
  910. if (str_starts_with($s, 'user/-/label/') && str_starts_with($dest, 'user/-/label/')) {
  911. $s = substr($s, 13);
  912. $s = htmlspecialchars($s, ENT_COMPAT, 'UTF-8');
  913. $dest = substr($dest, 13);
  914. $dest = htmlspecialchars($dest, ENT_COMPAT, 'UTF-8');
  915. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  916. $cat = $categoryDAO->searchByName($s);
  917. if ($cat != null) {
  918. $categoryDAO->updateCategory($cat->id(), [
  919. 'name' => $dest, 'kind' => $cat->kind(), 'attributes' => $cat->attributes()
  920. ]);
  921. exit('OK');
  922. } else {
  923. $tagDAO = FreshRSS_Factory::createTagDao();
  924. $tag = $tagDAO->searchByName($s);
  925. if ($tag != null) {
  926. $tagDAO->updateTagName($tag->id(), $dest);
  927. exit('OK');
  928. }
  929. }
  930. }
  931. self::badRequest();
  932. }
  933. private static function disableTag(string $s): never {
  934. if (str_starts_with($s, 'user/-/label/')) {
  935. $s = substr($s, 13);
  936. $s = htmlspecialchars($s, ENT_COMPAT, 'UTF-8');
  937. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  938. $cat = $categoryDAO->searchByName($s);
  939. if ($cat != null) {
  940. $feedDAO = FreshRSS_Factory::createFeedDao();
  941. $feedDAO->changeCategory($cat->id(), 0);
  942. if ($cat->id() > FreshRSS_CategoryDAO::DEFAULTCATEGORYID) {
  943. $categoryDAO->deleteCategory($cat->id());
  944. }
  945. exit('OK');
  946. } else {
  947. $tagDAO = FreshRSS_Factory::createTagDao();
  948. $tag = $tagDAO->searchByName($s);
  949. if ($tag != null) {
  950. $tagDAO->deleteTag($tag->id());
  951. exit('OK');
  952. }
  953. }
  954. }
  955. self::badRequest();
  956. }
  957. /**
  958. * @param numeric-string $olderThanId
  959. */
  960. private static function markAllAsRead(string $streamId, string $olderThanId): never {
  961. $entryDAO = FreshRSS_Factory::createEntryDao();
  962. if (str_starts_with($streamId, 'feed/')) {
  963. $f_id = basename($streamId);
  964. if (!is_numeric($f_id)) {
  965. self::badRequest();
  966. }
  967. $f_id = (int)$f_id;
  968. $entryDAO->markReadFeed($f_id, $olderThanId);
  969. } elseif (str_starts_with($streamId, 'user/-/label/')) {
  970. $c_name = substr($streamId, 13);
  971. $c_name = htmlspecialchars($c_name, ENT_COMPAT, 'UTF-8');
  972. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  973. $cat = $categoryDAO->searchByName($c_name);
  974. if ($cat != null) {
  975. $entryDAO->markReadCat($cat->id(), $olderThanId);
  976. } else {
  977. $tagDAO = FreshRSS_Factory::createTagDao();
  978. $tag = $tagDAO->searchByName($c_name);
  979. if ($tag != null) {
  980. $entryDAO->markReadTag($tag->id(), $olderThanId);
  981. } else {
  982. self::badRequest();
  983. }
  984. }
  985. } elseif ($streamId === 'user/-/state/com.google/reading-list') {
  986. $entryDAO->markReadEntries($olderThanId, priorityMin: FreshRSS_Feed::PRIORITY_HIDDEN + 1);
  987. } elseif ($streamId === 'user/-/state/com.google/starred') {
  988. $entryDAO->markReadEntries($olderThanId, onlyFavorites: true, priorityMin: FreshRSS_Feed::PRIORITY_HIDDEN + 1);
  989. } elseif ($streamId === 'user/-/state/org.freshrss/main') {
  990. $entryDAO->markReadEntries($olderThanId, priorityMin: FreshRSS_Feed::PRIORITY_MAIN_STREAM);
  991. } elseif ($streamId === 'user/-/state/org.freshrss/important') {
  992. $entryDAO->markReadEntries($olderThanId, priorityMin: FreshRSS_Feed::PRIORITY_IMPORTANT);
  993. } elseif ($streamId === 'user/-/state/com.google/read') {
  994. $entryDAO->markReadEntries($olderThanId, state: FreshRSS_Entry::STATE_READ);
  995. } elseif ($streamId === 'user/-/state/com.google/unread') {
  996. $entryDAO->markReadEntries($olderThanId, state: FreshRSS_Entry::STATE_NOT_READ, priorityMin: FreshRSS_Feed::PRIORITY_HIDDEN + 1);
  997. } else {
  998. self::badRequest();
  999. }
  1000. exit('OK');
  1001. }
  1002. public static function parse(): never {
  1003. header('Access-Control-Allow-Headers: Authorization');
  1004. header('Access-Control-Allow-Methods: GET, POST');
  1005. header('Access-Control-Allow-Origin: *');
  1006. header('Access-Control-Max-Age: 600');
  1007. if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') {
  1008. self::noContent();
  1009. }
  1010. $pathInfo = '';
  1011. if (empty($_SERVER['PATH_INFO']) || !is_string($_SERVER['PATH_INFO'])) {
  1012. if (!empty($_SERVER['ORIG_PATH_INFO']) && is_string($_SERVER['ORIG_PATH_INFO'])) {
  1013. // Compatibility https://www.php.net/reserved.variables.server
  1014. $pathInfo = $_SERVER['ORIG_PATH_INFO'];
  1015. }
  1016. } else {
  1017. $pathInfo = $_SERVER['PATH_INFO'];
  1018. }
  1019. $pathInfo = rawurldecode($pathInfo);
  1020. $pathInfo = '' . preg_replace('%^(/api)?(/greader\.php)?%', '', $pathInfo); //Discard common errors
  1021. if ($pathInfo == '' && empty($_SERVER['QUERY_STRING'])) {
  1022. exit('OK');
  1023. }
  1024. $pathInfos = explode('/', $pathInfo);
  1025. if (count($pathInfos) < 3) {
  1026. self::badRequest();
  1027. }
  1028. FreshRSS_Context::initSystem();
  1029. //Minz_Log::debug('----------------------------------------------------------------', API_LOG);
  1030. //Minz_Log::debug(self::debugInfo(), API_LOG);
  1031. if (!FreshRSS_Context::hasSystemConf() || !FreshRSS_Context::systemConf()->api_enabled) {
  1032. self::serviceUnavailable();
  1033. } elseif ($pathInfos[1] === 'check' && $pathInfos[2] === 'compatibility') {
  1034. self::checkCompatibility();
  1035. }
  1036. Minz_Session::init('FreshRSS', true);
  1037. if ($pathInfos[1] !== 'accounts') {
  1038. self::authorizationToUser();
  1039. }
  1040. if (FreshRSS_Context::hasUserConf()) {
  1041. Minz_Translate::init(FreshRSS_Context::userConf()->language);
  1042. Minz_ExtensionManager::init();
  1043. Minz_ExtensionManager::enableByList(FreshRSS_Context::userConf()->extensions_enabled, 'user');
  1044. } else {
  1045. Minz_Translate::init();
  1046. }
  1047. self::$ORIGINAL_INPUT = file_get_contents('php://input', false, null, 0, 1048576) ?: '';
  1048. if ($pathInfos[1] === 'accounts') {
  1049. if ($pathInfos[2] === 'ClientLogin') {
  1050. $email = $_POST['Email'] ?? $_GET['Email'] ?? null;
  1051. $passwd = $_POST['Passwd'] ?? $_GET['Passwd'] ?? null;
  1052. if (is_string($email) && is_string($passwd)) {
  1053. if (isset($_GET['Email']) || isset($_GET['Passwd'])) {
  1054. $user_agent = is_string($_SERVER['HTTP_USER_AGENT'] ?? null) ? $_SERVER['HTTP_USER_AGENT'] : '';
  1055. $warning_message = 'ClientLogin using GET method is deprecated: password may appear in logs. Use POST instead. User-Agent: ' . $user_agent;
  1056. Minz_Log::warning($warning_message, API_LOG);
  1057. }
  1058. self::clientLogin($email, $passwd);
  1059. }
  1060. }
  1061. } elseif (isset($pathInfos[3], $pathInfos[4]) && $pathInfos[1] === 'reader' && $pathInfos[2] === 'api' && $pathInfos[3] === '0') {
  1062. if (Minz_User::name() === null) {
  1063. self::unauthorized();
  1064. }
  1065. // ck=[unix timestamp]: Use the current Unix time here, helps Google with caching
  1066. $timestamp = is_numeric($_GET['ck'] ?? null) ? (int)$_GET['ck'] : 0;
  1067. switch ($pathInfos[4]) {
  1068. case 'stream':
  1069. /**
  1070. * xt=[exclude target]: Used to exclude certain items from the feed.
  1071. * For example, using xt=user/-/state/com.google/read will exclude items
  1072. * that the current user has marked as read, or xt=feed/[feedurl] will
  1073. * exclude items from a particular feed (obviously not useful in this request,
  1074. * but xt appears in other listing requests).
  1075. */
  1076. $exclude_target = is_string($_GET['xt'] ?? null) ? $_GET['xt'] : '';
  1077. $filter_target = is_string($_GET['it'] ?? null) ? $_GET['it'] : '';
  1078. //n=[integer] : The maximum number of results to return.
  1079. $count = is_numeric($_GET['n'] ?? null) ? (int)$_GET['n'] : 20;
  1080. //r=[d|n|o] : Sort order of item results. d or n gives items in descending date order, o in ascending order.
  1081. $order = is_string($_GET['r'] ?? null) ? $_GET['r'] : 'd';
  1082. /**
  1083. * ot=[unix timestamp] : The time from which you want to retrieve items.
  1084. * Only items that have been crawled by Google Reader after this time will be returned.
  1085. */
  1086. $start_time = is_numeric($_GET['ot'] ?? null) ? (int)$_GET['ot'] : 0;
  1087. $stop_time = is_numeric($_GET['nt'] ?? null) ? (int)$_GET['nt'] : 0;
  1088. /**
  1089. * Continuation token. If a StreamContents response does not represent
  1090. * all items in a timestamp range, it will have a continuation attribute.
  1091. * The same request can be re-issued with the value of that attribute put
  1092. * in this parameter to get more items
  1093. */
  1094. $continuation = is_string($_GET['c'] ?? null) ? trim($_GET['c']) : '';
  1095. if (!ctype_digit($continuation)) {
  1096. $continuation = '0';
  1097. }
  1098. if (isset($pathInfos[5]) && $pathInfos[5] === 'contents') {
  1099. if (!isset($pathInfos[6]) && is_string($_GET['s'] ?? null)) {
  1100. // Compatibility BazQux API https://github.com/bazqux/bazqux-api#fetching-streams
  1101. $streamIdInfos = explode('/', $_GET['s']);
  1102. foreach ($streamIdInfos as $streamIdInfo) {
  1103. $pathInfos[] = $streamIdInfo;
  1104. }
  1105. }
  1106. if (isset($pathInfos[6], $pathInfos[7])) {
  1107. if ($pathInfos[6] === 'feed') {
  1108. $include_target = $pathInfos[7];
  1109. if ($include_target !== '' && !is_numeric($include_target)) {
  1110. $include_target = empty($_SERVER['REQUEST_URI']) || !is_string($_SERVER['REQUEST_URI']) ? '' : $_SERVER['REQUEST_URI'];
  1111. if (preg_match('#/reader/api/0/stream/contents/feed/([A-Za-z0-9\'!*()%$_.~+-]+)#', $include_target, $matches) === 1) {
  1112. $include_target = urldecode($matches[1]);
  1113. } else {
  1114. $include_target = '';
  1115. }
  1116. }
  1117. self::streamContents($pathInfos[6], $include_target, $start_time, $stop_time,
  1118. $count, $order, $filter_target, $exclude_target, $continuation);
  1119. } elseif (isset($pathInfos[8], $pathInfos[9]) && $pathInfos[6] === 'user') {
  1120. if ($pathInfos[8] === 'state') {
  1121. if (in_array($pathInfos[9], ['com.google', 'org.freshrss'], true) && isset($pathInfos[10])) {
  1122. if (in_array($pathInfos[10], ['reading-list', 'starred', 'main', 'important'], true)) {
  1123. $include_target = '';
  1124. self::streamContents($pathInfos[10], $include_target, $start_time, $stop_time, $count, $order,
  1125. $filter_target, $exclude_target, $continuation);
  1126. }
  1127. }
  1128. } elseif ($pathInfos[8] === 'label') {
  1129. $include_target = empty($_SERVER['REQUEST_URI']) || !is_string($_SERVER['REQUEST_URI']) ? '' : $_SERVER['REQUEST_URI'];
  1130. if (preg_match('#/reader/api/0/stream/contents/user/[^/+]/label/([A-Za-z0-9\'!*()%$_.~+-]+)#', $include_target, $matches)) {
  1131. $include_target = urldecode($matches[1]);
  1132. } else {
  1133. $include_target = $pathInfos[9];
  1134. }
  1135. self::streamContents($pathInfos[8], $include_target, $start_time, $stop_time,
  1136. $count, $order, $filter_target, $exclude_target, $continuation);
  1137. }
  1138. }
  1139. } else { //EasyRSS, FeedMe
  1140. $include_target = '';
  1141. self::streamContents('reading-list', $include_target, $start_time, $stop_time,
  1142. $count, $order, $filter_target, $exclude_target, $continuation);
  1143. }
  1144. } elseif ($pathInfos[5] === 'items') {
  1145. if ($pathInfos[6] === 'ids' && is_string($_GET['s'] ?? null)) {
  1146. // StreamId for which to fetch the item IDs.
  1147. // TODO: support multiple streams
  1148. $streamId = $_GET['s'];
  1149. self::streamContentsItemsIds($streamId, $start_time, $stop_time, $count, $order, $filter_target, $exclude_target, $continuation);
  1150. } elseif ($pathInfos[6] === 'contents' && isset($_POST['i'])) { //FeedMe
  1151. $e_ids = self::multiplePosts('i'); //item IDs
  1152. self::streamContentsItems($e_ids, $order);
  1153. }
  1154. }
  1155. break;
  1156. case 'tag':
  1157. if (isset($pathInfos[5]) && $pathInfos[5] === 'list') {
  1158. $output = $_GET['output'] ?? '';
  1159. if ($output !== 'json') self::notImplemented();
  1160. self::tagList();
  1161. }
  1162. break;
  1163. case 'subscription':
  1164. if (isset($pathInfos[5])) {
  1165. switch ($pathInfos[5]) {
  1166. case 'export':
  1167. self::subscriptionExport();
  1168. // Always exits
  1169. case 'import':
  1170. if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' && self::$ORIGINAL_INPUT != '') {
  1171. self::subscriptionImport(self::$ORIGINAL_INPUT);
  1172. }
  1173. break;
  1174. case 'list':
  1175. $output = $_GET['output'] ?? '';
  1176. if ($output !== 'json') self::notImplemented();
  1177. self::subscriptionList();
  1178. // Always exits
  1179. case 'edit':
  1180. if (isset($_REQUEST['s'], $_REQUEST['ac'])) {
  1181. // StreamId to operate on. The parameter may be repeated to edit multiple subscriptions at once
  1182. $streamNames = empty($_POST['s']) && is_string($_GET['s'] ?? null) ? [$_GET['s']] : self::multiplePosts('s');
  1183. /* Title to use for the subscription. For the `subscribe` action,
  1184. * if not specified then the feed’s current title will be used. Can
  1185. * be used with the `edit` action to rename a subscription */
  1186. $titles = empty($_POST['t']) && is_string($_GET['t'] ?? null) ? [$_GET['t']] : self::multiplePosts('t');
  1187. // Action to perform on the given StreamId. Possible values are `subscribe`, `unsubscribe` and `edit`
  1188. $action = is_string($_REQUEST['ac'] ?? null) ? $_REQUEST['ac'] : '';
  1189. // StreamId to add the subscription to (generally a user label)
  1190. // (in FreshRSS, we do not support repeated values since a feed can only be in one category)
  1191. $add = is_string($_REQUEST['a'] ?? null) ? $_REQUEST['a'] : '';
  1192. // StreamId to remove the subscription from (generally a user label) (in FreshRSS, we do not support repeated values)
  1193. $remove = is_string($_REQUEST['r'] ?? null) ? $_REQUEST['r'] : '';
  1194. self::subscriptionEdit($streamNames, $titles, $action, $add, $remove);
  1195. }
  1196. break;
  1197. case 'quickadd': //https://github.com/theoldreader/api
  1198. if (is_string($_REQUEST['quickadd'] ?? null)) {
  1199. self::quickadd($_REQUEST['quickadd']);
  1200. }
  1201. break;
  1202. }
  1203. }
  1204. break;
  1205. case 'unread-count':
  1206. $output = $_GET['output'] ?? '';
  1207. if ($output !== 'json') self::notImplemented();
  1208. self::unreadCount();
  1209. // Always exits
  1210. case 'edit-tag': // https://web.archive.org/web/20200616071132/https://blog.martindoms.com/2010/01/20/using-the-google-reader-api-part-3
  1211. $token = is_string($_POST['T'] ?? null) ? trim($_POST['T']) : '';
  1212. self::checkToken(FreshRSS_Context::userConf(), $token);
  1213. // Add (Can be repeated to add multiple tags at once): user/-/state/com.google/read user/-/state/com.google/starred
  1214. $as = self::multiplePosts('a');
  1215. // Remove (Can be repeated to remove multiple tags at once): user/-/state/com.google/read user/-/state/com.google/starred
  1216. $rs = self::multiplePosts('r');
  1217. $e_ids = self::multiplePosts('i'); //item IDs
  1218. self::editTag($e_ids, $as, $rs);
  1219. // Always exits
  1220. case 'rename-tag': //https://github.com/theoldreader/api
  1221. $token = is_string($_POST['T'] ?? null) ? trim($_POST['T']) : '';
  1222. self::checkToken(FreshRSS_Context::userConf(), $token);
  1223. $s = is_string($_POST['s'] ?? null) ? trim($_POST['s']) : ''; //user/-/label/Folder
  1224. $dest = is_string($_POST['dest'] ?? null) ? trim($_POST['dest']) : ''; //user/-/label/NewFolder
  1225. self::renameTag($s, $dest);
  1226. // Always exits
  1227. case 'disable-tag': //https://github.com/theoldreader/api
  1228. $token = is_string($_POST['T'] ?? null) ? trim($_POST['T']) : '';
  1229. self::checkToken(FreshRSS_Context::userConf(), $token);
  1230. $s_s = self::multiplePosts('s');
  1231. foreach ($s_s as $s) {
  1232. self::disableTag($s); //user/-/label/Folder
  1233. }
  1234. // Always exits
  1235. case 'mark-all-as-read':
  1236. $token = is_string($_POST['T'] ?? null) ? trim($_POST['T']) : '';
  1237. self::checkToken(FreshRSS_Context::userConf(), $token);
  1238. $streamId = is_string($_POST['s'] ?? null) ? trim($_POST['s']) : '';
  1239. $ts = is_string($_POST['ts'] ?? null) ? trim($_POST['ts']) : '0'; //Older than timestamp in nanoseconds
  1240. if (!ctype_digit($ts)) {
  1241. self::badRequest();
  1242. }
  1243. self::markAllAsRead($streamId, $ts);
  1244. // Always exits
  1245. case 'token':
  1246. self::token(FreshRSS_Context::userConf());
  1247. // Always exits
  1248. case 'user-info':
  1249. self::userInfo();
  1250. // Always exits
  1251. }
  1252. }
  1253. self::badRequest();
  1254. }
  1255. }
  1256. GReaderAPI::parse();