greader.php 28 KB

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