feedController.php 45 KB

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