feedController.php 43 KB

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