fever.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. <?php
  2. /**
  3. * Fever API for FreshRSS
  4. * Version 0.1
  5. * Author: Kevin Papst / https://github.com/kevinpapst
  6. *
  7. * Inspired by:
  8. * TinyTinyRSS Fever API plugin @dasmurphy
  9. * See https://github.com/dasmurphy/tinytinyrss-fever-plugin
  10. */
  11. // ================================================================================================
  12. // BOOTSTRAP FreshRSS
  13. require(__DIR__ . '/../../constants.php');
  14. require(LIB_PATH . '/lib_rss.php'); //Includes class autoloader
  15. Minz_Configuration::register('system', DATA_PATH . '/config.php', FRESHRSS_PATH . '/config.default.php');
  16. // check if API is enabled globally
  17. FreshRSS_Context::$system_conf = Minz_Configuration::get('system');
  18. if (!FreshRSS_Context::$system_conf->api_enabled) {
  19. Minz_Log::warning('serviceUnavailable() ' . debugInfo(), API_LOG);
  20. header('HTTP/1.1 503 Service Unavailable');
  21. header('Content-Type: text/plain; charset=UTF-8');
  22. die('Service Unavailable!');
  23. }
  24. ini_set('session.use_cookies', '0');
  25. register_shutdown_function('session_destroy');
  26. Minz_Session::init('FreshRSS');
  27. // ================================================================================================
  28. class FeverAPI_EntryDAO extends FreshRSS_EntryDAO
  29. {
  30. /**
  31. * @return array
  32. */
  33. public function countFever()
  34. {
  35. $values = array(
  36. 'total' => 0,
  37. 'min' => 0,
  38. 'max' => 0,
  39. );
  40. $sql = 'SELECT COUNT(id) as `total`, MIN(id) as `min`, MAX(id) as `max` FROM `' . $this->prefix . 'entry`';
  41. $stm = $this->bd->prepare($sql);
  42. $stm->execute();
  43. $result = $stm->fetchAll(PDO::FETCH_ASSOC);
  44. if (!empty($result[0])) {
  45. $values = $result[0];
  46. }
  47. return $values;
  48. }
  49. /**
  50. * @param string $prefix
  51. * @param array $values
  52. * @param array $bindArray
  53. * @return string
  54. */
  55. protected function bindParamArray($prefix, $values, &$bindArray)
  56. {
  57. $str = '';
  58. for ($i = 0; $i < count($values); $i++) {
  59. $str .= ':' . $prefix . $i . ',';
  60. $bindArray[$prefix . $i] = $values[$i];
  61. }
  62. return rtrim($str, ',');
  63. }
  64. /**
  65. * @param array $feed_ids
  66. * @param array $entry_ids
  67. * @param int|null $max_id
  68. * @param int|null $since_id
  69. * @return FreshRSS_Entry[]
  70. */
  71. public function findEntries(array $feed_ids, array $entry_ids, $max_id, $since_id)
  72. {
  73. $values = array();
  74. $order = '';
  75. $sql = 'SELECT id, guid, title, author, '
  76. . ($this->isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content')
  77. . ', link, date, is_read, is_favorite, id_feed, tags '
  78. . 'FROM `' . $this->prefix . 'entry` WHERE';
  79. if (!empty($entry_ids)) {
  80. $bindEntryIds = $this->bindParamArray("id", $entry_ids, $values);
  81. $sql .= " id IN($bindEntryIds)";
  82. } else if (!empty($max_id)) {
  83. $sql .= ' id < :id';
  84. $values[':id'] = $max_id;
  85. $order = ' ORDER BY id DESC';
  86. } else {
  87. $sql .= ' id > :id';
  88. $values[':id'] = $since_id;
  89. $order = ' ORDER BY id ASC';
  90. }
  91. if (!empty($feed_ids)) {
  92. $bindFeedIds = $this->bindParamArray("feed", $feed_ids, $values);
  93. $sql .= " AND id_feed IN($bindFeedIds)";
  94. }
  95. $sql .= $order;
  96. $sql .= ' LIMIT 50';
  97. $stm = $this->bd->prepare($sql);
  98. $stm->execute($values);
  99. $result = $stm->fetchAll(PDO::FETCH_ASSOC);
  100. $entries = array();
  101. foreach ($result as $dao) {
  102. $entries[] = self::daoToEntry($dao);
  103. }
  104. return $entries;
  105. }
  106. }
  107. /**
  108. * Class FeverAPI
  109. */
  110. class FeverAPI
  111. {
  112. const API_LEVEL = 3;
  113. const STATUS_OK = 1;
  114. const STATUS_ERR = 0;
  115. /**
  116. * Authenticate the user
  117. *
  118. * API Password sent from client is the result of the md5 sum of
  119. * your FreshRSS "username:your-api-password" combination
  120. */
  121. private function authenticate()
  122. {
  123. FreshRSS_Context::$user_conf = null;
  124. Minz_Session::_param('currentUser');
  125. $feverKey = empty($_POST['api_key']) ? '' : substr(trim($_POST['api_key']), 0, 128);
  126. if (ctype_xdigit($feverKey)) {
  127. $feverKey = strtolower($feverKey);
  128. $username = @file_get_contents(DATA_PATH . '/fever/.key-' . sha1(FreshRSS_Context::$system_conf->salt) . '-' . $feverKey . '.txt', false);
  129. if ($username != false) {
  130. $username = trim($username);
  131. $user_conf = get_user_configuration($username);
  132. if ($user_conf != null && $feverKey === $user_conf->feverKey) {
  133. FreshRSS_Context::$user_conf = $user_conf;
  134. Minz_Session::_param('currentUser', $username);
  135. }
  136. }
  137. }
  138. }
  139. /**
  140. * @return bool
  141. */
  142. public function isAuthenticatedApiUser()
  143. {
  144. $this->authenticate();
  145. if (FreshRSS_Context::$user_conf !== null) {
  146. return true;
  147. }
  148. return false;
  149. }
  150. /**
  151. * @return FreshRSS_FeedDAO
  152. */
  153. protected function getDaoForFeeds()
  154. {
  155. return new FreshRSS_FeedDAO();
  156. }
  157. /**
  158. * @return FreshRSS_CategoryDAO
  159. */
  160. protected function getDaoForCategories()
  161. {
  162. return new FreshRSS_CategoryDAO();
  163. }
  164. /**
  165. * @return FeverAPI_EntryDAO
  166. */
  167. protected function getDaoForEntries()
  168. {
  169. return new FeverAPI_EntryDAO();
  170. }
  171. /**
  172. * This does all the processing, since the fever api does not have a specific variable that specifies the operation
  173. *
  174. * @return array
  175. * @throws Exception
  176. */
  177. public function process()
  178. {
  179. $response_arr = array();
  180. if (!$this->isAuthenticatedApiUser()) {
  181. throw new Exception('No user given or user is not allowed to access API');
  182. }
  183. if (isset($_REQUEST["groups"])) {
  184. $response_arr["groups"] = $this->getGroups();
  185. $response_arr["feeds_groups"] = $this->getFeedsGroup();
  186. }
  187. if (isset($_REQUEST["feeds"])) {
  188. $response_arr["feeds"] = $this->getFeeds();
  189. $response_arr["feeds_groups"] = $this->getFeedsGroup();
  190. }
  191. if (isset($_REQUEST["favicons"])) {
  192. $response_arr["favicons"] = $this->getFavicons();
  193. }
  194. if (isset($_REQUEST["items"])) {
  195. $response_arr["total_items"] = $this->getTotalItems();
  196. $response_arr["items"] = $this->getItems();
  197. }
  198. if (isset($_REQUEST["links"])) {
  199. $response_arr["links"] = $this->getLinks();
  200. }
  201. if (isset($_REQUEST["unread_item_ids"])) {
  202. $response_arr["unread_item_ids"] = $this->getUnreadItemIds();
  203. }
  204. if (isset($_REQUEST["saved_item_ids"])) {
  205. $response_arr["saved_item_ids"] = $this->getSavedItemIds();
  206. }
  207. if (isset($_REQUEST["mark"], $_REQUEST["as"], $_REQUEST["id"]) && is_numeric($_REQUEST["id"])) {
  208. $method_name = "set" . ucfirst($_REQUEST["mark"]) . "As" . ucfirst($_REQUEST["as"]);
  209. $allowedMethods = array(
  210. 'setFeedAsRead', 'setGroupAsRead', 'setItemAsRead',
  211. 'setItemAsSaved', 'setItemAsUnread', 'setItemAsUnsaved'
  212. );
  213. if (in_array($method_name, $allowedMethods)) {
  214. $id = intval($_REQUEST["id"]);
  215. switch (strtolower($_REQUEST["mark"])) {
  216. case 'item':
  217. $this->{$method_name}($id);
  218. break;
  219. case 'feed':
  220. case 'group':
  221. $before = (isset($_REQUEST["before"])) ? $_REQUEST["before"] : null;
  222. $this->{$method_name}($id, $before);
  223. break;
  224. }
  225. switch ($_REQUEST["as"]) {
  226. case "read":
  227. case "unread":
  228. $response_arr["unread_item_ids"] = $this->getUnreadItemIds();
  229. break;
  230. case 'saved':
  231. case 'unsaved':
  232. $response_arr["saved_item_ids"] = $this->getSavedItemIds();
  233. break;
  234. }
  235. }
  236. }
  237. return $response_arr;
  238. }
  239. /**
  240. * Returns the complete JSON, with 'api_version' and status as 'auth'.
  241. *
  242. * @param int $status
  243. * @param array $reply
  244. * @return string
  245. */
  246. public function wrap($status, array $reply = array())
  247. {
  248. $arr = array('api_version' => self::API_LEVEL, 'auth' => $status);
  249. if ($status === self::STATUS_OK) {
  250. $arr['last_refreshed_on_time'] = (string) $this->lastRefreshedOnTime();
  251. $arr = array_merge($arr, $reply);
  252. }
  253. return json_encode($arr);
  254. }
  255. /**
  256. * every authenticated method includes last_refreshed_on_time
  257. *
  258. * @return int
  259. */
  260. protected function lastRefreshedOnTime()
  261. {
  262. $lastUpdate = 0;
  263. $dao = $this->getDaoForFeeds();
  264. $entries = $dao->listFeedsOrderUpdate(-1, 1);
  265. $feed = current($entries);
  266. if (!empty($feed)) {
  267. $lastUpdate = $feed->lastUpdate();
  268. }
  269. return $lastUpdate;
  270. }
  271. /**
  272. * @return array
  273. */
  274. protected function getFeeds()
  275. {
  276. $feeds = array();
  277. $dao = $this->getDaoForFeeds();
  278. $myFeeds = $dao->listFeeds();
  279. /** @var FreshRSS_Feed $feed */
  280. foreach ($myFeeds as $feed) {
  281. $feeds[] = array(
  282. "id" => $feed->id(),
  283. "favicon_id" => $feed->id(),
  284. "title" => $feed->name(),
  285. "url" => $feed->url(),
  286. "site_url" => $feed->website(),
  287. "is_spark" => 0, // unsupported
  288. "last_updated_on_time" => $feed->lastUpdate()
  289. );
  290. }
  291. return $feeds;
  292. }
  293. /**
  294. * @return array
  295. */
  296. protected function getGroups()
  297. {
  298. $groups = array();
  299. $dao = $this->getDaoForCategories();
  300. $categories = $dao->listCategories(false, false);
  301. /** @var FreshRSS_Category $category */
  302. foreach ($categories as $category) {
  303. $groups[] = array(
  304. 'id' => $category->id(),
  305. 'title' => $category->name()
  306. );
  307. }
  308. return $groups;
  309. }
  310. /**
  311. * @return array
  312. */
  313. protected function getFavicons()
  314. {
  315. $favicons = array();
  316. $dao = $this->getDaoForFeeds();
  317. $myFeeds = $dao->listFeeds();
  318. $salt = FreshRSS_Context::$system_conf->salt;
  319. /** @var FreshRSS_Feed $feed */
  320. foreach ($myFeeds as $feed) {
  321. $id = hash('crc32b', $salt . $feed->url());
  322. $filename = DATA_PATH . '/favicons/' . $id . '.ico';
  323. if (!file_exists($filename)) {
  324. continue;
  325. }
  326. $favicons[] = array(
  327. "id" => $feed->id(),
  328. "data" => image_type_to_mime_type(exif_imagetype($filename)) . ";base64," . base64_encode(file_get_contents($filename))
  329. );
  330. }
  331. return $favicons;
  332. }
  333. /**
  334. * @return int
  335. */
  336. protected function getTotalItems()
  337. {
  338. $total_items = 0;
  339. $dao = $this->getDaoForEntries();
  340. $result = $dao->countFever();
  341. if (!empty($result)) {
  342. $total_items = $result['total'];
  343. }
  344. return $total_items;
  345. }
  346. /**
  347. * @return array
  348. */
  349. protected function getFeedsGroup()
  350. {
  351. $groups = array();
  352. $ids = array();
  353. $dao = $this->getDaoForFeeds();
  354. $myFeeds = $dao->listFeeds();
  355. /** @var FreshRSS_Feed $feed */
  356. foreach ($myFeeds as $feed) {
  357. $ids[$feed->category()][] = $feed->id();
  358. }
  359. foreach($ids as $category => $feedIds) {
  360. $groups[] = array(
  361. 'group_id' => $category,
  362. 'feed_ids' => implode(',', $feedIds)
  363. );
  364. }
  365. return $groups;
  366. }
  367. /**
  368. * AFAIK there is no 'hot links' alternative in FreshRSS
  369. * @return array
  370. */
  371. protected function getLinks()
  372. {
  373. return array();
  374. }
  375. /**
  376. * @param array $ids
  377. * @return string
  378. */
  379. protected function entriesToIdList($ids = array())
  380. {
  381. return implode(',', array_values($ids));
  382. }
  383. /**
  384. * @return string
  385. */
  386. protected function getUnreadItemIds()
  387. {
  388. $dao = $this->getDaoForEntries();
  389. $entries = $dao->listIdsWhere('a', '', FreshRSS_Entry::STATE_NOT_READ, 'ASC', 0);
  390. return $this->entriesToIdList($entries);
  391. }
  392. /**
  393. * @return string
  394. */
  395. protected function getSavedItemIds()
  396. {
  397. $dao = $this->getDaoForEntries();
  398. $entries = $dao->listIdsWhere('a', '', FreshRSS_Entry::STATE_FAVORITE, 'ASC', 0);
  399. return $this->entriesToIdList($entries);
  400. }
  401. protected function setItemAsRead($id)
  402. {
  403. $dao = $this->getDaoForEntries();
  404. $dao->markRead($id, true);
  405. }
  406. protected function setItemAsUnread($id)
  407. {
  408. $dao = $this->getDaoForEntries();
  409. $dao->markRead($id, false);
  410. }
  411. protected function setItemAsSaved($id)
  412. {
  413. $dao = $this->getDaoForEntries();
  414. $dao->markFavorite($id, true);
  415. }
  416. protected function setItemAsUnsaved($id)
  417. {
  418. $dao = $this->getDaoForEntries();
  419. $dao->markFavorite($id, false);
  420. }
  421. /**
  422. * @return array
  423. */
  424. protected function getItems()
  425. {
  426. $feed_ids = array();
  427. $entry_ids = array();
  428. $max_id = null;
  429. $since_id = null;
  430. if (isset($_REQUEST["feed_ids"]) || isset($_REQUEST["group_ids"])) {
  431. if (isset($_REQUEST["feed_ids"])) {
  432. $feed_ids = explode(",", $_REQUEST["feed_ids"]);
  433. }
  434. $dao = $this->getDaoForCategories();
  435. if (isset($_REQUEST["group_ids"])) {
  436. $group_ids = explode(",", $_REQUEST["group_ids"]);
  437. foreach ($group_ids as $id) {
  438. /** @var FreshRSS_Category $category */
  439. $category = $dao->searchById($id);
  440. /** @var FreshRSS_Feed $feed */
  441. foreach ($category->feeds() as $feed) {
  442. $feeds[] = $feed->id();
  443. }
  444. }
  445. $feed_ids = array_unique($feeds);
  446. }
  447. }
  448. if (isset($_REQUEST["max_id"])) {
  449. // use the max_id argument to request the previous $item_limit items
  450. if (is_numeric($_REQUEST["max_id"])) {
  451. $max = ($_REQUEST["max_id"] > 0) ? intval($_REQUEST["max_id"]) : 0;
  452. if ($max) {
  453. $max_id = $max;
  454. }
  455. }
  456. } else if (isset($_REQUEST["with_ids"])) {
  457. $entry_ids = explode(",", $_REQUEST["with_ids"]);
  458. } else {
  459. // use the since_id argument to request the next $item_limit items
  460. $since_id = isset($_REQUEST["since_id"]) && is_numeric($_REQUEST["since_id"]) ? intval($_REQUEST["since_id"]) : 0;
  461. }
  462. $items = array();
  463. $dao = $this->getDaoForEntries();
  464. $entries = $dao->findEntries($feed_ids, $entry_ids, $max_id, $since_id);
  465. // Load list of extensions and enable the "system" ones.
  466. Minz_ExtensionManager::init();
  467. foreach($entries as $item) {
  468. /** @var FreshRSS_Entry $entry */
  469. $entry = Minz_ExtensionManager::callHook('entry_before_display', $item);
  470. if (is_null($entry)) {
  471. continue;
  472. }
  473. $items[] = array(
  474. "id" => $entry->id(),
  475. "feed_id" => $entry->feed(false),
  476. "title" => $entry->title(),
  477. "author" => $entry->author(),
  478. "html" => $entry->content(),
  479. "url" => $entry->link(),
  480. "is_saved" => $entry->isFavorite() ? 1 : 0,
  481. "is_read" => $entry->isRead() ? 1 : 0,
  482. "created_on_time" => $entry->date(true)
  483. );
  484. }
  485. return $items;
  486. }
  487. /**
  488. * TODO replace by a dynamic fetch for id <= $before timestamp
  489. *
  490. * @param int $beforeTimestamp
  491. * @return int
  492. */
  493. protected function convertBeforeToId($beforeTimestamp)
  494. {
  495. // if before is zero, set it to now so feeds all items are read from before this point in time
  496. if ($beforeTimestamp == 0) {
  497. $before = time();
  498. }
  499. $before = PHP_INT_MAX;
  500. return $before;
  501. }
  502. protected function setFeedAsRead($id, $before)
  503. {
  504. $before = $this->convertBeforeToId($before);
  505. $dao = $this->getDaoForEntries();
  506. return $dao->markReadFeed($id, $before);
  507. }
  508. protected function setGroupAsRead($id, $before)
  509. {
  510. $dao = $this->getDaoForEntries();
  511. // special case to mark all items as read
  512. if ($id === 0) {
  513. $result = $dao->countFever();
  514. if (!empty($result)) {
  515. return $dao->markReadEntries($result['max']);
  516. }
  517. }
  518. $before = $this->convertBeforeToId($before);
  519. return $dao->markReadCat($id, $before);
  520. }
  521. }
  522. // ================================================================================================
  523. // refresh is not allowed yet, probably we find a way to support it later
  524. if (isset($_REQUEST["refresh"])) {
  525. Minz_Log::warning('Refresh items for fever API - notImplemented()', API_LOG);
  526. header('HTTP/1.1 501 Not Implemented');
  527. header('Content-Type: text/plain; charset=UTF-8');
  528. die('Not Implemented!');
  529. }
  530. // Start the Fever API handling
  531. $handler = new FeverAPI();
  532. header("Content-Type: application/json; charset=UTF-8");
  533. if (!$handler->isAuthenticatedApiUser()) {
  534. echo $handler->wrap(FeverAPI::STATUS_ERR, array());
  535. } else {
  536. echo $handler->wrap(FeverAPI::STATUS_OK, $handler->process());
  537. }