greader.php 38 KB

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