fever.php 15 KB

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