greader.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  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');
  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 (function_exists('getallheaders')) {
  44. $ALL_HEADERS = getallheaders();
  45. if (isset($ALL_HEADERS[$headerName])) {
  46. $header = $ALL_HEADERS[$headerName];
  47. }
  48. }
  49. parse_str($header, $pairs);
  50. return isset($pairs[$varName]) ? $pairs[$varName] : null;
  51. }
  52. function multiplePosts($name) { //https://bugs.php.net/bug.php?id=51633
  53. global $ORIGINAL_INPUT;
  54. $inputs = explode('&', $ORIGINAL_INPUT);
  55. $result = array();
  56. $prefix = $name . '=';
  57. $prefixLength = strlen($prefix);
  58. foreach ($inputs as $input) {
  59. if (strpos($input, $prefix) === 0) {
  60. $result[] = urldecode(substr($input, $prefixLength));
  61. }
  62. }
  63. return $result;
  64. }
  65. class MyPDO extends Minz_ModelPdo {
  66. function prepare($sql) {
  67. return $this->bd->prepare(str_replace('%_', $this->prefix, $sql));
  68. }
  69. }
  70. function logMe($text) {
  71. file_put_contents(join_path(USERS_PATH, '_', 'log_api.txt'), $text, FILE_APPEND);
  72. }
  73. function debugInfo() {
  74. if (function_exists('getallheaders')) {
  75. $ALL_HEADERS = getallheaders();
  76. } else { //nginx http://php.net/getallheaders#84262
  77. $ALL_HEADERS = '';
  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(array('date' => date('c'), 'headers' => $ALL_HEADERS, '_SERVER' => $_SERVER, '_GET' => $_GET, '_POST' => $_POST, '_COOKIE' => $_COOKIE, 'INPUT' => $ORIGINAL_INPUT), true);
  86. }
  87. function badRequest() {
  88. logMe("badRequest()\n");
  89. logMe(debugInfo());
  90. header('HTTP/1.1 400 Bad Request');
  91. header('Content-Type: text/plain; charset=UTF-8');
  92. die('Bad Request!');
  93. }
  94. function unauthorized() {
  95. logMe("unauthorized()\n");
  96. logMe(debugInfo());
  97. header('HTTP/1.1 401 Unauthorized');
  98. header('Content-Type: text/plain; charset=UTF-8');
  99. header('Google-Bad-Token: true');
  100. die('Unauthorized!');
  101. }
  102. function notImplemented() {
  103. logMe("notImplemented()\n");
  104. logMe(debugInfo());
  105. header('HTTP/1.1 501 Not Implemented');
  106. header('Content-Type: text/plain; charset=UTF-8');
  107. die('Not Implemented!');
  108. }
  109. function serviceUnavailable() {
  110. logMe("serviceUnavailable()\n");
  111. header('HTTP/1.1 503 Service Unavailable');
  112. header('Content-Type: text/plain; charset=UTF-8');
  113. die('Service Unavailable!');
  114. }
  115. function checkCompatibility() {
  116. logMe("checkCompatibility()\n");
  117. header('Content-Type: text/plain; charset=UTF-8');
  118. if (PHP_INT_SIZE < 8 && !function_exists('gmp_init')) {
  119. die('FAIL 64-bit or GMP extension!');
  120. }
  121. if ((!array_key_exists('HTTP_AUTHORIZATION', $_SERVER)) && //Apache mod_rewrite trick should be fine
  122. (empty($_SERVER['SERVER_SOFTWARE']) || (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') === false)) && //nginx should be fine
  123. (empty($_SERVER['SERVER_SOFTWARE']) || (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') === false)) && //lighttpd should be fine
  124. ((!function_exists('getallheaders')) || (stripos(php_sapi_name(), 'cgi') !== false))) { //Main problem is Apache/CGI mode
  125. die('FAIL getallheaders! (probably)');
  126. }
  127. echo 'PASS';
  128. exit();
  129. }
  130. function authorizationToUserConf() {
  131. $headerAuth = headerVariable('Authorization', 'GoogleLogin_auth'); //Input is 'GoogleLogin auth', but PHP replaces spaces by '_' http://php.net/language.variables.external
  132. if ($headerAuth != '') {
  133. $headerAuthX = explode('/', $headerAuth, 2);
  134. if (count($headerAuthX) === 2) {
  135. $user = $headerAuthX[0];
  136. if (ctype_alnum($user)) {
  137. $conf = get_user_configuration($user);
  138. if (is_null($conf)) {
  139. Minz_Log::warning('Invalid API user ' . $user . ': configuration cannot be found.');
  140. unauthorized();
  141. }
  142. $system_conf = Minz_Configuration::get('system');
  143. if ($headerAuthX[1] === sha1($system_conf->salt . $conf->user . $conf->apiPasswordHash)) {
  144. return $conf;
  145. } else {
  146. logMe('Invalid API authorisation for user ' . $user . ': ' . $headerAuthX[1] . "\n");
  147. Minz_Log::warning('Invalid API authorisation for user ' . $user . ': ' . $headerAuthX[1]);
  148. unauthorized();
  149. }
  150. } else {
  151. badRequest();
  152. }
  153. }
  154. }
  155. return null;
  156. }
  157. function clientLogin($email, $pass) { //http://web.archive.org/web/20130604091042/http://undoc.in/clientLogin.html
  158. logMe('clientLogin(' . $email . ")\n");
  159. if (ctype_alnum($email)) {
  160. if (!function_exists('password_verify')) {
  161. include_once(LIB_PATH . '/password_compat.php');
  162. }
  163. $conf = get_user_configuration($email);
  164. if (is_null($conf)) {
  165. Minz_Log::warning('Invalid API user ' . $email . ': configuration cannot be found.');
  166. unauthorized();
  167. }
  168. if ($conf->apiPasswordHash != '' && password_verify($pass, $conf->apiPasswordHash)) {
  169. header('Content-Type: text/plain; charset=UTF-8');
  170. $system_conf = Minz_Configuration::get('system');
  171. $auth = $email . '/' . sha1($system_conf->salt . $conf->user . $conf->apiPasswordHash);
  172. echo 'SID=', $auth, "\n",
  173. 'Auth=', $auth, "\n";
  174. exit();
  175. } else {
  176. Minz_Log::warning('Password API mismatch for user ' . $email);
  177. unauthorized();
  178. }
  179. } else {
  180. badRequest();
  181. }
  182. die();
  183. }
  184. function token($conf) {
  185. //http://blog.martindoms.com/2009/08/15/using-the-google-reader-api-part-1/
  186. //https://github.com/ericmann/gReader-Library/blob/master/greader.class.php
  187. logMe('token('. $conf->user . ")\n"); //TODO: Implement real token that expires
  188. $system_conf = Minz_Configuration::get('system');
  189. $token = str_pad(sha1($system_conf->salt . $conf->user . $conf->apiPasswordHash), 57, 'Z'); //Must have 57 characters
  190. echo $token, "\n";
  191. exit();
  192. }
  193. function checkToken($conf, $token) {
  194. //http://code.google.com/p/google-reader-api/wiki/ActionToken
  195. logMe('checkToken(' . $token . ")\n");
  196. $system_conf = Minz_Configuration::get('system');
  197. if ($token === str_pad(sha1($system_conf->salt . $conf->user . $conf->apiPasswordHash), 57, 'Z')) {
  198. return true;
  199. }
  200. unauthorized();
  201. }
  202. function tagList() {
  203. logMe("tagList()\n");
  204. header('Content-Type: application/json; charset=UTF-8');
  205. $pdo = new MyPDO();
  206. $stm = $pdo->prepare('SELECT c.name FROM `%_category` c');
  207. $stm->execute();
  208. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  209. $tags = array(
  210. array('id' => 'user/-/state/com.google/starred'),
  211. //array('id' => 'user/-/state/com.google/broadcast', 'sortid' => '2'),
  212. );
  213. foreach ($res as $cName) {
  214. $tags[] = array(
  215. 'id' => 'user/-/label/' . $cName,
  216. //'sortid' => $cName,
  217. );
  218. }
  219. echo json_encode(array('tags' => $tags)), "\n";
  220. exit();
  221. }
  222. function subscriptionList() {
  223. logMe("subscriptionList()\n");
  224. header('Content-Type: application/json; charset=UTF-8');
  225. $pdo = new MyPDO();
  226. $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
  227. INNER JOIN `%_category` c ON c.id = f.category');
  228. $stm->execute();
  229. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  230. $subscriptions = array();
  231. foreach ($res as $line) {
  232. $subscriptions[] = array(
  233. 'id' => 'feed/' . $line['id'],
  234. 'title' => $line['name'],
  235. 'categories' => array(
  236. array(
  237. 'id' => 'user/-/label/' . $line['c_name'],
  238. 'label' => $line['c_name'],
  239. ),
  240. ),
  241. //'sortid' => $line['name'],
  242. //'firstitemmsec' => 0,
  243. 'url' => $line['url'],
  244. 'htmlUrl' => $line['website'],
  245. //'iconUrl' => '',
  246. );
  247. }
  248. echo json_encode(array('subscriptions' => $subscriptions)), "\n";
  249. exit();
  250. }
  251. function unreadCount() { //http://blog.martindoms.com/2009/10/16/using-the-google-reader-api-part-2/#unread-count
  252. logMe("unreadCount()\n");
  253. header('Content-Type: application/json; charset=UTF-8');
  254. $totalUnreads = 0;
  255. $totalLastUpdate = 0;
  256. $categoryDAO = new FreshRSS_CategoryDAO();
  257. foreach ($categoryDAO->listCategories(true, true) as $cat) {
  258. $catLastUpdate = 0;
  259. foreach ($cat->feeds() as $feed) {
  260. $lastUpdate = $feed->lastUpdate();
  261. $unreadcounts[] = array(
  262. 'id' => 'feed/' . $feed->id(),
  263. 'count' => $feed->nbNotRead(),
  264. 'newestItemTimestampUsec' => $lastUpdate . '000000',
  265. );
  266. if ($catLastUpdate < $lastUpdate) {
  267. $catLastUpdate = $lastUpdate;
  268. }
  269. }
  270. $unreadcounts[] = array(
  271. 'id' => 'user/-/label/' . $cat->name(),
  272. 'count' => $cat->nbNotRead(),
  273. 'newestItemTimestampUsec' => $catLastUpdate . '000000',
  274. );
  275. $totalUnreads += $cat->nbNotRead();
  276. if ($totalLastUpdate < $catLastUpdate) {
  277. $totalLastUpdate = $catLastUpdate;
  278. }
  279. }
  280. $unreadcounts[] = array(
  281. 'id' => 'user/-/state/com.google/reading-list',
  282. 'count' => $totalUnreads,
  283. 'newestItemTimestampUsec' => $totalLastUpdate . '000000',
  284. );
  285. echo json_encode(array(
  286. 'max' => $totalUnreads,
  287. 'unreadcounts' => $unreadcounts,
  288. )), "\n";
  289. exit();
  290. }
  291. function streamContents($path, $include_target, $start_time, $count, $order, $exclude_target, $continuation) {
  292. //http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI
  293. //http://blog.martindoms.com/2009/10/16/using-the-google-reader-api-part-2/#feed
  294. logMe("streamContents($path, $include_target, $start_time, $count, $order, $exclude_target, $continuation)\n");
  295. header('Content-Type: application/json; charset=UTF-8');
  296. $feedDAO = FreshRSS_Factory::createFeedDao();
  297. $arrayFeedCategoryNames = $feedDAO->arrayFeedCategoryNames();
  298. switch ($path) {
  299. case 'reading-list':
  300. $type = 'A';
  301. break;
  302. case 'starred':
  303. $type = 's';
  304. break;
  305. case 'feed':
  306. $type = 'f';
  307. break;
  308. case 'label':
  309. $type = 'c';
  310. $categoryDAO = new FreshRSS_CategoryDAO();
  311. $cat = $categoryDAO->searchByName($include_target);
  312. $include_target = $cat == null ? -1 : $cat->id();
  313. break;
  314. default:
  315. $type = 'A';
  316. break;
  317. }
  318. switch ($exclude_target) {
  319. case 'user/-/state/com.google/read':
  320. $state = FreshRSS_Entry::STATE_NOT_READ;
  321. break;
  322. default:
  323. $state = FreshRSS_Entry::STATE_ALL;
  324. break;
  325. }
  326. if (!empty($continuation)) {
  327. $count++; //Shift by one element
  328. }
  329. $entryDAO = FreshRSS_Factory::createEntryDao();
  330. $entries = $entryDAO->listWhere($type, $include_target, $state, $order === 'o' ? 'ASC' : 'DESC', $count, $continuation, '', $start_time);
  331. $items = array();
  332. foreach ($entries as $entry) {
  333. $f_id = $entry->feed();
  334. if (isset($arrayFeedCategoryNames[$f_id])) {
  335. $c_name = $arrayFeedCategoryNames[$f_id]['c_name'];
  336. $f_name = $arrayFeedCategoryNames[$f_id]['name'];
  337. } else {
  338. $c_name = '_';
  339. $f_name = '_';
  340. }
  341. $item = array(
  342. 'id' => /*'tag:google.com,2005:reader/item/' .*/ dec2hex($entry->id()), //64-bit hexa http://code.google.com/p/google-reader-api/wiki/ItemId
  343. 'crawlTimeMsec' => substr($entry->id(), 0, -3),
  344. 'timestampUsec' => $entry->id(), //EasyRSS
  345. 'published' => $entry->date(true),
  346. 'title' => $entry->title(),
  347. 'summary' => array('content' => $entry->content()),
  348. 'alternate' => array(
  349. array('href' => $entry->link()),
  350. ),
  351. 'categories' => array(
  352. 'user/-/state/com.google/reading-list',
  353. 'user/-/label/' . $c_name,
  354. ),
  355. 'origin' => array(
  356. 'streamId' => 'feed/' . $f_id,
  357. 'title' => $f_name, //EasyRSS
  358. //'htmlUrl' => $line['f_website'],
  359. ),
  360. );
  361. if ($entry->author() != '') {
  362. $item['author'] = $entry->author();
  363. }
  364. if ($entry->isRead()) {
  365. $item['categories'][] = 'user/-/state/com.google/read';
  366. }
  367. if ($entry->isFavorite()) {
  368. $item['categories'][] = 'user/-/state/com.google/starred';
  369. }
  370. $items[] = $item;
  371. }
  372. if (!empty($continuation)) {
  373. array_shift($items); //Discard first element that was already sent in the previous response
  374. }
  375. $response = array(
  376. 'id' => 'user/-/state/com.google/reading-list',
  377. 'updated' => time(),
  378. 'items' => $items,
  379. );
  380. if ((count($entries) >= $count) && (!empty($entry))) {
  381. $response['continuation'] = $entry->id();
  382. }
  383. echo json_encode($response), "\n";
  384. exit();
  385. }
  386. function streamContentsItemsIds($streamId, $start_time, $count, $order, $exclude_target) {
  387. //http://code.google.com/p/google-reader-api/wiki/ApiStreamItemsIds
  388. //http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI
  389. //http://blog.martindoms.com/2009/10/16/using-the-google-reader-api-part-2/#feed
  390. logMe("streamContentsItemsIds($streamId, $start_time, $count, $order, $exclude_target)\n");
  391. $type = 'A';
  392. $id = '';
  393. if ($streamId === 'user/-/state/com.google/reading-list') {
  394. $type = 'A';
  395. } elseif ('user/-/state/com.google/starred') {
  396. $type = 's';
  397. } elseif (strpos($streamId, 'feed/') === 0) {
  398. $type = 'f';
  399. $id = basename($streamId);
  400. } elseif (strpos($streamId, 'user/-/label/') === 0) {
  401. $type = 'c';
  402. $c_name = basename($streamId);
  403. $categoryDAO = new FreshRSS_CategoryDAO();
  404. $cat = $categoryDAO->searchByName($c_name);
  405. $id = $cat == null ? -1 : $cat->id();
  406. }
  407. switch ($exclude_target) {
  408. case 'user/-/state/com.google/read':
  409. $state = FreshRSS_Entry::STATE_NOT_READ;
  410. break;
  411. default:
  412. $state = FreshRSS_Entry::STATE_ALL;
  413. break;
  414. }
  415. $entryDAO = FreshRSS_Factory::createEntryDao();
  416. $ids = $entryDAO->listIdsWhere($type, $id, $state, $order === 'o' ? 'ASC' : 'DESC', $count, '', '', $start_time);
  417. $itemRefs = array();
  418. foreach ($ids as $id) {
  419. $itemRefs[] = array(
  420. 'id' => $id, //64-bit decimal
  421. );
  422. }
  423. echo json_encode(array(
  424. 'itemRefs' => $itemRefs,
  425. )), "\n";
  426. exit();
  427. }
  428. function editTag($e_ids, $a, $r) {
  429. logMe("editTag()\n");
  430. foreach ($e_ids as $i => $e_id) {
  431. $e_ids[$i] = hex2dec(basename($e_id)); //Strip prefix 'tag:google.com,2005:reader/item/'
  432. }
  433. $entryDAO = FreshRSS_Factory::createEntryDao();
  434. switch ($a) {
  435. case 'user/-/state/com.google/read':
  436. $entryDAO->markRead($e_ids, true);
  437. break;
  438. case 'user/-/state/com.google/starred':
  439. $entryDAO->markFavorite($e_ids, true);
  440. break;
  441. /*case 'user/-/state/com.google/tracking-kept-unread':
  442. break;
  443. case 'user/-/state/com.google/like':
  444. break;
  445. case 'user/-/state/com.google/broadcast':
  446. break;*/
  447. }
  448. switch ($r) {
  449. case 'user/-/state/com.google/read':
  450. $entryDAO->markRead($e_ids, false);
  451. break;
  452. case 'user/-/state/com.google/starred':
  453. $entryDAO->markFavorite($e_ids, false);
  454. break;
  455. }
  456. echo 'OK';
  457. exit();
  458. }
  459. function markAllAsRead($streamId, $olderThanId) {
  460. logMe("markAllAsRead($streamId, $olderThanId)\n");
  461. $entryDAO = FreshRSS_Factory::createEntryDao();
  462. if (strpos($streamId, 'feed/') === 0) {
  463. $f_id = basename($streamId);
  464. $entryDAO->markReadFeed($f_id, $olderThanId);
  465. } elseif (strpos($streamId, 'user/-/label/') === 0) {
  466. $c_name = basename($streamId);
  467. $categoryDAO = new FreshRSS_CategoryDAO();
  468. $cat = $categoryDAO->searchByName($c_name);
  469. $entryDAO->markReadCat($cat === null ? -1 : $cat->id(), $olderThanId);
  470. } elseif ($streamId === 'user/-/state/com.google/reading-list') {
  471. $entryDAO->markReadEntries($olderThanId, false, -1);
  472. }
  473. echo 'OK';
  474. exit();
  475. }
  476. logMe('----------------------------------------------------------------'."\n");
  477. //logMe(debugInfo());
  478. $pathInfo = empty($_SERVER['PATH_INFO']) ? '/Error' : urldecode($_SERVER['PATH_INFO']);
  479. $pathInfos = explode('/', $pathInfo);
  480. Minz_Configuration::register('system',
  481. DATA_PATH . '/config.php',
  482. DATA_PATH . '/config.default.php');
  483. $system_conf = Minz_Configuration::get('system');
  484. if (!$system_conf->api_enabled) {
  485. serviceUnavailable();
  486. }
  487. Minz_Session::init('FreshRSS');
  488. $conf = authorizationToUserConf();
  489. $user = $conf == null ? '' : $conf->user;
  490. logMe('User => ' . $user . "\n");
  491. Minz_Session::_param('currentUser', $user);
  492. if (count($pathInfos) < 3) {
  493. badRequest();
  494. }
  495. elseif ($pathInfos[1] === 'accounts') {
  496. if (($pathInfos[2] === 'ClientLogin') && isset($_REQUEST['Email']) && isset($_REQUEST['Passwd'])) {
  497. clientLogin($_REQUEST['Email'], $_REQUEST['Passwd']);
  498. }
  499. }
  500. elseif ($pathInfos[1] === 'reader' && $pathInfos[2] === 'api' && isset($pathInfos[3]) && $pathInfos[3] === '0' && isset($pathInfos[4])) {
  501. if ($user == '') {
  502. unauthorized();
  503. }
  504. $timestamp = isset($_GET['ck']) ? intval($_GET['ck']) : 0; //ck=[unix timestamp] : Use the current Unix time here, helps Google with caching.
  505. switch ($pathInfos[4]) {
  506. case 'stream':
  507. $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).
  508. $count = isset($_GET['n']) ? intval($_GET['n']) : 20; //n=[integer] : The maximum number of results to return.
  509. $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.
  510. $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.
  511. $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
  512. if (isset($pathInfos[5]) && $pathInfos[5] === 'contents' && isset($pathInfos[6])) {
  513. if (isset($pathInfos[7])) {
  514. if ($pathInfos[6] === 'feed') {
  515. $include_target = $pathInfos[7];
  516. StreamContents($pathInfos[6], $include_target, $start_time, $count, $order, $exclude_target, $continuation);
  517. } elseif ($pathInfos[6] === 'user' && isset($pathInfos[8]) && isset($pathInfos[9])) {
  518. if ($pathInfos[8] === 'state') {
  519. if ($pathInfos[9] === 'com.google' && isset($pathInfos[10])) {
  520. if ($pathInfos[10] === 'reading-list' || $pathInfos[10] === 'starred') {
  521. $include_target = '';
  522. streamContents($pathInfos[10], $include_target, $start_time, $count, $order, $exclude_target, $continuation);
  523. }
  524. }
  525. } elseif ($pathInfos[8] === 'label') {
  526. $include_target = $pathInfos[9];
  527. streamContents($pathInfos[8], $include_target, $start_time, $count, $order, $exclude_target, $continuation);
  528. }
  529. }
  530. } else { //EasyRSS
  531. $include_target = '';
  532. streamContents('reading-list', $include_target, $start_time, $count, $order, $exclude_target, $continuation);
  533. }
  534. } elseif ($pathInfos[5] === 'items') {
  535. if ($pathInfos[6] === 'ids' && isset($_GET['s'])) {
  536. $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).
  537. streamContentsItemsIds($streamId, $start_time, $count, $order, $exclude_target);
  538. }
  539. }
  540. break;
  541. case 'tag':
  542. if (isset($pathInfos[5]) && $pathInfos[5] === 'list') {
  543. $output = isset($_GET['output']) ? $_GET['output'] : '';
  544. if ($output !== 'json') notImplemented();
  545. tagList($_GET['output']);
  546. }
  547. break;
  548. case 'subscription':
  549. if (isset($pathInfos[5]) && $pathInfos[5] === 'list') {
  550. $output = isset($_GET['output']) ? $_GET['output'] : '';
  551. if ($output !== 'json') notImplemented();
  552. subscriptionList($_GET['output']);
  553. }
  554. break;
  555. case 'unread-count':
  556. $output = isset($_GET['output']) ? $_GET['output'] : '';
  557. if ($output !== 'json') notImplemented();
  558. $all = isset($_GET['all']) ? $_GET['all'] : '';
  559. unreadCount($all);
  560. break;
  561. case 'edit-tag': //http://blog.martindoms.com/2010/01/20/using-the-google-reader-api-part-3/
  562. $token = isset($_POST['T']) ? trim($_POST['T']) : '';
  563. checkToken($conf, $token);
  564. $a = isset($_POST['a']) ? $_POST['a'] : ''; //Add: user/-/state/com.google/read user/-/state/com.google/starred
  565. $r = isset($_POST['r']) ? $_POST['r'] : ''; //Remove: user/-/state/com.google/read user/-/state/com.google/starred
  566. $e_ids = multiplePosts('i'); //item IDs
  567. editTag($e_ids, $a, $r);
  568. break;
  569. case 'mark-all-as-read':
  570. $token = isset($_POST['T']) ? trim($_POST['T']) : '';
  571. checkToken($conf, $token);
  572. $streamId = $_POST['s']; //StreamId
  573. $ts = isset($_POST['ts']) ? $_POST['ts'] : '0'; //Older than timestamp in nanoseconds
  574. if (!ctype_digit($ts)) {
  575. $ts = '0';
  576. }
  577. markAllAsRead($streamId, $ts);
  578. break;
  579. case 'token':
  580. Token($conf);
  581. break;
  582. }
  583. } elseif ($pathInfos[1] === 'check' && $pathInfos[2] === 'compatibility') {
  584. checkCompatibility();
  585. }
  586. badRequest();