4
0

fever.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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 (hash_equals(FreshRSS_Context::userConf()->feverKey, $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 .
  173. ' ; Remote IP address=' . Minz_Request::connectionRemoteAddress(), API_LOG);
  174. }
  175. return false;
  176. }
  177. public function isAuthenticatedApiUser(): bool {
  178. $this->authenticate();
  179. return FreshRSS_Context::hasUserConf();
  180. }
  181. /**
  182. * This does all the processing, since the fever api does not have a specific variable that specifies the operation
  183. * @return array<string,mixed>
  184. * @throws Exception
  185. */
  186. public function process(): array {
  187. $response_arr = [];
  188. if (!$this->isAuthenticatedApiUser()) {
  189. throw new Exception('No user given or user is not allowed to access API');
  190. }
  191. if (isset($_REQUEST['groups'])) {
  192. $response_arr['groups'] = $this->getGroups();
  193. $response_arr['feeds_groups'] = $this->getFeedsGroup();
  194. }
  195. if (isset($_REQUEST['feeds'])) {
  196. $response_arr['feeds'] = $this->getFeeds();
  197. $response_arr['feeds_groups'] = $this->getFeedsGroup();
  198. }
  199. if (isset($_REQUEST['favicons'])) {
  200. $response_arr['favicons'] = $this->getFavicons();
  201. }
  202. if (isset($_REQUEST['items'])) {
  203. $response_arr['total_items'] = $this->getTotalItems();
  204. $response_arr['items'] = $this->getItems();
  205. }
  206. if (isset($_REQUEST['links'])) {
  207. $response_arr['links'] = $this->getLinks();
  208. }
  209. if (isset($_REQUEST['unread_item_ids'])) {
  210. $response_arr['unread_item_ids'] = $this->getUnreadItemIds();
  211. }
  212. if (isset($_REQUEST['saved_item_ids'])) {
  213. $response_arr['saved_item_ids'] = $this->getSavedItemIds();
  214. }
  215. if (is_string($_REQUEST['mark'] ?? null) && is_string($_REQUEST['as'] ?? null)) {
  216. if (is_string($_REQUEST['id'] ?? null) && ctype_digit($_REQUEST['id'])) {
  217. $id = $_REQUEST['id'];
  218. } elseif (is_string($_REQUEST['with_ids'] ?? null)) {
  219. $id = array_values(array_filter(explode(',', $_REQUEST['with_ids']), 'ctype_digit'));
  220. // N.B.: Not supported by 'feed' and 'group' functions
  221. } else {
  222. $id = '0';
  223. }
  224. $before = is_numeric($_REQUEST['before'] ?? null) ? (int)$_REQUEST['before'] : 0;
  225. switch (strtolower($_REQUEST['mark'])) {
  226. case 'item':
  227. switch ($_REQUEST['as']) {
  228. case 'read':
  229. $this->setItemAsRead($id);
  230. break;
  231. case 'saved':
  232. $this->setItemAsSaved($id);
  233. break;
  234. case 'unread':
  235. $this->setItemAsUnread($id);
  236. break;
  237. case 'unsaved':
  238. $this->setItemAsUnsaved($id);
  239. break;
  240. }
  241. break;
  242. case 'feed':
  243. switch ($_REQUEST['as']) {
  244. case 'read':
  245. $this->setFeedAsRead(is_numeric($id) ? (int)$id : 0, $before);
  246. break;
  247. }
  248. break;
  249. case 'group':
  250. switch ($_REQUEST['as']) {
  251. case 'read':
  252. $this->setGroupAsRead(is_numeric($id) ? (int)$id : 0, $before);
  253. break;
  254. }
  255. break;
  256. }
  257. switch ($_REQUEST['as']) {
  258. case 'read':
  259. case 'unread':
  260. $response_arr['unread_item_ids'] = $this->getUnreadItemIds();
  261. break;
  262. case 'saved':
  263. case 'unsaved':
  264. $response_arr['saved_item_ids'] = $this->getSavedItemIds();
  265. break;
  266. }
  267. }
  268. return $response_arr;
  269. }
  270. /**
  271. * Returns the complete JSON, with 'api_version' and status as 'auth'.
  272. * @param array<string,mixed> $reply
  273. */
  274. public function wrap(int $status, array $reply = []): string {
  275. $arr = ['api_version' => self::API_LEVEL, 'auth' => $status];
  276. if ($status === self::STATUS_OK) {
  277. $arr['last_refreshed_on_time'] = $this->lastRefreshedOnTime();
  278. $arr = array_merge($arr, $reply);
  279. }
  280. return json_encode($arr) ?: '';
  281. }
  282. /**
  283. * every authenticated method includes last_refreshed_on_time
  284. */
  285. private function lastRefreshedOnTime(): int {
  286. $lastUpdate = 0;
  287. $entries = $this->feedDAO->listFeedsOrderUpdate(-1, 1);
  288. $feed = current($entries);
  289. if (!empty($feed)) {
  290. $lastUpdate = $feed->lastUpdate();
  291. }
  292. return $lastUpdate;
  293. }
  294. /** @return list<array{id:int,favicon_id:int,title:string,url:string,site_url:string,is_spark:int,last_updated_on_time:int}> */
  295. private function getFeeds(): array {
  296. $feeds = [];
  297. $myFeeds = $this->feedDAO->listFeeds();
  298. /** @var FreshRSS_Feed $feed */
  299. foreach ($myFeeds as $feed) {
  300. if ($feed->priority() <= FreshRSS_Feed::PRIORITY_HIDDEN) {
  301. continue;
  302. }
  303. $feeds[] = [
  304. 'id' => $feed->id(),
  305. 'favicon_id' => $feed->id(),
  306. 'title' => escapeToUnicodeAlternative($feed->name(), true),
  307. 'url' => htmlspecialchars_decode($feed->url(), ENT_QUOTES),
  308. 'site_url' => htmlspecialchars_decode($feed->website(), ENT_QUOTES),
  309. 'is_spark' => 0,
  310. // unsupported
  311. 'last_updated_on_time' => $feed->lastUpdate(),
  312. ];
  313. }
  314. return $feeds;
  315. }
  316. /** @return list<array{id:int,title:string}> */
  317. private function getGroups(): array {
  318. $groups = [];
  319. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  320. $categories = $categoryDAO->listCategories(prePopulateFeeds: false, details: false);
  321. foreach ($categories as $category) {
  322. $groups[] = [
  323. 'id' => $category->id(),
  324. 'title' => escapeToUnicodeAlternative($category->name(), true)
  325. ];
  326. }
  327. return $groups;
  328. }
  329. /** @return list<array{id:int,data:string}> */
  330. private function getFavicons(): array {
  331. if (!FreshRSS_Context::hasSystemConf()) {
  332. return [];
  333. }
  334. require_once LIB_PATH . '/favicons.php';
  335. $favicons = [];
  336. $salt = FreshRSS_Context::systemConf()->salt;
  337. $myFeeds = $this->feedDAO->listFeeds();
  338. foreach ($myFeeds as $feed) {
  339. if ($feed->priority() <= FreshRSS_Feed::PRIORITY_HIDDEN) {
  340. continue;
  341. }
  342. $id = $feed->hashFavicon();
  343. $filename = DATA_PATH . '/favicons/' . $id . '.ico';
  344. if (!file_exists($filename)) {
  345. continue;
  346. }
  347. $favicons[] = [
  348. 'id' => $feed->id(),
  349. 'data' => contentType($filename) . ';base64,' . base64_encode(file_get_contents($filename) ?: '')
  350. ];
  351. }
  352. return $favicons;
  353. }
  354. private function getTotalItems(): int {
  355. return $this->entryDAO->count();
  356. }
  357. /**
  358. * @return list<array<string,int|string>>
  359. */
  360. private function getFeedsGroup(): array {
  361. $groups = [];
  362. $ids = [];
  363. $myFeeds = $this->feedDAO->listFeeds();
  364. foreach ($myFeeds as $feed) {
  365. if ($feed->priority() <= FreshRSS_Feed::PRIORITY_HIDDEN) {
  366. continue;
  367. }
  368. $ids[$feed->categoryId()][] = $feed->id();
  369. }
  370. foreach ($ids as $category => $feedIds) {
  371. $groups[] = [
  372. 'group_id' => $category,
  373. 'feed_ids' => implode(',', $feedIds)
  374. ];
  375. }
  376. return $groups;
  377. }
  378. /**
  379. * AFAIK there is no 'hot links' alternative in FreshRSS
  380. * @return list<string>
  381. */
  382. private function getLinks(): array {
  383. return [];
  384. }
  385. /**
  386. * @param array<numeric-string> $ids
  387. */
  388. private function entriesToIdList(array $ids = []): string {
  389. return implode(',', array_values($ids));
  390. }
  391. private function getUnreadItemIds(): string {
  392. $entries = $this->entryDAO->listIdsWhere('a', 0, FreshRSS_Entry::STATE_NOT_READ, order: 'ASC', limit: 0) ?? [];
  393. return $this->entriesToIdList($entries);
  394. }
  395. private function getSavedItemIds(): string {
  396. $entries = $this->entryDAO->listIdsWhere('a', 0, FreshRSS_Entry::STATE_FAVORITE, order: 'ASC', limit: 0) ?? [];
  397. return $this->entriesToIdList($entries);
  398. }
  399. /**
  400. * @param list<numeric-string>|numeric-string $id
  401. */
  402. private function setItemAsRead(array|string $id): int|false {
  403. return $this->entryDAO->markRead($id, true);
  404. }
  405. /**
  406. * @param list<numeric-string>|numeric-string $id
  407. */
  408. private function setItemAsUnread(array|string $id): int|false {
  409. return $this->entryDAO->markRead($id, false);
  410. }
  411. /**
  412. * @param list<numeric-string>|numeric-string $id
  413. */
  414. private function setItemAsSaved(array|string $id): int|false {
  415. return $this->entryDAO->markFavorite($id, true);
  416. }
  417. /**
  418. * @param list<numeric-string>|numeric-string $id
  419. */
  420. private function setItemAsUnsaved(array|string $id): int|false {
  421. return $this->entryDAO->markFavorite($id, false);
  422. }
  423. /** @return list<array<string,string|int>> */
  424. private function getItems(): array {
  425. $feed_ids = [];
  426. $entry_ids = [];
  427. $max_id = '';
  428. $since_id = '';
  429. if (is_string($_REQUEST['feed_ids'] ?? null)) {
  430. $feed_ids = array_filter(explode(',', $_REQUEST['feed_ids']), 'ctype_digit');
  431. } elseif (is_string($_REQUEST['group_ids'] ?? null)) {
  432. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  433. $group_ids = explode(',', $_REQUEST['group_ids']);
  434. $feeds = [];
  435. foreach ($group_ids as $id) {
  436. if (!is_numeric($id)) {
  437. continue;
  438. }
  439. $category = $categoryDAO->searchById((int)$id); //TODO: Transform to SQL query without loop! Consider FreshRSS_CategoryDAO::listCategories(true)
  440. if ($category === null) {
  441. continue;
  442. }
  443. foreach ($category->feeds() as $feed) {
  444. if ($feed->priority() <= FreshRSS_Feed::PRIORITY_HIDDEN) {
  445. continue;
  446. }
  447. $feeds[] = $feed->id();
  448. }
  449. }
  450. $feed_ids = array_unique($feeds);
  451. }
  452. if (is_string($_REQUEST['max_id'] ?? null)) {
  453. // use the max_id argument to request the previous $item_limit items
  454. $max_id = $_REQUEST['max_id'];
  455. if (!ctype_digit($max_id)) {
  456. $max_id = '';
  457. }
  458. } elseif (is_string($_REQUEST['with_ids'] ?? null)) {
  459. $entry_ids = array_filter(explode(',', $_REQUEST['with_ids']), 'ctype_digit');
  460. } elseif (is_string($_REQUEST['since_id'] ?? null)) {
  461. // use the since_id argument to request the next $item_limit items
  462. $since_id = $_REQUEST['since_id'];
  463. if (!ctype_digit($since_id)) {
  464. $since_id = '';
  465. }
  466. }
  467. $items = [];
  468. $feverDAO = new FeverDAO();
  469. $entries = $feverDAO->findEntries($feed_ids, $entry_ids, $max_id, $since_id);
  470. // Load list of extensions and enable the "system" ones.
  471. Minz_ExtensionManager::init();
  472. foreach ($entries as $item) {
  473. /** @var FreshRSS_Entry|null $entry */
  474. $entry = Minz_ExtensionManager::callHook(Minz_HookType::EntryBeforeDisplay, $item);
  475. if ($entry === null) {
  476. continue;
  477. }
  478. $items[] = [
  479. 'id' => $entry->id(),
  480. 'feed_id' => $entry->feedId(),
  481. 'title' => escapeToUnicodeAlternative($entry->title(), false),
  482. 'author' => escapeToUnicodeAlternative(trim($entry->authors(true), '; '), false),
  483. 'html' => $entry->content(), 'url' => htmlspecialchars_decode($entry->link(), ENT_QUOTES),
  484. 'is_saved' => $entry->isFavorite() ? 1 : 0,
  485. 'is_read' => $entry->isRead() ? 1 : 0,
  486. 'created_on_time' => $entry->date(true),
  487. ];
  488. }
  489. return $items;
  490. }
  491. /**
  492. * TODO replace by a dynamic fetch for id <= $before timestamp
  493. * @return numeric-string
  494. */
  495. private function convertBeforeToId(int $beforeTimestamp): string {
  496. return $beforeTimestamp == 0 ? '0' : $beforeTimestamp . '000000';
  497. }
  498. private function setFeedAsRead(int $id, int $before): int|false {
  499. $before = $this->convertBeforeToId($before);
  500. return $this->entryDAO->markReadFeed($id, $before);
  501. }
  502. private function setGroupAsRead(int $id, int $before): int|false {
  503. $before = $this->convertBeforeToId($before);
  504. // special case to mark all items as read
  505. if ($id == 0) {
  506. return $this->entryDAO->markReadEntries($before);
  507. }
  508. return $this->entryDAO->markReadCat($id, $before);
  509. }
  510. }
  511. // ================================================================================================
  512. // refresh is not allowed yet, probably we find a way to support it later
  513. if (isset($_REQUEST['refresh'])) {
  514. Minz_Log::warning('Fever API: Refresh items - notImplemented()', API_LOG);
  515. header('HTTP/1.1 501 Not Implemented');
  516. header('Content-Type: text/plain; charset=UTF-8');
  517. die('Not Implemented!');
  518. }
  519. // Start the Fever API handling
  520. $handler = new FeverAPI();
  521. header('Content-Type: application/json; charset=UTF-8');
  522. if (!$handler->isAuthenticatedApiUser()) {
  523. echo $handler->wrap(FeverAPI::STATUS_ERR, []);
  524. } else {
  525. echo $handler->wrap(FeverAPI::STATUS_OK, $handler->process());
  526. }