greader.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  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-02: 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. define('TEMP_PASSWORD', 'temp123'); //Change to another ASCII password
  21. require('../../constants.php');
  22. require(LIB_PATH . '/lib_rss.php'); //Includes class autoloader
  23. $ORIGINAL_INPUT = file_get_contents('php://input');
  24. $ALL_HEADERS = getallheaders();
  25. $debugInfo = array('date' => date('c'), 'headers' => $ALL_HEADERS, '_SERVER' => $_SERVER, '_GET' => $_GET, '_POST' => $_POST, '_COOKIE' => $_COOKIE, 'INPUT' => $ORIGINAL_INPUT);
  26. if (PHP_INT_SIZE < 8) { //32-bit
  27. function dec2hex($dec) {
  28. return str_pad(gmp_strval(gmp_init($dec, 10), 16), 16, '0', STR_PAD_LEFT);
  29. }
  30. function hex2dec($hex) {
  31. return gmp_strval(gmp_init($hex, 16), 10);
  32. }
  33. } else { //64-bit
  34. function dec2hex($dec) { //http://code.google.com/p/google-reader-api/wiki/ItemId
  35. return str_pad(dechex($dec), 16, '0', STR_PAD_LEFT);
  36. }
  37. function hex2dec($hex) {
  38. return hexdec($hex);
  39. }
  40. }
  41. function headerVariable($headerName, $varName) {
  42. global $ALL_HEADERS;
  43. if (empty($ALL_HEADERS[$headerName])) {
  44. return null;
  45. }
  46. parse_str($ALL_HEADERS[$headerName], $pairs);
  47. //logMe('headerVariable(' . $headerName . ') => ' . print_r($pairs, true));
  48. return isset($pairs[$varName]) ? $pairs[$varName] : null;
  49. }
  50. function multiplePosts($name) { //https://bugs.php.net/bug.php?id=51633
  51. global $ORIGINAL_INPUT;
  52. $inputs = explode('&', $ORIGINAL_INPUT);
  53. $result = array();
  54. $prefix = $name . '=';
  55. $prefixLength = strlen($prefix);
  56. foreach ($inputs as $input) {
  57. if (strpos($input, $prefix) === 0) {
  58. $result[] = urldecode(substr($input, $prefixLength));
  59. }
  60. }
  61. return $result;
  62. }
  63. class MyPDO extends Minz_ModelPdo {
  64. function prepare($sql) {
  65. return $this->bd->prepare(str_replace('%_', $this->prefix, $sql));
  66. }
  67. }
  68. function logMe($text) {
  69. file_put_contents(LOG_PATH . '/api.log', $text, FILE_APPEND);
  70. }
  71. function badRequest() {
  72. logMe("badRequest()\n");
  73. header('HTTP/1.1 400 Bad Request');
  74. header('Content-Type: text/plain; charset=UTF-8');
  75. die('Bad Request!');
  76. }
  77. function unauthorized() {
  78. logMe("unauthorized()\n");
  79. header('HTTP/1.1 401 Unauthorized');
  80. header('Content-Type: text/plain; charset=UTF-8');
  81. header('Google-Bad-Token: true');
  82. die('Unauthorized!');
  83. }
  84. function notImplemented() {
  85. logMe("notImplemented()\n");
  86. header('HTTP/1.1 501 Not Implemented');
  87. header('Content-Type: text/plain; charset=UTF-8');
  88. die('Not Implemented!');
  89. }
  90. function serviceUnavailable() {
  91. logMe("serviceUnavailable()\n");
  92. header('HTTP/1.1 503 Service Unavailable');
  93. header('Content-Type: text/plain; charset=UTF-8');
  94. die('Service Unavailable!');
  95. }
  96. function checkCompatibility() {
  97. logMe("checkCompatibility()\n");
  98. header('Content-Type: text/plain; charset=UTF-8');
  99. $ok = true;
  100. $ok &= function_exists('getallheaders');
  101. echo $ok ? 'PASS' : 'FAIL';
  102. exit();
  103. }
  104. function authorizationToUser() {
  105. $auth = headerVariable('Authorization', 'GoogleLogin_auth'); //Input is 'GoogleLogin auth', but PHP replaces spaces by '_' http://php.net/language.variables.external
  106. //logMe('authorizationToUser, auth => ' . $auth . "\n");
  107. list($userName) = explode('/', $auth);
  108. return $userName;
  109. }
  110. function clientLogin($email, $pass) { //http://web.archive.org/web/20130604091042/http://undoc.in/clientLogin.html
  111. logMe('clientLogin(' . $email . ")\n");
  112. if ($pass !== TEMP_PASSWORD) {
  113. unauthorized();
  114. }
  115. header('Content-Type: text/plain; charset=UTF-8');
  116. $auth = $email . '/' . '0123456789';
  117. echo 'SID=', $auth, "\n",
  118. 'Auth=', $auth, "\n";
  119. exit();
  120. }
  121. function token($user) {
  122. //http://blog.martindoms.com/2009/08/15/using-the-google-reader-api-part-1/ https://github.com/ericmann/gReader-Library/blob/master/greader.class.php
  123. logMe('token('. $user . ")\n");
  124. $token = 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ01234'; //Must have 57 characters...
  125. echo $token, "\n";
  126. exit();
  127. }
  128. function checkToken($user, $token) {
  129. //http://code.google.com/p/google-reader-api/wiki/ActionToken
  130. logMe('checkToken(' . $token . ")\n");
  131. if ($token === 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ01234') {
  132. return true;
  133. }
  134. unauthorized();
  135. }
  136. function tagList() {
  137. logMe("tagList()\n");
  138. header('Content-Type: application/json; charset=UTF-8');
  139. $pdo = new MyPDO();
  140. $stm = $pdo->prepare('SELECT c.name FROM `%_category` c');
  141. $stm->execute();
  142. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  143. $tags = array(
  144. array('id' => 'user/-/state/com.google/starred'),
  145. //array('id' => 'user/-/state/com.google/broadcast', 'sortid' => '2'),
  146. );
  147. foreach ($res as $cName) {
  148. $tags[] = array(
  149. 'id' => 'user/-/label/' . $cName,
  150. //'sortid' => $cName,
  151. );
  152. }
  153. echo json_encode(array('tags' => $tags)), "\n";
  154. exit();
  155. }
  156. function subscriptionList() {
  157. logMe("subscriptionList()\n");
  158. header('Content-Type: application/json; charset=UTF-8');
  159. $pdo = new MyPDO();
  160. $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
  161. INNER JOIN `%_category` c ON c.id = f.category');
  162. $stm->execute();
  163. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  164. $subscriptions = array();
  165. foreach ($res as $line) {
  166. $subscriptions[] = array(
  167. 'id' => 'feed/' . $line['id'],
  168. 'title' => $line['name'],
  169. 'categories' => array(
  170. array(
  171. 'id' => 'user/-/label/' . $line['c_name'],
  172. 'label' => $line['c_name'],
  173. ),
  174. ),
  175. //'sortid' => $line['name'],
  176. //'firstitemmsec' => 0,
  177. 'url' => $line['url'],
  178. 'htmlUrl' => $line['website'],
  179. //'iconUrl' => '',
  180. );
  181. }
  182. echo json_encode(array('subscriptions' => $subscriptions)), "\n";
  183. exit();
  184. }
  185. function unreadCount() {
  186. logMe("unreadCount()\n");
  187. header('Content-Type: application/json; charset=UTF-8');
  188. $pdo = new MyPDO();
  189. $stm = $pdo->prepare('SELECT f.id, f.lastUpdate, f.cache_nbUnreads FROM `%_feed` f');
  190. $stm->execute();
  191. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  192. $unreadcounts = array();
  193. $totalUnreads = 0;
  194. $totalLastUpdate = 0;
  195. foreach ($res as $line) {
  196. $nbUnreads = $line['cache_nbUnreads'];
  197. $totalUnreads += $nbUnreads;
  198. $lastUpdate = $line['lastUpdate'];
  199. if ($totalLastUpdate < $lastUpdate) {
  200. $totalLastUpdate = $lastUpdate;
  201. }
  202. $unreadcounts[] = array(
  203. 'id' => 'feed/' . $line['id'],
  204. 'count' => $nbUnreads,
  205. 'newestItemTimestampUsec' => $lastUpdate . '000000',
  206. );
  207. }
  208. $unreadcounts[] = array(
  209. 'id' => 'user/-/state/com.google/reading-list',
  210. 'count' => $totalUnreads,
  211. 'newestItemTimestampUsec' => $totalLastUpdate . '000000',
  212. );
  213. echo json_encode(array(
  214. 'max' => $totalUnreads,
  215. 'unreadcounts' => $unreadcounts,
  216. )), "\n";
  217. exit();
  218. }
  219. function streamContents($path, $include_target, $start_time, $count, $order, $exclude_target)
  220. {//http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI http://blog.martindoms.com/2009/10/16/using-the-google-reader-api-part-2/#feed
  221. logMe('streamContents(' . $include_target . ")\n");
  222. header('Content-Type: application/json; charset=UTF-8');
  223. $feedDAO = new FreshRSS_FeedDAO();
  224. $feedCategoryNames = $feedDAO->listCategoryNames();
  225. switch ($path) {
  226. case 'reading-list':
  227. $type = 'A';
  228. break;
  229. case 'starred':
  230. $type = 's';
  231. break;
  232. case 'label':
  233. $type = 'c';
  234. break;
  235. default:
  236. $type = 'A';
  237. break;
  238. }
  239. switch ($exclude_target) {
  240. case 'user/-/state/com.google/read':
  241. $state = 'not_read';
  242. break;
  243. default:
  244. $state = 'all';
  245. break;
  246. }
  247. $entryDAO = new FreshRSS_EntryDAO();
  248. $entries = $entryDAO->listWhere($type, $include_target, $state, $order === 'o' ? 'ASC' : 'DESC', $count, '', '', $start_time);
  249. $items = array();
  250. foreach ($entries as $entry) {
  251. $f_id = $entry->feed();
  252. $c_name = isset($feedCategoryNames[$f_id]) ? $feedCategoryNames[$f_id] : '_';
  253. $item = array(
  254. 'id' => /*'tag:google.com,2005:reader/item/' .*/ dec2hex($entry->id()), //64-bit hexa http://code.google.com/p/google-reader-api/wiki/ItemId
  255. 'crawlTimeMsec' => substr($entry->id(), 0, -3),
  256. 'published' => $entry->date(true),
  257. 'title' => $entry->title(),
  258. 'summary' => array('content' => $entry->content()),
  259. 'alternate' => array(
  260. array('href' => $entry->link()),
  261. ),
  262. 'categories' => array(
  263. 'user/-/state/com.google/reading-list',
  264. 'user/-/label/' . $c_name,
  265. ),
  266. 'origin' => array(
  267. 'streamId' => 'feed/' . $f_id,
  268. //'title' => $line['f_name'],
  269. //'htmlUrl' => $line['f_website'],
  270. ),
  271. );
  272. if ($entry->author() != '') {
  273. $item['author'] = $entry->author();
  274. }
  275. if ($entry->isRead()) {
  276. $item['categories'][] = 'user/-/state/com.google/read';
  277. }
  278. if ($entry->isFavorite()) {
  279. $item['categories'][] = 'user/-/state/com.google/starred';
  280. }
  281. $items[] = $item;
  282. }
  283. echo json_encode(array(
  284. 'id' => 'user/-/state/com.google/reading-list',
  285. 'updated' => time(),
  286. 'items' => $items,
  287. )), "\n";
  288. exit();
  289. }
  290. function streamContentsItemsIds($streamId, $start_time, $count, $order, $exclude_target)
  291. {//http://code.google.com/p/google-reader-api/wiki/ApiStreamItemsIds http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI http://blog.martindoms.com/2009/10/16/using-the-google-reader-api-part-2/#feed
  292. logMe('streamContentsItemsIds(' . $streamId . ")\n");
  293. $type = 'A';
  294. $id = '';
  295. if ($streamId === 'user/-/state/com.google/reading-list') {
  296. $type = 'A';
  297. } elseif ('user/-/state/com.google/starred') {
  298. $type = 's';
  299. } elseif (strpos($streamId, 'feed/') === 0) {
  300. $type = 'f';
  301. $id = basename($streamId);
  302. } elseif (strpos($streamId, 'user/-/label/') === 0) {
  303. $type = 'C';
  304. $c_name = basename($streamId);
  305. notImplemented(); //TODO
  306. }
  307. switch ($exclude_target) {
  308. case 'user/-/state/com.google/read':
  309. $state = 'not_read';
  310. break;
  311. default:
  312. $state = 'all';
  313. break;
  314. }
  315. $entryDAO = new FreshRSS_EntryDAO();
  316. $entries = $entryDAO->listWhere($type, $id, $state, $order === 'o' ? 'ASC' : 'DESC', $count, '', '', $start_time);
  317. $itemRefs = array();
  318. foreach ($entries as $entry) {
  319. $f_id = $entry->feed();
  320. $itemRefs[] = array(
  321. 'id' => $entry->id(), //64-bit decimal
  322. //'timestampUsec' => $entry->dateAdded(true),
  323. /*'directStreamIds' => array(
  324. 'feed/' . $entry->feed()
  325. ),*/
  326. );
  327. }
  328. echo json_encode(array(
  329. 'itemRefs' => $itemRefs,
  330. )), "\n";
  331. exit();
  332. }
  333. function editTag($e_ids, $a, $r) {
  334. logMe("editTag()\n");
  335. $entryDAO = new FreshRSS_EntryDAO();
  336. foreach ($e_ids as $e_id) { //TODO: User WHERE...IN
  337. $e_id = hex2dec(basename($e_id)); //Strip prefix 'tag:google.com,2005:reader/item/'
  338. switch ($a) {
  339. case 'user/-/state/com.google/read':
  340. $entryDAO->markRead($e_id, true);
  341. break;
  342. case 'user/-/state/com.google/starred':
  343. $entryDAO->markFavorite($e_id, true);
  344. break;
  345. /*case 'user/-/state/com.google/tracking-kept-unread':
  346. break;
  347. case 'user/-/state/com.google/like':
  348. break;
  349. case 'user/-/state/com.google/broadcast':
  350. break;*/
  351. }
  352. switch ($r) {
  353. case 'user/-/state/com.google/read':
  354. $entryDAO->markRead($e_id, false);
  355. break;
  356. case 'user/-/state/com.google/starred':
  357. $entryDAO->markFavorite($e_id, false);
  358. break;
  359. }
  360. }
  361. echo 'OK';
  362. exit();
  363. }
  364. function markAllAsRead($streamId, $olderThanId) {
  365. logMe('markAllAsRead(' . $streamId . ")\n");
  366. $entryDAO = new FreshRSS_EntryDAO();
  367. if (strpos($streamId, 'feed/') === 0) {
  368. $f_id = basename($streamId);
  369. $entryDAO->markReadFeed($f_id, $olderThanId);
  370. } elseif (strpos($streamId, 'user/-/label/') === 0) {
  371. $c_name = basename($streamId);
  372. $entryDAO->markReadCatName($c_name, $olderThanId);
  373. } elseif ($streamId === 'user/-/state/com.google/reading-list') {
  374. $entryDAO->markReadEntries($olderThanId, false, -1);
  375. }
  376. echo 'OK';
  377. exit();
  378. }
  379. logMe('----------------------------------------------------------------'."\n");
  380. logMe(print_r($debugInfo, true));
  381. $pathInfo = empty($_SERVER['PATH_INFO']) ? '/Error' : $_SERVER['PATH_INFO'];
  382. $pathInfos = explode('/', $pathInfo);
  383. logMe('pathInfos => ' . print_r($pathInfos, true));
  384. Minz_Configuration::init();
  385. if (!Minz_Configuration::apiEnabled()) {
  386. serviceUnavailable();
  387. }
  388. Minz_Session::init('FreshRSS');
  389. $user = authorizationToUser();
  390. $conf = null;
  391. logMe('User => ' . $user . "\n");
  392. if ($user != null) {
  393. try {
  394. $conf = new FreshRSS_Configuration($user);
  395. } catch (Exception $e) {
  396. logMe($e->getMessage());
  397. $user = null;
  398. badRequest();
  399. }
  400. }
  401. Minz_Session::_param('currentUser', $user);
  402. if (count($pathInfos)<3) badRequest();
  403. elseif ($pathInfos[1] === 'accounts') {
  404. if (($pathInfos[2] === 'ClientLogin') && isset($_REQUEST['Email']) && isset($_REQUEST['Passwd']))
  405. clientLogin($_REQUEST['Email'], $_REQUEST['Passwd']);
  406. }
  407. elseif ($pathInfos[1] === 'reader' && $pathInfos[2] === 'api' && isset($pathInfos[3]) && $pathInfos[3] === '0' && isset($pathInfos[4])) {
  408. if ($user == null) {
  409. unauthorized();
  410. }
  411. $timestamp = isset($_GET['ck']) ? intval($_GET['ck']) : 0; //ck=[unix timestamp] : Use the current Unix time here, helps Google with caching.
  412. switch ($pathInfos[4]) {
  413. case 'stream':
  414. $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).
  415. $count = isset($_GET['n']) ? intval($_GET['n']) : 20; //n=[integer] : The maximum number of results to return.
  416. $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.
  417. $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.
  418. if (isset($pathInfos[5]) && $pathInfos[5] === 'contents' && isset($pathInfos[6]) && isset($pathInfos[7])) {
  419. if ($pathInfos[6] === 'feed') {
  420. $include_target = $pathInfos[7];
  421. StreamContents($pathInfos[6], $include_target, $start_time, $count, $order, $exclude_target);
  422. } elseif ($pathInfos[6] === 'user' && isset($pathInfos[8]) && isset($pathInfos[9])) {
  423. if ($pathInfos[8] === 'state') {
  424. if ($pathInfos[9] === 'com.google' && isset($pathInfos[10])) {
  425. if ($pathInfos[10] === 'reading-list' || $pathInfos[10] === 'starred') {
  426. $include_target = '';
  427. streamContents($pathInfos[10], $include_target, $start_time, $count, $order, $exclude_target);
  428. }
  429. }
  430. } elseif ($pathInfos[8] === 'label') {
  431. $include_target = $pathInfos[9];
  432. streamContents($pathInfos[8], $include_target, $start_time, $count, $order, $exclude_target);
  433. }
  434. }
  435. } elseif ($pathInfos[5] === 'items') {
  436. if ($pathInfos[6] === 'ids' && isset($_GET['s'])) {
  437. $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).
  438. streamContentsItemsIds($streamId, $start_time, $count, $order, $exclude_target);
  439. }
  440. }
  441. break;
  442. case 'tag':
  443. if (isset($pathInfos[5]) && $pathInfos[5] === 'list') {
  444. $output = isset($_GET['output']) ? $_GET['output'] : '';
  445. if ($output !== 'json') notImplemented();
  446. tagList($_GET['output']);
  447. }
  448. break;
  449. case 'subscription':
  450. if (isset($pathInfos[5]) && $pathInfos[5] === 'list') {
  451. $output = isset($_GET['output']) ? $_GET['output'] : '';
  452. if ($output !== 'json') notImplemented();
  453. subscriptionList($_GET['output']);
  454. }
  455. break;
  456. case 'unread-count':
  457. $output = isset($_GET['output']) ? $_GET['output'] : '';
  458. if ($output !== 'json') notImplemented();
  459. $all = isset($_GET['all']) ? $_GET['all'] : '';
  460. unreadCount($all);
  461. break;
  462. case 'edit-tag': //http://blog.martindoms.com/2010/01/20/using-the-google-reader-api-part-3/
  463. $token = isset($_POST['T']) ? trim($_POST['T']) : '';
  464. checkToken($user, $token);
  465. $a = isset($_POST['a']) ? $_POST['a'] : ''; //Add: user/-/state/com.google/read user/-/state/com.google/starred
  466. $r = isset($_POST['r']) ? $_POST['r'] : ''; //Remove: user/-/state/com.google/read user/-/state/com.google/starred
  467. $e_ids = multiplePosts('i'); //item IDs
  468. editTag($e_ids, $a, $r);
  469. break;
  470. case 'mark-all-as-read':
  471. $token = isset($_POST['T']) ? trim($_POST['T']) : '';
  472. checkToken($user, $token);
  473. $streamId = $_POST['s']; //StreamId
  474. $ts = isset($_POST['ts']) ? $_POST['ts'] : '0'; //Older than timestamp in nanoseconds
  475. if (!ctype_digit($ts)) {
  476. $ts = '0';
  477. }
  478. markAllAsRead($streamId, $ts);
  479. break;
  480. case 'token':
  481. Token($user);
  482. break;
  483. }
  484. } elseif ($pathInfos[1] === 'check' && $pathInfos[2] === 'compatibility') {
  485. checkCompatibility();
  486. }
  487. badRequest();