feedController.php 41 KB

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