4
0

greader.php 41 KB

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