4
0

greader.php 43 KB

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