greader.php 40 KB

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