greader.php 30 KB

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