greader.php 28 KB

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