feedController.php 33 KB

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