feedController.php 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168
  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. #[\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. $feedIsEmpty = false;
  442. $feedIsUnchanged = false;
  443. try {
  444. if ($simplePiePush !== null) {
  445. $simplePie = $simplePiePush; //Used by WebSub
  446. } elseif ($feed->kind() === FreshRSS_Feed::KIND_HTML_XPATH) {
  447. $simplePie = $feed->loadHtmlXpath();
  448. if ($simplePie === null) {
  449. throw new FreshRSS_Feed_Exception('HTML+XPath Web scraping failed for [' . $feed->url(false) . ']');
  450. }
  451. } elseif ($feed->kind() === FreshRSS_Feed::KIND_XML_XPATH) {
  452. $simplePie = $feed->loadHtmlXpath();
  453. if ($simplePie === null) {
  454. throw new FreshRSS_Feed_Exception('XML+XPath parsing failed for [' . $feed->url(false) . ']');
  455. }
  456. } elseif ($feed->kind() === FreshRSS_Feed::KIND_JSON_DOTNOTATION) {
  457. $simplePie = $feed->loadJson();
  458. if ($simplePie === null) {
  459. throw new FreshRSS_Feed_Exception('JSON dot notation parsing failed for [' . $feed->url(false) . ']');
  460. }
  461. } elseif ($feed->kind() === FreshRSS_Feed::KIND_JSONFEED) {
  462. $simplePie = $feed->loadJson();
  463. if ($simplePie === null) {
  464. throw new FreshRSS_Feed_Exception('JSON Feed parsing failed for [' . $feed->url(false) . ']');
  465. }
  466. } else {
  467. $simplePie = $feed->load(false, $feedIsNew);
  468. }
  469. if ($simplePie === null) {
  470. // Feed is cached and unchanged
  471. $newGuids = [];
  472. $entries = [];
  473. $feedIsEmpty = false; // We do not know
  474. $feedIsUnchanged = true;
  475. } else {
  476. $newGuids = $feed->loadGuids($simplePie);
  477. $entries = $feed->loadEntries($simplePie);
  478. $feedIsEmpty = $simplePiePush !== null && empty($newGuids);
  479. $feedIsUnchanged = false;
  480. }
  481. $mtime = $feed->cacheModifiedTime() ?: time();
  482. } catch (FreshRSS_Feed_Exception $e) {
  483. Minz_Log::warning($e->getMessage());
  484. $feedDAO->updateLastUpdate($feed->id(), true);
  485. if ($e->getCode() === 410) {
  486. // HTTP 410 Gone
  487. Minz_Log::warning('Muting gone feed: ' . $feed->url(false));
  488. $feedDAO->mute($feed->id(), true);
  489. }
  490. $feed->unlock();
  491. continue;
  492. }
  493. $needFeedCacheRefresh = false;
  494. $nbMarkedUnread = 0;
  495. if (count($newGuids) > 0) {
  496. if (!$feed->hasAttribute('read_when_same_title_in_feed')) {
  497. $readWhenSameTitleInFeed = (int)FreshRSS_Context::userConf()->mark_when['same_title_in_feed'];
  498. } elseif ($feed->attributeBoolean('read_when_same_title_in_feed') === false) {
  499. $readWhenSameTitleInFeed = 0;
  500. } else {
  501. $readWhenSameTitleInFeed = $feed->attributeInt('read_when_same_title_in_feed') ?? 0;
  502. }
  503. if ($readWhenSameTitleInFeed > 0) {
  504. $titlesAsRead = array_fill_keys($feedDAO->listTitles($feed->id(), $readWhenSameTitleInFeed), true);
  505. } else {
  506. $titlesAsRead = [];
  507. }
  508. $mark_updated_article_unread = $feed->attributeBoolean('mark_updated_article_unread') ?? FreshRSS_Context::userConf()->mark_updated_article_unread;
  509. // For this feed, check existing GUIDs already in database.
  510. $existingHashForGuids = $entryDAO->listHashForFeedGuids($feed->id(), $newGuids) ?: [];
  511. /** @var array<string,bool> $newGuids */
  512. $newGuids = [];
  513. // Add entries in database if possible.
  514. /** @var FreshRSS_Entry $entry */
  515. foreach ($entries as $entry) {
  516. if (isset($newGuids[$entry->guid()])) {
  517. continue; //Skip subsequent articles with same GUID
  518. }
  519. $newGuids[$entry->guid()] = true;
  520. $entry->_lastSeen($mtime);
  521. if (isset($existingHashForGuids[$entry->guid()])) {
  522. $existingHash = $existingHashForGuids[$entry->guid()];
  523. if (strcasecmp($existingHash, $entry->hash()) !== 0) {
  524. //This entry already exists but has been updated
  525. $entry->_isUpdated(true);
  526. //Minz_Log::debug('Entry with GUID `' . $entry->guid() . '` updated in feed ' . $feed->url(false) .
  527. //', old hash ' . $existingHash . ', new hash ' . $entry->hash());
  528. $entry->_isFavorite(null); // Do not change favourite state
  529. $entry->_isRead($mark_updated_article_unread ? false : null); //Change is_read according to policy.
  530. if ($mark_updated_article_unread) {
  531. Minz_ExtensionManager::callHook('entry_auto_unread', $entry, 'updated_article');
  532. }
  533. $entry = Minz_ExtensionManager::callHook('entry_before_insert', $entry);
  534. if (!($entry instanceof FreshRSS_Entry)) {
  535. // An extension has returned a null value, there is nothing to insert.
  536. continue;
  537. }
  538. $entry->applyFilterActions($titlesAsRead);
  539. if ($readWhenSameTitleInFeed > 0) {
  540. $titlesAsRead[$entry->title()] = true;
  541. }
  542. if (!$entry->isRead()) {
  543. $needFeedCacheRefresh = true; //Maybe
  544. $nbMarkedUnread++;
  545. }
  546. // If the entry has changed, there is a good chance for the full content to have changed as well.
  547. $entry->loadCompleteContent(true);
  548. if (!$entryDAO->inTransaction()) {
  549. $entryDAO->beginTransaction();
  550. }
  551. $entryDAO->updateEntry($entry->toArray());
  552. }
  553. } else {
  554. $entry->_isUpdated(false);
  555. $id = uTimeString();
  556. $entry->_id($id);
  557. $entry = Minz_ExtensionManager::callHook('entry_before_insert', $entry);
  558. if (!($entry instanceof FreshRSS_Entry)) {
  559. // An extension has returned a null value, there is nothing to insert.
  560. continue;
  561. }
  562. $entry->applyFilterActions($titlesAsRead);
  563. if ($readWhenSameTitleInFeed > 0) {
  564. $titlesAsRead[$entry->title()] = true;
  565. }
  566. if ($pubSubHubbubEnabled && !$simplePiePush) { //We use push, but have discovered an article by pull!
  567. $text = 'An article was discovered by pull although we use PubSubHubbub!: Feed ' .
  568. SimplePie_Misc::url_remove_credentials($url) .
  569. ' GUID ' . $entry->guid();
  570. Minz_Log::warning($text, PSHB_LOG);
  571. Minz_Log::warning($text);
  572. $pubSubHubbubEnabled = false;
  573. $feed->pubSubHubbubError(true);
  574. }
  575. if (!$entryDAO->inTransaction()) {
  576. $entryDAO->beginTransaction();
  577. }
  578. $entryDAO->addEntry($entry->toArray(), true);
  579. $nb_new_articles++;
  580. }
  581. }
  582. // N.B.: Applies to _entry table and not _entrytmp:
  583. $entryDAO->updateLastSeen($feed->id(), array_keys($newGuids), $mtime);
  584. } elseif ($feedIsUnchanged) {
  585. // Feed cache was unchanged, so mark as seen the same entries as last time
  586. if (!$entryDAO->inTransaction()) {
  587. $entryDAO->beginTransaction();
  588. }
  589. $entryDAO->updateLastSeenUnchanged($feed->id(), $mtime);
  590. }
  591. unset($entries);
  592. if (rand(0, 30) === 1) { // Remove old entries once in 30.
  593. if (!$entryDAO->inTransaction()) {
  594. $entryDAO->beginTransaction();
  595. }
  596. $nb = $feed->cleanOldEntries();
  597. if ($nb > 0) {
  598. $needFeedCacheRefresh = true;
  599. }
  600. }
  601. $feedDAO->updateLastUpdate($feed->id(), false, $mtime);
  602. if ($feed->keepMaxUnread() !== null && ($feed->nbNotRead() + $nbMarkedUnread > $feed->keepMaxUnread())) {
  603. Minz_Log::debug('Existing unread entries (' . ($feed->nbNotRead() + $nbMarkedUnread) . ') exceeding max number of ' .
  604. $feed->keepMaxUnread() . ' for [' . $feed->url(false) . ']');
  605. $needFeedCacheRefresh |= ($feed->markAsReadMaxUnread() != false);
  606. }
  607. if ($simplePiePush === null) {
  608. // Do not call for WebSub events, as we do not know the list of articles still on the upstream feed.
  609. $needFeedCacheRefresh |= ($feed->markAsReadUponGone($feedIsEmpty, $mtime) != false);
  610. }
  611. if ($needFeedCacheRefresh) {
  612. $feedDAO->updateCachedValues($feed->id());
  613. }
  614. if ($entryDAO->inTransaction()) {
  615. $entryDAO->commit();
  616. }
  617. $feedProperties = [];
  618. if ($pubsubhubbubEnabledGeneral && $feed->hubUrl() && $feed->selfUrl()) { //selfUrl has priority for WebSub
  619. if ($feed->selfUrl() !== $url) { // https://github.com/pubsubhubbub/PubSubHubbub/wiki/Moving-Feeds-or-changing-Hubs
  620. $selfUrl = checkUrl($feed->selfUrl());
  621. if ($selfUrl) {
  622. Minz_Log::debug('WebSub unsubscribe ' . $feed->url(false));
  623. if (!$feed->pubSubHubbubSubscribe(false)) { //Unsubscribe
  624. Minz_Log::warning('Error while WebSub unsubscribing from ' . $feed->url(false));
  625. }
  626. $feed->_url($selfUrl, false);
  627. Minz_Log::notice('Feed ' . $url . ' canonical address moved to ' . $feed->url(false));
  628. $feedDAO->updateFeed($feed->id(), ['url' => $feed->url()]);
  629. }
  630. }
  631. } elseif ($feed->url() !== $url) { // HTTP 301 Moved Permanently
  632. Minz_Log::notice('Feed ' . SimplePie_Misc::url_remove_credentials($url) .
  633. ' moved permanently to ' . SimplePie_Misc::url_remove_credentials($feed->url(false)));
  634. $feedProperties['url'] = $feed->url();
  635. }
  636. if ($simplePie != null) {
  637. if ($feed->name(true) === '') {
  638. //HTML to HTML-PRE //ENT_COMPAT except '&'
  639. $name = strtr(html_only_entity_decode($simplePie->get_title()), ['<' => '&lt;', '>' => '&gt;', '"' => '&quot;']);
  640. $feed->_name($name);
  641. $feedProperties['name'] = $feed->name(false);
  642. }
  643. if (trim($feed->website()) === '') {
  644. $website = html_only_entity_decode($simplePie->get_link());
  645. $feed->_website($website == '' ? $feed->url() : $website);
  646. $feedProperties['website'] = $feed->website();
  647. $feed->faviconPrepare();
  648. }
  649. if (trim($feed->description()) === '') {
  650. $description = html_only_entity_decode($simplePie->get_description());
  651. if ($description !== '') {
  652. $feed->_description($description);
  653. $feedProperties['description'] = $feed->description();
  654. }
  655. }
  656. }
  657. if (!empty($feedProperties)) {
  658. $ok = $feedDAO->updateFeed($feed->id(), $feedProperties);
  659. if (!$ok && $feedIsNew) {
  660. //Cancel adding new feed in case of database error at first actualize
  661. $feedDAO->deleteFeed($feed->id());
  662. $feed->unlock();
  663. break;
  664. }
  665. }
  666. $feed->faviconPrepare();
  667. if ($pubsubhubbubEnabledGeneral && $feed->pubSubHubbubPrepare()) {
  668. Minz_Log::notice('WebSub subscribe ' . $feed->url(false));
  669. if (!$feed->pubSubHubbubSubscribe(true)) { //Subscribe
  670. Minz_Log::warning('Error while WebSub subscribing to ' . $feed->url(false));
  671. }
  672. }
  673. $feed->unlock();
  674. $updated_feeds++;
  675. unset($feed);
  676. gc_collect_cycles();
  677. if ($updated_feeds >= $maxFeeds) {
  678. break;
  679. }
  680. }
  681. return [$updated_feeds, reset($feeds) ?: null, $nb_new_articles];
  682. }
  683. /**
  684. * @return int|false The number of articles marked as read, of false if error
  685. */
  686. private static function keepMaxUnreads() {
  687. $affected = 0;
  688. $entryDAO = FreshRSS_Factory::createEntryDao();
  689. $newUnreadEntriesPerFeed = $entryDAO->newUnreadEntriesPerFeed();
  690. $feedDAO = FreshRSS_Factory::createFeedDao();
  691. $feeds = $feedDAO->listFeedsOrderUpdate(-1);
  692. foreach ($feeds as $feed) {
  693. if (!empty($newUnreadEntriesPerFeed[$feed->id()]) && $feed->keepMaxUnread() !== null &&
  694. ($feed->nbNotRead() + $newUnreadEntriesPerFeed[$feed->id()] > $feed->keepMaxUnread())) {
  695. Minz_Log::debug('New unread entries (' . ($feed->nbNotRead() + $newUnreadEntriesPerFeed[$feed->id()]) . ') exceeding max number of ' .
  696. $feed->keepMaxUnread() . ' for [' . $feed->url(false) . ']');
  697. $n = $feed->markAsReadMaxUnread();
  698. if ($n === false) {
  699. $affected = false;
  700. break;
  701. } else {
  702. $affected += $n;
  703. }
  704. }
  705. }
  706. if ($feedDAO->updateCachedValues() === false) {
  707. $affected = false;
  708. }
  709. return $affected;
  710. }
  711. /**
  712. * Auto-add labels to new articles.
  713. * @param int $nbNewEntries The number of top recent entries to process.
  714. * @return int|false The number of new labels added, or false in case of error.
  715. */
  716. private static function applyLabelActions(int $nbNewEntries) {
  717. $tagDAO = FreshRSS_Factory::createTagDao();
  718. $labels = FreshRSS_Context::labels();
  719. $labels = array_filter($labels, static function (FreshRSS_Tag $label) {
  720. return !empty($label->filtersAction('label'));
  721. });
  722. if (count($labels) <= 0) {
  723. return 0;
  724. }
  725. $entryDAO = FreshRSS_Factory::createEntryDao();
  726. /** @var array<array{id_tag:int,id_entry:string}> $applyLabels */
  727. $applyLabels = [];
  728. foreach (FreshRSS_Entry::fromTraversable($entryDAO->selectAll($nbNewEntries)) as $entry) {
  729. foreach ($labels as $label) {
  730. $label->applyFilterActions($entry, $applyLabel);
  731. if ($applyLabel) {
  732. $applyLabels[] = [
  733. 'id_tag' => $label->id(),
  734. 'id_entry' => $entry->id(),
  735. ];
  736. }
  737. }
  738. }
  739. return $tagDAO->tagEntries($applyLabels);
  740. }
  741. public static function commitNewEntries(): void {
  742. $entryDAO = FreshRSS_Factory::createEntryDao();
  743. ['all' => $nbNewEntries, 'unread' => $nbNewUnreadEntries] = $entryDAO->countNewEntries();
  744. if ($nbNewEntries > 0) {
  745. if (!$entryDAO->inTransaction()) {
  746. $entryDAO->beginTransaction();
  747. }
  748. if ($entryDAO->commitNewEntries()) {
  749. self::applyLabelActions($nbNewEntries);
  750. if ($nbNewUnreadEntries > 0) {
  751. self::keepMaxUnreads();
  752. }
  753. }
  754. if ($entryDAO->inTransaction()) {
  755. $entryDAO->commit();
  756. }
  757. }
  758. }
  759. /**
  760. * This action actualizes entries from one or several feeds.
  761. *
  762. * Parameters are:
  763. * - id (default: null): Feed ID, or set to -1 to commit new articles to the main database
  764. * - url (default: null): Feed URL (instead of feed ID)
  765. * - maxFeeds (default: 10): Max number of feeds to refresh
  766. * - noCommit (default: 0): Set to 1 to prevent committing the new articles to the main database
  767. * If id and url are not specified, all the feeds are actualized, within the limits of maxFeeds.
  768. */
  769. public function actualizeAction(): int {
  770. Minz_Session::_param('actualize_feeds', false);
  771. $id = Minz_Request::paramInt('id');
  772. $url = Minz_Request::paramString('url');
  773. $maxFeeds = Minz_Request::paramInt('maxFeeds') ?: 10;
  774. $noCommit = ($_POST['noCommit'] ?? 0) == 1;
  775. if ($id === -1 && !$noCommit) { //Special request only to commit & refresh DB cache
  776. $updated_feeds = 0;
  777. $feed = null;
  778. self::commitNewEntries();
  779. } else {
  780. if ($id === 0 && $url === '') {
  781. // Case of a batch refresh (e.g. cron)
  782. $databaseDAO = FreshRSS_Factory::createDatabaseDAO();
  783. $databaseDAO->minorDbMaintenance();
  784. Minz_ExtensionManager::callHookVoid('freshrss_user_maintenance');
  785. FreshRSS_feed_Controller::commitNewEntries();
  786. FreshRSS_category_Controller::refreshDynamicOpmls();
  787. }
  788. [$updated_feeds, $feed, $nbNewArticles] = self::actualizeFeeds($id, $url, $maxFeeds);
  789. if (!$noCommit && $nbNewArticles > 0) {
  790. FreshRSS_feed_Controller::commitNewEntries();
  791. }
  792. }
  793. if (Minz_Request::paramBoolean('ajax')) {
  794. // Most of the time, ajax request is for only one feed. But since
  795. // there are several parallel requests, we should return that there
  796. // are several updated feeds.
  797. Minz_Request::setGoodNotification(_t('feedback.sub.feed.actualizeds'));
  798. // No layout in ajax request.
  799. $this->view->_layout(null);
  800. } elseif ($feed instanceof FreshRSS_Feed) {
  801. // Redirect to the main page with correct notification.
  802. Minz_Request::good(_t('feedback.sub.feed.actualized', $feed->name()), [
  803. 'params' => ['get' => 'f_' . $id]
  804. ]);
  805. } elseif ($updated_feeds >= 1) {
  806. Minz_Request::good(_t('feedback.sub.feed.n_actualized', $updated_feeds), []);
  807. } else {
  808. Minz_Request::good(_t('feedback.sub.feed.no_refresh'), []);
  809. }
  810. return $updated_feeds;
  811. }
  812. /**
  813. * @throws Minz_ConfigurationNamespaceException
  814. * @throws Minz_PDOConnectionException
  815. */
  816. public static function renameFeed(int $feed_id, string $feed_name): bool {
  817. if ($feed_id <= 0 || $feed_name === '') {
  818. return false;
  819. }
  820. FreshRSS_UserDAO::touch();
  821. $feedDAO = FreshRSS_Factory::createFeedDao();
  822. return $feedDAO->updateFeed($feed_id, ['name' => $feed_name]) === 1;
  823. }
  824. public static function moveFeed(int $feed_id, int $cat_id, string $new_cat_name = ''): bool {
  825. if ($feed_id <= 0 || ($cat_id <= 0 && $new_cat_name === '')) {
  826. return false;
  827. }
  828. FreshRSS_UserDAO::touch();
  829. $catDAO = FreshRSS_Factory::createCategoryDao();
  830. if ($cat_id > 0) {
  831. $cat = $catDAO->searchById($cat_id);
  832. $cat_id = $cat === null ? 0 : $cat->id();
  833. }
  834. if ($cat_id <= 1 && $new_cat_name != '') {
  835. $cat_id = $catDAO->addCategory(['name' => $new_cat_name]);
  836. }
  837. if ($cat_id <= 1) {
  838. $catDAO->checkDefault();
  839. $cat_id = FreshRSS_CategoryDAO::DEFAULTCATEGORYID;
  840. }
  841. $feedDAO = FreshRSS_Factory::createFeedDao();
  842. return $feedDAO->updateFeed($feed_id, ['category' => $cat_id]) === 1;
  843. }
  844. /**
  845. * This action changes the category of a feed.
  846. *
  847. * This page must be reached by a POST request.
  848. *
  849. * Parameters are:
  850. * - f_id (default: false)
  851. * - c_id (default: false)
  852. * If c_id is false, default category is used.
  853. *
  854. * @todo should handle order of the feed inside the category.
  855. */
  856. public function moveAction(): void {
  857. if (!Minz_Request::isPost()) {
  858. Minz_Request::forward(['c' => 'subscription'], true);
  859. }
  860. $feed_id = Minz_Request::paramInt('f_id');
  861. $cat_id = Minz_Request::paramInt('c_id');
  862. if (self::moveFeed($feed_id, $cat_id)) {
  863. // TODO: return something useful
  864. // Log a notice to prevent "Empty IF statement" warning in PHP_CodeSniffer
  865. Minz_Log::notice('Moved feed `' . $feed_id . '` in the category `' . $cat_id . '`');
  866. } else {
  867. Minz_Log::warning('Cannot move feed `' . $feed_id . '` in the category `' . $cat_id . '`');
  868. Minz_Error::error(404);
  869. }
  870. }
  871. public static function deleteFeed(int $feed_id): bool {
  872. FreshRSS_UserDAO::touch();
  873. $feedDAO = FreshRSS_Factory::createFeedDao();
  874. if ($feedDAO->deleteFeed($feed_id)) {
  875. // TODO: Delete old favicon
  876. // Remove related queries
  877. /** @var array<array{'get'?:string,'name'?:string,'order'?:string,'search'?:string,'state'?:int,'url'?:string}> $queries */
  878. $queries = remove_query_by_get('f_' . $feed_id, FreshRSS_Context::userConf()->queries);
  879. FreshRSS_Context::userConf()->queries = $queries;
  880. FreshRSS_Context::userConf()->save();
  881. return true;
  882. }
  883. return false;
  884. }
  885. /**
  886. * This action deletes a feed.
  887. *
  888. * This page must be reached by a POST request.
  889. * If there are related queries, they are deleted too.
  890. *
  891. * Parameters are:
  892. * - id (default: false)
  893. */
  894. public function deleteAction(): void {
  895. $from = Minz_Request::paramString('from');
  896. $id = Minz_Request::paramInt('id');
  897. switch ($from) {
  898. case 'stats':
  899. $redirect_url = ['c' => 'stats', 'a' => 'idle'];
  900. break;
  901. case 'normal':
  902. $get = Minz_Request::paramString('get');
  903. if ($get) {
  904. $redirect_url = ['c' => 'index', 'a' => 'normal', 'params' => ['get' => $get]];
  905. } else {
  906. $redirect_url = ['c' => 'index', 'a' => 'normal'];
  907. }
  908. break;
  909. default:
  910. $redirect_url = ['c' => 'subscription', 'a' => 'index'];
  911. if (!Minz_Request::isPost()) {
  912. Minz_Request::forward($redirect_url, true);
  913. }
  914. }
  915. if (self::deleteFeed($id)) {
  916. Minz_Request::good(_t('feedback.sub.feed.deleted'), $redirect_url);
  917. } else {
  918. Minz_Request::bad(_t('feedback.sub.feed.error'), $redirect_url);
  919. }
  920. }
  921. /**
  922. * This action force clears the cache of a feed.
  923. *
  924. * Parameters are:
  925. * - id (mandatory - no default): Feed ID
  926. *
  927. */
  928. public function clearCacheAction(): void {
  929. //Get Feed.
  930. $id = Minz_Request::paramInt('id');
  931. $feedDAO = FreshRSS_Factory::createFeedDao();
  932. $feed = $feedDAO->searchById($id);
  933. if ($feed === null) {
  934. Minz_Request::bad(_t('feedback.sub.feed.not_found'), []);
  935. return;
  936. }
  937. $feed->clearCache();
  938. Minz_Request::good(_t('feedback.sub.feed.cache_cleared', $feed->name()), [
  939. 'params' => ['get' => 'f_' . $feed->id()],
  940. ]);
  941. }
  942. /**
  943. * This action forces reloading the articles of a feed.
  944. *
  945. * Parameters are:
  946. * - id (mandatory - no default): Feed ID
  947. *
  948. * @throws FreshRSS_BadUrl_Exception
  949. */
  950. public function reloadAction(): void {
  951. if (function_exists('set_time_limit')) {
  952. @set_time_limit(300);
  953. }
  954. //Get Feed ID.
  955. $feed_id = Minz_Request::paramInt('id');
  956. $limit = Minz_Request::paramInt('reload_limit') ?: 10;
  957. $feedDAO = FreshRSS_Factory::createFeedDao();
  958. $entryDAO = FreshRSS_Factory::createEntryDao();
  959. $feed = $feedDAO->searchById($feed_id);
  960. if ($feed === null) {
  961. Minz_Request::bad(_t('feedback.sub.feed.not_found'), []);
  962. return;
  963. }
  964. //Re-fetch articles as if the feed was new.
  965. $feedDAO->updateFeed($feed->id(), [ 'lastUpdate' => 0 ]);
  966. [, , $nb_new_articles] = self::actualizeFeeds($feed_id);
  967. if ($nb_new_articles > 0) {
  968. FreshRSS_feed_Controller::commitNewEntries();
  969. }
  970. //Extract all feed entries from database, load complete content and store them back in database.
  971. $entries = $entryDAO->listWhere('f', $feed_id, FreshRSS_Entry::STATE_ALL, 'DESC', $limit);
  972. //We need another DB connection in parallel for unbuffered streaming
  973. Minz_ModelPdo::$usesSharedPdo = false;
  974. if (FreshRSS_Context::systemConf()->db['type'] === 'mysql') {
  975. // Second parallel connection for unbuffered streaming: MySQL
  976. $entryDAO2 = FreshRSS_Factory::createEntryDao();
  977. } else {
  978. // Single connection for buffered queries (in memory): SQLite, PostgreSQL
  979. //TODO: Consider an unbuffered query for PostgreSQL
  980. $entryDAO2 = $entryDAO;
  981. }
  982. foreach ($entries as $entry) {
  983. if ($entry->loadCompleteContent(true)) {
  984. $entryDAO2->updateEntry($entry->toArray());
  985. }
  986. }
  987. Minz_ModelPdo::$usesSharedPdo = true;
  988. //Give feedback to user.
  989. Minz_Request::good(_t('feedback.sub.feed.reloaded', $feed->name()), [
  990. 'params' => ['get' => 'f_' . $feed->id()]
  991. ]);
  992. }
  993. /**
  994. * This action creates a preview of a content-selector.
  995. *
  996. * Parameters are:
  997. * - id (mandatory - no default): Feed ID
  998. * - selector (mandatory - no default): Selector to preview
  999. *
  1000. */
  1001. public function contentSelectorPreviewAction(): void {
  1002. //Configure.
  1003. $this->view->fatalError = '';
  1004. $this->view->selectorSuccess = false;
  1005. $this->view->htmlContent = '';
  1006. $this->view->_layout(null);
  1007. $this->_csp([
  1008. 'default-src' => "'self'",
  1009. 'frame-src' => '*',
  1010. 'img-src' => '* data:',
  1011. 'media-src' => '*',
  1012. ]);
  1013. //Get parameters.
  1014. $feed_id = Minz_Request::paramInt('id');
  1015. $content_selector = Minz_Request::paramString('selector');
  1016. if ($content_selector === '') {
  1017. $this->view->fatalError = _t('feedback.sub.feed.selector_preview.selector_empty');
  1018. return;
  1019. }
  1020. //Check Feed ID validity.
  1021. $entryDAO = FreshRSS_Factory::createEntryDao();
  1022. $entries = $entryDAO->listWhere('f', $feed_id);
  1023. $entry = null;
  1024. //Get first entry (syntax robust for Generator or Array)
  1025. foreach ($entries as $myEntry) {
  1026. $entry = $myEntry;
  1027. }
  1028. if ($entry == null) {
  1029. $this->view->fatalError = _t('feedback.sub.feed.selector_preview.no_entries');
  1030. return;
  1031. }
  1032. //Get feed.
  1033. $feed = $entry->feed();
  1034. if ($feed === null) {
  1035. $this->view->fatalError = _t('feedback.sub.feed.selector_preview.no_feed');
  1036. return;
  1037. }
  1038. $feed->_pathEntries($content_selector);
  1039. $feed->_attribute('path_entries_filter', Minz_Request::paramString('selector_filter', true));
  1040. //Fetch & select content.
  1041. try {
  1042. $fullContent = $entry->getContentByParsing();
  1043. if ($fullContent != '') {
  1044. $this->view->selectorSuccess = true;
  1045. $this->view->htmlContent = $fullContent;
  1046. } else {
  1047. $this->view->selectorSuccess = false;
  1048. $this->view->htmlContent = $entry->content(false);
  1049. }
  1050. } catch (Exception $e) {
  1051. $this->view->fatalError = _t('feedback.sub.feed.selector_preview.http_error');
  1052. }
  1053. }
  1054. }