fever.php 14 KB

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