fever.php 15 KB

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