greader.php 38 KB

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