feedController.php 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * Controller to handle every feed actions.
  5. */
  6. class FreshRSS_feed_Controller extends FreshRSS_ActionController {
  7. /**
  8. * This action is called before every other action in that class. It is
  9. * the common boiler plate for every action. It is triggered by the
  10. * underlying framework.
  11. */
  12. public function firstAction(): void {
  13. if (!FreshRSS_Auth::hasAccess()) {
  14. // Token is useful in the case that anonymous refresh is forbidden
  15. // and CRON task cannot be used with php command so the user can
  16. // set a CRON task to refresh his feeds by using token inside url
  17. $token = FreshRSS_Context::userConf()->token;
  18. $token_param = Minz_Request::paramString('token');
  19. $token_is_ok = ($token != '' && $token == $token_param);
  20. $action = Minz_Request::actionName();
  21. $allow_anonymous_refresh = FreshRSS_Context::systemConf()->allow_anonymous_refresh;
  22. if ($action !== 'actualize' ||
  23. !($allow_anonymous_refresh || $token_is_ok)) {
  24. Minz_Error::error(403);
  25. }
  26. }
  27. }
  28. /**
  29. * @param array<string,mixed> $attributes
  30. * @throws FreshRSS_AlreadySubscribed_Exception
  31. * @throws FreshRSS_FeedNotAdded_Exception
  32. * @throws FreshRSS_Feed_Exception
  33. * @throws Minz_FileNotExistException
  34. */
  35. public static function addFeed(string $url, string $title = '', int $cat_id = 0, string $new_cat_name = '',
  36. string $http_auth = '', array $attributes = [], int $kind = FreshRSS_Feed::KIND_RSS): FreshRSS_Feed {
  37. FreshRSS_UserDAO::touch();
  38. if (function_exists('set_time_limit')) {
  39. @set_time_limit(300);
  40. }
  41. $catDAO = FreshRSS_Factory::createCategoryDao();
  42. $url = trim($url);
  43. /** @var string|null $urlHooked */
  44. $urlHooked = Minz_ExtensionManager::callHook('check_url_before_add', $url);
  45. if ($urlHooked === null) {
  46. throw new FreshRSS_FeedNotAdded_Exception($url);
  47. }
  48. $url = $urlHooked;
  49. $cat = null;
  50. if ($cat_id > 0) {
  51. $cat = $catDAO->searchById($cat_id);
  52. }
  53. if ($cat === null && $new_cat_name != '') {
  54. $new_cat_id = $catDAO->addCategory(['name' => $new_cat_name]);
  55. $cat_id = $new_cat_id > 0 ? $new_cat_id : $cat_id;
  56. $cat = $catDAO->searchById($cat_id);
  57. }
  58. if ($cat === null) {
  59. $catDAO->checkDefault();
  60. }
  61. $feed = new FreshRSS_Feed($url); //Throws FreshRSS_BadUrl_Exception
  62. $title = trim($title);
  63. if ($title !== '') {
  64. $feed->_name($title);
  65. }
  66. $feed->_kind($kind);
  67. $feed->_attributes($attributes);
  68. $feed->_httpAuth($http_auth);
  69. if ($cat === null) {
  70. $feed->_categoryId(FreshRSS_CategoryDAO::DEFAULTCATEGORYID);
  71. } else {
  72. $feed->_category($cat);
  73. }
  74. switch ($kind) {
  75. case FreshRSS_Feed::KIND_RSS:
  76. case FreshRSS_Feed::KIND_RSS_FORCED:
  77. $feed->load(true); //Throws FreshRSS_Feed_Exception, Minz_FileNotExistException
  78. break;
  79. case FreshRSS_Feed::KIND_HTML_XPATH:
  80. case FreshRSS_Feed::KIND_XML_XPATH:
  81. $feed->_website($url);
  82. break;
  83. }
  84. $feedDAO = FreshRSS_Factory::createFeedDao();
  85. if ($feedDAO->searchByUrl($feed->url())) {
  86. throw new FreshRSS_AlreadySubscribed_Exception($url, $feed->name());
  87. }
  88. /** @var FreshRSS_Feed|null $feed */
  89. $feed = Minz_ExtensionManager::callHook('feed_before_insert', $feed);
  90. if ($feed === null) {
  91. throw new FreshRSS_FeedNotAdded_Exception($url);
  92. }
  93. $id = $feedDAO->addFeedObject($feed);
  94. if (!$id) {
  95. // There was an error in database… we cannot say what here.
  96. throw new FreshRSS_FeedNotAdded_Exception($url);
  97. }
  98. $feed->_id($id);
  99. // Ok, feed has been added in database. Now we have to refresh entries.
  100. [, , $nb_new_articles] = self::actualizeFeeds($id, $url);
  101. if ($nb_new_articles > 0) {
  102. self::commitNewEntries();
  103. }
  104. return $feed;
  105. }
  106. /**
  107. * This action subscribes to a feed.
  108. *
  109. * It can be reached by both GET and POST requests.
  110. *
  111. * GET request displays a form to add and configure a feed.
  112. * Request parameter is:
  113. * - url_rss (default: false)
  114. *
  115. * POST request adds a feed in database.
  116. * Parameters are:
  117. * - url_rss (default: false)
  118. * - category (default: false)
  119. * - http_user (default: false)
  120. * - http_pass (default: false)
  121. * It tries to get website information from RSS feed.
  122. * If no category is given, feed is added to the default one.
  123. *
  124. * If url_rss is false, nothing happened.
  125. */
  126. public function addAction(): void {
  127. $url = Minz_Request::paramString('url_rss');
  128. if ($url === '') {
  129. // No url, do nothing
  130. Minz_Request::forward([
  131. 'c' => 'subscription',
  132. 'a' => 'index',
  133. ], true);
  134. }
  135. $feedDAO = FreshRSS_Factory::createFeedDao();
  136. $url_redirect = [
  137. 'c' => 'subscription',
  138. 'a' => 'add',
  139. 'params' => [],
  140. ];
  141. $limits = FreshRSS_Context::systemConf()->limits;
  142. $this->view->feeds = $feedDAO->listFeeds();
  143. if (count($this->view->feeds) >= $limits['max_feeds']) {
  144. Minz_Request::bad(_t('feedback.sub.feed.over_max', $limits['max_feeds']), $url_redirect);
  145. }
  146. if (Minz_Request::isPost()) {
  147. $cat = Minz_Request::paramInt('category');
  148. // HTTP information are useful if feed is protected behind a
  149. // HTTP authentication
  150. $user = Minz_Request::paramString('http_user');
  151. $pass = Minz_Request::paramString('http_pass');
  152. $http_auth = '';
  153. if ($user != '' && $pass != '') { //TODO: Sanitize
  154. $http_auth = $user . ':' . $pass;
  155. }
  156. $cookie = Minz_Request::paramString('curl_params_cookie');
  157. $cookie_file = Minz_Request::paramBoolean('curl_params_cookiefile');
  158. $max_redirs = Minz_Request::paramInt('curl_params_redirects');
  159. $useragent = Minz_Request::paramString('curl_params_useragent');
  160. $proxy_address = Minz_Request::paramString('curl_params');
  161. $proxy_type = Minz_Request::paramString('proxy_type');
  162. $opts = [];
  163. if ($proxy_type !== '') {
  164. $opts[CURLOPT_PROXY] = $proxy_address;
  165. $opts[CURLOPT_PROXYTYPE] = (int)$proxy_type;
  166. }
  167. if ($cookie !== '') {
  168. $opts[CURLOPT_COOKIE] = $cookie;
  169. }
  170. if ($cookie_file) {
  171. // Pass empty cookie file name to enable the libcurl cookie engine
  172. // without reading any existing cookie data.
  173. $opts[CURLOPT_COOKIEFILE] = '';
  174. }
  175. if ($max_redirs !== 0) {
  176. $opts[CURLOPT_MAXREDIRS] = $max_redirs;
  177. $opts[CURLOPT_FOLLOWLOCATION] = 1;
  178. }
  179. if ($useragent !== '') {
  180. $opts[CURLOPT_USERAGENT] = $useragent;
  181. }
  182. $attributes = [
  183. 'curl_params' => empty($opts) ? null : $opts,
  184. ];
  185. $attributes['ssl_verify'] = Minz_Request::paramTernary('ssl_verify');
  186. $timeout = Minz_Request::paramInt('timeout');
  187. $attributes['timeout'] = $timeout > 0 ? $timeout : null;
  188. $feed_kind = Minz_Request::paramInt('feed_kind') ?: FreshRSS_Feed::KIND_RSS;
  189. if ($feed_kind === FreshRSS_Feed::KIND_HTML_XPATH || $feed_kind === FreshRSS_Feed::KIND_XML_XPATH) {
  190. $xPathSettings = [];
  191. if (Minz_Request::paramString('xPathFeedTitle') !== '') {
  192. $xPathSettings['feedTitle'] = Minz_Request::paramString('xPathFeedTitle', true);
  193. }
  194. if (Minz_Request::paramString('xPathItem') !== '') {
  195. $xPathSettings['item'] = Minz_Request::paramString('xPathItem', true);
  196. }
  197. if (Minz_Request::paramString('xPathItemTitle') !== '') {
  198. $xPathSettings['itemTitle'] = Minz_Request::paramString('xPathItemTitle', true);
  199. }
  200. if (Minz_Request::paramString('xPathItemContent') !== '') {
  201. $xPathSettings['itemContent'] = Minz_Request::paramString('xPathItemContent', true);
  202. }
  203. if (Minz_Request::paramString('xPathItemUri') !== '') {
  204. $xPathSettings['itemUri'] = Minz_Request::paramString('xPathItemUri', true);
  205. }
  206. if (Minz_Request::paramString('xPathItemAuthor') !== '') {
  207. $xPathSettings['itemAuthor'] = Minz_Request::paramString('xPathItemAuthor', true);
  208. }
  209. if (Minz_Request::paramString('xPathItemTimestamp') !== '') {
  210. $xPathSettings['itemTimestamp'] = Minz_Request::paramString('xPathItemTimestamp', true);
  211. }
  212. if (Minz_Request::paramString('xPathItemTimeFormat') !== '') {
  213. $xPathSettings['itemTimeFormat'] = Minz_Request::paramString('xPathItemTimeFormat', true);
  214. }
  215. if (Minz_Request::paramString('xPathItemThumbnail') !== '') {
  216. $xPathSettings['itemThumbnail'] = Minz_Request::paramString('xPathItemThumbnail', true);
  217. }
  218. if (Minz_Request::paramString('xPathItemCategories') !== '') {
  219. $xPathSettings['itemCategories'] = Minz_Request::paramString('xPathItemCategories', true);
  220. }
  221. if (Minz_Request::paramString('xPathItemUid') !== '') {
  222. $xPathSettings['itemUid'] = Minz_Request::paramString('xPathItemUid', true);
  223. }
  224. if (!empty($xPathSettings)) {
  225. $attributes['xpath'] = $xPathSettings;
  226. }
  227. }
  228. try {
  229. $feed = self::addFeed($url, '', $cat, '', $http_auth, $attributes, $feed_kind);
  230. } catch (FreshRSS_BadUrl_Exception $e) {
  231. // Given url was not a valid url!
  232. Minz_Log::warning($e->getMessage());
  233. Minz_Request::bad(_t('feedback.sub.feed.invalid_url', $url), $url_redirect);
  234. return;
  235. } catch (FreshRSS_Feed_Exception $e) {
  236. // Something went bad (timeout, server not found, etc.)
  237. Minz_Log::warning($e->getMessage());
  238. Minz_Request::bad(_t('feedback.sub.feed.internal_problem', _url('index', 'logs')), $url_redirect);
  239. return;
  240. } catch (Minz_FileNotExistException $e) {
  241. // Cache directory doesn’t exist!
  242. Minz_Log::error($e->getMessage());
  243. Minz_Request::bad(_t('feedback.sub.feed.internal_problem', _url('index', 'logs')), $url_redirect);
  244. return;
  245. } catch (FreshRSS_AlreadySubscribed_Exception $e) {
  246. Minz_Request::bad(_t('feedback.sub.feed.already_subscribed', $e->feedName()), $url_redirect);
  247. return;
  248. } catch (FreshRSS_FeedNotAdded_Exception $e) {
  249. Minz_Request::bad(_t('feedback.sub.feed.not_added', $e->url()), $url_redirect);
  250. return;
  251. }
  252. // Entries are in DB, we redirect to feed configuration page.
  253. $url_redirect['a'] = 'feed';
  254. $url_redirect['params']['id'] = '' . $feed->id();
  255. Minz_Request::good(_t('feedback.sub.feed.added', $feed->name()), $url_redirect);
  256. } else {
  257. // GET request: we must ask confirmation to user before adding feed.
  258. FreshRSS_View::prependTitle(_t('sub.feed.title_add') . ' · ');
  259. $catDAO = FreshRSS_Factory::createCategoryDao();
  260. $this->view->categories = $catDAO->listCategories(false) ?: [];
  261. $this->view->feed = new FreshRSS_Feed($url);
  262. try {
  263. // We try to get more information about the feed.
  264. $this->view->feed->load(true);
  265. $this->view->load_ok = true;
  266. } catch (Exception $e) {
  267. $this->view->load_ok = false;
  268. }
  269. $feed = $feedDAO->searchByUrl($this->view->feed->url());
  270. if ($feed) {
  271. // Already subscribe so we redirect to the feed configuration page.
  272. $url_redirect['a'] = 'feed';
  273. $url_redirect['params']['id'] = $feed->id();
  274. Minz_Request::good(_t('feedback.sub.feed.already_subscribed', $feed->name()), $url_redirect);
  275. }
  276. }
  277. }
  278. /**
  279. * This action remove entries from a given feed.
  280. *
  281. * It should be reached by a POST action.
  282. *
  283. * Parameter is:
  284. * - id (default: false)
  285. */
  286. public function truncateAction(): void {
  287. $id = Minz_Request::paramInt('id');
  288. $url_redirect = [
  289. 'c' => 'subscription',
  290. 'a' => 'index',
  291. 'params' => ['id' => $id],
  292. ];
  293. if (!Minz_Request::isPost()) {
  294. Minz_Request::forward($url_redirect, true);
  295. }
  296. $feedDAO = FreshRSS_Factory::createFeedDao();
  297. $n = $feedDAO->truncate($id);
  298. invalidateHttpCache();
  299. if ($n === false) {
  300. Minz_Request::bad(_t('feedback.sub.feed.error'), $url_redirect);
  301. } else {
  302. Minz_Request::good(_t('feedback.sub.feed.n_entries_deleted', $n), $url_redirect);
  303. }
  304. }
  305. /**
  306. * @return array{0:int,1:FreshRSS_Feed|null,2:int} Number of updated feeds, first feed or null, number of new articles
  307. * @throws FreshRSS_BadUrl_Exception
  308. */
  309. public static function actualizeFeeds(?int $feed_id = null, ?string $feed_url = null, ?int $maxFeeds = null, ?SimplePie $simplePiePush = null): array {
  310. if (function_exists('set_time_limit')) {
  311. @set_time_limit(300);
  312. }
  313. if (!is_int($feed_id) || $feed_id <= 0) {
  314. $feed_id = null;
  315. }
  316. if (!is_string($feed_url) || trim($feed_url) === '') {
  317. $feed_url = null;
  318. }
  319. if (!is_int($maxFeeds) || $maxFeeds <= 0) {
  320. $maxFeeds = PHP_INT_MAX;
  321. }
  322. $feedDAO = FreshRSS_Factory::createFeedDao();
  323. $entryDAO = FreshRSS_Factory::createEntryDao();
  324. // Create a list of feeds to actualize.
  325. $feeds = [];
  326. if ($feed_id !== null || $feed_url !== null) {
  327. $feed = $feed_id !== null ? $feedDAO->searchById($feed_id) : $feedDAO->searchByUrl($feed_url);
  328. if ($feed !== null && $feed->id() > 0) {
  329. $feeds[] = $feed;
  330. $feed_id = $feed->id();
  331. }
  332. } else {
  333. $feeds = $feedDAO->listFeedsOrderUpdate(-1);
  334. // Hydrate category for each feed to avoid that each feed has to make an SQL request
  335. $categories = [];
  336. $catDAO = FreshRSS_Factory::createCategoryDao();
  337. foreach ($catDAO->listCategories(false, false) as $category) {
  338. $categories[$category->id()] = $category;
  339. }
  340. foreach ($feeds as $feed) {
  341. $category = $categories[$feed->categoryId()] ?? null;
  342. if ($category !== null) {
  343. $feed->_category($category);
  344. }
  345. }
  346. }
  347. // WebSub (PubSubHubbub) support
  348. $pubsubhubbubEnabledGeneral = FreshRSS_Context::systemConf()->pubsubhubbub_enabled;
  349. $pshbMinAge = time() - (3600 * 24); //TODO: Make a configuration.
  350. $updated_feeds = 0;
  351. $nb_new_articles = 0;
  352. foreach ($feeds as $feed) {
  353. /** @var FreshRSS_Feed|null $feed */
  354. $feed = Minz_ExtensionManager::callHook('feed_before_actualize', $feed);
  355. if (null === $feed) {
  356. continue;
  357. }
  358. $url = $feed->url(); //For detection of HTTP 301
  359. $pubSubHubbubEnabled = $pubsubhubbubEnabledGeneral && $feed->pubSubHubbubEnabled();
  360. if ($simplePiePush === null && $feed_id === null && $pubSubHubbubEnabled && ($feed->lastUpdate() > $pshbMinAge)) {
  361. //$text = 'Skip pull of feed using PubSubHubbub: ' . $url;
  362. //Minz_Log::debug($text);
  363. //Minz_Log::debug($text, PSHB_LOG);
  364. continue; //When PubSubHubbub is used, do not pull refresh so often
  365. }
  366. if ($feed->mute()) {
  367. continue; //Feed refresh is disabled
  368. }
  369. $mtime = $feed->cacheModifiedTime() ?: 0;
  370. $ttl = $feed->ttl();
  371. if ($ttl === FreshRSS_Feed::TTL_DEFAULT) {
  372. $ttl = FreshRSS_Context::userConf()->ttl_default;
  373. }
  374. if ($simplePiePush === null && $feed_id === null && (time() <= $feed->lastUpdate() + $ttl)) {
  375. //Too early to refresh from source, but check whether the feed was updated by another user
  376. $ε = 10; // negligible offset errors in seconds
  377. if ($mtime <= 0 ||
  378. $feed->lastUpdate() + $ε >= $mtime ||
  379. time() + $ε >= $mtime + FreshRSS_Context::systemConf()->limits['cache_duration']) { // is cache still valid?
  380. continue; //Nothing newer from other users
  381. }
  382. Minz_Log::debug('Feed ' . $feed->url(false) . ' was updated at ' . date('c', $feed->lastUpdate()) .
  383. ', and at ' . date('c', $mtime) . ' by another user; take advantage of newer cache.');
  384. }
  385. if (!$feed->lock()) {
  386. Minz_Log::notice('Feed already being actualized: ' . $feed->url(false));
  387. continue;
  388. }
  389. $feedIsNew = $feed->lastUpdate() <= 0;
  390. $feedIsEmpty = false;
  391. $feedIsUnchanged = false;
  392. try {
  393. if ($simplePiePush !== null) {
  394. $simplePie = $simplePiePush; //Used by WebSub
  395. } elseif ($feed->kind() === FreshRSS_Feed::KIND_HTML_XPATH) {
  396. $simplePie = $feed->loadHtmlXpath();
  397. if ($simplePie === null) {
  398. throw new FreshRSS_Feed_Exception('HTML+XPath Web scraping failed for [' . $feed->url(false) . ']');
  399. }
  400. } elseif ($feed->kind() === FreshRSS_Feed::KIND_XML_XPATH) {
  401. $simplePie = $feed->loadHtmlXpath();
  402. if ($simplePie === null) {
  403. throw new FreshRSS_Feed_Exception('XML+XPath parsing failed for [' . $feed->url(false) . ']');
  404. }
  405. } else {
  406. $simplePie = $feed->load(false, $feedIsNew);
  407. }
  408. if ($simplePie === null) {
  409. // Feed is cached and unchanged
  410. $newGuids = [];
  411. $entries = [];
  412. $feedIsEmpty = false; // We do not know
  413. $feedIsUnchanged = true;
  414. } else {
  415. $newGuids = $feed->loadGuids($simplePie);
  416. $entries = $feed->loadEntries($simplePie);
  417. $feedIsEmpty = $simplePiePush !== null && empty($newGuids);
  418. $feedIsUnchanged = false;
  419. }
  420. $mtime = $feed->cacheModifiedTime() ?: time();
  421. } catch (FreshRSS_Feed_Exception $e) {
  422. Minz_Log::warning($e->getMessage());
  423. $feedDAO->updateLastUpdate($feed->id(), true);
  424. if ($e->getCode() === 410) {
  425. // HTTP 410 Gone
  426. Minz_Log::warning('Muting gone feed: ' . $feed->url(false));
  427. $feedDAO->mute($feed->id(), true);
  428. }
  429. $feed->unlock();
  430. continue;
  431. }
  432. $needFeedCacheRefresh = false;
  433. $nbMarkedUnread = 0;
  434. if (count($newGuids) > 0) {
  435. if ($feed->attributeBoolean('read_when_same_title_in_feed') === null) {
  436. $readWhenSameTitleInFeed = (int)FreshRSS_Context::userConf()->mark_when['same_title_in_feed'];
  437. } elseif ($feed->attributeBoolean('read_when_same_title_in_feed') === false) {
  438. $readWhenSameTitleInFeed = 0;
  439. } else {
  440. $readWhenSameTitleInFeed = $feed->attributeInt('read_when_same_title_in_feed') ?? 0;
  441. }
  442. if ($readWhenSameTitleInFeed > 0) {
  443. $titlesAsRead = array_flip($feedDAO->listTitles($feed->id(), $readWhenSameTitleInFeed));
  444. } else {
  445. $titlesAsRead = [];
  446. }
  447. $mark_updated_article_unread = $feed->attributeBoolean('mark_updated_article_unread') ?? FreshRSS_Context::userConf()->mark_updated_article_unread;
  448. // For this feed, check existing GUIDs already in database.
  449. $existingHashForGuids = $entryDAO->listHashForFeedGuids($feed->id(), $newGuids) ?: [];
  450. /** @var array<string,bool> $newGuids */
  451. $newGuids = [];
  452. // Add entries in database if possible.
  453. /** @var FreshRSS_Entry $entry */
  454. foreach ($entries as $entry) {
  455. if (isset($newGuids[$entry->guid()])) {
  456. continue; //Skip subsequent articles with same GUID
  457. }
  458. $newGuids[$entry->guid()] = true;
  459. $entry->_lastSeen($mtime);
  460. if (isset($existingHashForGuids[$entry->guid()])) {
  461. $existingHash = $existingHashForGuids[$entry->guid()];
  462. if (strcasecmp($existingHash, $entry->hash()) !== 0) {
  463. //This entry already exists but has been updated
  464. //Minz_Log::debug('Entry with GUID `' . $entry->guid() . '` updated in feed ' . $feed->url(false) .
  465. //', old hash ' . $existingHash . ', new hash ' . $entry->hash());
  466. $entry->_isFavorite(null); // Do not change favourite state
  467. $entry->_isRead($mark_updated_article_unread ? false : null); //Change is_read according to policy.
  468. if ($mark_updated_article_unread) {
  469. Minz_ExtensionManager::callHook('entry_auto_unread', $entry, 'updated_article');
  470. }
  471. $entry = Minz_ExtensionManager::callHook('entry_before_insert', $entry);
  472. if (!($entry instanceof FreshRSS_Entry)) {
  473. // An extension has returned a null value, there is nothing to insert.
  474. continue;
  475. }
  476. if (!$entry->isRead()) {
  477. $needFeedCacheRefresh = true; //Maybe
  478. $nbMarkedUnread++;
  479. }
  480. // If the entry has changed, there is a good chance for the full content to have changed as well.
  481. $entry->loadCompleteContent(true);
  482. if (!$entryDAO->inTransaction()) {
  483. $entryDAO->beginTransaction();
  484. }
  485. $entryDAO->updateEntry($entry->toArray());
  486. }
  487. } else {
  488. $id = uTimeString();
  489. $entry->_id($id);
  490. $entry->applyFilterActions($titlesAsRead);
  491. if ($readWhenSameTitleInFeed > 0) {
  492. $titlesAsRead[$entry->title()] = true;
  493. }
  494. $entry = Minz_ExtensionManager::callHook('entry_before_insert', $entry);
  495. if (!($entry instanceof FreshRSS_Entry)) {
  496. // An extension has returned a null value, there is nothing to insert.
  497. continue;
  498. }
  499. if ($pubSubHubbubEnabled && !$simplePiePush) { //We use push, but have discovered an article by pull!
  500. $text = 'An article was discovered by pull although we use PubSubHubbub!: Feed ' .
  501. SimplePie_Misc::url_remove_credentials($url) .
  502. ' GUID ' . $entry->guid();
  503. Minz_Log::warning($text, PSHB_LOG);
  504. Minz_Log::warning($text);
  505. $pubSubHubbubEnabled = false;
  506. $feed->pubSubHubbubError(true);
  507. }
  508. if (!$entryDAO->inTransaction()) {
  509. $entryDAO->beginTransaction();
  510. }
  511. $entryDAO->addEntry($entry->toArray(), true);
  512. $nb_new_articles++;
  513. }
  514. }
  515. // N.B.: Applies to _entry table and not _entrytmp:
  516. $entryDAO->updateLastSeen($feed->id(), array_keys($newGuids), $mtime);
  517. } elseif ($feedIsUnchanged) {
  518. // Feed cache was unchanged, so mark as seen the same entries as last time
  519. if (!$entryDAO->inTransaction()) {
  520. $entryDAO->beginTransaction();
  521. }
  522. $entryDAO->updateLastSeenUnchanged($feed->id(), $mtime);
  523. }
  524. unset($entries);
  525. if (rand(0, 30) === 1) { // Remove old entries once in 30.
  526. if (!$entryDAO->inTransaction()) {
  527. $entryDAO->beginTransaction();
  528. }
  529. $nb = $feed->cleanOldEntries();
  530. if ($nb > 0) {
  531. $needFeedCacheRefresh = true;
  532. }
  533. }
  534. $feedDAO->updateLastUpdate($feed->id(), false, $mtime);
  535. if ($feed->keepMaxUnread() !== null && ($feed->nbNotRead() + $nbMarkedUnread > $feed->keepMaxUnread())) {
  536. Minz_Log::debug('Existing unread entries (' . ($feed->nbNotRead() + $nbMarkedUnread) . ') exceeding max number of ' .
  537. $feed->keepMaxUnread() . ' for [' . $feed->url(false) . ']');
  538. $needFeedCacheRefresh |= ($feed->markAsReadMaxUnread() != false);
  539. }
  540. if ($simplePiePush === null) {
  541. // Do not call for WebSub events, as we do not know the list of articles still on the upstream feed.
  542. $needFeedCacheRefresh |= ($feed->markAsReadUponGone($feedIsEmpty, $mtime) != false);
  543. }
  544. if ($needFeedCacheRefresh) {
  545. $feedDAO->updateCachedValues($feed->id());
  546. }
  547. if ($entryDAO->inTransaction()) {
  548. $entryDAO->commit();
  549. }
  550. $feedProperties = [];
  551. if ($pubsubhubbubEnabledGeneral && $feed->hubUrl() && $feed->selfUrl()) { //selfUrl has priority for WebSub
  552. if ($feed->selfUrl() !== $url) { // https://github.com/pubsubhubbub/PubSubHubbub/wiki/Moving-Feeds-or-changing-Hubs
  553. $selfUrl = checkUrl($feed->selfUrl());
  554. if ($selfUrl) {
  555. Minz_Log::debug('WebSub unsubscribe ' . $feed->url(false));
  556. if (!$feed->pubSubHubbubSubscribe(false)) { //Unsubscribe
  557. Minz_Log::warning('Error while WebSub unsubscribing from ' . $feed->url(false));
  558. }
  559. $feed->_url($selfUrl, false);
  560. Minz_Log::notice('Feed ' . $url . ' canonical address moved to ' . $feed->url(false));
  561. $feedDAO->updateFeed($feed->id(), ['url' => $feed->url()]);
  562. }
  563. }
  564. } elseif ($feed->url() !== $url) { // HTTP 301 Moved Permanently
  565. Minz_Log::notice('Feed ' . SimplePie_Misc::url_remove_credentials($url) .
  566. ' moved permanently to ' . SimplePie_Misc::url_remove_credentials($feed->url(false)));
  567. $feedProperties['url'] = $feed->url();
  568. }
  569. if ($simplePie != null) {
  570. if ($feed->name(true) === '') {
  571. //HTML to HTML-PRE //ENT_COMPAT except '&'
  572. $name = strtr(html_only_entity_decode($simplePie->get_title()), ['<' => '&lt;', '>' => '&gt;', '"' => '&quot;']);
  573. $feed->_name($name);
  574. $feedProperties['name'] = $feed->name(false);
  575. }
  576. if (trim($feed->website()) === '') {
  577. $website = html_only_entity_decode($simplePie->get_link());
  578. $feed->_website($website == '' ? $feed->url() : $website);
  579. $feedProperties['website'] = $feed->website();
  580. $feed->faviconPrepare();
  581. }
  582. if (trim($feed->description()) === '') {
  583. $description = html_only_entity_decode($simplePie->get_description());
  584. if ($description !== '') {
  585. $feed->_description($description);
  586. $feedProperties['description'] = $feed->description();
  587. }
  588. }
  589. }
  590. if (!empty($feedProperties)) {
  591. $ok = $feedDAO->updateFeed($feed->id(), $feedProperties);
  592. if (!$ok && $feedIsNew) {
  593. //Cancel adding new feed in case of database error at first actualize
  594. $feedDAO->deleteFeed($feed->id());
  595. $feed->unlock();
  596. break;
  597. }
  598. }
  599. $feed->faviconPrepare();
  600. if ($pubsubhubbubEnabledGeneral && $feed->pubSubHubbubPrepare()) {
  601. Minz_Log::notice('WebSub subscribe ' . $feed->url(false));
  602. if (!$feed->pubSubHubbubSubscribe(true)) { //Subscribe
  603. Minz_Log::warning('Error while WebSub subscribing to ' . $feed->url(false));
  604. }
  605. }
  606. $feed->unlock();
  607. $updated_feeds++;
  608. unset($feed);
  609. gc_collect_cycles();
  610. if ($updated_feeds >= $maxFeeds) {
  611. break;
  612. }
  613. }
  614. return [$updated_feeds, reset($feeds) ?: null, $nb_new_articles];
  615. }
  616. public static function commitNewEntries(): bool {
  617. $entryDAO = FreshRSS_Factory::createEntryDao();
  618. if (!$entryDAO->inTransaction()) {
  619. $entryDAO->beginTransaction();
  620. }
  621. $newUnreadEntriesPerFeed = $entryDAO->newUnreadEntriesPerFeed();
  622. if ($entryDAO->commitNewEntries()) {
  623. $feedDAO = FreshRSS_Factory::createFeedDao();
  624. $feeds = $feedDAO->listFeedsOrderUpdate(-1);
  625. foreach ($feeds as $feed) {
  626. if (!empty($newUnreadEntriesPerFeed[$feed->id()]) && $feed->keepMaxUnread() !== null &&
  627. ($feed->nbNotRead() + $newUnreadEntriesPerFeed[$feed->id()] > $feed->keepMaxUnread())) {
  628. Minz_Log::debug('New unread entries (' . ($feed->nbNotRead() + $newUnreadEntriesPerFeed[$feed->id()]) . ') exceeding max number of ' .
  629. $feed->keepMaxUnread() . ' for [' . $feed->url(false) . ']');
  630. $feed->markAsReadMaxUnread();
  631. }
  632. }
  633. $feedDAO->updateCachedValues();
  634. }
  635. if ($entryDAO->inTransaction()) {
  636. $entryDAO->commit();
  637. }
  638. $databaseDAO = FreshRSS_Factory::createDatabaseDAO();
  639. $databaseDAO->minorDbMaintenance();
  640. return true;
  641. }
  642. /**
  643. * This action actualizes entries from one or several feeds.
  644. *
  645. * Parameters are:
  646. * - id (default: null): Feed ID, or set to -1 to commit new articles to the main database
  647. * - url (default: null): Feed URL (instead of feed ID)
  648. * - maxFeeds (default: 10): Max number of feeds to refresh
  649. * - noCommit (default: 0): Set to 1 to prevent committing the new articles to the main database
  650. * If id and url are not specified, all the feeds are actualized, within the limits of maxFeeds.
  651. */
  652. public function actualizeAction(): int {
  653. Minz_Session::_param('actualize_feeds', false);
  654. $id = Minz_Request::paramInt('id');
  655. $url = Minz_Request::paramString('url');
  656. $maxFeeds = Minz_Request::paramInt('maxFeeds') ?: 10;
  657. $noCommit = ($_POST['noCommit'] ?? 0) == 1;
  658. if ($id === -1 && !$noCommit) { //Special request only to commit & refresh DB cache
  659. $updated_feeds = 0;
  660. $feed = null;
  661. self::commitNewEntries();
  662. } else {
  663. if ($id === 0 && $url === '') {
  664. FreshRSS_category_Controller::refreshDynamicOpmls();
  665. }
  666. [$updated_feeds, $feed, $nbNewArticles] = self::actualizeFeeds($id, $url, $maxFeeds);
  667. if (!$noCommit && $nbNewArticles > 0) {
  668. FreshRSS_feed_Controller::commitNewEntries();
  669. }
  670. }
  671. if (Minz_Request::paramBoolean('ajax')) {
  672. // Most of the time, ajax request is for only one feed. But since
  673. // there are several parallel requests, we should return that there
  674. // are several updated feeds.
  675. Minz_Request::setGoodNotification(_t('feedback.sub.feed.actualizeds'));
  676. // No layout in ajax request.
  677. $this->view->_layout(null);
  678. } elseif ($feed instanceof FreshRSS_Feed) {
  679. // Redirect to the main page with correct notification.
  680. Minz_Request::good(_t('feedback.sub.feed.actualized', $feed->name()), [
  681. 'params' => ['get' => 'f_' . $id]
  682. ]);
  683. } elseif ($updated_feeds >= 1) {
  684. Minz_Request::good(_t('feedback.sub.feed.n_actualized', $updated_feeds), []);
  685. } else {
  686. Minz_Request::good(_t('feedback.sub.feed.no_refresh'), []);
  687. }
  688. return $updated_feeds;
  689. }
  690. /**
  691. * @throws Minz_ConfigurationNamespaceException
  692. * @throws JsonException
  693. * @throws Minz_PDOConnectionException
  694. */
  695. public static function renameFeed(int $feed_id, string $feed_name): bool {
  696. if ($feed_id <= 0 || $feed_name === '') {
  697. return false;
  698. }
  699. FreshRSS_UserDAO::touch();
  700. $feedDAO = FreshRSS_Factory::createFeedDao();
  701. return $feedDAO->updateFeed($feed_id, ['name' => $feed_name]) === 1;
  702. }
  703. public static function moveFeed(int $feed_id, int $cat_id, string $new_cat_name = ''): bool {
  704. if ($feed_id <= 0 || ($cat_id <= 0 && $new_cat_name === '')) {
  705. return false;
  706. }
  707. FreshRSS_UserDAO::touch();
  708. $catDAO = FreshRSS_Factory::createCategoryDao();
  709. if ($cat_id > 0) {
  710. $cat = $catDAO->searchById($cat_id);
  711. $cat_id = $cat === null ? 0 : $cat->id();
  712. }
  713. if ($cat_id <= 1 && $new_cat_name != '') {
  714. $cat_id = $catDAO->addCategory(['name' => $new_cat_name]);
  715. }
  716. if ($cat_id <= 1) {
  717. $catDAO->checkDefault();
  718. $cat_id = FreshRSS_CategoryDAO::DEFAULTCATEGORYID;
  719. }
  720. $feedDAO = FreshRSS_Factory::createFeedDao();
  721. return $feedDAO->updateFeed($feed_id, ['category' => $cat_id]) === 1;
  722. }
  723. /**
  724. * This action changes the category of a feed.
  725. *
  726. * This page must be reached by a POST request.
  727. *
  728. * Parameters are:
  729. * - f_id (default: false)
  730. * - c_id (default: false)
  731. * If c_id is false, default category is used.
  732. *
  733. * @todo should handle order of the feed inside the category.
  734. */
  735. public function moveAction(): void {
  736. if (!Minz_Request::isPost()) {
  737. Minz_Request::forward(['c' => 'subscription'], true);
  738. }
  739. $feed_id = Minz_Request::paramInt('f_id');
  740. $cat_id = Minz_Request::paramInt('c_id');
  741. if (self::moveFeed($feed_id, $cat_id)) {
  742. // TODO: return something useful
  743. // Log a notice to prevent "Empty IF statement" warning in PHP_CodeSniffer
  744. Minz_Log::notice('Moved feed `' . $feed_id . '` in the category `' . $cat_id . '`');
  745. } else {
  746. Minz_Log::warning('Cannot move feed `' . $feed_id . '` in the category `' . $cat_id . '`');
  747. Minz_Error::error(404);
  748. }
  749. }
  750. public static function deleteFeed(int $feed_id): bool {
  751. FreshRSS_UserDAO::touch();
  752. $feedDAO = FreshRSS_Factory::createFeedDao();
  753. if ($feedDAO->deleteFeed($feed_id)) {
  754. // TODO: Delete old favicon
  755. // Remove related queries
  756. /** @var array<array{'get'?:string,'name'?:string,'order'?:string,'search'?:string,'state'?:int,'url'?:string}> $queries */
  757. $queries = remove_query_by_get('f_' . $feed_id, FreshRSS_Context::userConf()->queries);
  758. FreshRSS_Context::userConf()->queries = $queries;
  759. FreshRSS_Context::userConf()->save();
  760. return true;
  761. }
  762. return false;
  763. }
  764. /**
  765. * This action deletes a feed.
  766. *
  767. * This page must be reached by a POST request.
  768. * If there are related queries, they are deleted too.
  769. *
  770. * Parameters are:
  771. * - id (default: false)
  772. */
  773. public function deleteAction(): void {
  774. $from = Minz_Request::paramString('from');
  775. $id = Minz_Request::paramInt('id');
  776. switch ($from) {
  777. case 'stats':
  778. $redirect_url = ['c' => 'stats', 'a' => 'idle'];
  779. break;
  780. case 'normal':
  781. $get = Minz_Request::paramString('get');
  782. if ($get) {
  783. $redirect_url = ['c' => 'index', 'a' => 'normal', 'params' => ['get' => $get]];
  784. } else {
  785. $redirect_url = ['c' => 'index', 'a' => 'normal'];
  786. }
  787. break;
  788. default:
  789. $redirect_url = ['c' => 'subscription', 'a' => 'index'];
  790. if (!Minz_Request::isPost()) {
  791. Minz_Request::forward($redirect_url, true);
  792. }
  793. }
  794. if (self::deleteFeed($id)) {
  795. Minz_Request::good(_t('feedback.sub.feed.deleted'), $redirect_url);
  796. } else {
  797. Minz_Request::bad(_t('feedback.sub.feed.error'), $redirect_url);
  798. }
  799. }
  800. /**
  801. * This action force clears the cache of a feed.
  802. *
  803. * Parameters are:
  804. * - id (mandatory - no default): Feed ID
  805. *
  806. */
  807. public function clearCacheAction(): void {
  808. //Get Feed.
  809. $id = Minz_Request::paramInt('id');
  810. $feedDAO = FreshRSS_Factory::createFeedDao();
  811. $feed = $feedDAO->searchById($id);
  812. if ($feed === null) {
  813. Minz_Request::bad(_t('feedback.sub.feed.not_found'), []);
  814. return;
  815. }
  816. $feed->clearCache();
  817. Minz_Request::good(_t('feedback.sub.feed.cache_cleared', $feed->name()), [
  818. 'params' => ['get' => 'f_' . $feed->id()],
  819. ]);
  820. }
  821. /**
  822. * This action forces reloading the articles of a feed.
  823. *
  824. * Parameters are:
  825. * - id (mandatory - no default): Feed ID
  826. *
  827. * @throws FreshRSS_BadUrl_Exception
  828. */
  829. public function reloadAction(): void {
  830. if (function_exists('set_time_limit')) {
  831. @set_time_limit(300);
  832. }
  833. //Get Feed ID.
  834. $feed_id = Minz_Request::paramInt('id');
  835. $limit = Minz_Request::paramInt('reload_limit') ?: 10;
  836. $feedDAO = FreshRSS_Factory::createFeedDao();
  837. $entryDAO = FreshRSS_Factory::createEntryDao();
  838. $feed = $feedDAO->searchById($feed_id);
  839. if ($feed === null) {
  840. Minz_Request::bad(_t('feedback.sub.feed.not_found'), []);
  841. return;
  842. }
  843. //Re-fetch articles as if the feed was new.
  844. $feedDAO->updateFeed($feed->id(), [ 'lastUpdate' => 0 ]);
  845. [, , $nb_new_articles] = self::actualizeFeeds($feed_id);
  846. if ($nb_new_articles > 0) {
  847. FreshRSS_feed_Controller::commitNewEntries();
  848. }
  849. //Extract all feed entries from database, load complete content and store them back in database.
  850. $entries = $entryDAO->listWhere('f', $feed_id, FreshRSS_Entry::STATE_ALL, 'DESC', $limit);
  851. //We need another DB connection in parallel for unbuffered streaming
  852. Minz_ModelPdo::$usesSharedPdo = false;
  853. if (FreshRSS_Context::systemConf()->db['type'] === 'mysql') {
  854. // Second parallel connection for unbuffered streaming: MySQL
  855. $entryDAO2 = FreshRSS_Factory::createEntryDao();
  856. } else {
  857. // Single connection for buffered queries (in memory): SQLite, PostgreSQL
  858. //TODO: Consider an unbuffered query for PostgreSQL
  859. $entryDAO2 = $entryDAO;
  860. }
  861. foreach ($entries as $entry) {
  862. if ($entry->loadCompleteContent(true)) {
  863. $entryDAO2->updateEntry($entry->toArray());
  864. }
  865. }
  866. Minz_ModelPdo::$usesSharedPdo = true;
  867. //Give feedback to user.
  868. Minz_Request::good(_t('feedback.sub.feed.reloaded', $feed->name()), [
  869. 'params' => ['get' => 'f_' . $feed->id()]
  870. ]);
  871. }
  872. /**
  873. * This action creates a preview of a content-selector.
  874. *
  875. * Parameters are:
  876. * - id (mandatory - no default): Feed ID
  877. * - selector (mandatory - no default): Selector to preview
  878. *
  879. */
  880. public function contentSelectorPreviewAction(): void {
  881. //Configure.
  882. $this->view->fatalError = '';
  883. $this->view->selectorSuccess = false;
  884. $this->view->htmlContent = '';
  885. $this->view->_layout(null);
  886. $this->_csp([
  887. 'default-src' => "'self'",
  888. 'frame-src' => '*',
  889. 'img-src' => '* data:',
  890. 'media-src' => '*',
  891. ]);
  892. //Get parameters.
  893. $feed_id = Minz_Request::paramInt('id');
  894. $content_selector = Minz_Request::paramString('selector');
  895. if (!$content_selector) {
  896. $this->view->fatalError = _t('feedback.sub.feed.selector_preview.selector_empty');
  897. return;
  898. }
  899. //Check Feed ID validity.
  900. $entryDAO = FreshRSS_Factory::createEntryDao();
  901. $entries = $entryDAO->listWhere('f', $feed_id);
  902. $entry = null;
  903. //Get first entry (syntax robust for Generator or Array)
  904. foreach ($entries as $myEntry) {
  905. $entry = $myEntry;
  906. }
  907. if ($entry == null) {
  908. $this->view->fatalError = _t('feedback.sub.feed.selector_preview.no_entries');
  909. return;
  910. }
  911. //Get feed.
  912. $feed = $entry->feed();
  913. if ($feed === null) {
  914. $this->view->fatalError = _t('feedback.sub.feed.selector_preview.no_feed');
  915. return;
  916. }
  917. $attributes = $feed->attributes();
  918. $attributes['path_entries_filter'] = Minz_Request::paramString('selector_filter', true);
  919. //Fetch & select content.
  920. try {
  921. $fullContent = FreshRSS_Entry::getContentByParsing(
  922. htmlspecialchars_decode($entry->link(), ENT_QUOTES),
  923. htmlspecialchars_decode($content_selector, ENT_QUOTES),
  924. $attributes
  925. );
  926. if ($fullContent != '') {
  927. $this->view->selectorSuccess = true;
  928. $this->view->htmlContent = $fullContent;
  929. } else {
  930. $this->view->selectorSuccess = false;
  931. $this->view->htmlContent = $entry->content(false);
  932. }
  933. } catch (Exception $e) {
  934. $this->view->fatalError = _t('feedback.sub.feed.selector_preview.http_error');
  935. }
  936. }
  937. }