fever.php 14 KB

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