fever.php 15 KB

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