feedController.php 43 KB

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