feedController.php 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288
  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(Minz_HookType::CheckUrlBeforeAdd, $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(Minz_HookType::FeedBeforeInsert, $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(
  322. _t('feedback.sub.feed.added', $feed->name()),
  323. $url_redirect,
  324. showNotification: FreshRSS_Context::userConf()->good_notification_timeout > 0
  325. );
  326. } else {
  327. // GET request: we must ask confirmation to user before adding feed.
  328. FreshRSS_View::prependTitle(_t('sub.feed.title_add') . ' · ');
  329. $catDAO = FreshRSS_Factory::createCategoryDao();
  330. $this->view->categories = $catDAO->listCategories(prePopulateFeeds: false);
  331. $this->view->feed = new FreshRSS_Feed($url);
  332. try {
  333. // We try to get more information about the feed.
  334. $this->view->feed->load(loadDetails: true);
  335. $this->view->load_ok = true;
  336. } catch (Exception) {
  337. $this->view->load_ok = false;
  338. }
  339. $feed = $feedDAO->searchByUrl($this->view->feed->url());
  340. if ($feed !== null) {
  341. // Already subscribe so we redirect to the feed configuration page.
  342. $url_redirect['a'] = 'feed';
  343. $url_redirect['params']['id'] = $feed->id();
  344. Minz_Request::good(
  345. _t('feedback.sub.feed.already_subscribed', $feed->name()),
  346. $url_redirect,
  347. showNotification: FreshRSS_Context::userConf()->good_notification_timeout > 0
  348. );
  349. }
  350. }
  351. }
  352. /**
  353. * This action remove entries from a given feed.
  354. *
  355. * It should be reached by a POST action.
  356. *
  357. * Parameter is:
  358. * - id (default: false)
  359. */
  360. public function truncateAction(): void {
  361. if (!Minz_Request::isPost()) {
  362. Minz_Request::forward(['c' => 'subscription'], true);
  363. }
  364. $id = Minz_Request::paramInt('id');
  365. $url_redirect = [
  366. 'c' => 'subscription',
  367. 'a' => 'index',
  368. 'params' => ['id' => $id],
  369. ];
  370. if (!Minz_Request::isPost()) {
  371. Minz_Request::forward($url_redirect, true);
  372. }
  373. $feedDAO = FreshRSS_Factory::createFeedDao();
  374. $n = $feedDAO->truncate($id);
  375. invalidateHttpCache();
  376. if ($n === false) {
  377. Minz_Request::bad(_t('feedback.sub.feed.error'), $url_redirect);
  378. } else {
  379. Minz_Request::good(
  380. _t('feedback.sub.feed.n_entries_deleted', $n),
  381. $url_redirect,
  382. showNotification: FreshRSS_Context::userConf()->good_notification_timeout > 0
  383. );
  384. }
  385. }
  386. /**
  387. * @param \SimplePie\SimplePie|null $simplePiePush Used by WebSub (PubSubHubbub) to push updates
  388. * @param string $selfUrl Used by WebSub (PubSubHubbub) to override the feed URL
  389. * @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,
  390. * list of feeds for which a cache refresh is needed
  391. * @throws FreshRSS_BadUrl_Exception
  392. */
  393. public static function actualizeFeeds(?int $feed_id = null, ?string $feed_url = null, ?int $maxFeeds = null,
  394. ?\SimplePie\SimplePie $simplePiePush = null, string $selfUrl = ''): array {
  395. if (function_exists('set_time_limit')) {
  396. @set_time_limit(300);
  397. }
  398. if (!is_int($feed_id) || $feed_id <= 0) {
  399. $feed_id = null;
  400. }
  401. if (!is_string($feed_url) || trim($feed_url) === '') {
  402. $feed_url = null;
  403. }
  404. if (!is_int($maxFeeds) || $maxFeeds <= 0) {
  405. $maxFeeds = PHP_INT_MAX;
  406. }
  407. $catDAO = FreshRSS_Factory::createCategoryDao();
  408. $feedDAO = FreshRSS_Factory::createFeedDao();
  409. $entryDAO = FreshRSS_Factory::createEntryDao();
  410. // Create a list of feeds to actualize.
  411. $feeds = [];
  412. if ($feed_id !== null || $feed_url !== null) {
  413. $feed = $feed_id !== null ? $feedDAO->searchById($feed_id) : $feedDAO->searchByUrl($feed_url);
  414. if ($feed !== null && $feed->id() > 0) {
  415. if ($selfUrl !== '') {
  416. $feed->_selfUrl($selfUrl);
  417. }
  418. $feeds[] = $feed;
  419. $feed_id = $feed->id();
  420. }
  421. } else {
  422. $feeds = $feedDAO->listFeedsOrderUpdate(-1);
  423. // Hydrate category for each feed to avoid that each feed has to make an SQL request
  424. $categories = $catDAO->listCategories(prePopulateFeeds: false, details: false);
  425. foreach ($feeds as $feed) {
  426. $category = $categories[$feed->categoryId()] ?? null;
  427. if ($category !== null) {
  428. $feed->_category($category);
  429. }
  430. }
  431. }
  432. // WebSub (PubSubHubbub) support
  433. $pubsubhubbubEnabledGeneral = FreshRSS_Context::systemConf()->pubsubhubbub_enabled;
  434. $pshbMinAge = time() - (3600 * 24); //TODO: Make a configuration.
  435. $nbUpdatedFeeds = 0;
  436. $nbNewArticles = 0;
  437. $feedsCacheToRefresh = [];
  438. /** @var array<int,array<string,true>> */
  439. $categoriesEntriesTitle = [];
  440. foreach ($feeds as $feed) {
  441. $feed = Minz_ExtensionManager::callHook(Minz_HookType::FeedBeforeActualize, $feed);
  442. if (!($feed instanceof FreshRSS_Feed)) {
  443. continue;
  444. }
  445. $url = $feed->url(); //For detection of HTTP 301
  446. $oldSimplePieHash = $feed->attributeString('SimplePieHash');
  447. $pubSubHubbubEnabled = $pubsubhubbubEnabledGeneral && $feed->pubSubHubbubEnabled();
  448. if ($simplePiePush === null && $feed_id === null && $pubSubHubbubEnabled && ($feed->lastUpdate() > $pshbMinAge)) {
  449. //$text = 'Skip pull of feed using PubSubHubbub: ' . $url;
  450. //Minz_Log::debug($text);
  451. //Minz_Log::debug($text, PSHB_LOG);
  452. continue; //When PubSubHubbub is used, do not pull refresh so often
  453. }
  454. if ($feed->mute() && ($feed_id === null || $simplePiePush !== null)) {
  455. continue; // If the feed is disabled, only allow refresh if manually requested for that specific feed
  456. }
  457. $mtime = $feed->cacheModifiedTime() ?: 0;
  458. $ttl = $feed->ttl();
  459. if ($ttl === FreshRSS_Feed::TTL_DEFAULT) {
  460. $ttl = FreshRSS_Context::userConf()->ttl_default;
  461. }
  462. if ($simplePiePush === null && $feed_id === null && (time() <= $feed->lastUpdate() + $ttl)) {
  463. //Too early to refresh from source, but check whether the feed was updated by another user
  464. $ε = 10; // negligible offset errors in seconds
  465. if ($mtime <= 0 ||
  466. $feed->lastUpdate() + $ε >= $mtime ||
  467. time() + $ε >= $mtime + FreshRSS_Context::systemConf()->limits['cache_duration']) { // is cache still valid?
  468. continue; //Nothing newer from other users
  469. }
  470. Minz_Log::debug('Feed ' . $feed->url(false) . ' was updated at ' . date('c', $feed->lastUpdate()) .
  471. ', and at ' . date('c', $mtime) . ' by another user; take advantage of newer cache.');
  472. }
  473. if (!$feed->lock()) {
  474. Minz_Log::notice('Feed already being actualized: ' . $feed->url(false));
  475. continue;
  476. }
  477. $feedIsNew = $feed->lastUpdate() <= 0;
  478. try {
  479. if ($simplePiePush !== null) {
  480. $simplePie = $simplePiePush; //Used by WebSub
  481. } elseif ($feed->kind() === FreshRSS_Feed::KIND_HTML_XPATH) {
  482. $simplePie = $feed->loadHtmlXpath();
  483. if ($simplePie === null) {
  484. throw new FreshRSS_Feed_Exception('HTML+XPath Web scraping failed for [' . $feed->url(false) . ']');
  485. }
  486. } elseif ($feed->kind() === FreshRSS_Feed::KIND_XML_XPATH) {
  487. $simplePie = $feed->loadHtmlXpath();
  488. if ($simplePie === null) {
  489. throw new FreshRSS_Feed_Exception('XML+XPath parsing failed for [' . $feed->url(false) . ']');
  490. }
  491. } elseif ($feed->kind() === FreshRSS_Feed::KIND_JSON_DOTNOTATION) {
  492. $simplePie = $feed->loadJson();
  493. if ($simplePie === null) {
  494. throw new FreshRSS_Feed_Exception('JSON dot notation parsing failed for [' . $feed->url(false) . ']');
  495. }
  496. } elseif ($feed->kind() === FreshRSS_Feed::KIND_JSONFEED) {
  497. $simplePie = $feed->loadJson();
  498. if ($simplePie === null) {
  499. throw new FreshRSS_Feed_Exception('JSON Feed parsing failed for [' . $feed->url(false) . ']');
  500. }
  501. } elseif ($feed->kind() === FreshRSS_Feed::KIND_HTML_XPATH_JSON_DOTNOTATION) {
  502. $simplePie = $feed->loadJson();
  503. if ($simplePie === null) {
  504. throw new FreshRSS_Feed_Exception('HTML+XPath+JSON parsing failed for [' . $feed->url(false) . ']');
  505. }
  506. } else {
  507. $simplePie = $feed->load(false, $feedIsNew);
  508. }
  509. if ($simplePie === null) {
  510. // Feed is cached and unchanged
  511. $newGuids = [];
  512. $entries = [];
  513. $feedIsEmpty = false; // We do not know
  514. $feedIsUnchanged = true;
  515. } else {
  516. $newGuids = $feed->loadGuids($simplePie);
  517. $entries = $feed->loadEntries($simplePie);
  518. $feedIsEmpty = $simplePiePush === null && empty($newGuids);
  519. $feedIsUnchanged = false;
  520. }
  521. $mtime = $feed->cacheModifiedTime() ?: time();
  522. } catch (FreshRSS_Feed_Exception $e) {
  523. Minz_Log::warning($e->getMessage());
  524. $feedDAO->updateLastUpdate($feed->id(), true);
  525. if ($e->getCode() === 410) {
  526. // HTTP 410 Gone
  527. Minz_Log::warning('Muting gone feed: ' . $feed->url(false));
  528. $feedDAO->mute($feed->id(), true);
  529. }
  530. $feed->unlock();
  531. continue;
  532. }
  533. $needFeedCacheRefresh = false;
  534. $nbMarkedUnread = 0;
  535. if (count($newGuids) > 0) {
  536. if (!$feed->hasAttribute('read_when_same_title_in_feed')) {
  537. $readWhenSameTitleInFeed = (int)FreshRSS_Context::userConf()->mark_when['same_title_in_feed'];
  538. } elseif ($feed->attributeBoolean('read_when_same_title_in_feed') === false) {
  539. $readWhenSameTitleInFeed = 0;
  540. } else {
  541. $readWhenSameTitleInFeed = $feed->attributeInt('read_when_same_title_in_feed') ?? 0;
  542. }
  543. if ($readWhenSameTitleInFeed > 0) {
  544. $titlesAsRead = array_fill_keys($feedDAO->listTitles($feed->id(), $readWhenSameTitleInFeed), true);
  545. } else {
  546. $titlesAsRead = [];
  547. }
  548. $category = $feed->category();
  549. if (!isset($categoriesEntriesTitle[$feed->categoryId()]) && $category !== null && $category->hasAttribute('read_when_same_title_in_category')) {
  550. $categoriesEntriesTitle[$feed->categoryId()] = array_fill_keys(
  551. $catDAO->listTitles($feed->categoryId(), $category->attributeInt('read_when_same_title_in_category') ?? 0),
  552. true
  553. );
  554. }
  555. $mark_updated_article_unread = $feed->attributeBoolean('mark_updated_article_unread') ?? FreshRSS_Context::userConf()->mark_updated_article_unread;
  556. // For this feed, check existing GUIDs already in database.
  557. $existingHashForGuids = $entryDAO->listHashForFeedGuids($feed->id(), $newGuids);
  558. /** @var array<string,bool> $newGuids */
  559. $newGuids = [];
  560. // Add entries in database if possible.
  561. /** @var FreshRSS_Entry $entry */
  562. foreach ($entries as $entry) {
  563. if (isset($newGuids[$entry->guid()])) {
  564. continue; //Skip subsequent articles with same GUID
  565. }
  566. $newGuids[$entry->guid()] = true;
  567. $entry->_lastSeen($mtime);
  568. if (isset($existingHashForGuids[$entry->guid()])) {
  569. $existingHash = $existingHashForGuids[$entry->guid()];
  570. if (strcasecmp($existingHash, $entry->hash()) !== 0) {
  571. //This entry already exists but has been updated
  572. $entry->_isUpdated(true);
  573. //Minz_Log::debug('Entry with GUID `' . $entry->guid() . '` updated in feed ' . $feed->url(false) .
  574. //', old hash ' . $existingHash . ', new hash ' . $entry->hash());
  575. $entry->_isFavorite(null); // Do not change favourite state
  576. $entry->_isRead($mark_updated_article_unread ? false : null); //Change is_read according to policy.
  577. if ($mark_updated_article_unread) {
  578. Minz_ExtensionManager::callHook(Minz_HookType::EntryAutoUnread, $entry, 'updated_article');
  579. }
  580. $entry = Minz_ExtensionManager::callHook(Minz_HookType::EntryBeforeInsert, $entry);
  581. if (!($entry instanceof FreshRSS_Entry)) {
  582. // An extension has returned a null value, there is nothing to insert.
  583. continue;
  584. }
  585. // NB: Do not mark updated articles as read based on their title, as the duplicate title maybe be from the same article.
  586. $entry->applyFilterActions([]);
  587. if ($readWhenSameTitleInFeed > 0) {
  588. $titlesAsRead[$entry->title()] = true;
  589. }
  590. if (isset($categoriesEntriesTitle[$feed->categoryId()])) {
  591. $categoriesEntriesTitle[$feed->categoryId()][$entry->title()] = true;
  592. }
  593. if (!$entry->isRead()) {
  594. $needFeedCacheRefresh = true; //Maybe
  595. $nbMarkedUnread++;
  596. }
  597. // If the entry has changed, there is a good chance for the full content to have changed as well.
  598. $entry->loadCompleteContent(true);
  599. $entry = Minz_ExtensionManager::callHook(Minz_HookType::EntryBeforeUpdate, $entry);
  600. if (!($entry instanceof FreshRSS_Entry)) {
  601. // An extension has returned a null value, there is nothing to insert.
  602. continue;
  603. }
  604. $entryDAO->updateEntry($entry->toArray());
  605. }
  606. } else {
  607. $entry->_isUpdated(false);
  608. $id = uTimeString();
  609. $entry->_id($id);
  610. $entry = Minz_ExtensionManager::callHook(Minz_HookType::EntryBeforeInsert, $entry);
  611. if (!($entry instanceof FreshRSS_Entry)) {
  612. // An extension has returned a null value, there is nothing to insert.
  613. continue;
  614. }
  615. $entry->applyFilterActions(array_merge($titlesAsRead, $categoriesEntriesTitle[$feed->categoryId()] ?? []));
  616. if ($readWhenSameTitleInFeed > 0) {
  617. $titlesAsRead[$entry->title()] = true;
  618. }
  619. if (isset($categoriesEntriesTitle[$feed->categoryId()])) {
  620. $categoriesEntriesTitle[$feed->categoryId()][$entry->title()] = true;
  621. }
  622. $needFeedCacheRefresh = true;
  623. if ($pubSubHubbubEnabled && $simplePiePush === null) { //We use push, but have discovered an article by pull!
  624. $text = 'An article was discovered by pull although we use PubSubHubbub!: Feed ' .
  625. \SimplePie\Misc::url_remove_credentials($url) .
  626. ' GUID ' . $entry->guid();
  627. Minz_Log::warning($text, PSHB_LOG);
  628. Minz_Log::warning($text);
  629. $pubSubHubbubEnabled = false;
  630. $feed->pubSubHubbubError(true);
  631. }
  632. $entry = Minz_ExtensionManager::callHook(Minz_HookType::EntryBeforeAdd, $entry);
  633. if (!($entry instanceof FreshRSS_Entry)) {
  634. // An extension has returned a null value, there is nothing to insert.
  635. continue;
  636. }
  637. if ($entryDAO->addEntry($entry->toArray(), true)) {
  638. $nbNewArticles++;
  639. }
  640. }
  641. }
  642. // N.B.: Applies to _entry table and not _entrytmp:
  643. $entryDAO->updateLastSeen($feed->id(), array_keys($newGuids), $mtime);
  644. } elseif ($feedIsUnchanged) {
  645. // Feed cache was unchanged, so mark as seen the same entries as last time
  646. $entryDAO->updateLastSeenUnchanged($feed->id(), $mtime);
  647. }
  648. unset($entries);
  649. if (rand(0, 30) === 1) { // Remove old entries once in 30.
  650. $nb = $feed->cleanOldEntries();
  651. if ($nb > 0) {
  652. $needFeedCacheRefresh = true;
  653. }
  654. }
  655. $feedDAO->updateLastUpdate($feed->id(), false, $mtime);
  656. if ($simplePiePush === null) {
  657. // Do not call for WebSub events, as we do not know the list of articles still on the upstream feed.
  658. $needFeedCacheRefresh |= ($feed->markAsReadUponGone($feedIsEmpty, $mtime) != false);
  659. }
  660. if ($needFeedCacheRefresh) {
  661. $feedsCacheToRefresh[] = $feed;
  662. }
  663. $feedProperties = [];
  664. if ($oldSimplePieHash !== $feed->attributeString('SimplePieHash')) {
  665. $feedProperties['attributes'] = $feed->attributes();
  666. }
  667. if ($feed->url() !== $url) { // HTTP 301 Moved Permanently
  668. Minz_Log::warning('Feed ' . \SimplePie\Misc::url_remove_credentials($url) .
  669. ' moved permanently to ' . $feed->url(includeCredentials: false));
  670. $feedProperties['url'] = $feed->url();
  671. } elseif ($simplePiePush !== null && $selfUrl !== '' && $selfUrl !== $feed->url()) { // selfUrl has priority for WebSub
  672. // https://github.com/pubsubhubbub/PubSubHubbub/wiki/Moving-Feeds-or-changing-Hubs
  673. Minz_Log::debug('WebSub unsubscribe ' . $feed->url(includeCredentials: false));
  674. if (!$feed->pubSubHubbubSubscribe(false)) { //Unsubscribe
  675. Minz_Log::warning('Error while WebSub unsubscribing from ' . $feed->url(includeCredentials: false));
  676. }
  677. $feed->_url($selfUrl);
  678. Minz_Log::warning('Feed ' . \SimplePie\Misc::url_remove_credentials($url) .
  679. ' canonical address moved to ' . $feed->url(includeCredentials: false));
  680. $feedProperties['url'] = $feed->url();
  681. }
  682. if ($simplePie != null) {
  683. if ($feed->name(true) === '') {
  684. //HTML to HTML-PRE //ENT_COMPAT except '&'
  685. $name = strtr(html_only_entity_decode($simplePie->get_title()), ['<' => '&lt;', '>' => '&gt;', '"' => '&quot;']);
  686. $feed->_name($name);
  687. $feedProperties['name'] = $feed->name(false);
  688. }
  689. if ($feed->website() === '' || $feed->website() === $feed->url()) {
  690. $website = html_only_entity_decode($simplePie->get_link());
  691. if ($website !== $feed->website()) {
  692. $feed->_website($website);
  693. $feedProperties['website'] = $feed->website();
  694. $feed->faviconPrepare();
  695. }
  696. }
  697. if (trim($feed->description()) === '') {
  698. $description = html_only_entity_decode($simplePie->get_description());
  699. if ($description !== '') {
  700. $feed->_description($description);
  701. $feedProperties['description'] = $feed->description();
  702. }
  703. }
  704. }
  705. if (!empty($feedProperties) || $feedIsNew) {
  706. $feedProperties['attributes'] = $feed->attributes();
  707. $ok = $feedDAO->updateFeed($feed->id(), $feedProperties);
  708. if (!$ok && $feedIsNew) {
  709. //Cancel adding new feed in case of database error at first actualize
  710. $feedDAO->deleteFeed($feed->id());
  711. $feed->unlock();
  712. break;
  713. }
  714. }
  715. $feed->faviconPrepare();
  716. if ($pubsubhubbubEnabledGeneral && $feed->pubSubHubbubPrepare() != false) {
  717. Minz_Log::notice('WebSub subscribe ' . $feed->url(false));
  718. if (!$feed->pubSubHubbubSubscribe(true)) { //Subscribe
  719. Minz_Log::warning('Error while WebSub subscribing to ' . $feed->url(false));
  720. }
  721. }
  722. $feed->unlock();
  723. $nbUpdatedFeeds++;
  724. unset($feed);
  725. gc_collect_cycles();
  726. if ($nbUpdatedFeeds >= $maxFeeds) {
  727. break;
  728. }
  729. }
  730. return [$nbUpdatedFeeds, reset($feeds) ?: null, $nbNewArticles, $feedsCacheToRefresh];
  731. }
  732. /**
  733. * Feeds on which to apply a the keep max unreads policy, or all feeds if none specified.
  734. * @return int The number of articles marked as read
  735. */
  736. private static function keepMaxUnreads(FreshRSS_Feed ...$feeds): int {
  737. $affected = 0;
  738. if (empty($feeds)) {
  739. $feedDAO = FreshRSS_Factory::createFeedDao();
  740. $feeds = $feedDAO->listFeedsOrderUpdate(-1);
  741. }
  742. foreach ($feeds as $feed) {
  743. $n = $feed->markAsReadMaxUnread();
  744. if ($n !== false && $n > 0) {
  745. Minz_Log::debug($n . ' unread entries exceeding max number of ' . $feed->keepMaxUnread() . ' for [' . $feed->url(false) . ']');
  746. $affected += $n;
  747. }
  748. }
  749. return $affected;
  750. }
  751. /**
  752. * Auto-add labels to new articles.
  753. * @param int $nbNewEntries The number of top recent entries to process.
  754. * @return int|false The number of new labels added, or false in case of error.
  755. */
  756. private static function applyLabelActions(int $nbNewEntries): int|false {
  757. $tagDAO = FreshRSS_Factory::createTagDao();
  758. $labels = FreshRSS_Context::labels();
  759. $labels = array_filter($labels, static fn(FreshRSS_Tag $label) => !empty($label->filtersAction('label')));
  760. if (count($labels) <= 0) {
  761. return 0;
  762. }
  763. $entryDAO = FreshRSS_Factory::createEntryDao();
  764. $applyLabels = [];
  765. foreach (FreshRSS_Entry::fromTraversable($entryDAO->selectAll(order: 'DESC', limit: $nbNewEntries)) as $entry) {
  766. foreach ($labels as $label) {
  767. $label->applyFilterActions($entry, $applyLabel);
  768. if ($applyLabel) {
  769. $applyLabels[] = [
  770. 'id_tag' => $label->id(),
  771. 'id_entry' => $entry->id(),
  772. ];
  773. }
  774. }
  775. }
  776. return $tagDAO->tagEntries($applyLabels);
  777. }
  778. public static function commitNewEntries(): int {
  779. $entryDAO = FreshRSS_Factory::createEntryDao();
  780. $nbNewEntries = $entryDAO->countNewEntries();
  781. if ($nbNewEntries > 0) {
  782. if ($entryDAO->commitNewEntries()) {
  783. self::applyLabelActions($nbNewEntries);
  784. }
  785. }
  786. return $nbNewEntries;
  787. }
  788. /**
  789. * @param \SimplePie\SimplePie|null $simplePiePush Used by WebSub (PubSubHubbub) to push updates
  790. * @param string $selfUrl Used by WebSub (PubSubHubbub) to override the feed URL
  791. * @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,
  792. * list of feeds for which a cache refresh is needed
  793. * @throws FreshRSS_BadUrl_Exception
  794. */
  795. public static function actualizeFeedsAndCommit(?int $feed_id = null, ?string $feed_url = null, ?int $maxFeeds = null,
  796. ?SimplePie\SimplePie $simplePiePush = null, string $selfUrl = ''): array {
  797. $entryDAO = FreshRSS_Factory::createEntryDao();
  798. [$nbUpdatedFeeds, $feed, $nbNewArticles, $feedsCacheToRefresh] =
  799. FreshRSS_feed_Controller::actualizeFeeds($feed_id, $feed_url, $maxFeeds, $simplePiePush, $selfUrl);
  800. if ($nbNewArticles > 0) {
  801. $entryDAO->beginTransaction();
  802. FreshRSS_feed_Controller::commitNewEntries();
  803. }
  804. if (count($feedsCacheToRefresh) > 0) {
  805. $feedDAO = FreshRSS_Factory::createFeedDao();
  806. self::keepMaxUnreads(...$feedsCacheToRefresh);
  807. $feedDAO->updateCachedValues(...array_map(fn(FreshRSS_Feed $f) => $f->id(), $feedsCacheToRefresh));
  808. }
  809. if ($entryDAO->inTransaction()) {
  810. $entryDAO->commit();
  811. }
  812. if (rand(0, 30) === 1) { // Remove old cache once in a while
  813. cleanCache(CLEANCACHE_HOURS);
  814. }
  815. return [$nbUpdatedFeeds, $feed, $nbNewArticles, $feedsCacheToRefresh];
  816. }
  817. /**
  818. * This action actualizes entries from one or several feeds.
  819. *
  820. * Parameters are:
  821. * - id (default: null): Feed ID, or set to -1 to commit new articles to the main database
  822. * - url (default: null): Feed URL (instead of feed ID)
  823. * - maxFeeds (default: 10): Max number of feeds to refresh
  824. * - noCommit (default: 0): Set to 1 to prevent committing the new articles to the main database
  825. * If id and url are not specified, all the feeds are actualized, within the limits of maxFeeds.
  826. */
  827. public function actualizeAction(): int {
  828. Minz_Session::_param('actualize_feeds', false);
  829. $id = Minz_Request::paramInt('id');
  830. $url = Minz_Request::paramString('url');
  831. $maxFeeds = Minz_Request::paramInt('maxFeeds') ?: 10;
  832. $noCommit = ($_POST['noCommit'] ?? 0) == 1;
  833. if ($id === -1 && !$noCommit) { //Special request only to commit & refresh DB cache
  834. $nbUpdatedFeeds = 0;
  835. $feed = null;
  836. FreshRSS_feed_Controller::commitNewEntries();
  837. $feedDAO = FreshRSS_Factory::createFeedDao();
  838. $feedDAO->updateCachedValues();
  839. } else {
  840. if ($id === 0 && $url === '') {
  841. // Case of a batch refresh (e.g. cron)
  842. $databaseDAO = FreshRSS_Factory::createDatabaseDAO();
  843. $databaseDAO->minorDbMaintenance();
  844. Minz_ExtensionManager::callHookVoid(Minz_HookType::FreshrssUserMaintenance);
  845. FreshRSS_feed_Controller::commitNewEntries();
  846. $feedDAO = FreshRSS_Factory::createFeedDao();
  847. $feedDAO->updateCachedValues();
  848. FreshRSS_category_Controller::refreshDynamicOpmls();
  849. }
  850. $entryDAO = FreshRSS_Factory::createEntryDao();
  851. [$nbUpdatedFeeds, $feed, $nbNewArticles, $feedsCacheToRefresh] = self::actualizeFeeds($id, $url, $maxFeeds);
  852. if (!$noCommit) {
  853. if ($nbNewArticles > 0) {
  854. $entryDAO->beginTransaction();
  855. FreshRSS_feed_Controller::commitNewEntries();
  856. }
  857. $feedDAO = FreshRSS_Factory::createFeedDao();
  858. if ($id !== 0 && $id !== -1) {
  859. if ($feed instanceof FreshRSS_Feed) {
  860. self::keepMaxUnreads($feed);
  861. }
  862. // Case of single feed refreshed, always update its cache
  863. $feedDAO->updateCachedValues($id);
  864. } elseif (count($feedsCacheToRefresh) > 0) {
  865. self::keepMaxUnreads(...$feedsCacheToRefresh);
  866. // Case of multiple feeds refreshed, only update cache of affected feeds
  867. $feedDAO->updateCachedValues(...array_map(fn(FreshRSS_Feed $f) => $f->id(), $feedsCacheToRefresh));
  868. }
  869. }
  870. if ($entryDAO->inTransaction()) {
  871. $entryDAO->commit();
  872. }
  873. }
  874. if (Minz_Request::paramBoolean('ajax')) {
  875. // Most of the time, ajax request is for only one feed. But since
  876. // there are several parallel requests, we should return that there
  877. // are several updated feeds.
  878. Minz_Request::setGoodNotification(_t('feedback.sub.feed.actualizeds'));
  879. // No layout in ajax request.
  880. $this->view->_layout(null);
  881. } elseif ($feed instanceof FreshRSS_Feed && $id > 0) {
  882. // Redirect to the main page with correct notification.
  883. Minz_Request::good(
  884. _t('feedback.sub.feed.actualized', $feed->name()),
  885. ['params' => ['get' => 'f_' . $id]],
  886. notificationName: 'actualizeAction',
  887. showNotification: FreshRSS_Context::userConf()->good_notification_timeout > 0);
  888. } elseif ($nbUpdatedFeeds >= 1) {
  889. Minz_Request::good(
  890. _t('feedback.sub.feed.n_actualized', $nbUpdatedFeeds),
  891. [],
  892. showNotification: FreshRSS_Context::userConf()->good_notification_timeout > 0
  893. );
  894. } else {
  895. Minz_Request::good(
  896. _t('feedback.sub.feed.no_refresh'),
  897. [],
  898. showNotification: FreshRSS_Context::userConf()->good_notification_timeout > 0
  899. );
  900. }
  901. return $nbUpdatedFeeds;
  902. }
  903. /**
  904. * @throws Minz_ConfigurationNamespaceException
  905. * @throws Minz_PDOConnectionException
  906. */
  907. public static function renameFeed(int $feed_id, string $feed_name): bool {
  908. if ($feed_id <= 0 || $feed_name === '') {
  909. return false;
  910. }
  911. FreshRSS_UserDAO::touch();
  912. $feedDAO = FreshRSS_Factory::createFeedDao();
  913. return $feedDAO->updateFeed($feed_id, ['name' => $feed_name]);
  914. }
  915. public static function moveFeed(int $feed_id, int $cat_id, string $new_cat_name = ''): bool {
  916. if ($feed_id <= 0 || ($cat_id <= 0 && $new_cat_name === '')) {
  917. return false;
  918. }
  919. FreshRSS_UserDAO::touch();
  920. $catDAO = FreshRSS_Factory::createCategoryDao();
  921. if ($cat_id > 0) {
  922. $cat = $catDAO->searchById($cat_id);
  923. $cat_id = $cat === null ? 0 : $cat->id();
  924. }
  925. if ($cat_id <= 1 && $new_cat_name != '') {
  926. $cat_id = $catDAO->addCategory(['name' => $new_cat_name]);
  927. }
  928. if ($cat_id <= 1) {
  929. $catDAO->checkDefault();
  930. $cat_id = FreshRSS_CategoryDAO::DEFAULTCATEGORYID;
  931. }
  932. $feedDAO = FreshRSS_Factory::createFeedDao();
  933. return $feedDAO->updateFeed($feed_id, ['category' => $cat_id]);
  934. }
  935. /**
  936. * This action changes the category of a feed.
  937. *
  938. * This page must be reached by a POST request.
  939. *
  940. * Parameters are:
  941. * - f_id (default: false)
  942. * - c_id (default: false)
  943. * If c_id is false, default category is used.
  944. *
  945. * @todo should handle order of the feed inside the category.
  946. */
  947. public function moveAction(): void {
  948. if (!Minz_Request::isPost()) {
  949. Minz_Request::forward(['c' => 'subscription'], true);
  950. }
  951. $feed_id = Minz_Request::paramInt('f_id');
  952. $cat_id = Minz_Request::paramInt('c_id');
  953. if (self::moveFeed($feed_id, $cat_id)) {
  954. // TODO: return something useful
  955. // Log a notice to prevent "Empty IF statement" warning in PHP_CodeSniffer
  956. Minz_Log::notice('Moved feed `' . $feed_id . '` in the category `' . $cat_id . '`');
  957. } else {
  958. Minz_Log::warning('Cannot move feed `' . $feed_id . '` in the category `' . $cat_id . '`');
  959. Minz_Error::error(404);
  960. }
  961. }
  962. public static function deleteFeed(int $feed_id): bool {
  963. FreshRSS_UserDAO::touch();
  964. $feedDAO = FreshRSS_Factory::createFeedDao();
  965. $feed = $feedDAO->searchById($feed_id);
  966. if ($feed === null) {
  967. return false;
  968. }
  969. if ($feedDAO->deleteFeed($feed_id)) {
  970. // TODO: Delete old favicon (non-custom)
  971. if ($feed->customFavicon() && !$feed->attributeBoolean('customFaviconDisallowDel')) {
  972. FreshRSS_Feed::faviconDelete($feed->hashFavicon());
  973. }
  974. // Remove related queries
  975. $queries = remove_query_by_get('f_' . $feed_id, FreshRSS_Context::userConf()->queries);
  976. FreshRSS_Context::userConf()->queries = $queries;
  977. FreshRSS_Context::userConf()->save();
  978. return true;
  979. }
  980. return false;
  981. }
  982. /**
  983. * This action deletes a feed.
  984. *
  985. * This page must be reached by a POST request.
  986. * If there are related queries, they are deleted too.
  987. *
  988. * Parameters are:
  989. * - id (default: false)
  990. */
  991. public function deleteAction(): void {
  992. if (!Minz_Request::isPost()) {
  993. Minz_Request::forward(['c' => 'subscription'], true);
  994. }
  995. $from = Minz_Request::paramString('from');
  996. $id = Minz_Request::paramInt('id');
  997. switch ($from) {
  998. case 'stats':
  999. $redirect_url = ['c' => 'stats', 'a' => 'idle'];
  1000. break;
  1001. case 'normal':
  1002. $get = Minz_Request::paramString('get');
  1003. if ($get !== '') {
  1004. $redirect_url = ['c' => 'index', 'a' => 'normal', 'params' => ['get' => $get]];
  1005. } else {
  1006. $redirect_url = ['c' => 'index', 'a' => 'normal'];
  1007. }
  1008. break;
  1009. default:
  1010. $redirect_url = ['c' => 'subscription', 'a' => 'index'];
  1011. if (!Minz_Request::isPost()) {
  1012. Minz_Request::forward($redirect_url, true);
  1013. }
  1014. }
  1015. if (self::deleteFeed($id)) {
  1016. Minz_Request::good(
  1017. _t('feedback.sub.feed.deleted'),
  1018. $redirect_url,
  1019. showNotification: FreshRSS_Context::userConf()->good_notification_timeout > 0
  1020. );
  1021. } else {
  1022. Minz_Request::bad(_t('feedback.sub.feed.error'), $redirect_url);
  1023. }
  1024. }
  1025. /**
  1026. * This action force clears the cache of a feed.
  1027. *
  1028. * Parameters are:
  1029. * - id (mandatory - no default): Feed ID
  1030. *
  1031. */
  1032. public function clearCacheAction(): void {
  1033. if (!Minz_Request::isPost()) {
  1034. Minz_Request::forward(['c' => 'subscription'], true);
  1035. }
  1036. //Get Feed.
  1037. $id = Minz_Request::paramInt('id');
  1038. $feedDAO = FreshRSS_Factory::createFeedDao();
  1039. $feed = $feedDAO->searchById($id);
  1040. if ($feed === null) {
  1041. Minz_Request::bad(_t('feedback.sub.feed.not_found'), []);
  1042. return;
  1043. }
  1044. $feed->clearCache();
  1045. Minz_Request::good(
  1046. _t('feedback.sub.feed.cache_cleared', $feed->name()),
  1047. ['params' => ['get' => 'f_' . $feed->id()]],
  1048. showNotification: FreshRSS_Context::userConf()->good_notification_timeout > 0
  1049. );
  1050. }
  1051. /**
  1052. * This action forces reloading the articles of a feed.
  1053. *
  1054. * Parameters are:
  1055. * - id (mandatory - no default): Feed ID
  1056. *
  1057. * @throws FreshRSS_BadUrl_Exception
  1058. */
  1059. public function reloadAction(): void {
  1060. if (!Minz_Request::isPost()) {
  1061. Minz_Request::forward(['c' => 'subscription'], true);
  1062. }
  1063. if (function_exists('set_time_limit')) {
  1064. @set_time_limit(300);
  1065. }
  1066. //Get Feed ID.
  1067. $feed_id = Minz_Request::paramInt('id');
  1068. $limit = Minz_Request::paramInt('reload_limit') ?: 10;
  1069. $feedDAO = FreshRSS_Factory::createFeedDao();
  1070. $feed = $feedDAO->searchById($feed_id);
  1071. if ($feed === null) {
  1072. Minz_Request::bad(_t('feedback.sub.feed.not_found'), []);
  1073. return;
  1074. }
  1075. //Re-fetch articles as if the feed was new.
  1076. $feedDAO->updateFeed($feed->id(), [ 'lastUpdate' => 0 ]);
  1077. self::actualizeFeedsAndCommit($feed_id);
  1078. //Extract all feed entries from database, load complete content and store them back in database.
  1079. $entryDAO = FreshRSS_Factory::createEntryDao();
  1080. $entries = $entryDAO->listWhere('f', $feed_id, FreshRSS_Entry::STATE_ALL, order: 'DESC', limit: $limit);
  1081. //We need another DB connection in parallel for unbuffered streaming
  1082. Minz_ModelPdo::$usesSharedPdo = false;
  1083. if (FreshRSS_Context::systemConf()->db['type'] === 'mysql') {
  1084. // Second parallel connection for unbuffered streaming: MySQL
  1085. $entryDAO2 = FreshRSS_Factory::createEntryDao();
  1086. } else {
  1087. // Single connection for buffered queries (in memory): SQLite, PostgreSQL
  1088. //TODO: Consider an unbuffered query for PostgreSQL
  1089. $entryDAO2 = $entryDAO;
  1090. }
  1091. foreach ($entries as $entry) {
  1092. if ($entry->loadCompleteContent(true)) {
  1093. $entryDAO2->updateEntry($entry->toArray());
  1094. }
  1095. }
  1096. Minz_ModelPdo::$usesSharedPdo = true;
  1097. //Give feedback to user.
  1098. Minz_Request::good(
  1099. _t('feedback.sub.feed.reloaded', $feed->name()),
  1100. ['params' => ['get' => 'f_' . $feed->id()]],
  1101. showNotification: FreshRSS_Context::userConf()->good_notification_timeout > 0
  1102. );
  1103. }
  1104. /**
  1105. * This action creates a preview of a content-selector.
  1106. *
  1107. * Parameters are:
  1108. * - id (mandatory - no default): Feed ID
  1109. * - selector (mandatory - no default): Selector to preview
  1110. *
  1111. */
  1112. public function contentSelectorPreviewAction(): void {
  1113. //Configure.
  1114. $this->view->fatalError = '';
  1115. $this->view->selectorSuccess = false;
  1116. $this->view->htmlContent = '';
  1117. $this->view->_layout(null);
  1118. $this->_csp([
  1119. 'default-src' => "'self'",
  1120. 'frame-ancestors' => "'self'",
  1121. 'frame-src' => '*',
  1122. 'img-src' => '* data:',
  1123. 'media-src' => '*',
  1124. ]);
  1125. //Get parameters.
  1126. $feed_id = Minz_Request::paramInt('id');
  1127. $content_selector = Minz_Request::paramString('selector');
  1128. if ($content_selector === '') {
  1129. $this->view->fatalError = _t('feedback.sub.feed.selector_preview.selector_empty');
  1130. return;
  1131. }
  1132. //Check Feed ID validity.
  1133. $entryDAO = FreshRSS_Factory::createEntryDao();
  1134. $entries = $entryDAO->listWhere('f', $feed_id);
  1135. $entry = null;
  1136. //Get first entry (syntax robust for Generator or Array)
  1137. foreach ($entries as $myEntry) {
  1138. $entry = $myEntry;
  1139. }
  1140. if ($entry == null) {
  1141. $this->view->fatalError = _t('feedback.sub.feed.selector_preview.no_entries');
  1142. return;
  1143. }
  1144. //Get feed.
  1145. $feed = $entry->feed();
  1146. if ($feed === null) {
  1147. $this->view->fatalError = _t('feedback.sub.feed.selector_preview.no_feed');
  1148. return;
  1149. }
  1150. $feed->_pathEntries($content_selector);
  1151. $feed->_attribute('path_entries_filter', Minz_Request::paramString('selector_filter', true));
  1152. //Fetch & select content.
  1153. try {
  1154. $fullContent = $entry->getContentByParsing();
  1155. if ($fullContent != '') {
  1156. $this->view->selectorSuccess = true;
  1157. $this->view->htmlContent = $fullContent;
  1158. } else {
  1159. $this->view->selectorSuccess = false;
  1160. $this->view->htmlContent = $entry->content(false);
  1161. }
  1162. } catch (Exception) {
  1163. $this->view->fatalError = _t('feedback.sub.feed.selector_preview.http_error');
  1164. }
  1165. }
  1166. }