feedController.php 41 KB

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