fever.php 15 KB

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