4
0

fever.php 17 KB

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