feedController.php 35 KB

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