4
0

feedController.php 39 KB

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