feedController.php 41 KB

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