greader.php 30 KB

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