fever.php 15 KB

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