4
0

feedController.php 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246
  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. $entry = Minz_ExtensionManager::callHook('entry_before_update', $entry);
  585. if (!($entry instanceof FreshRSS_Entry)) {
  586. // An extension has returned a null value, there is nothing to insert.
  587. continue;
  588. }
  589. $entryDAO->updateEntry($entry->toArray());
  590. }
  591. } else {
  592. $entry->_isUpdated(false);
  593. $id = uTimeString();
  594. $entry->_id($id);
  595. $entry = Minz_ExtensionManager::callHook('entry_before_insert', $entry);
  596. if (!($entry instanceof FreshRSS_Entry)) {
  597. // An extension has returned a null value, there is nothing to insert.
  598. continue;
  599. }
  600. $entry->applyFilterActions(array_merge($titlesAsRead, $categoriesEntriesTitle[$feed->categoryId()] ?? []));
  601. if ($readWhenSameTitleInFeed > 0) {
  602. $titlesAsRead[$entry->title()] = true;
  603. }
  604. if (isset($categoriesEntriesTitle[$feed->categoryId()])) {
  605. $categoriesEntriesTitle[$feed->categoryId()][$entry->title()] = true;
  606. }
  607. $needFeedCacheRefresh = true;
  608. if ($pubSubHubbubEnabled && $simplePiePush === null) { //We use push, but have discovered an article by pull!
  609. $text = 'An article was discovered by pull although we use PubSubHubbub!: Feed ' .
  610. \SimplePie\Misc::url_remove_credentials($url) .
  611. ' GUID ' . $entry->guid();
  612. Minz_Log::warning($text, PSHB_LOG);
  613. Minz_Log::warning($text);
  614. $pubSubHubbubEnabled = false;
  615. $feed->pubSubHubbubError(true);
  616. }
  617. $entry = Minz_ExtensionManager::callHook('entry_before_add', $entry);
  618. if (!($entry instanceof FreshRSS_Entry)) {
  619. // An extension has returned a null value, there is nothing to insert.
  620. continue;
  621. }
  622. if ($entryDAO->addEntry($entry->toArray(), true)) {
  623. $nbNewArticles++;
  624. }
  625. }
  626. }
  627. // N.B.: Applies to _entry table and not _entrytmp:
  628. $entryDAO->updateLastSeen($feed->id(), array_keys($newGuids), $mtime);
  629. } elseif ($feedIsUnchanged) {
  630. // Feed cache was unchanged, so mark as seen the same entries as last time
  631. $entryDAO->updateLastSeenUnchanged($feed->id(), $mtime);
  632. }
  633. unset($entries);
  634. if (rand(0, 30) === 1) { // Remove old entries once in 30.
  635. $nb = $feed->cleanOldEntries();
  636. if ($nb > 0) {
  637. $needFeedCacheRefresh = true;
  638. }
  639. }
  640. $feedDAO->updateLastUpdate($feed->id(), false, $mtime);
  641. if ($simplePiePush === null) {
  642. // Do not call for WebSub events, as we do not know the list of articles still on the upstream feed.
  643. $needFeedCacheRefresh |= ($feed->markAsReadUponGone($feedIsEmpty, $mtime) != false);
  644. }
  645. if ($needFeedCacheRefresh) {
  646. $feedsCacheToRefresh[] = $feed;
  647. }
  648. $feedProperties = [];
  649. if ($oldSimplePieHash !== $feed->attributeString('SimplePieHash')) {
  650. $feedProperties['attributes'] = $feed->attributes();
  651. }
  652. if ($feed->url() !== $url) { // HTTP 301 Moved Permanently
  653. Minz_Log::warning('Feed ' . \SimplePie\Misc::url_remove_credentials($url) .
  654. ' moved permanently to ' . $feed->url(includeCredentials: false));
  655. $feedProperties['url'] = $feed->url();
  656. } elseif ($simplePiePush !== null && $selfUrl !== '' && $selfUrl !== $feed->url()) { // selfUrl has priority for WebSub
  657. // https://github.com/pubsubhubbub/PubSubHubbub/wiki/Moving-Feeds-or-changing-Hubs
  658. Minz_Log::debug('WebSub unsubscribe ' . $feed->url(includeCredentials: false));
  659. if (!$feed->pubSubHubbubSubscribe(false)) { //Unsubscribe
  660. Minz_Log::warning('Error while WebSub unsubscribing from ' . $feed->url(includeCredentials: false));
  661. }
  662. $feed->_url($selfUrl);
  663. Minz_Log::warning('Feed ' . \SimplePie\Misc::url_remove_credentials($url) .
  664. ' canonical address moved to ' . $feed->url(includeCredentials: false));
  665. $feedProperties['url'] = $feed->url();
  666. }
  667. if ($simplePie != null) {
  668. if ($feed->name(true) === '') {
  669. //HTML to HTML-PRE //ENT_COMPAT except '&'
  670. $name = strtr(html_only_entity_decode($simplePie->get_title()), ['<' => '&lt;', '>' => '&gt;', '"' => '&quot;']);
  671. $feed->_name($name);
  672. $feedProperties['name'] = $feed->name(false);
  673. }
  674. if ($feed->website() === '' || $feed->website() === $feed->url()) {
  675. $website = html_only_entity_decode($simplePie->get_link());
  676. if ($website !== $feed->website()) {
  677. $feed->_website($website);
  678. $feedProperties['website'] = $feed->website();
  679. $feed->faviconPrepare();
  680. }
  681. }
  682. if (trim($feed->description()) === '') {
  683. $description = html_only_entity_decode($simplePie->get_description());
  684. if ($description !== '') {
  685. $feed->_description($description);
  686. $feedProperties['description'] = $feed->description();
  687. }
  688. }
  689. }
  690. if (!empty($feedProperties) || $feedIsNew) {
  691. $feedProperties['attributes'] = $feed->attributes();
  692. $ok = $feedDAO->updateFeed($feed->id(), $feedProperties);
  693. if (!$ok && $feedIsNew) {
  694. //Cancel adding new feed in case of database error at first actualize
  695. $feedDAO->deleteFeed($feed->id());
  696. $feed->unlock();
  697. break;
  698. }
  699. }
  700. $feed->faviconPrepare();
  701. if ($pubsubhubbubEnabledGeneral && $feed->pubSubHubbubPrepare() != false) {
  702. Minz_Log::notice('WebSub subscribe ' . $feed->url(false));
  703. if (!$feed->pubSubHubbubSubscribe(true)) { //Subscribe
  704. Minz_Log::warning('Error while WebSub subscribing to ' . $feed->url(false));
  705. }
  706. }
  707. $feed->unlock();
  708. $nbUpdatedFeeds++;
  709. unset($feed);
  710. gc_collect_cycles();
  711. if ($nbUpdatedFeeds >= $maxFeeds) {
  712. break;
  713. }
  714. }
  715. return [$nbUpdatedFeeds, reset($feeds) ?: null, $nbNewArticles, $feedsCacheToRefresh];
  716. }
  717. /**
  718. * Feeds on which to apply a the keep max unreads policy, or all feeds if none specified.
  719. * @return int The number of articles marked as read
  720. */
  721. private static function keepMaxUnreads(FreshRSS_Feed ...$feeds): int {
  722. $affected = 0;
  723. if (empty($feeds)) {
  724. $feedDAO = FreshRSS_Factory::createFeedDao();
  725. $feeds = $feedDAO->listFeedsOrderUpdate(-1);
  726. }
  727. foreach ($feeds as $feed) {
  728. $n = $feed->markAsReadMaxUnread();
  729. if ($n !== false && $n > 0) {
  730. Minz_Log::debug($n . ' unread entries exceeding max number of ' . $feed->keepMaxUnread() . ' for [' . $feed->url(false) . ']');
  731. $affected += $n;
  732. }
  733. }
  734. return $affected;
  735. }
  736. /**
  737. * Auto-add labels to new articles.
  738. * @param int $nbNewEntries The number of top recent entries to process.
  739. * @return int|false The number of new labels added, or false in case of error.
  740. */
  741. private static function applyLabelActions(int $nbNewEntries): int|false {
  742. $tagDAO = FreshRSS_Factory::createTagDao();
  743. $labels = FreshRSS_Context::labels();
  744. $labels = array_filter($labels, static fn(FreshRSS_Tag $label) => !empty($label->filtersAction('label')));
  745. if (count($labels) <= 0) {
  746. return 0;
  747. }
  748. $entryDAO = FreshRSS_Factory::createEntryDao();
  749. $applyLabels = [];
  750. foreach (FreshRSS_Entry::fromTraversable($entryDAO->selectAll(order: 'DESC', limit: $nbNewEntries)) as $entry) {
  751. foreach ($labels as $label) {
  752. $label->applyFilterActions($entry, $applyLabel);
  753. if ($applyLabel) {
  754. $applyLabels[] = [
  755. 'id_tag' => $label->id(),
  756. 'id_entry' => $entry->id(),
  757. ];
  758. }
  759. }
  760. }
  761. return $tagDAO->tagEntries($applyLabels);
  762. }
  763. public static function commitNewEntries(): int {
  764. $entryDAO = FreshRSS_Factory::createEntryDao();
  765. $nbNewEntries = $entryDAO->countNewEntries();
  766. if ($nbNewEntries > 0) {
  767. if ($entryDAO->commitNewEntries()) {
  768. self::applyLabelActions($nbNewEntries);
  769. }
  770. }
  771. return $nbNewEntries;
  772. }
  773. /**
  774. * @param \SimplePie\SimplePie|null $simplePiePush Used by WebSub (PubSubHubbub) to push updates
  775. * @param string $selfUrl Used by WebSub (PubSubHubbub) to override the feed URL
  776. * @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,
  777. * list of feeds for which a cache refresh is needed
  778. * @throws FreshRSS_BadUrl_Exception
  779. */
  780. public static function actualizeFeedsAndCommit(?int $feed_id = null, ?string $feed_url = null, ?int $maxFeeds = null,
  781. ?SimplePie\SimplePie $simplePiePush = null, string $selfUrl = ''): array {
  782. $entryDAO = FreshRSS_Factory::createEntryDao();
  783. [$nbUpdatedFeeds, $feed, $nbNewArticles, $feedsCacheToRefresh] =
  784. FreshRSS_feed_Controller::actualizeFeeds($feed_id, $feed_url, $maxFeeds, $simplePiePush, $selfUrl);
  785. if ($nbNewArticles > 0) {
  786. $entryDAO->beginTransaction();
  787. FreshRSS_feed_Controller::commitNewEntries();
  788. }
  789. if (count($feedsCacheToRefresh) > 0) {
  790. $feedDAO = FreshRSS_Factory::createFeedDao();
  791. self::keepMaxUnreads(...$feedsCacheToRefresh);
  792. $feedDAO->updateCachedValues(...array_map(fn(FreshRSS_Feed $f) => $f->id(), $feedsCacheToRefresh));
  793. }
  794. if ($entryDAO->inTransaction()) {
  795. $entryDAO->commit();
  796. }
  797. if (rand(0, 30) === 1) { // Remove old cache once in a while
  798. cleanCache(CLEANCACHE_HOURS);
  799. }
  800. return [$nbUpdatedFeeds, $feed, $nbNewArticles, $feedsCacheToRefresh];
  801. }
  802. /**
  803. * This action actualizes entries from one or several feeds.
  804. *
  805. * Parameters are:
  806. * - id (default: null): Feed ID, or set to -1 to commit new articles to the main database
  807. * - url (default: null): Feed URL (instead of feed ID)
  808. * - maxFeeds (default: 10): Max number of feeds to refresh
  809. * - noCommit (default: 0): Set to 1 to prevent committing the new articles to the main database
  810. * If id and url are not specified, all the feeds are actualized, within the limits of maxFeeds.
  811. */
  812. public function actualizeAction(): int {
  813. Minz_Session::_param('actualize_feeds', false);
  814. $id = Minz_Request::paramInt('id');
  815. $url = Minz_Request::paramString('url');
  816. $maxFeeds = Minz_Request::paramInt('maxFeeds') ?: 10;
  817. $noCommit = ($_POST['noCommit'] ?? 0) == 1;
  818. if ($id === -1 && !$noCommit) { //Special request only to commit & refresh DB cache
  819. $nbUpdatedFeeds = 0;
  820. $feed = null;
  821. FreshRSS_feed_Controller::commitNewEntries();
  822. $feedDAO = FreshRSS_Factory::createFeedDao();
  823. $feedDAO->updateCachedValues();
  824. } else {
  825. if ($id === 0 && $url === '') {
  826. // Case of a batch refresh (e.g. cron)
  827. $databaseDAO = FreshRSS_Factory::createDatabaseDAO();
  828. $databaseDAO->minorDbMaintenance();
  829. Minz_ExtensionManager::callHookVoid('freshrss_user_maintenance');
  830. FreshRSS_feed_Controller::commitNewEntries();
  831. $feedDAO = FreshRSS_Factory::createFeedDao();
  832. $feedDAO->updateCachedValues();
  833. FreshRSS_category_Controller::refreshDynamicOpmls();
  834. }
  835. $entryDAO = FreshRSS_Factory::createEntryDao();
  836. [$nbUpdatedFeeds, $feed, $nbNewArticles, $feedsCacheToRefresh] = self::actualizeFeeds($id, $url, $maxFeeds);
  837. if (!$noCommit) {
  838. if ($nbNewArticles > 0) {
  839. $entryDAO->beginTransaction();
  840. FreshRSS_feed_Controller::commitNewEntries();
  841. }
  842. $feedDAO = FreshRSS_Factory::createFeedDao();
  843. if ($id !== 0 && $id !== -1) {
  844. if ($feed instanceof FreshRSS_Feed) {
  845. self::keepMaxUnreads($feed);
  846. }
  847. // Case of single feed refreshed, always update its cache
  848. $feedDAO->updateCachedValues($id);
  849. } elseif (count($feedsCacheToRefresh) > 0) {
  850. self::keepMaxUnreads(...$feedsCacheToRefresh);
  851. // Case of multiple feeds refreshed, only update cache of affected feeds
  852. $feedDAO->updateCachedValues(...array_map(fn(FreshRSS_Feed $f) => $f->id(), $feedsCacheToRefresh));
  853. }
  854. }
  855. if ($entryDAO->inTransaction()) {
  856. $entryDAO->commit();
  857. }
  858. }
  859. if (Minz_Request::paramBoolean('ajax')) {
  860. // Most of the time, ajax request is for only one feed. But since
  861. // there are several parallel requests, we should return that there
  862. // are several updated feeds.
  863. Minz_Request::setGoodNotification(_t('feedback.sub.feed.actualizeds'));
  864. // No layout in ajax request.
  865. $this->view->_layout(null);
  866. } elseif ($feed instanceof FreshRSS_Feed && $id > 0) {
  867. // Redirect to the main page with correct notification.
  868. Minz_Request::good(_t('feedback.sub.feed.actualized', $feed->name()), [
  869. 'params' => ['get' => 'f_' . $id]
  870. ], 'actualizeAction');
  871. } elseif ($nbUpdatedFeeds >= 1) {
  872. Minz_Request::good(_t('feedback.sub.feed.n_actualized', $nbUpdatedFeeds), []);
  873. } else {
  874. Minz_Request::good(_t('feedback.sub.feed.no_refresh'), []);
  875. }
  876. return $nbUpdatedFeeds;
  877. }
  878. /**
  879. * @throws Minz_ConfigurationNamespaceException
  880. * @throws Minz_PDOConnectionException
  881. */
  882. public static function renameFeed(int $feed_id, string $feed_name): bool {
  883. if ($feed_id <= 0 || $feed_name === '') {
  884. return false;
  885. }
  886. FreshRSS_UserDAO::touch();
  887. $feedDAO = FreshRSS_Factory::createFeedDao();
  888. return $feedDAO->updateFeed($feed_id, ['name' => $feed_name]);
  889. }
  890. public static function moveFeed(int $feed_id, int $cat_id, string $new_cat_name = ''): bool {
  891. if ($feed_id <= 0 || ($cat_id <= 0 && $new_cat_name === '')) {
  892. return false;
  893. }
  894. FreshRSS_UserDAO::touch();
  895. $catDAO = FreshRSS_Factory::createCategoryDao();
  896. if ($cat_id > 0) {
  897. $cat = $catDAO->searchById($cat_id);
  898. $cat_id = $cat === null ? 0 : $cat->id();
  899. }
  900. if ($cat_id <= 1 && $new_cat_name != '') {
  901. $cat_id = $catDAO->addCategory(['name' => $new_cat_name]);
  902. }
  903. if ($cat_id <= 1) {
  904. $catDAO->checkDefault();
  905. $cat_id = FreshRSS_CategoryDAO::DEFAULTCATEGORYID;
  906. }
  907. $feedDAO = FreshRSS_Factory::createFeedDao();
  908. return $feedDAO->updateFeed($feed_id, ['category' => $cat_id]);
  909. }
  910. /**
  911. * This action changes the category of a feed.
  912. *
  913. * This page must be reached by a POST request.
  914. *
  915. * Parameters are:
  916. * - f_id (default: false)
  917. * - c_id (default: false)
  918. * If c_id is false, default category is used.
  919. *
  920. * @todo should handle order of the feed inside the category.
  921. */
  922. public function moveAction(): void {
  923. if (!Minz_Request::isPost()) {
  924. Minz_Request::forward(['c' => 'subscription'], true);
  925. }
  926. $feed_id = Minz_Request::paramInt('f_id');
  927. $cat_id = Minz_Request::paramInt('c_id');
  928. if (self::moveFeed($feed_id, $cat_id)) {
  929. // TODO: return something useful
  930. // Log a notice to prevent "Empty IF statement" warning in PHP_CodeSniffer
  931. Minz_Log::notice('Moved feed `' . $feed_id . '` in the category `' . $cat_id . '`');
  932. } else {
  933. Minz_Log::warning('Cannot move feed `' . $feed_id . '` in the category `' . $cat_id . '`');
  934. Minz_Error::error(404);
  935. }
  936. }
  937. public static function deleteFeed(int $feed_id): bool {
  938. FreshRSS_UserDAO::touch();
  939. $feedDAO = FreshRSS_Factory::createFeedDao();
  940. $feed = $feedDAO->searchById($feed_id);
  941. if ($feed === null) {
  942. return false;
  943. }
  944. if ($feedDAO->deleteFeed($feed_id)) {
  945. // TODO: Delete old favicon (non-custom)
  946. if ($feed->customFavicon() && !$feed->attributeBoolean('customFaviconDisallowDel')) {
  947. FreshRSS_Feed::faviconDelete($feed->hashFavicon());
  948. }
  949. // Remove related queries
  950. $queries = remove_query_by_get('f_' . $feed_id, FreshRSS_Context::userConf()->queries);
  951. FreshRSS_Context::userConf()->queries = $queries;
  952. FreshRSS_Context::userConf()->save();
  953. return true;
  954. }
  955. return false;
  956. }
  957. /**
  958. * This action deletes a feed.
  959. *
  960. * This page must be reached by a POST request.
  961. * If there are related queries, they are deleted too.
  962. *
  963. * Parameters are:
  964. * - id (default: false)
  965. */
  966. public function deleteAction(): void {
  967. $from = Minz_Request::paramString('from');
  968. $id = Minz_Request::paramInt('id');
  969. switch ($from) {
  970. case 'stats':
  971. $redirect_url = ['c' => 'stats', 'a' => 'idle'];
  972. break;
  973. case 'normal':
  974. $get = Minz_Request::paramString('get');
  975. if ($get !== '') {
  976. $redirect_url = ['c' => 'index', 'a' => 'normal', 'params' => ['get' => $get]];
  977. } else {
  978. $redirect_url = ['c' => 'index', 'a' => 'normal'];
  979. }
  980. break;
  981. default:
  982. $redirect_url = ['c' => 'subscription', 'a' => 'index'];
  983. if (!Minz_Request::isPost()) {
  984. Minz_Request::forward($redirect_url, true);
  985. }
  986. }
  987. if (self::deleteFeed($id)) {
  988. Minz_Request::good(_t('feedback.sub.feed.deleted'), $redirect_url);
  989. } else {
  990. Minz_Request::bad(_t('feedback.sub.feed.error'), $redirect_url);
  991. }
  992. }
  993. /**
  994. * This action force clears the cache of a feed.
  995. *
  996. * Parameters are:
  997. * - id (mandatory - no default): Feed ID
  998. *
  999. */
  1000. public function clearCacheAction(): void {
  1001. //Get Feed.
  1002. $id = Minz_Request::paramInt('id');
  1003. $feedDAO = FreshRSS_Factory::createFeedDao();
  1004. $feed = $feedDAO->searchById($id);
  1005. if ($feed === null) {
  1006. Minz_Request::bad(_t('feedback.sub.feed.not_found'), []);
  1007. return;
  1008. }
  1009. $feed->clearCache();
  1010. Minz_Request::good(_t('feedback.sub.feed.cache_cleared', $feed->name()), [
  1011. 'params' => ['get' => 'f_' . $feed->id()],
  1012. ]);
  1013. }
  1014. /**
  1015. * This action forces reloading the articles of a feed.
  1016. *
  1017. * Parameters are:
  1018. * - id (mandatory - no default): Feed ID
  1019. *
  1020. * @throws FreshRSS_BadUrl_Exception
  1021. */
  1022. public function reloadAction(): void {
  1023. if (function_exists('set_time_limit')) {
  1024. @set_time_limit(300);
  1025. }
  1026. //Get Feed ID.
  1027. $feed_id = Minz_Request::paramInt('id');
  1028. $limit = Minz_Request::paramInt('reload_limit') ?: 10;
  1029. $feedDAO = FreshRSS_Factory::createFeedDao();
  1030. $feed = $feedDAO->searchById($feed_id);
  1031. if ($feed === null) {
  1032. Minz_Request::bad(_t('feedback.sub.feed.not_found'), []);
  1033. return;
  1034. }
  1035. //Re-fetch articles as if the feed was new.
  1036. $feedDAO->updateFeed($feed->id(), [ 'lastUpdate' => 0 ]);
  1037. self::actualizeFeedsAndCommit($feed_id);
  1038. //Extract all feed entries from database, load complete content and store them back in database.
  1039. $entryDAO = FreshRSS_Factory::createEntryDao();
  1040. $entries = $entryDAO->listWhere('f', $feed_id, FreshRSS_Entry::STATE_ALL, order: 'DESC', limit: $limit);
  1041. //We need another DB connection in parallel for unbuffered streaming
  1042. Minz_ModelPdo::$usesSharedPdo = false;
  1043. if (FreshRSS_Context::systemConf()->db['type'] === 'mysql') {
  1044. // Second parallel connection for unbuffered streaming: MySQL
  1045. $entryDAO2 = FreshRSS_Factory::createEntryDao();
  1046. } else {
  1047. // Single connection for buffered queries (in memory): SQLite, PostgreSQL
  1048. //TODO: Consider an unbuffered query for PostgreSQL
  1049. $entryDAO2 = $entryDAO;
  1050. }
  1051. foreach ($entries as $entry) {
  1052. if ($entry->loadCompleteContent(true)) {
  1053. $entryDAO2->updateEntry($entry->toArray());
  1054. }
  1055. }
  1056. Minz_ModelPdo::$usesSharedPdo = true;
  1057. //Give feedback to user.
  1058. Minz_Request::good(_t('feedback.sub.feed.reloaded', $feed->name()), [
  1059. 'params' => ['get' => 'f_' . $feed->id()]
  1060. ]);
  1061. }
  1062. /**
  1063. * This action creates a preview of a content-selector.
  1064. *
  1065. * Parameters are:
  1066. * - id (mandatory - no default): Feed ID
  1067. * - selector (mandatory - no default): Selector to preview
  1068. *
  1069. */
  1070. public function contentSelectorPreviewAction(): void {
  1071. //Configure.
  1072. $this->view->fatalError = '';
  1073. $this->view->selectorSuccess = false;
  1074. $this->view->htmlContent = '';
  1075. $this->view->_layout(null);
  1076. $this->_csp([
  1077. 'default-src' => "'self'",
  1078. 'frame-ancestors' => "'self'",
  1079. 'frame-src' => '*',
  1080. 'img-src' => '* data:',
  1081. 'media-src' => '*',
  1082. ]);
  1083. //Get parameters.
  1084. $feed_id = Minz_Request::paramInt('id');
  1085. $content_selector = Minz_Request::paramString('selector');
  1086. if ($content_selector === '') {
  1087. $this->view->fatalError = _t('feedback.sub.feed.selector_preview.selector_empty');
  1088. return;
  1089. }
  1090. //Check Feed ID validity.
  1091. $entryDAO = FreshRSS_Factory::createEntryDao();
  1092. $entries = $entryDAO->listWhere('f', $feed_id);
  1093. $entry = null;
  1094. //Get first entry (syntax robust for Generator or Array)
  1095. foreach ($entries as $myEntry) {
  1096. $entry = $myEntry;
  1097. }
  1098. if ($entry == null) {
  1099. $this->view->fatalError = _t('feedback.sub.feed.selector_preview.no_entries');
  1100. return;
  1101. }
  1102. //Get feed.
  1103. $feed = $entry->feed();
  1104. if ($feed === null) {
  1105. $this->view->fatalError = _t('feedback.sub.feed.selector_preview.no_feed');
  1106. return;
  1107. }
  1108. $feed->_pathEntries($content_selector);
  1109. $feed->_attribute('path_entries_filter', Minz_Request::paramString('selector_filter', true));
  1110. //Fetch & select content.
  1111. try {
  1112. $fullContent = $entry->getContentByParsing();
  1113. if ($fullContent != '') {
  1114. $this->view->selectorSuccess = true;
  1115. $this->view->htmlContent = $fullContent;
  1116. } else {
  1117. $this->view->selectorSuccess = false;
  1118. $this->view->htmlContent = $entry->content(false);
  1119. }
  1120. } catch (Exception) {
  1121. $this->view->fatalError = _t('feedback.sub.feed.selector_preview.http_error');
  1122. }
  1123. }
  1124. }