greader.php 38 KB

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