fever.php 15 KB

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