feedController.php 43 KB

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