feedController.php 47 KB

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