greader.php 40 KB

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