feedController.php 40 KB

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