fever.php 17 KB

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