feedController.php 33 KB

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