4
0

greader.php 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. == Description ==
  5. Server-side API compatible with Google Reader API layer 2
  6. for the FreshRSS project https://freshrss.org
  7. == Credits ==
  8. * 2014-03: Released by Alexandre Alapetite https://alexandre.alapetite.fr
  9. under GNU AGPL 3 license http://www.gnu.org/licenses/agpl-3.0.html
  10. == Documentation ==
  11. * https://code.google.com/archive/p/pyrfeed/wikis/GoogleReaderAPI.wiki
  12. * https://web.archive.org/web/20130718025427/http://undoc.in/
  13. * http://ranchero.com/downloads/GoogleReaderAPI-2009.pdf
  14. * https://github.com/mihaip/google-reader-api
  15. * https://web.archive.org/web/20210126113527/https://blog.martindoms.com/2009/08/15/using-the-google-reader-api-part-1
  16. * https://github.com/noinnion/newsplus/blob/master/extensions/GoogleReaderCloneExtension/src/com/noinnion/android/newsplus/extension/google_reader/GoogleReaderClient.java
  17. * https://github.com/ericmann/gReader-Library/blob/master/greader.class.php
  18. * https://github.com/devongovett/reader
  19. * https://github.com/theoldreader/api
  20. * https://www.inoreader.com/developers/
  21. * https://feedhq.readthedocs.io/en/latest/api/index.html
  22. * https://github.com/bazqux/bazqux-api
  23. */
  24. require(__DIR__ . '/../../constants.php');
  25. require(LIB_PATH . '/lib_rss.php'); //Includes class autoloader
  26. $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 = [];
  70. $prefix = $name . '=';
  71. $prefixLength = strlen($prefix);
  72. foreach ($inputs as $input) {
  73. if (str_starts_with($input, $prefix)) {
  74. $result[] = urldecode(substr($input, $prefixLength));
  75. }
  76. }
  77. return $result;
  78. }
  79. function debugInfo(): string {
  80. if (function_exists('getallheaders')) {
  81. $ALL_HEADERS = getallheaders();
  82. } else { //nginx http://php.net/getallheaders#84262
  83. $ALL_HEADERS = [];
  84. foreach ($_SERVER as $name => $value) {
  85. if (str_starts_with($name, '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. // https://web.archive.org/web/20210126113527/https://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. // https://github.com/mihaip/google-reader-api/blob/master/wiki/ActionToken.wiki
  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([
  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 = [
  255. ['id' => 'user/-/state/com.google/starred'],
  256. // ['id' => 'user/-/state/com.google/broadcast', 'sortid' => '2']
  257. ];
  258. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  259. $categories = $categoryDAO->listCategories(prePopulateFeeds: false, details: false) ?: [];
  260. foreach ($categories as $cat) {
  261. $tags[] = [
  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[] = [
  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(['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 = [];
  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(['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 (str_starts_with($streamUrl, 'feed/')) {
  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([
  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([
  444. 'numResults' => 0,
  445. 'error' => $e->getMessage(),
  446. ], JSON_OPTIONS));
  447. }
  448. }
  449. private static function unreadCount(): never {
  450. // https://web.archive.org/web/20210126115837/https://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. $unreadcounts = [];
  458. foreach ($categoryDAO->listCategories(true, true) ?: [] as $cat) {
  459. $catLastUpdate = 0;
  460. foreach ($cat->feeds() as $feed) {
  461. $lastUpdate = $feedsNewestItemUsec['f_' . $feed->id()] ?? 0;
  462. $unreadcounts[] = [
  463. 'id' => 'feed/' . $feed->id(),
  464. 'count' => $feed->nbNotRead(),
  465. 'newestItemTimestampUsec' => '' . $lastUpdate,
  466. ];
  467. if ($catLastUpdate < $lastUpdate) {
  468. $catLastUpdate = $lastUpdate;
  469. }
  470. }
  471. $unreadcounts[] = [
  472. 'id' => 'user/-/label/' . htmlspecialchars_decode($cat->name(), ENT_QUOTES),
  473. 'count' => $cat->nbNotRead(),
  474. 'newestItemTimestampUsec' => '' . $catLastUpdate,
  475. ];
  476. $totalUnreads += $cat->nbNotRead();
  477. if ($totalLastUpdate < $catLastUpdate) {
  478. $totalLastUpdate = $catLastUpdate;
  479. }
  480. }
  481. $tagDAO = FreshRSS_Factory::createTagDao();
  482. $tagsNewestItemUsec = $tagDAO->listTagsNewestItemUsec();
  483. foreach ($tagDAO->listTags(true) ?: [] as $label) {
  484. $lastUpdate = $tagsNewestItemUsec['t_' . $label->id()] ?? 0;
  485. $unreadcounts[] = [
  486. 'id' => 'user/-/label/' . htmlspecialchars_decode($label->name(), ENT_QUOTES),
  487. 'count' => $label->nbUnread(),
  488. 'newestItemTimestampUsec' => '' . $lastUpdate,
  489. ];
  490. }
  491. $unreadcounts[] = [
  492. 'id' => 'user/-/state/com.google/reading-list',
  493. 'count' => $totalUnreads,
  494. 'newestItemTimestampUsec' => '' . $totalLastUpdate,
  495. ];
  496. echo json_encode([
  497. 'max' => $totalUnreads,
  498. 'unreadcounts' => $unreadcounts,
  499. ], JSON_OPTIONS), "\n";
  500. exit();
  501. }
  502. /**
  503. * @param array<FreshRSS_Entry> $entries
  504. * @return array<array<string,mixed>>
  505. */
  506. private static function entriesToArray(array $entries): array {
  507. if (empty($entries)) {
  508. return [];
  509. }
  510. $catDAO = FreshRSS_Factory::createCategoryDao();
  511. $categories = $catDAO->listCategories(true) ?: [];
  512. $tagDAO = FreshRSS_Factory::createTagDao();
  513. $entryIdsTagNames = $tagDAO->getEntryIdsTagNames($entries);
  514. $items = [];
  515. foreach ($entries as $item) {
  516. /** @var FreshRSS_Entry $entry */
  517. $entry = Minz_ExtensionManager::callHook('entry_before_display', $item);
  518. if ($entry == null) {
  519. continue;
  520. }
  521. $feed = FreshRSS_Category::findFeed($categories, $entry->feedId());
  522. if ($feed === null) {
  523. continue;
  524. }
  525. $entry->_feed($feed);
  526. $items[] = $entry->toGReader('compat', $entryIdsTagNames['e_' . $entry->id()] ?? []);
  527. }
  528. return $items;
  529. }
  530. /**
  531. * @param 'A'|'c'|'f'|'s' $type
  532. * @phpstan-return array{'A'|'c'|'f'|'s'|'t',int,int,FreshRSS_BooleanSearch}
  533. */
  534. private static function streamContentsFilters(string $type, int|string $streamId,
  535. string $filter_target, string $exclude_target, int $start_time, int $stop_time): array {
  536. switch ($type) {
  537. case 'f': //feed
  538. if ($streamId != '' && is_string($streamId) && !is_numeric($streamId)) {
  539. $feedDAO = FreshRSS_Factory::createFeedDao();
  540. $streamId = htmlspecialchars($streamId, ENT_COMPAT, 'UTF-8');
  541. $feed = $feedDAO->searchByUrl($streamId);
  542. $streamId = $feed == null ? 0 : $feed->id();
  543. }
  544. break;
  545. case 'c': //category or label
  546. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  547. $streamId = htmlspecialchars((string)$streamId, ENT_COMPAT, 'UTF-8');
  548. $cat = $categoryDAO->searchByName($streamId);
  549. if ($cat != null) {
  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. $streamId = -1;
  559. }
  560. }
  561. break;
  562. }
  563. $streamId = (int)$streamId;
  564. $state = match ($filter_target) {
  565. 'user/-/state/com.google/read' => FreshRSS_Entry::STATE_READ,
  566. 'user/-/state/com.google/unread' => FreshRSS_Entry::STATE_NOT_READ,
  567. 'user/-/state/com.google/starred' => FreshRSS_Entry::STATE_FAVORITE,
  568. default => FreshRSS_Entry::STATE_ALL,
  569. };
  570. switch ($exclude_target) {
  571. case 'user/-/state/com.google/read':
  572. $state &= FreshRSS_Entry::STATE_NOT_READ;
  573. break;
  574. case 'user/-/state/com.google/unread':
  575. $state &= FreshRSS_Entry::STATE_READ;
  576. break;
  577. case 'user/-/state/com.google/starred':
  578. $state &= FreshRSS_Entry::STATE_NOT_FAVORITE;
  579. break;
  580. }
  581. $searches = new FreshRSS_BooleanSearch('');
  582. if ($start_time !== 0) {
  583. $search = new FreshRSS_Search('');
  584. $search->setMinDate($start_time);
  585. $searches->add($search);
  586. }
  587. if ($stop_time !== 0) {
  588. $search = new FreshRSS_Search('');
  589. $search->setMaxDate($stop_time);
  590. $searches->add($search);
  591. }
  592. return [$type, $streamId, $state, $searches];
  593. }
  594. private static function streamContents(string $path, string $include_target, int $start_time, int $stop_time, int $count,
  595. string $order, string $filter_target, string $exclude_target, string $continuation): never {
  596. // https://code.google.com/archive/p/pyrfeed/wikis/GoogleReaderAPI.wiki
  597. // https://web.archive.org/web/20210126115837/https://blog.martindoms.com/2009/10/16/using-the-google-reader-api-part-2#feed
  598. header('Content-Type: application/json; charset=UTF-8');
  599. $type = match ($path) {
  600. 'starred' => 's',
  601. 'feed' => 'f',
  602. 'label' => 'c',
  603. 'reading-list' => 'A',
  604. default => 'A',
  605. };
  606. [$type, $include_target, $state, $searches] =
  607. self::streamContentsFilters($type, $include_target, $filter_target, $exclude_target, $start_time, $stop_time);
  608. if ($continuation != '') {
  609. $count++; //Shift by one element
  610. }
  611. $entryDAO = FreshRSS_Factory::createEntryDao();
  612. $entries = $entryDAO->listWhere($type, $include_target, $state, $order === 'o' ? 'ASC' : 'DESC', $count, 0, $continuation, $searches);
  613. $entries = iterator_to_array($entries); //TODO: Improve
  614. $items = self::entriesToArray($entries);
  615. if ($continuation != '') {
  616. array_shift($items); //Discard first element that was already sent in the previous response
  617. $count--;
  618. }
  619. $response = [
  620. 'id' => 'user/-/state/com.google/reading-list',
  621. 'updated' => time(),
  622. 'items' => $items,
  623. ];
  624. if (count($entries) >= $count) {
  625. $entry = end($entries);
  626. if ($entry != false) {
  627. $response['continuation'] = '' . $entry->id();
  628. }
  629. }
  630. unset($entries, $entryDAO, $items);
  631. gc_collect_cycles();
  632. echoJson($response, 2); // $optimisationDepth=2 as we are interested in being memory efficient for {"items":[...]}
  633. exit();
  634. }
  635. private static function streamContentsItemsIds(string $streamId, int $start_time, int $stop_time, int $count,
  636. string $order, string $filter_target, string $exclude_target, string $continuation): never {
  637. // https://github.com/mihaip/google-reader-api/blob/master/wiki/ApiStreamItemsIds.wiki
  638. // https://code.google.com/archive/p/pyrfeed/wikis/GoogleReaderAPI.wiki
  639. // https://web.archive.org/web/20210126115837/https://blog.martindoms.com/2009/10/16/using-the-google-reader-api-part-2#feed
  640. $type = 'A';
  641. if ($streamId === 'user/-/state/com.google/reading-list') {
  642. $type = 'A';
  643. } elseif ($streamId === 'user/-/state/com.google/starred') {
  644. $type = 's';
  645. } elseif (str_starts_with($streamId, 'feed/')) {
  646. $type = 'f';
  647. $streamId = substr($streamId, 5);
  648. } elseif (str_starts_with($streamId, 'user/-/label/')) {
  649. $type = 'c';
  650. $streamId = substr($streamId, 13);
  651. }
  652. [$type, $id, $state, $searches] = self::streamContentsFilters($type, $streamId, $filter_target, $exclude_target, $start_time, $stop_time);
  653. if ($continuation != '') {
  654. $count++; //Shift by one element
  655. }
  656. $entryDAO = FreshRSS_Factory::createEntryDao();
  657. $ids = $entryDAO->listIdsWhere($type, $id, $state, $order === 'o' ? 'ASC' : 'DESC', $count, 0, $continuation, $searches);
  658. if ($ids === null) {
  659. self::internalServerError();
  660. }
  661. if ($continuation != '') {
  662. array_shift($ids); //Discard first element that was already sent in the previous response
  663. $count--;
  664. }
  665. if (empty($ids) && isset($_GET['client']) && $_GET['client'] === 'newsplus') {
  666. $ids = [ 0 ]; //For News+ bug https://github.com/noinnion/newsplus/issues/84#issuecomment-57834632
  667. }
  668. $itemRefs = [];
  669. foreach ($ids as $entryId) {
  670. $itemRefs[] = [
  671. 'id' => '' . $entryId, //64-bit decimal
  672. ];
  673. }
  674. $response = [
  675. 'itemRefs' => $itemRefs,
  676. ];
  677. if (count($ids) >= $count) {
  678. $entryId = end($ids);
  679. if ($entryId != false) {
  680. $response['continuation'] = '' . $entryId;
  681. }
  682. }
  683. echo json_encode($response, JSON_OPTIONS), "\n";
  684. exit();
  685. }
  686. /**
  687. * @param array<string> $e_ids
  688. */
  689. private static function streamContentsItems(array $e_ids, string $order): never {
  690. header('Content-Type: application/json; charset=UTF-8');
  691. foreach ($e_ids as $i => $e_id) {
  692. // https://feedhq.readthedocs.io/en/latest/api/terminology.html#items
  693. if (!ctype_digit($e_id) || $e_id[0] === '0') {
  694. $e_ids[$i] = hex2dec(basename($e_id)); //Strip prefix 'tag:google.com,2005:reader/item/'
  695. }
  696. }
  697. /** @var array<numeric-string> $e_ids */
  698. $entryDAO = FreshRSS_Factory::createEntryDao();
  699. $entries = $entryDAO->listByIds($e_ids, $order === 'o' ? 'ASC' : 'DESC');
  700. $entries = iterator_to_array($entries); //TODO: Improve
  701. $items = self::entriesToArray($entries);
  702. $response = [
  703. 'id' => 'user/-/state/com.google/reading-list',
  704. 'updated' => time(),
  705. 'items' => $items,
  706. ];
  707. unset($entries, $entryDAO, $items);
  708. gc_collect_cycles();
  709. echoJson($response, 2); // $optimisationDepth=2 as we are interested in being memory efficient for {"items":[...]}
  710. exit();
  711. }
  712. /**
  713. * @param array<string> $e_ids IDs of the items to edit
  714. * @param array<string> $as tags to add to all the listed items
  715. * @param array<string> $rs tags to remove from all the listed items
  716. */
  717. private static function editTag(array $e_ids, array $as, array $rs): never {
  718. foreach ($e_ids as $i => $e_id) {
  719. if (!ctype_digit($e_id) || $e_id[0] === '0') {
  720. $e_ids[$i] = hex2dec(basename($e_id)); //Strip prefix 'tag:google.com,2005:reader/item/'
  721. }
  722. }
  723. /** @var array<numeric-string> $e_ids */
  724. $entryDAO = FreshRSS_Factory::createEntryDao();
  725. $tagDAO = FreshRSS_Factory::createTagDao();
  726. foreach ($as as $a) {
  727. switch ($a) {
  728. case 'user/-/state/com.google/read':
  729. $entryDAO->markRead($e_ids, true);
  730. break;
  731. case 'user/-/state/com.google/starred':
  732. $entryDAO->markFavorite($e_ids, true);
  733. break;
  734. case 'user/-/state/com.google/broadcast':
  735. case 'user/-/state/com.google/like':
  736. case 'user/-/state/com.google/tracking-kept-unread':
  737. // Not supported
  738. break;
  739. default:
  740. $tagName = '';
  741. if (str_starts_with($a, 'user/-/label/')) {
  742. $tagName = substr($a, 13);
  743. } else {
  744. $user = Minz_User::name() ?? '';
  745. $prefix = 'user/' . $user . '/label/';
  746. if (str_starts_with($a, $prefix)) {
  747. $tagName = substr($a, strlen($prefix));
  748. }
  749. }
  750. if ($tagName !== '') {
  751. $tagName = htmlspecialchars($tagName, ENT_COMPAT, 'UTF-8');
  752. $tag = $tagDAO->searchByName($tagName);
  753. if ($tag === null) {
  754. $tagDAO->addTag(['name' => $tagName]);
  755. $tag = $tagDAO->searchByName($tagName);
  756. }
  757. if ($tag !== null) {
  758. foreach ($e_ids as $e_id) {
  759. $tagDAO->tagEntry($tag->id(), $e_id, true);
  760. }
  761. }
  762. }
  763. break;
  764. }
  765. }
  766. foreach ($rs as $r) {
  767. switch ($r) {
  768. case 'user/-/state/com.google/read':
  769. $entryDAO->markRead($e_ids, false);
  770. break;
  771. case 'user/-/state/com.google/starred':
  772. $entryDAO->markFavorite($e_ids, false);
  773. break;
  774. case 'user/-/state/com.google/broadcast':
  775. case 'user/-/state/com.google/like':
  776. case 'user/-/state/com.google/tracking-kept-unread':
  777. // Not supported
  778. break;
  779. default:
  780. if (str_starts_with($r, 'user/-/label/')) {
  781. $tagName = substr($r, 13);
  782. $tagName = htmlspecialchars($tagName, ENT_COMPAT, 'UTF-8');
  783. $tag = $tagDAO->searchByName($tagName);
  784. if ($tag !== null) {
  785. foreach ($e_ids as $e_id) {
  786. $tagDAO->tagEntry($tag->id(), $e_id, false);
  787. }
  788. }
  789. }
  790. break;
  791. }
  792. }
  793. exit('OK');
  794. }
  795. private static function renameTag(string $s, string $dest): never {
  796. if (str_starts_with($s, 'user/-/label/') && str_starts_with($dest, 'user/-/label/')) {
  797. $s = substr($s, 13);
  798. $s = htmlspecialchars($s, ENT_COMPAT, 'UTF-8');
  799. $dest = substr($dest, 13);
  800. $dest = htmlspecialchars($dest, ENT_COMPAT, 'UTF-8');
  801. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  802. $cat = $categoryDAO->searchByName($s);
  803. if ($cat != null) {
  804. $categoryDAO->updateCategory($cat->id(), [
  805. 'name' => $dest, 'kind' => $cat->kind(), 'attributes' => $cat->attributes()
  806. ]);
  807. exit('OK');
  808. } else {
  809. $tagDAO = FreshRSS_Factory::createTagDao();
  810. $tag = $tagDAO->searchByName($s);
  811. if ($tag != null) {
  812. $tagDAO->updateTagName($tag->id(), $dest);
  813. exit('OK');
  814. }
  815. }
  816. }
  817. self::badRequest();
  818. }
  819. private static function disableTag(string $s): never {
  820. if (str_starts_with($s, 'user/-/label/')) {
  821. $s = substr($s, 13);
  822. $s = htmlspecialchars($s, ENT_COMPAT, 'UTF-8');
  823. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  824. $cat = $categoryDAO->searchByName($s);
  825. if ($cat != null) {
  826. $feedDAO = FreshRSS_Factory::createFeedDao();
  827. $feedDAO->changeCategory($cat->id(), 0);
  828. if ($cat->id() > 1) {
  829. $categoryDAO->deleteCategory($cat->id());
  830. }
  831. exit('OK');
  832. } else {
  833. $tagDAO = FreshRSS_Factory::createTagDao();
  834. $tag = $tagDAO->searchByName($s);
  835. if ($tag != null) {
  836. $tagDAO->deleteTag($tag->id());
  837. exit('OK');
  838. }
  839. }
  840. }
  841. self::badRequest();
  842. }
  843. /**
  844. * @param numeric-string $olderThanId
  845. */
  846. private static function markAllAsRead(string $streamId, string $olderThanId): never {
  847. $entryDAO = FreshRSS_Factory::createEntryDao();
  848. if (str_starts_with($streamId, 'feed/')) {
  849. $f_id = basename($streamId);
  850. if (!is_numeric($f_id)) {
  851. self::badRequest();
  852. }
  853. $f_id = (int)$f_id;
  854. $entryDAO->markReadFeed($f_id, $olderThanId);
  855. } elseif (str_starts_with($streamId, 'user/-/label/')) {
  856. $c_name = substr($streamId, 13);
  857. $c_name = htmlspecialchars($c_name, ENT_COMPAT, 'UTF-8');
  858. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  859. $cat = $categoryDAO->searchByName($c_name);
  860. if ($cat != null) {
  861. $entryDAO->markReadCat($cat->id(), $olderThanId);
  862. } else {
  863. $tagDAO = FreshRSS_Factory::createTagDao();
  864. $tag = $tagDAO->searchByName($c_name);
  865. if ($tag != null) {
  866. $entryDAO->markReadTag($tag->id(), $olderThanId);
  867. } else {
  868. self::badRequest();
  869. }
  870. }
  871. } elseif ($streamId === 'user/-/state/com.google/reading-list') {
  872. $entryDAO->markReadEntries($olderThanId, false);
  873. } else {
  874. self::badRequest();
  875. }
  876. exit('OK');
  877. }
  878. public static function parse(): never {
  879. global $ORIGINAL_INPUT;
  880. header('Access-Control-Allow-Headers: Authorization');
  881. header('Access-Control-Allow-Methods: GET, POST');
  882. header('Access-Control-Allow-Origin: *');
  883. header('Access-Control-Max-Age: 600');
  884. if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') {
  885. self::noContent();
  886. }
  887. $pathInfo = '';
  888. if (empty($_SERVER['PATH_INFO'])) {
  889. if (!empty($_SERVER['ORIG_PATH_INFO'])) {
  890. // Compatibility https://php.net/reserved.variables.server
  891. $pathInfo = $_SERVER['ORIG_PATH_INFO'];
  892. }
  893. } else {
  894. $pathInfo = $_SERVER['PATH_INFO'];
  895. }
  896. $pathInfo = rawurldecode($pathInfo);
  897. $pathInfo = '' . preg_replace('%^(/api)?(/greader\.php)?%', '', $pathInfo); //Discard common errors
  898. if ($pathInfo == '' && empty($_SERVER['QUERY_STRING'])) {
  899. exit('OK');
  900. }
  901. $pathInfos = explode('/', $pathInfo);
  902. if (count($pathInfos) < 3) {
  903. self::badRequest();
  904. }
  905. FreshRSS_Context::initSystem();
  906. //Minz_Log::debug('----------------------------------------------------------------', API_LOG);
  907. //Minz_Log::debug(debugInfo(), API_LOG);
  908. if (!FreshRSS_Context::hasSystemConf() || !FreshRSS_Context::systemConf()->api_enabled) {
  909. self::serviceUnavailable();
  910. } elseif ($pathInfos[1] === 'check' && $pathInfos[2] === 'compatibility') {
  911. self::checkCompatibility();
  912. }
  913. Minz_Session::init('FreshRSS', true);
  914. if ($pathInfos[1] !== 'accounts') {
  915. self::authorizationToUser();
  916. }
  917. if (FreshRSS_Context::hasUserConf()) {
  918. Minz_Translate::init(FreshRSS_Context::userConf()->language);
  919. Minz_ExtensionManager::init();
  920. Minz_ExtensionManager::enableByList(FreshRSS_Context::userConf()->extensions_enabled, 'user');
  921. } else {
  922. Minz_Translate::init();
  923. }
  924. if ($pathInfos[1] === 'accounts') {
  925. if (($pathInfos[2] === 'ClientLogin') && isset($_REQUEST['Email']) && isset($_REQUEST['Passwd'])) {
  926. self::clientLogin($_REQUEST['Email'], $_REQUEST['Passwd']);
  927. }
  928. } elseif (isset($pathInfos[3], $pathInfos[4]) && $pathInfos[1] === 'reader' && $pathInfos[2] === 'api' && $pathInfos[3] === '0') {
  929. if (Minz_User::name() === null) {
  930. self::unauthorized();
  931. }
  932. $timestamp = isset($_GET['ck']) ? (int)$_GET['ck'] : 0; //ck=[unix timestamp] : Use the current Unix time here, helps Google with caching.
  933. switch ($pathInfos[4]) {
  934. case 'stream':
  935. /**
  936. * xt=[exclude target]: Used to exclude certain items from the feed.
  937. * For example, using xt=user/-/state/com.google/read will exclude items
  938. * that the current user has marked as read, or xt=feed/[feedurl] will
  939. * exclude items from a particular feed (obviously not useful in this request,
  940. * but xt appears in other listing requests).
  941. */
  942. $exclude_target = $_GET['xt'] ?? '';
  943. $filter_target = $_GET['it'] ?? '';
  944. //n=[integer] : The maximum number of results to return.
  945. $count = isset($_GET['n']) ? (int)$_GET['n'] : 20;
  946. //r=[d|n|o] : Sort order of item results. d or n gives items in descending date order, o in ascending order.
  947. $order = $_GET['r'] ?? 'd';
  948. /**
  949. * ot=[unix timestamp] : The time from which you want to retrieve items.
  950. * Only items that have been crawled by Google Reader after this time will be returned.
  951. */
  952. $start_time = isset($_GET['ot']) ? (int)$_GET['ot'] : 0;
  953. $stop_time = isset($_GET['nt']) ? (int)$_GET['nt'] : 0;
  954. /**
  955. * Continuation token. If a StreamContents response does not represent
  956. * all items in a timestamp range, it will have a continuation attribute.
  957. * The same request can be re-issued with the value of that attribute put
  958. * in this parameter to get more items
  959. */
  960. $continuation = isset($_GET['c']) ? trim((string)$_GET['c']) : '';
  961. if (!ctype_digit($continuation)) {
  962. $continuation = '';
  963. }
  964. if (isset($pathInfos[5]) && $pathInfos[5] === 'contents') {
  965. if (!isset($pathInfos[6]) && isset($_GET['s'])) {
  966. // Compatibility BazQux API https://github.com/bazqux/bazqux-api#fetching-streams
  967. $streamIdInfos = explode('/', $_GET['s']);
  968. foreach ($streamIdInfos as $streamIdInfo) {
  969. $pathInfos[] = $streamIdInfo;
  970. }
  971. }
  972. if (isset($pathInfos[6]) && isset($pathInfos[7])) {
  973. if ($pathInfos[6] === 'feed') {
  974. $include_target = $pathInfos[7];
  975. if ($include_target != '' && !is_numeric($include_target)) {
  976. $include_target = empty($_SERVER['REQUEST_URI']) ? '' : $_SERVER['REQUEST_URI'];
  977. if (preg_match('#/reader/api/0/stream/contents/feed/([A-Za-z0-9\'!*()%$_.~+-]+)#', $include_target, $matches) === 1) {
  978. $include_target = urldecode($matches[1]);
  979. } else {
  980. $include_target = '';
  981. }
  982. }
  983. self::streamContents($pathInfos[6], $include_target, $start_time, $stop_time,
  984. $count, $order, $filter_target, $exclude_target, $continuation);
  985. } elseif (isset($pathInfos[8], $pathInfos[9]) && $pathInfos[6] === 'user') {
  986. if ($pathInfos[8] === 'state') {
  987. if ($pathInfos[9] === 'com.google' && isset($pathInfos[10])) {
  988. if ($pathInfos[10] === 'reading-list' || $pathInfos[10] === 'starred') {
  989. $include_target = '';
  990. self::streamContents($pathInfos[10], $include_target, $start_time, $stop_time, $count, $order,
  991. $filter_target, $exclude_target, $continuation);
  992. }
  993. }
  994. } elseif ($pathInfos[8] === 'label') {
  995. $include_target = $pathInfos[9];
  996. self::streamContents($pathInfos[8], $include_target, $start_time, $stop_time,
  997. $count, $order, $filter_target, $exclude_target, $continuation);
  998. }
  999. }
  1000. } else { //EasyRSS, FeedMe
  1001. $include_target = '';
  1002. self::streamContents('reading-list', $include_target, $start_time, $stop_time,
  1003. $count, $order, $filter_target, $exclude_target, $continuation);
  1004. }
  1005. } elseif ($pathInfos[5] === 'items') {
  1006. if ($pathInfos[6] === 'ids' && isset($_GET['s'])) {
  1007. // StreamId for which to fetch the item IDs.
  1008. // TODO: support multiple streams
  1009. $streamId = $_GET['s'];
  1010. self::streamContentsItemsIds($streamId, $start_time, $stop_time, $count, $order, $filter_target, $exclude_target, $continuation);
  1011. } elseif ($pathInfos[6] === 'contents' && isset($_POST['i'])) { //FeedMe
  1012. $e_ids = multiplePosts('i'); //item IDs
  1013. self::streamContentsItems($e_ids, $order);
  1014. }
  1015. }
  1016. break;
  1017. case 'tag':
  1018. if (isset($pathInfos[5]) && $pathInfos[5] === 'list') {
  1019. $output = $_GET['output'] ?? '';
  1020. if ($output !== 'json') self::notImplemented();
  1021. self::tagList();
  1022. }
  1023. break;
  1024. case 'subscription':
  1025. if (isset($pathInfos[5])) {
  1026. switch ($pathInfos[5]) {
  1027. case 'export':
  1028. self::subscriptionExport();
  1029. // Always exits
  1030. case 'import':
  1031. if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' && $ORIGINAL_INPUT != '') {
  1032. self::subscriptionImport($ORIGINAL_INPUT);
  1033. }
  1034. break;
  1035. case 'list':
  1036. $output = $_GET['output'] ?? '';
  1037. if ($output !== 'json') self::notImplemented();
  1038. self::subscriptionList();
  1039. // Always exits
  1040. case 'edit':
  1041. if (isset($_REQUEST['s'], $_REQUEST['ac'])) {
  1042. // StreamId to operate on. The parameter may be repeated to edit multiple subscriptions at once
  1043. $streamNames = empty($_POST['s']) && isset($_GET['s']) ? [$_GET['s']] : multiplePosts('s');
  1044. /* Title to use for the subscription. For the `subscribe` action,
  1045. * if not specified then the feed’s current title will be used. Can
  1046. * be used with the `edit` action to rename a subscription */
  1047. $titles = empty($_POST['t']) && isset($_GET['t']) ? [$_GET['t']] : multiplePosts('t');
  1048. // Action to perform on the given StreamId. Possible values are `subscribe`, `unsubscribe` and `edit`
  1049. $action = $_REQUEST['ac'];
  1050. // StreamId to add the subscription to (generally a user label)
  1051. // (in FreshRSS, we do not support repeated values since a feed can only be in one category)
  1052. $add = $_REQUEST['a'] ?? '';
  1053. // StreamId to remove the subscription from (generally a user label) (in FreshRSS, we do not support repeated values)
  1054. $remove = $_REQUEST['r'] ?? '';
  1055. self::subscriptionEdit($streamNames, $titles, $action, $add, $remove);
  1056. }
  1057. break;
  1058. case 'quickadd': //https://github.com/theoldreader/api
  1059. if (isset($_REQUEST['quickadd'])) {
  1060. self::quickadd($_REQUEST['quickadd']);
  1061. }
  1062. break;
  1063. }
  1064. }
  1065. break;
  1066. case 'unread-count':
  1067. $output = $_GET['output'] ?? '';
  1068. if ($output !== 'json') self::notImplemented();
  1069. self::unreadCount();
  1070. // Always exits
  1071. case 'edit-tag': // https://web.archive.org/web/20200616071132/https://blog.martindoms.com/2010/01/20/using-the-google-reader-api-part-3
  1072. $token = isset($_POST['T']) ? trim($_POST['T']) : '';
  1073. self::checkToken(FreshRSS_Context::userConf(), $token);
  1074. // Add (Can be repeated to add multiple tags at once): user/-/state/com.google/read user/-/state/com.google/starred
  1075. $as = multiplePosts('a');
  1076. // Remove (Can be repeated to remove multiple tags at once): user/-/state/com.google/read user/-/state/com.google/starred
  1077. $rs = multiplePosts('r');
  1078. $e_ids = multiplePosts('i'); //item IDs
  1079. self::editTag($e_ids, $as, $rs);
  1080. // Always exits
  1081. case 'rename-tag': //https://github.com/theoldreader/api
  1082. $token = isset($_POST['T']) ? trim($_POST['T']) : '';
  1083. self::checkToken(FreshRSS_Context::userConf(), $token);
  1084. $s = $_POST['s'] ?? ''; //user/-/label/Folder
  1085. $dest = $_POST['dest'] ?? ''; //user/-/label/NewFolder
  1086. self::renameTag($s, $dest);
  1087. // Always exits
  1088. case 'disable-tag': //https://github.com/theoldreader/api
  1089. $token = isset($_POST['T']) ? trim($_POST['T']) : '';
  1090. self::checkToken(FreshRSS_Context::userConf(), $token);
  1091. $s_s = multiplePosts('s');
  1092. foreach ($s_s as $s) {
  1093. self::disableTag($s); //user/-/label/Folder
  1094. }
  1095. // Always exits
  1096. case 'mark-all-as-read':
  1097. $token = isset($_POST['T']) ? trim($_POST['T']) : '';
  1098. self::checkToken(FreshRSS_Context::userConf(), $token);
  1099. $streamId = trim($_POST['s'] ?? '');
  1100. $ts = trim($_POST['ts'] ?? '0'); //Older than timestamp in nanoseconds
  1101. if (!ctype_digit($ts)) {
  1102. self::badRequest();
  1103. }
  1104. self::markAllAsRead($streamId, $ts);
  1105. // Always exits
  1106. case 'token':
  1107. self::token(FreshRSS_Context::userConf());
  1108. // Always exits
  1109. case 'user-info':
  1110. self::userInfo();
  1111. // Always exits
  1112. }
  1113. }
  1114. self::badRequest();
  1115. }
  1116. }
  1117. GReaderAPI::parse();