feedController.php 49 KB

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