greader.php 33 KB

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