feedController.php 47 KB

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