greader.php 41 KB

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