fever.php 15 KB

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