fever.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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<string|int> $feed_ids
  74. * @param array<string> $entry_ids
  75. * @return FreshRSS_Entry[]
  76. */
  77. public function findEntries(array $feed_ids, array $entry_ids, string $max_id, string $since_id): array {
  78. $values = [];
  79. $order = '';
  80. $entryDAO = FreshRSS_Factory::createEntryDao();
  81. $sql = 'SELECT id, guid, title, author, '
  82. . ($entryDAO::isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content')
  83. . ', link, date, is_read, is_favorite, id_feed, attributes '
  84. . 'FROM `_entry` WHERE';
  85. if (!empty($entry_ids)) {
  86. $bindEntryIds = $this->bindParamArray('id', $entry_ids, $values);
  87. $sql .= " id IN($bindEntryIds)";
  88. } elseif ($max_id != '') {
  89. $sql .= ' id < :id';
  90. $values[':id'] = $max_id;
  91. $order = ' ORDER BY id DESC';
  92. } elseif ($since_id != '') {
  93. $sql .= ' id > :id';
  94. $values[':id'] = $since_id;
  95. $order = ' ORDER BY id ASC';
  96. } else {
  97. $sql .= ' 1=1';
  98. }
  99. if (!empty($feed_ids)) {
  100. $bindFeedIds = $this->bindParamArray('feed', $feed_ids, $values);
  101. $sql .= " AND id_feed IN($bindFeedIds)";
  102. }
  103. $sql .= $order;
  104. $sql .= ' LIMIT 50';
  105. $stm = $this->pdo->prepare($sql);
  106. if ($stm !== false && $stm->execute($values)) {
  107. $result = $stm->fetchAll(PDO::FETCH_ASSOC);
  108. $entries = [];
  109. foreach ($result as $dao) {
  110. /** @var array{id?:string,id_feed?:int,guid?:string,title?:string,author?:string,content?:string,link?:string,date?:int|string,lastSeen?:int,
  111. * hash?:string,is_read?:bool|int,is_favorite?:bool|int,tags?:string|array<string>,attributes?:?string,thumbnail?:string,timestamp?:string} $dao */
  112. $entries[] = FreshRSS_Entry::fromArray($dao);
  113. }
  114. return $entries;
  115. }
  116. return [];
  117. }
  118. }
  119. /**
  120. * Class FeverAPI
  121. */
  122. final class FeverAPI
  123. {
  124. public const API_LEVEL = 3;
  125. public const STATUS_OK = 1;
  126. public const STATUS_ERR = 0;
  127. private FreshRSS_EntryDAO $entryDAO;
  128. private FreshRSS_FeedDAO $feedDAO;
  129. /**
  130. * Authenticate the user
  131. *
  132. * API Password sent from client is the result of the md5 sum of
  133. * your FreshRSS "username:your-api-password" combination
  134. */
  135. private function authenticate(): bool {
  136. FreshRSS_Context::clearUserConf();
  137. Minz_User::change();
  138. $feverKey = empty($_POST['api_key']) || !is_string($_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::systemConf()->salt) . '-' . $feverKey . '.txt', false);
  142. if ($username != false) {
  143. $username = trim($username);
  144. FreshRSS_Context::initUser($username);
  145. if ($feverKey === FreshRSS_Context::userConf()->feverKey && FreshRSS_Context::userConf()->enabled) {
  146. Minz_Translate::init(FreshRSS_Context::userConf()->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_User::change();
  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::hasUserConf();
  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 = [];
  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 (is_string($_REQUEST['mark'] ?? null) && is_string($_REQUEST['as'] ?? null) && is_string($_REQUEST['id'] ?? null) && ctype_digit($_REQUEST['id'])) {
  200. $id = $_REQUEST['id'];
  201. $before = is_numeric($_REQUEST['before'] ?? null) ? (int)$_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((int)$id, $before);
  223. break;
  224. }
  225. break;
  226. case 'group':
  227. switch ($_REQUEST['as']) {
  228. case 'read':
  229. $this->setGroupAsRead((int)$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 = []): string {
  252. $arr = ['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. private 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 list<array{id:int,favicon_id:int,title:string,url:string,site_url:string,is_spark:int,last_updated_on_time:int}> */
  272. private function getFeeds(): array {
  273. $feeds = [];
  274. $myFeeds = $this->feedDAO->listFeeds();
  275. /** @var FreshRSS_Feed $feed */
  276. foreach ($myFeeds as $feed) {
  277. $feeds[] = [
  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,
  284. // unsupported
  285. 'last_updated_on_time' => $feed->lastUpdate(),
  286. ];
  287. }
  288. return $feeds;
  289. }
  290. /** @return list<array{id:int,title:string}> */
  291. private function getGroups(): array {
  292. $groups = [];
  293. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  294. $categories = $categoryDAO->listCategories(prePopulateFeeds: false, details: false);
  295. foreach ($categories as $category) {
  296. $groups[] = [
  297. 'id' => $category->id(),
  298. 'title' => escapeToUnicodeAlternative($category->name(), true)
  299. ];
  300. }
  301. return $groups;
  302. }
  303. /** @return list<array{id:int,data:string}> */
  304. private function getFavicons(): array {
  305. if (!FreshRSS_Context::hasSystemConf()) {
  306. return [];
  307. }
  308. require_once LIB_PATH . '/favicons.php';
  309. $favicons = [];
  310. $salt = FreshRSS_Context::systemConf()->salt;
  311. $myFeeds = $this->feedDAO->listFeeds();
  312. foreach ($myFeeds as $feed) {
  313. $id = $feed->hashFavicon();
  314. $filename = DATA_PATH . '/favicons/' . $id . '.ico';
  315. if (!file_exists($filename)) {
  316. continue;
  317. }
  318. $favicons[] = [
  319. 'id' => $feed->id(),
  320. 'data' => contentType($filename) . ';base64,' . base64_encode(file_get_contents($filename) ?: '')
  321. ];
  322. }
  323. return $favicons;
  324. }
  325. private function getTotalItems(): int {
  326. return $this->entryDAO->count();
  327. }
  328. /**
  329. * @return list<array<string,int|string>>
  330. */
  331. private function getFeedsGroup(): array {
  332. $groups = [];
  333. $ids = [];
  334. $myFeeds = $this->feedDAO->listFeeds();
  335. foreach ($myFeeds as $feed) {
  336. $ids[$feed->categoryId()][] = $feed->id();
  337. }
  338. foreach ($ids as $category => $feedIds) {
  339. $groups[] = [
  340. 'group_id' => $category,
  341. 'feed_ids' => implode(',', $feedIds)
  342. ];
  343. }
  344. return $groups;
  345. }
  346. /**
  347. * AFAIK there is no 'hot links' alternative in FreshRSS
  348. * @return list<string>
  349. */
  350. private function getLinks(): array {
  351. return [];
  352. }
  353. /**
  354. * @param array<numeric-string> $ids
  355. */
  356. private function entriesToIdList(array $ids = []): string {
  357. return implode(',', array_values($ids));
  358. }
  359. private function getUnreadItemIds(): string {
  360. $entries = $this->entryDAO->listIdsWhere('a', 0, FreshRSS_Entry::STATE_NOT_READ, order: 'ASC', limit: 0) ?? [];
  361. return $this->entriesToIdList($entries);
  362. }
  363. private function getSavedItemIds(): string {
  364. $entries = $this->entryDAO->listIdsWhere('a', 0, FreshRSS_Entry::STATE_FAVORITE, order: 'ASC', limit: 0) ?? [];
  365. return $this->entriesToIdList($entries);
  366. }
  367. /**
  368. * @param numeric-string $id
  369. */
  370. private function setItemAsRead(string $id): int|false {
  371. return $this->entryDAO->markRead($id, true);
  372. }
  373. /**
  374. * @param numeric-string $id
  375. */
  376. private function setItemAsUnread(string $id): int|false {
  377. return $this->entryDAO->markRead($id, false);
  378. }
  379. /**
  380. * @param numeric-string $id
  381. */
  382. private function setItemAsSaved(string $id): int|false {
  383. return $this->entryDAO->markFavorite($id, true);
  384. }
  385. /**
  386. * @param numeric-string $id
  387. */
  388. private function setItemAsUnsaved(string $id): int|false {
  389. return $this->entryDAO->markFavorite($id, false);
  390. }
  391. /** @return list<array<string,string|int>> */
  392. private function getItems(): array {
  393. $feed_ids = [];
  394. $entry_ids = [];
  395. $max_id = '';
  396. $since_id = '';
  397. if (is_string($_REQUEST['feed_ids'] ?? null)) {
  398. $feed_ids = explode(',', $_REQUEST['feed_ids']);
  399. } elseif (is_string($_REQUEST['group_ids'] ?? null)) {
  400. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  401. $group_ids = explode(',', $_REQUEST['group_ids']);
  402. $feeds = [];
  403. foreach ($group_ids as $id) {
  404. $category = $categoryDAO->searchById((int)$id); //TODO: Transform to SQL query without loop! Consider FreshRSS_CategoryDAO::listCategories(true)
  405. if ($category == null) {
  406. continue;
  407. }
  408. foreach ($category->feeds() as $feed) {
  409. $feeds[] = $feed->id();
  410. }
  411. }
  412. $feed_ids = array_unique($feeds);
  413. }
  414. if (is_string($_REQUEST['max_id'] ?? null)) {
  415. // use the max_id argument to request the previous $item_limit items
  416. $max_id = $_REQUEST['max_id'];
  417. if (!ctype_digit($max_id)) {
  418. $max_id = '';
  419. }
  420. } elseif (is_string($_REQUEST['with_ids'] ?? null)) {
  421. $entry_ids = explode(',', $_REQUEST['with_ids']);
  422. } elseif (is_string($_REQUEST['since_id'] ?? null)) {
  423. // use the since_id argument to request the next $item_limit items
  424. $since_id = $_REQUEST['since_id'];
  425. if (!ctype_digit($since_id)) {
  426. $since_id = '';
  427. }
  428. }
  429. $items = [];
  430. $feverDAO = new FeverDAO();
  431. $entries = $feverDAO->findEntries($feed_ids, $entry_ids, $max_id, $since_id);
  432. // Load list of extensions and enable the "system" ones.
  433. Minz_ExtensionManager::init();
  434. foreach ($entries as $item) {
  435. /** @var FreshRSS_Entry|null $entry */
  436. $entry = Minz_ExtensionManager::callHook('entry_before_display', $item);
  437. if ($entry === null) {
  438. continue;
  439. }
  440. $items[] = [
  441. 'id' => $entry->id(),
  442. 'feed_id' => $entry->feedId(),
  443. 'title' => escapeToUnicodeAlternative($entry->title(), false),
  444. 'author' => escapeToUnicodeAlternative(trim($entry->authors(true), '; '), false),
  445. 'html' => $entry->content(), 'url' => htmlspecialchars_decode($entry->link(), ENT_QUOTES),
  446. 'is_saved' => $entry->isFavorite() ? 1 : 0,
  447. 'is_read' => $entry->isRead() ? 1 : 0,
  448. 'created_on_time' => $entry->date(true),
  449. ];
  450. }
  451. return $items;
  452. }
  453. /**
  454. * TODO replace by a dynamic fetch for id <= $before timestamp
  455. * @return numeric-string
  456. */
  457. private function convertBeforeToId(int $beforeTimestamp): string {
  458. return $beforeTimestamp == 0 ? '0' : $beforeTimestamp . '000000';
  459. }
  460. private function setFeedAsRead(int $id, int $before): int|false {
  461. $before = $this->convertBeforeToId($before);
  462. return $this->entryDAO->markReadFeed($id, $before);
  463. }
  464. private function setGroupAsRead(int $id, int $before): int|false {
  465. $before = $this->convertBeforeToId($before);
  466. // special case to mark all items as read
  467. if ($id == 0) {
  468. return $this->entryDAO->markReadEntries($before);
  469. }
  470. return $this->entryDAO->markReadCat($id, $before);
  471. }
  472. }
  473. // ================================================================================================
  474. // refresh is not allowed yet, probably we find a way to support it later
  475. if (isset($_REQUEST['refresh'])) {
  476. Minz_Log::warning('Fever API: Refresh items - notImplemented()', API_LOG);
  477. header('HTTP/1.1 501 Not Implemented');
  478. header('Content-Type: text/plain; charset=UTF-8');
  479. die('Not Implemented!');
  480. }
  481. // Start the Fever API handling
  482. $handler = new FeverAPI();
  483. header('Content-Type: application/json; charset=UTF-8');
  484. if (!$handler->isAuthenticatedApiUser()) {
  485. echo $handler->wrap(FeverAPI::STATUS_ERR, []);
  486. } else {
  487. echo $handler->wrap(FeverAPI::STATUS_OK, $handler->process());
  488. }