greader.php 40 KB

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