fever.php 14 KB

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