fever.php 15 KB

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