greader.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  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. */
  20. require('../../constants.php');
  21. require(LIB_PATH . '/lib_rss.php'); //Includes class autoloader
  22. $ORIGINAL_INPUT = file_get_contents('php://input', false, null, 0, 1048576);
  23. if (PHP_INT_SIZE < 8) { //32-bit
  24. function dec2hex($dec) {
  25. return str_pad(gmp_strval(gmp_init($dec, 10), 16), 16, '0', STR_PAD_LEFT);
  26. }
  27. function hex2dec($hex) {
  28. return gmp_strval(gmp_init($hex, 16), 10);
  29. }
  30. } else { //64-bit
  31. function dec2hex($dec) { //http://code.google.com/p/google-reader-api/wiki/ItemId
  32. return str_pad(dechex($dec), 16, '0', STR_PAD_LEFT);
  33. }
  34. function hex2dec($hex) {
  35. return hexdec($hex);
  36. }
  37. }
  38. function headerVariable($headerName, $varName) {
  39. $header = '';
  40. $upName = 'HTTP_' . strtoupper($headerName);
  41. if (isset($_SERVER[$upName])) {
  42. $header = $_SERVER[$upName];
  43. } elseif (isset($_SERVER['REDIRECT_' . $upName])) {
  44. $header = $_SERVER['REDIRECT_' . $upName];
  45. } elseif (function_exists('getallheaders')) {
  46. $ALL_HEADERS = getallheaders();
  47. if (isset($ALL_HEADERS[$headerName])) {
  48. $header = $ALL_HEADERS[$headerName];
  49. }
  50. }
  51. parse_str($header, $pairs);
  52. return isset($pairs[$varName]) ? $pairs[$varName] : null;
  53. }
  54. function multiplePosts($name) { //https://bugs.php.net/bug.php?id=51633
  55. global $ORIGINAL_INPUT;
  56. $inputs = explode('&', $ORIGINAL_INPUT);
  57. $result = array();
  58. $prefix = $name . '=';
  59. $prefixLength = strlen($prefix);
  60. foreach ($inputs as $input) {
  61. if (strpos($input, $prefix) === 0) {
  62. $result[] = urldecode(substr($input, $prefixLength));
  63. }
  64. }
  65. return $result;
  66. }
  67. class MyPDO extends Minz_ModelPdo {
  68. function prepare($sql) {
  69. return $this->bd->prepare(str_replace('%_', $this->prefix, $sql));
  70. }
  71. }
  72. function logMe($text) {
  73. file_put_contents(join_path(USERS_PATH, '_', 'log_api.txt'), date('c') . "\t" . $text . "\n", FILE_APPEND);
  74. }
  75. function debugInfo() {
  76. if (function_exists('getallheaders')) {
  77. $ALL_HEADERS = getallheaders();
  78. } else { //nginx http://php.net/getallheaders#84262
  79. $ALL_HEADERS = array();
  80. foreach ($_SERVER as $name => $value) {
  81. if (substr($name, 0, 5) === 'HTTP_') {
  82. $ALL_HEADERS[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
  83. }
  84. }
  85. }
  86. global $ORIGINAL_INPUT;
  87. return print_r(
  88. array(
  89. 'date' => date('c'),
  90. 'headers' => $ALL_HEADERS,
  91. '_SERVER' => $_SERVER,
  92. '_GET' => $_GET,
  93. '_POST' => $_POST,
  94. '_COOKIE' => $_COOKIE,
  95. 'INPUT' => $ORIGINAL_INPUT
  96. ), true);
  97. }
  98. function badRequest() {
  99. logMe("badRequest()");
  100. logMe(debugInfo());
  101. header('HTTP/1.1 400 Bad Request');
  102. header('Content-Type: text/plain; charset=UTF-8');
  103. die('Bad Request!');
  104. }
  105. function unauthorized() {
  106. logMe("unauthorized()");
  107. logMe(debugInfo());
  108. header('HTTP/1.1 401 Unauthorized');
  109. header('Content-Type: text/plain; charset=UTF-8');
  110. header('Google-Bad-Token: true');
  111. die('Unauthorized!');
  112. }
  113. function notImplemented() {
  114. logMe("notImplemented()");
  115. logMe(debugInfo());
  116. header('HTTP/1.1 501 Not Implemented');
  117. header('Content-Type: text/plain; charset=UTF-8');
  118. die('Not Implemented!');
  119. }
  120. function serviceUnavailable() {
  121. logMe("serviceUnavailable()");
  122. header('HTTP/1.1 503 Service Unavailable');
  123. header('Content-Type: text/plain; charset=UTF-8');
  124. die('Service Unavailable!');
  125. }
  126. function checkCompatibility() {
  127. logMe("checkCompatibility()");
  128. header('Content-Type: text/plain; charset=UTF-8');
  129. if (PHP_INT_SIZE < 8 && !function_exists('gmp_init')) {
  130. die('FAIL 64-bit or GMP extension!');
  131. }
  132. if ((!array_key_exists('HTTP_AUTHORIZATION', $_SERVER)) && //Apache mod_rewrite trick should be fine
  133. (!array_key_exists('REDIRECT_HTTP_AUTHORIZATION', $_SERVER)) && //Apache mod_rewrite with FCGI
  134. (empty($_SERVER['SERVER_SOFTWARE']) || (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') === false)) && //nginx should be fine
  135. (empty($_SERVER['SERVER_SOFTWARE']) || (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') === false)) && //lighttpd should be fine
  136. ((!function_exists('getallheaders')) || (stripos(php_sapi_name(), 'cgi') !== false))) { //Main problem is Apache/CGI mode
  137. die('FAIL getallheaders! (probably)');
  138. }
  139. echo 'PASS';
  140. exit();
  141. }
  142. function authorizationToUser() {
  143. $headerAuth = headerVariable('Authorization', 'GoogleLogin_auth'); //Input is 'GoogleLogin auth', but PHP replaces spaces by '_' http://php.net/language.variables.external
  144. if ($headerAuth != '') {
  145. $headerAuthX = explode('/', $headerAuth, 2);
  146. if (count($headerAuthX) === 2) {
  147. $user = $headerAuthX[0];
  148. if (FreshRSS_user_Controller::checkUsername($user)) {
  149. FreshRSS_Context::$user_conf = get_user_configuration($user);
  150. if (FreshRSS_Context::$user_conf == null) {
  151. Minz_Log::warning('Invalid API user ' . $user . ': configuration cannot be found.');
  152. unauthorized();
  153. }
  154. if ($headerAuthX[1] === sha1(FreshRSS_Context::$system_conf->salt . $user . FreshRSS_Context::$user_conf->apiPasswordHash)) {
  155. return $user;
  156. } else {
  157. logMe('Invalid API authorisation for user ' . $user . ': ' . $headerAuthX[1]);
  158. Minz_Log::warning('Invalid API authorisation for user ' . $user . ': ' . $headerAuthX[1]);
  159. unauthorized();
  160. }
  161. } else {
  162. badRequest();
  163. }
  164. }
  165. }
  166. return '';
  167. }
  168. function clientLogin($email, $pass) { //http://web.archive.org/web/20130604091042/http://undoc.in/clientLogin.html
  169. //logMe('clientLogin(' . $email . ")");
  170. if (ctype_alnum($email)) {
  171. if (!function_exists('password_verify')) {
  172. include_once(LIB_PATH . '/password_compat.php');
  173. }
  174. FreshRSS_Context::$user_conf = get_user_configuration($email);
  175. if (FreshRSS_Context::$user_conf == null) {
  176. Minz_Log::warning('Invalid API user ' . $email . ': configuration cannot be found.');
  177. unauthorized();
  178. }
  179. if (FreshRSS_Context::$user_conf->apiPasswordHash != '' && password_verify($pass, FreshRSS_Context::$user_conf->apiPasswordHash)) {
  180. header('Content-Type: text/plain; charset=UTF-8');
  181. $auth = $email . '/' . sha1(FreshRSS_Context::$system_conf->salt . $email . FreshRSS_Context::$user_conf->apiPasswordHash);
  182. echo 'SID=', $auth, "\n",
  183. 'Auth=', $auth, "\n";
  184. exit();
  185. } else {
  186. Minz_Log::warning('Password API mismatch for user ' . $email);
  187. unauthorized();
  188. }
  189. } else {
  190. badRequest();
  191. }
  192. die();
  193. }
  194. function token($conf) {
  195. //http://blog.martindoms.com/2009/08/15/using-the-google-reader-api-part-1/
  196. //https://github.com/ericmann/gReader-Library/blob/master/greader.class.php
  197. $user = Minz_Session::param('currentUser', '_');
  198. //logMe('token('. $user . ")"); //TODO: Implement real token that expires
  199. $token = str_pad(sha1(FreshRSS_Context::$system_conf->salt . $user . $conf->apiPasswordHash), 57, 'Z'); //Must have 57 characters
  200. echo $token, "\n";
  201. exit();
  202. }
  203. function checkToken($conf, $token) {
  204. //http://code.google.com/p/google-reader-api/wiki/ActionToken
  205. $user = Minz_Session::param('currentUser', '_');
  206. //logMe('checkToken(' . $token . ")");
  207. if ($token === str_pad(sha1(FreshRSS_Context::$system_conf->salt . $user . $conf->apiPasswordHash), 57, 'Z')) {
  208. return true;
  209. }
  210. unauthorized();
  211. }
  212. function userInfo() { //https://github.com/theoldreader/api#user-info
  213. //logMe("userInfo()");
  214. $user = Minz_Session::param('currentUser', '_');
  215. exit(json_encode(array(
  216. 'userId' => $user,
  217. 'userName' => $user,
  218. 'userProfileId' => $user,
  219. 'userEmail' => FreshRSS_Context::$user_conf->mail_login,
  220. )));
  221. }
  222. function tagList() {
  223. //logMe("tagList()");
  224. header('Content-Type: application/json; charset=UTF-8');
  225. $pdo = new MyPDO();
  226. $stm = $pdo->prepare('SELECT c.name FROM `%_category` c');
  227. $stm->execute();
  228. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  229. $tags = array(
  230. array('id' => 'user/-/state/com.google/starred'),
  231. //array('id' => 'user/-/state/com.google/broadcast', 'sortid' => '2'),
  232. );
  233. foreach ($res as $cName) {
  234. $tags[] = array(
  235. 'id' => 'user/-/label/' . $cName,
  236. //'sortid' => $cName,
  237. );
  238. }
  239. echo json_encode(array('tags' => $tags)), "\n";
  240. exit();
  241. }
  242. function subscriptionList() {
  243. //logMe("subscriptionList()");
  244. header('Content-Type: application/json; charset=UTF-8');
  245. $pdo = new MyPDO();
  246. $stm = $pdo->prepare('SELECT f.id, f.name, f.url, f.website, c.id as c_id, c.name as c_name FROM `%_feed` f
  247. INNER JOIN `%_category` c ON c.id = f.category');
  248. $stm->execute();
  249. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  250. $salt = FreshRSS_Context::$system_conf->salt;
  251. $subscriptions = array();
  252. foreach ($res as $line) {
  253. $subscriptions[] = array(
  254. 'id' => 'feed/' . $line['id'],
  255. 'title' => $line['name'],
  256. 'categories' => array(
  257. array(
  258. 'id' => 'user/-/label/' . $line['c_name'],
  259. 'label' => $line['c_name'],
  260. ),
  261. ),
  262. //'sortid' => $line['name'],
  263. //'firstitemmsec' => 0,
  264. 'url' => $line['url'],
  265. 'htmlUrl' => $line['website'],
  266. 'iconUrl' => Minz_Url::display('/f.php?' . hash('crc32b', $salt . $line['url']), '', true),
  267. );
  268. }
  269. echo json_encode(array('subscriptions' => $subscriptions)), "\n";
  270. exit();
  271. }
  272. function subscriptionEdit($streamNames, $titles, $action, $add = '', $remove = '') {
  273. //logMe("subscriptionEdit()");
  274. //https://github.com/mihaip/google-reader-api/blob/master/wiki/ApiSubscriptionEdit.wiki
  275. switch ($action) {
  276. case 'subscribe':
  277. case 'unsubscribe':
  278. case 'edit':
  279. break;
  280. default:
  281. badRequest();
  282. }
  283. $addCatId = 0;
  284. $categoryDAO = null;
  285. if ($add != '' || $remove != '') {
  286. $categoryDAO = new FreshRSS_CategoryDAO();
  287. }
  288. $c_name = '';
  289. if ($add != '' && strpos($add, 'user/') === 0) { //user/-/label/Example ; user/username/label/Example
  290. if (strpos($add, 'user/-/label/') === 0) {
  291. $c_name = substr($add, 13);
  292. } else {
  293. $user = Minz_Session::param('currentUser', '_');
  294. $prefix = 'user/' . $user . '/label/';
  295. if (strpos($add, $prefix) === 0) {
  296. $c_name = substr($add, strlen($prefix));
  297. } else {
  298. $c_name = '';
  299. }
  300. }
  301. $cat = $categoryDAO->searchByName($c_name);
  302. $addCatId = $cat == null ? 0 : $cat->id();
  303. } else if ($remove != '' && strpos($remove, 'user/-/label/')) {
  304. $addCatId = 1; //Default category
  305. }
  306. $feedDAO = FreshRSS_Factory::createFeedDao();
  307. for ($i = count($streamNames) - 1; $i >= 0; $i--) {
  308. $streamName = $streamNames[$i]; //feed/http://example.net/sample.xml ; feed/338
  309. if (strpos($streamName, 'feed/') === 0) {
  310. $streamName = substr($streamName, 5);
  311. $feedId = 0;
  312. if (ctype_digit($streamName)) {
  313. if ($action === 'subscribe') {
  314. continue;
  315. }
  316. $feedId = $streamName;
  317. } else {
  318. $feed = $feedDAO->searchByUrl($streamName);
  319. $feedId = $feed == null ? -1 : $feed->id();
  320. }
  321. $title = isset($titles[$i]) ? $titles[$i] : '';
  322. switch ($action) {
  323. case 'subscribe':
  324. if ($feedId <= 0) {
  325. $http_auth = ''; //TODO
  326. try {
  327. $feed = FreshRSS_feed_Controller::addFeed($streamName, $title, $addCatId, $c_name, $http_auth);
  328. continue;
  329. } catch (Exception $e) {
  330. logMe("subscriptionEdit error subscribe: " . $e->getMessage());
  331. }
  332. }
  333. badRequest();
  334. break;
  335. case 'unsubscribe':
  336. if (!($feedId > 0 && FreshRSS_feed_Controller::deleteFeed($feedId))) {
  337. badRequest();
  338. }
  339. break;
  340. case 'edit':
  341. if ($feedId > 0) {
  342. if ($addCatId > 0 || $c_name != '') {
  343. FreshRSS_feed_Controller::moveFeed($feedId, $addCatId, $c_name);
  344. }
  345. if ($title != '') {
  346. FreshRSS_feed_Controller::renameFeed($feedId, $title);
  347. }
  348. } else {
  349. badRequest();
  350. }
  351. break;
  352. }
  353. }
  354. }
  355. exit('OK');
  356. }
  357. function quickadd($url) {
  358. //logMe("quickadd($url)");
  359. try {
  360. $feed = FreshRSS_feed_Controller::addFeed($url);
  361. exit(json_encode(array(
  362. 'numResults' => 1,
  363. 'streamId' => $feed->id(),
  364. )));
  365. } catch (Exception $e) {
  366. logMe("subscriptionEdit error subscribe: " . $e->getMessage());
  367. die(json_encode(array(
  368. 'numResults' => 0,
  369. 'error' => $e->getMessage(),
  370. )));
  371. }
  372. }
  373. function unreadCount() { //http://blog.martindoms.com/2009/10/16/using-the-google-reader-api-part-2/#unread-count
  374. //logMe("unreadCount()");
  375. header('Content-Type: application/json; charset=UTF-8');
  376. $totalUnreads = 0;
  377. $totalLastUpdate = 0;
  378. $categoryDAO = new FreshRSS_CategoryDAO();
  379. foreach ($categoryDAO->listCategories(true, true) as $cat) {
  380. $catLastUpdate = 0;
  381. foreach ($cat->feeds() as $feed) {
  382. $lastUpdate = $feed->lastUpdate();
  383. $unreadcounts[] = array(
  384. 'id' => 'feed/' . $feed->id(),
  385. 'count' => $feed->nbNotRead(),
  386. 'newestItemTimestampUsec' => $lastUpdate . '000000',
  387. );
  388. if ($catLastUpdate < $lastUpdate) {
  389. $catLastUpdate = $lastUpdate;
  390. }
  391. }
  392. $unreadcounts[] = array(
  393. 'id' => 'user/-/label/' . $cat->name(),
  394. 'count' => $cat->nbNotRead(),
  395. 'newestItemTimestampUsec' => $catLastUpdate . '000000',
  396. );
  397. $totalUnreads += $cat->nbNotRead();
  398. if ($totalLastUpdate < $catLastUpdate) {
  399. $totalLastUpdate = $catLastUpdate;
  400. }
  401. }
  402. $unreadcounts[] = array(
  403. 'id' => 'user/-/state/com.google/reading-list',
  404. 'count' => $totalUnreads,
  405. 'newestItemTimestampUsec' => $totalLastUpdate . '000000',
  406. );
  407. echo json_encode(array(
  408. 'max' => $totalUnreads,
  409. 'unreadcounts' => $unreadcounts,
  410. )), "\n";
  411. exit();
  412. }
  413. function streamContents($path, $include_target, $start_time, $count, $order, $exclude_target, $continuation) {
  414. //http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI
  415. //http://blog.martindoms.com/2009/10/16/using-the-google-reader-api-part-2/#feed
  416. //logMe("streamContents($path, $include_target, $start_time, $count, $order, $exclude_target, $continuation)");
  417. header('Content-Type: application/json; charset=UTF-8');
  418. $feedDAO = FreshRSS_Factory::createFeedDao();
  419. $arrayFeedCategoryNames = $feedDAO->arrayFeedCategoryNames();
  420. switch ($path) {
  421. case 'reading-list':
  422. $type = 'A';
  423. break;
  424. case 'starred':
  425. $type = 's';
  426. break;
  427. case 'feed':
  428. $type = 'f';
  429. break;
  430. case 'label':
  431. $type = 'c';
  432. $categoryDAO = new FreshRSS_CategoryDAO();
  433. $cat = $categoryDAO->searchByName($include_target);
  434. $include_target = $cat == null ? -1 : $cat->id();
  435. break;
  436. default:
  437. $type = 'A';
  438. break;
  439. }
  440. switch ($exclude_target) {
  441. case 'user/-/state/com.google/read':
  442. $state = FreshRSS_Entry::STATE_NOT_READ;
  443. break;
  444. case 'user/-/state/com.google/unread':
  445. $state = FreshRSS_Entry::STATE_READ;
  446. break;
  447. default:
  448. $state = FreshRSS_Entry::STATE_ALL;
  449. break;
  450. }
  451. if (!empty($continuation)) {
  452. $count++; //Shift by one element
  453. }
  454. $entryDAO = FreshRSS_Factory::createEntryDao();
  455. $entries = $entryDAO->listWhere($type, $include_target, $state, $order === 'o' ? 'ASC' : 'DESC', $count, $continuation, new FreshRSS_Search(''), $start_time);
  456. $items = array();
  457. foreach ($entries as $entry) {
  458. $f_id = $entry->feed();
  459. if (isset($arrayFeedCategoryNames[$f_id])) {
  460. $c_name = $arrayFeedCategoryNames[$f_id]['c_name'];
  461. $f_name = $arrayFeedCategoryNames[$f_id]['name'];
  462. } else {
  463. $c_name = '_';
  464. $f_name = '_';
  465. }
  466. $item = array(
  467. 'id' => /*'tag:google.com,2005:reader/item/' .*/ dec2hex($entry->id()), //64-bit hexa http://code.google.com/p/google-reader-api/wiki/ItemId
  468. 'crawlTimeMsec' => substr($entry->id(), 0, -3),
  469. 'timestampUsec' => '' . $entry->id(), //EasyRSS
  470. 'published' => $entry->date(true),
  471. 'title' => $entry->title(),
  472. 'summary' => array('content' => $entry->content()),
  473. 'alternate' => array(
  474. array('href' => htmlspecialchars_decode($entry->link(), ENT_QUOTES)),
  475. ),
  476. 'categories' => array(
  477. 'user/-/state/com.google/reading-list',
  478. 'user/-/label/' . $c_name,
  479. ),
  480. 'origin' => array(
  481. 'streamId' => 'feed/' . $f_id,
  482. 'title' => $f_name, //EasyRSS
  483. //'htmlUrl' => $line['f_website'],
  484. ),
  485. );
  486. if ($entry->author() != '') {
  487. $item['author'] = $entry->author();
  488. }
  489. if ($entry->isRead()) {
  490. $item['categories'][] = 'user/-/state/com.google/read';
  491. }
  492. if ($entry->isFavorite()) {
  493. $item['categories'][] = 'user/-/state/com.google/starred';
  494. }
  495. $items[] = $item;
  496. }
  497. if (!empty($continuation)) {
  498. array_shift($items); //Discard first element that was already sent in the previous response
  499. }
  500. $response = array(
  501. 'id' => 'user/-/state/com.google/reading-list',
  502. 'updated' => time(),
  503. 'items' => $items,
  504. );
  505. if ((count($entries) >= $count) && (!empty($entry))) {
  506. $response['continuation'] = $entry->id();
  507. }
  508. echo json_encode($response), "\n";
  509. exit();
  510. }
  511. function streamContentsItemsIds($streamId, $start_time, $count, $order, $exclude_target) {
  512. //http://code.google.com/p/google-reader-api/wiki/ApiStreamItemsIds
  513. //http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI
  514. //http://blog.martindoms.com/2009/10/16/using-the-google-reader-api-part-2/#feed
  515. //logMe("streamContentsItemsIds($streamId, $start_time, $count, $order, $exclude_target)");
  516. $type = 'A';
  517. $id = '';
  518. if ($streamId === 'user/-/state/com.google/reading-list') {
  519. $type = 'A';
  520. } elseif ('user/-/state/com.google/starred') {
  521. $type = 's';
  522. } elseif (strpos($streamId, 'feed/') === 0) {
  523. $type = 'f';
  524. $id = basename($streamId);
  525. } elseif (strpos($streamId, 'user/-/label/') === 0) {
  526. $type = 'c';
  527. $c_name = substr($streamId, 13);
  528. $categoryDAO = new FreshRSS_CategoryDAO();
  529. $cat = $categoryDAO->searchByName($c_name);
  530. $id = $cat == null ? -1 : $cat->id();
  531. }
  532. switch ($exclude_target) {
  533. case 'user/-/state/com.google/read':
  534. $state = FreshRSS_Entry::STATE_NOT_READ;
  535. break;
  536. default:
  537. $state = FreshRSS_Entry::STATE_ALL;
  538. break;
  539. }
  540. $entryDAO = FreshRSS_Factory::createEntryDao();
  541. $ids = $entryDAO->listIdsWhere($type, $id, $state, $order === 'o' ? 'ASC' : 'DESC', $count, '', new FreshRSS_Search(''), $start_time);
  542. if (empty($ids)) { //For News+ bug https://github.com/noinnion/newsplus/issues/84#issuecomment-57834632
  543. $ids[] = 0;
  544. }
  545. $itemRefs = array();
  546. foreach ($ids as $id) {
  547. $itemRefs[] = array(
  548. 'id' => $id, //64-bit decimal
  549. );
  550. }
  551. echo json_encode(array(
  552. 'itemRefs' => $itemRefs,
  553. )), "\n";
  554. exit();
  555. }
  556. function editTag($e_ids, $a, $r) {
  557. //logMe("editTag()");
  558. foreach ($e_ids as $i => $e_id) {
  559. $e_ids[$i] = hex2dec(basename($e_id)); //Strip prefix 'tag:google.com,2005:reader/item/'
  560. }
  561. $entryDAO = FreshRSS_Factory::createEntryDao();
  562. switch ($a) {
  563. case 'user/-/state/com.google/read':
  564. $entryDAO->markRead($e_ids, true);
  565. break;
  566. case 'user/-/state/com.google/starred':
  567. $entryDAO->markFavorite($e_ids, true);
  568. break;
  569. /*case 'user/-/state/com.google/tracking-kept-unread':
  570. break;
  571. case 'user/-/state/com.google/like':
  572. break;
  573. case 'user/-/state/com.google/broadcast':
  574. break;*/
  575. }
  576. switch ($r) {
  577. case 'user/-/state/com.google/read':
  578. $entryDAO->markRead($e_ids, false);
  579. break;
  580. case 'user/-/state/com.google/starred':
  581. $entryDAO->markFavorite($e_ids, false);
  582. break;
  583. }
  584. exit('OK');
  585. }
  586. function renameTag($s, $dest) {
  587. //logMe("renameTag()");
  588. if ($s != '' && strpos($s, 'user/-/label/') === 0 &&
  589. $dest != '' && strpos($dest, 'user/-/label/') === 0) {
  590. $s = substr($s, 13);
  591. $categoryDAO = new FreshRSS_CategoryDAO();
  592. $cat = $categoryDAO->searchByName($s);
  593. if ($cat != null) {
  594. $dest = substr($dest, 13);
  595. $categoryDAO->updateCategory($cat->id(), array('name' => $dest));
  596. exit('OK');
  597. }
  598. }
  599. badRequest();
  600. }
  601. function disableTag($s) {
  602. //logMe("disableTag($s)");
  603. if ($s != '' && strpos($s, 'user/-/label/') === 0) {
  604. $s = substr($s, 13);
  605. $categoryDAO = new FreshRSS_CategoryDAO();
  606. $cat = $categoryDAO->searchByName($s);
  607. if ($cat != null) {
  608. $feedDAO = FreshRSS_Factory::createFeedDao();
  609. $feedDAO->changeCategory($cat->id(), 0);
  610. if ($cat->id() > 1) {
  611. $categoryDAO->deleteCategory($cat->id());
  612. }
  613. exit('OK');
  614. }
  615. }
  616. badRequest();
  617. }
  618. function markAllAsRead($streamId, $olderThanId) {
  619. //logMe("markAllAsRead($streamId, $olderThanId)");
  620. $entryDAO = FreshRSS_Factory::createEntryDao();
  621. if (strpos($streamId, 'feed/') === 0) {
  622. $f_id = basename($streamId);
  623. $entryDAO->markReadFeed($f_id, $olderThanId);
  624. } elseif (strpos($streamId, 'user/-/label/') === 0) {
  625. $c_name = substr($streamId, 13);
  626. $categoryDAO = new FreshRSS_CategoryDAO();
  627. $cat = $categoryDAO->searchByName($c_name);
  628. $entryDAO->markReadCat($cat === null ? -1 : $cat->id(), $olderThanId);
  629. } elseif ($streamId === 'user/-/state/com.google/reading-list') {
  630. $entryDAO->markReadEntries($olderThanId, false, -1);
  631. }
  632. exit('OK');
  633. }
  634. //logMe('----------------------------------------------------------------');
  635. //logMe(debugInfo());
  636. $pathInfo = empty($_SERVER['PATH_INFO']) ? '/Error' : urldecode($_SERVER['PATH_INFO']);
  637. $pathInfos = explode('/', $pathInfo);
  638. Minz_Configuration::register('system',
  639. DATA_PATH . '/config.php',
  640. FRESHRSS_PATH . '/config.default.php');
  641. FreshRSS_Context::$system_conf = Minz_Configuration::get('system');
  642. if (!FreshRSS_Context::$system_conf->api_enabled) {
  643. serviceUnavailable();
  644. }
  645. Minz_Session::init('FreshRSS');
  646. $user = authorizationToUser();
  647. FreshRSS_Context::$user_conf = null;
  648. if ($user !== '') {
  649. FreshRSS_Context::$user_conf = get_user_configuration($user);
  650. }
  651. //logMe('User => ' . $user);
  652. Minz_Session::_param('currentUser', $user);
  653. if (count($pathInfos) < 3) {
  654. badRequest();
  655. } elseif ($pathInfos[1] === 'accounts') {
  656. if (($pathInfos[2] === 'ClientLogin') && isset($_REQUEST['Email']) && isset($_REQUEST['Passwd'])) {
  657. clientLogin($_REQUEST['Email'], $_REQUEST['Passwd']);
  658. }
  659. } elseif ($pathInfos[1] === 'reader' && $pathInfos[2] === 'api' && isset($pathInfos[3]) && $pathInfos[3] === '0' && isset($pathInfos[4])) {
  660. if ($user == '') {
  661. unauthorized();
  662. }
  663. $timestamp = isset($_GET['ck']) ? intval($_GET['ck']) : 0; //ck=[unix timestamp] : Use the current Unix time here, helps Google with caching.
  664. switch ($pathInfos[4]) {
  665. case 'stream':
  666. /* xt=[exclude target] : Used to exclude certain items from the feed.
  667. * For example, using xt=user/-/state/com.google/read will exclude items
  668. * that the current user has marked as read, or xt=feed/[feedurl] will
  669. * exclude items from a particular feed (obviously not useful in this
  670. * request, but xt appears in other listing requests). */
  671. $exclude_target = isset($_GET['xt']) ? $_GET['xt'] : '';
  672. $count = isset($_GET['n']) ? intval($_GET['n']) : 20; //n=[integer] : The maximum number of results to return.
  673. $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.
  674. /* ot=[unix timestamp] : The time from which you want to retrieve
  675. * items. Only items that have been crawled by Google Reader after
  676. * this time will be returned. */
  677. $start_time = isset($_GET['ot']) ? intval($_GET['ot']) : 0;
  678. /* Continuation token. If a StreamContents response does not represent
  679. * all items in a timestamp range, it will have a continuation attribute.
  680. * The same request can be re-issued with the value of that attribute put
  681. * in this parameter to get more items */
  682. $continuation = isset($_GET['c']) ? $_GET['c'] : '';
  683. if (isset($pathInfos[5]) && $pathInfos[5] === 'contents' && isset($pathInfos[6])) {
  684. if (isset($pathInfos[7])) {
  685. if ($pathInfos[6] === 'feed') {
  686. $include_target = $pathInfos[7];
  687. StreamContents($pathInfos[6], $include_target, $start_time, $count, $order, $exclude_target, $continuation);
  688. } elseif ($pathInfos[6] === 'user' && isset($pathInfos[8]) && isset($pathInfos[9])) {
  689. if ($pathInfos[8] === 'state') {
  690. if ($pathInfos[9] === 'com.google' && isset($pathInfos[10])) {
  691. if ($pathInfos[10] === 'reading-list' || $pathInfos[10] === 'starred') {
  692. $include_target = '';
  693. streamContents($pathInfos[10], $include_target, $start_time, $count, $order, $exclude_target, $continuation);
  694. }
  695. }
  696. } elseif ($pathInfos[8] === 'label') {
  697. $include_target = $pathInfos[9];
  698. streamContents($pathInfos[8], $include_target, $start_time, $count, $order, $exclude_target, $continuation);
  699. }
  700. }
  701. } else { //EasyRSS
  702. $include_target = '';
  703. streamContents('reading-list', $include_target, $start_time, $count, $order, $exclude_target, $continuation);
  704. }
  705. } elseif ($pathInfos[5] === 'items') {
  706. if ($pathInfos[6] === 'ids' && isset($_GET['s'])) {
  707. /* StreamId for which to fetch the item IDs. The parameter may
  708. * be repeated to fetch the item IDs from multiple streams at once
  709. * (more efficient from a backend perspective than multiple requests). */
  710. $streamId = $_GET['s'];
  711. streamContentsItemsIds($streamId, $start_time, $count, $order, $exclude_target);
  712. }
  713. }
  714. break;
  715. case 'tag':
  716. if (isset($pathInfos[5]) && $pathInfos[5] === 'list') {
  717. $output = isset($_GET['output']) ? $_GET['output'] : '';
  718. if ($output !== 'json') notImplemented();
  719. tagList($output);
  720. }
  721. break;
  722. case 'subscription':
  723. if (isset($pathInfos[5])) {
  724. switch ($pathInfos[5]) {
  725. case 'list':
  726. $output = isset($_GET['output']) ? $_GET['output'] : '';
  727. if ($output !== 'json') notImplemented();
  728. subscriptionList($_GET['output']);
  729. break;
  730. case 'edit':
  731. if (isset($_POST['s']) && isset($_POST['ac'])) {
  732. //StreamId to operate on. The parameter may be repeated to edit multiple subscriptions at once
  733. $streamNames = multiplePosts('s');
  734. /* Title to use for the subscription. For the `subscribe` action,
  735. * if not specified then the feed's current title will be used. Can
  736. * be used with the `edit` action to rename a subscription */
  737. $titles = multiplePosts('t');
  738. $action = $_POST['ac']; //Action to perform on the given StreamId. Possible values are `subscribe`, `unsubscribe` and `edit`
  739. $add = isset($_POST['a']) ? $_POST['a'] : ''; //StreamId to add the subscription to (generally a user label)
  740. $remove = isset($_POST['r']) ? $_POST['r'] : ''; //StreamId to remove the subscription from (generally a user label)
  741. subscriptionEdit($streamNames, $titles, $action, $add, $remove);
  742. }
  743. break;
  744. case 'quickadd': //https://github.com/theoldreader/api
  745. if (isset($_GET['quickadd'])) {
  746. quickadd($_GET['quickadd']);
  747. }
  748. break;
  749. }
  750. }
  751. break;
  752. case 'unread-count':
  753. $output = isset($_GET['output']) ? $_GET['output'] : '';
  754. if ($output !== 'json') notImplemented();
  755. $all = isset($_GET['all']) ? $_GET['all'] : '';
  756. unreadCount($all);
  757. break;
  758. case 'edit-tag': //http://blog.martindoms.com/2010/01/20/using-the-google-reader-api-part-3/
  759. $token = isset($_POST['T']) ? trim($_POST['T']) : '';
  760. checkToken(FreshRSS_Context::$user_conf, $token);
  761. $a = isset($_POST['a']) ? $_POST['a'] : ''; //Add: user/-/state/com.google/read user/-/state/com.google/starred
  762. $r = isset($_POST['r']) ? $_POST['r'] : ''; //Remove: user/-/state/com.google/read user/-/state/com.google/starred
  763. $e_ids = multiplePosts('i'); //item IDs
  764. editTag($e_ids, $a, $r);
  765. break;
  766. case 'rename-tag': //https://github.com/theoldreader/api
  767. $token = isset($_POST['T']) ? trim($_POST['T']) : '';
  768. checkToken(FreshRSS_Context::$user_conf, $token);
  769. $s = isset($_POST['s']) ? $_POST['s'] : ''; //user/-/label/Folder
  770. $dest = isset($_POST['dest']) ? $_POST['dest'] : ''; //user/-/label/NewFolder
  771. renameTag($s, $dest);
  772. break;
  773. case 'disable-tag': //https://github.com/theoldreader/api
  774. $token = isset($_POST['T']) ? trim($_POST['T']) : '';
  775. checkToken(FreshRSS_Context::$user_conf, $token);
  776. $s_s = multiplePosts('s');
  777. foreach ($s_s as $s) {
  778. disableTag($s); //user/-/label/Folder
  779. }
  780. break;
  781. case 'mark-all-as-read':
  782. $token = isset($_POST['T']) ? trim($_POST['T']) : '';
  783. checkToken(FreshRSS_Context::$user_conf, $token);
  784. $streamId = $_POST['s']; //StreamId
  785. $ts = isset($_POST['ts']) ? $_POST['ts'] : '0'; //Older than timestamp in nanoseconds
  786. if (!ctype_digit($ts)) {
  787. $ts = '0';
  788. }
  789. markAllAsRead($streamId, $ts);
  790. break;
  791. case 'token':
  792. token(FreshRSS_Context::$user_conf);
  793. break;
  794. case 'user-info':
  795. userInfo();
  796. break;
  797. }
  798. } elseif ($pathInfos[1] === 'check' && $pathInfos[2] === 'compatibility') {
  799. checkCompatibility();
  800. }
  801. badRequest();