4
0

feedController.php 42 KB

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