feedController.php 49 KB

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