fever.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  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('Fever API: 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. Minz_Session::_param('currentUser', $username);
  132. $user_conf = get_user_configuration($username);
  133. if ($user_conf != null && $feverKey === $user_conf->feverKey) {
  134. FreshRSS_Context::$user_conf = $user_conf;
  135. return true;
  136. }
  137. Minz_Log::error('Fever API: Reset API password for user: ' . $username, API_LOG);
  138. Minz_Log::error('Fever API: Please reset your API password!');
  139. Minz_Session::_param('currentUser');
  140. }
  141. Minz_Log::warning('Fever API: wrong credentials! ' . $feverKey, API_LOG);
  142. }
  143. return false;
  144. }
  145. /**
  146. * @return bool
  147. */
  148. public function isAuthenticatedApiUser()
  149. {
  150. $this->authenticate();
  151. if (FreshRSS_Context::$user_conf !== null) {
  152. return true;
  153. }
  154. return false;
  155. }
  156. /**
  157. * @return FreshRSS_FeedDAO
  158. */
  159. protected function getDaoForFeeds()
  160. {
  161. return new FreshRSS_FeedDAO();
  162. }
  163. /**
  164. * @return FreshRSS_CategoryDAO
  165. */
  166. protected function getDaoForCategories()
  167. {
  168. return new FreshRSS_CategoryDAO();
  169. }
  170. /**
  171. * @return FeverAPI_EntryDAO
  172. */
  173. protected function getDaoForEntries()
  174. {
  175. return new FeverAPI_EntryDAO();
  176. }
  177. /**
  178. * This does all the processing, since the fever api does not have a specific variable that specifies the operation
  179. *
  180. * @return array
  181. * @throws Exception
  182. */
  183. public function process()
  184. {
  185. $response_arr = array();
  186. if (!$this->isAuthenticatedApiUser()) {
  187. throw new Exception('No user given or user is not allowed to access API');
  188. }
  189. if (isset($_REQUEST["groups"])) {
  190. $response_arr["groups"] = $this->getGroups();
  191. $response_arr["feeds_groups"] = $this->getFeedsGroup();
  192. }
  193. if (isset($_REQUEST["feeds"])) {
  194. $response_arr["feeds"] = $this->getFeeds();
  195. $response_arr["feeds_groups"] = $this->getFeedsGroup();
  196. }
  197. if (isset($_REQUEST["favicons"])) {
  198. $response_arr["favicons"] = $this->getFavicons();
  199. }
  200. if (isset($_REQUEST["items"])) {
  201. $response_arr["total_items"] = $this->getTotalItems();
  202. $response_arr["items"] = $this->getItems();
  203. }
  204. if (isset($_REQUEST["links"])) {
  205. $response_arr["links"] = $this->getLinks();
  206. }
  207. if (isset($_REQUEST["unread_item_ids"])) {
  208. $response_arr["unread_item_ids"] = $this->getUnreadItemIds();
  209. }
  210. if (isset($_REQUEST["saved_item_ids"])) {
  211. $response_arr["saved_item_ids"] = $this->getSavedItemIds();
  212. }
  213. if (isset($_REQUEST["mark"], $_REQUEST["as"], $_REQUEST["id"]) && is_numeric($_REQUEST["id"])) {
  214. $method_name = "set" . ucfirst($_REQUEST["mark"]) . "As" . ucfirst($_REQUEST["as"]);
  215. $allowedMethods = array(
  216. 'setFeedAsRead', 'setGroupAsRead', 'setItemAsRead',
  217. 'setItemAsSaved', 'setItemAsUnread', 'setItemAsUnsaved'
  218. );
  219. if (in_array($method_name, $allowedMethods)) {
  220. $id = intval($_REQUEST["id"]);
  221. switch (strtolower($_REQUEST["mark"])) {
  222. case 'item':
  223. $this->{$method_name}($id);
  224. break;
  225. case 'feed':
  226. case 'group':
  227. $before = (isset($_REQUEST["before"])) ? $_REQUEST["before"] : null;
  228. $this->{$method_name}($id, $before);
  229. break;
  230. }
  231. switch ($_REQUEST["as"]) {
  232. case "read":
  233. case "unread":
  234. $response_arr["unread_item_ids"] = $this->getUnreadItemIds();
  235. break;
  236. case 'saved':
  237. case 'unsaved':
  238. $response_arr["saved_item_ids"] = $this->getSavedItemIds();
  239. break;
  240. }
  241. }
  242. }
  243. return $response_arr;
  244. }
  245. /**
  246. * Returns the complete JSON, with 'api_version' and status as 'auth'.
  247. *
  248. * @param int $status
  249. * @param array $reply
  250. * @return string
  251. */
  252. public function wrap($status, array $reply = array())
  253. {
  254. $arr = array('api_version' => self::API_LEVEL, 'auth' => $status);
  255. if ($status === self::STATUS_OK) {
  256. $arr['last_refreshed_on_time'] = (string) $this->lastRefreshedOnTime();
  257. $arr = array_merge($arr, $reply);
  258. }
  259. return json_encode($arr);
  260. }
  261. /**
  262. * every authenticated method includes last_refreshed_on_time
  263. *
  264. * @return int
  265. */
  266. protected function lastRefreshedOnTime()
  267. {
  268. $lastUpdate = 0;
  269. $dao = $this->getDaoForFeeds();
  270. $entries = $dao->listFeedsOrderUpdate(-1, 1);
  271. $feed = current($entries);
  272. if (!empty($feed)) {
  273. $lastUpdate = $feed->lastUpdate();
  274. }
  275. return $lastUpdate;
  276. }
  277. /**
  278. * @return array
  279. */
  280. protected function getFeeds()
  281. {
  282. $feeds = array();
  283. $dao = $this->getDaoForFeeds();
  284. $myFeeds = $dao->listFeeds();
  285. /** @var FreshRSS_Feed $feed */
  286. foreach ($myFeeds as $feed) {
  287. $feeds[] = array(
  288. "id" => $feed->id(),
  289. "favicon_id" => $feed->id(),
  290. "title" => $feed->name(),
  291. "url" => $feed->url(),
  292. "site_url" => $feed->website(),
  293. "is_spark" => 0, // unsupported
  294. "last_updated_on_time" => $feed->lastUpdate()
  295. );
  296. }
  297. return $feeds;
  298. }
  299. /**
  300. * @return array
  301. */
  302. protected function getGroups()
  303. {
  304. $groups = array();
  305. $dao = $this->getDaoForCategories();
  306. $categories = $dao->listCategories(false, false);
  307. /** @var FreshRSS_Category $category */
  308. foreach ($categories as $category) {
  309. $groups[] = array(
  310. 'id' => $category->id(),
  311. 'title' => $category->name()
  312. );
  313. }
  314. return $groups;
  315. }
  316. /**
  317. * @return array
  318. */
  319. protected function getFavicons()
  320. {
  321. $favicons = array();
  322. $dao = $this->getDaoForFeeds();
  323. $myFeeds = $dao->listFeeds();
  324. $salt = FreshRSS_Context::$system_conf->salt;
  325. /** @var FreshRSS_Feed $feed */
  326. foreach ($myFeeds as $feed) {
  327. $id = hash('crc32b', $salt . $feed->url());
  328. $filename = DATA_PATH . '/favicons/' . $id . '.ico';
  329. if (!file_exists($filename)) {
  330. continue;
  331. }
  332. $favicons[] = array(
  333. "id" => $feed->id(),
  334. "data" => image_type_to_mime_type(exif_imagetype($filename)) . ";base64," . base64_encode(file_get_contents($filename))
  335. );
  336. }
  337. return $favicons;
  338. }
  339. /**
  340. * @return int
  341. */
  342. protected function getTotalItems()
  343. {
  344. $total_items = 0;
  345. $dao = $this->getDaoForEntries();
  346. $result = $dao->countFever();
  347. if (!empty($result)) {
  348. $total_items = $result['total'];
  349. }
  350. return $total_items;
  351. }
  352. /**
  353. * @return array
  354. */
  355. protected function getFeedsGroup()
  356. {
  357. $groups = array();
  358. $ids = array();
  359. $dao = $this->getDaoForFeeds();
  360. $myFeeds = $dao->listFeeds();
  361. /** @var FreshRSS_Feed $feed */
  362. foreach ($myFeeds as $feed) {
  363. $ids[$feed->category()][] = $feed->id();
  364. }
  365. foreach($ids as $category => $feedIds) {
  366. $groups[] = array(
  367. 'group_id' => $category,
  368. 'feed_ids' => implode(',', $feedIds)
  369. );
  370. }
  371. return $groups;
  372. }
  373. /**
  374. * AFAIK there is no 'hot links' alternative in FreshRSS
  375. * @return array
  376. */
  377. protected function getLinks()
  378. {
  379. return array();
  380. }
  381. /**
  382. * @param array $ids
  383. * @return string
  384. */
  385. protected function entriesToIdList($ids = array())
  386. {
  387. return implode(',', array_values($ids));
  388. }
  389. /**
  390. * @return string
  391. */
  392. protected function getUnreadItemIds()
  393. {
  394. $dao = $this->getDaoForEntries();
  395. $entries = $dao->listIdsWhere('a', '', FreshRSS_Entry::STATE_NOT_READ, 'ASC', 0);
  396. return $this->entriesToIdList($entries);
  397. }
  398. /**
  399. * @return string
  400. */
  401. protected function getSavedItemIds()
  402. {
  403. $dao = $this->getDaoForEntries();
  404. $entries = $dao->listIdsWhere('a', '', FreshRSS_Entry::STATE_FAVORITE, 'ASC', 0);
  405. return $this->entriesToIdList($entries);
  406. }
  407. protected function setItemAsRead($id)
  408. {
  409. $dao = $this->getDaoForEntries();
  410. $dao->markRead($id, true);
  411. }
  412. protected function setItemAsUnread($id)
  413. {
  414. $dao = $this->getDaoForEntries();
  415. $dao->markRead($id, false);
  416. }
  417. protected function setItemAsSaved($id)
  418. {
  419. $dao = $this->getDaoForEntries();
  420. $dao->markFavorite($id, true);
  421. }
  422. protected function setItemAsUnsaved($id)
  423. {
  424. $dao = $this->getDaoForEntries();
  425. $dao->markFavorite($id, false);
  426. }
  427. /**
  428. * @return array
  429. */
  430. protected function getItems()
  431. {
  432. $feed_ids = array();
  433. $entry_ids = array();
  434. $max_id = null;
  435. $since_id = null;
  436. if (isset($_REQUEST["feed_ids"]) || isset($_REQUEST["group_ids"])) {
  437. if (isset($_REQUEST["feed_ids"])) {
  438. $feed_ids = explode(",", $_REQUEST["feed_ids"]);
  439. }
  440. $dao = $this->getDaoForCategories();
  441. if (isset($_REQUEST["group_ids"])) {
  442. $group_ids = explode(",", $_REQUEST["group_ids"]);
  443. foreach ($group_ids as $id) {
  444. /** @var FreshRSS_Category $category */
  445. $category = $dao->searchById($id);
  446. /** @var FreshRSS_Feed $feed */
  447. foreach ($category->feeds() as $feed) {
  448. $feeds[] = $feed->id();
  449. }
  450. }
  451. $feed_ids = array_unique($feeds);
  452. }
  453. }
  454. if (isset($_REQUEST["max_id"])) {
  455. // use the max_id argument to request the previous $item_limit items
  456. if (is_numeric($_REQUEST["max_id"])) {
  457. $max = ($_REQUEST["max_id"] > 0) ? intval($_REQUEST["max_id"]) : 0;
  458. if ($max) {
  459. $max_id = $max;
  460. }
  461. }
  462. } else if (isset($_REQUEST["with_ids"])) {
  463. $entry_ids = explode(",", $_REQUEST["with_ids"]);
  464. } else {
  465. // use the since_id argument to request the next $item_limit items
  466. $since_id = isset($_REQUEST["since_id"]) && is_numeric($_REQUEST["since_id"]) ? intval($_REQUEST["since_id"]) : 0;
  467. }
  468. $items = array();
  469. $dao = $this->getDaoForEntries();
  470. $entries = $dao->findEntries($feed_ids, $entry_ids, $max_id, $since_id);
  471. // Load list of extensions and enable the "system" ones.
  472. Minz_ExtensionManager::init();
  473. foreach($entries as $item) {
  474. /** @var FreshRSS_Entry $entry */
  475. $entry = Minz_ExtensionManager::callHook('entry_before_display', $item);
  476. if (is_null($entry)) {
  477. continue;
  478. }
  479. $items[] = array(
  480. "id" => $entry->id(),
  481. "feed_id" => $entry->feed(false),
  482. "title" => $entry->title(),
  483. "author" => $entry->author(),
  484. "html" => $entry->content(),
  485. "url" => $entry->link(),
  486. "is_saved" => $entry->isFavorite() ? 1 : 0,
  487. "is_read" => $entry->isRead() ? 1 : 0,
  488. "created_on_time" => $entry->date(true)
  489. );
  490. }
  491. return $items;
  492. }
  493. /**
  494. * TODO replace by a dynamic fetch for id <= $before timestamp
  495. *
  496. * @param int $beforeTimestamp
  497. * @return int
  498. */
  499. protected function convertBeforeToId($beforeTimestamp)
  500. {
  501. // if before is zero, set it to now so feeds all items are read from before this point in time
  502. if ($beforeTimestamp == 0) {
  503. $before = time();
  504. }
  505. $before = PHP_INT_MAX;
  506. return $before;
  507. }
  508. protected function setFeedAsRead($id, $before)
  509. {
  510. $before = $this->convertBeforeToId($before);
  511. $dao = $this->getDaoForEntries();
  512. return $dao->markReadFeed($id, $before);
  513. }
  514. protected function setGroupAsRead($id, $before)
  515. {
  516. $dao = $this->getDaoForEntries();
  517. // special case to mark all items as read
  518. if ($id === 0) {
  519. $result = $dao->countFever();
  520. if (!empty($result)) {
  521. return $dao->markReadEntries($result['max']);
  522. }
  523. }
  524. $before = $this->convertBeforeToId($before);
  525. return $dao->markReadCat($id, $before);
  526. }
  527. }
  528. // ================================================================================================
  529. // refresh is not allowed yet, probably we find a way to support it later
  530. if (isset($_REQUEST["refresh"])) {
  531. Minz_Log::warning('Fever API: Refresh items - notImplemented()', API_LOG);
  532. header('HTTP/1.1 501 Not Implemented');
  533. header('Content-Type: text/plain; charset=UTF-8');
  534. die('Not Implemented!');
  535. }
  536. // Start the Fever API handling
  537. $handler = new FeverAPI();
  538. header("Content-Type: application/json; charset=UTF-8");
  539. if (!$handler->isAuthenticatedApiUser()) {
  540. echo $handler->wrap(FeverAPI::STATUS_ERR, array());
  541. } else {
  542. echo $handler->wrap(FeverAPI::STATUS_OK, $handler->process());
  543. }