fever.php 16 KB

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