4
0

feedController.php 47 KB

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