4
0

feedController.php 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  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(['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([
  122. 'c' => 'subscription',
  123. 'a' => 'index',
  124. ], true);
  125. }
  126. $feedDAO = FreshRSS_Factory::createFeedDao();
  127. $url_redirect = [
  128. 'c' => 'subscription',
  129. 'a' => 'add',
  130. 'params' => [],
  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 = [
  280. 'c' => 'subscription',
  281. 'a' => 'index',
  282. 'params' => ['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 = [];
  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. $ε = 10; // negligible offset errors in seconds
  351. if ($mtime <= 0 ||
  352. $feed->lastUpdate() + $ε >= $mtime ||
  353. time() + $ε >= $mtime + FreshRSS_Context::$system_conf->limits['cache_duration']) { // is cache still valid?
  354. continue; //Nothing newer from other users
  355. }
  356. Minz_Log::debug('Feed ' . $feed->url(false) . ' was updated at ' . date('c', $feed->lastUpdate()) .
  357. ', and at ' . date('c', $mtime) . ' by another user; take advantage of newer cache.');
  358. }
  359. if (!$feed->lock()) {
  360. Minz_Log::notice('Feed already being actualized: ' . $feed->url(false));
  361. continue;
  362. }
  363. $feedIsNew = $feed->lastUpdate() <= 0;
  364. $feedIsEmpty = false;
  365. $feedIsUnchanged = false;
  366. try {
  367. if ($simplePiePush !== null) {
  368. $simplePie = $simplePiePush; //Used by WebSub
  369. } elseif ($feed->kind() === FreshRSS_Feed::KIND_HTML_XPATH) {
  370. $simplePie = $feed->loadHtmlXpath();
  371. if ($simplePie === null) {
  372. throw new FreshRSS_Feed_Exception('HTML+XPath Web scraping failed for [' . $feed->url(false) . ']');
  373. }
  374. } elseif ($feed->kind() === FreshRSS_Feed::KIND_XML_XPATH) {
  375. $simplePie = $feed->loadHtmlXpath();
  376. if ($simplePie === null) {
  377. throw new FreshRSS_Feed_Exception('XML+XPath parsing failed for [' . $feed->url(false) . ']');
  378. }
  379. } else {
  380. $simplePie = $feed->load(false, $feedIsNew);
  381. }
  382. if ($simplePie === null) {
  383. // Feed is cached and unchanged
  384. $newGuids = [];
  385. $entries = [];
  386. $feedIsEmpty = false; // We do not know
  387. $feedIsUnchanged = true;
  388. } else {
  389. $newGuids = $feed->loadGuids($simplePie);
  390. $entries = $feed->loadEntries($simplePie);
  391. $feedIsEmpty = $simplePiePush !== null && empty($newGuids);
  392. $feedIsUnchanged = false;
  393. }
  394. $mtime = $feed->cacheModifiedTime() ?: time();
  395. } catch (FreshRSS_Feed_Exception $e) {
  396. Minz_Log::warning($e->getMessage());
  397. $feedDAO->updateLastUpdate($feed->id(), true);
  398. if ($e->getCode() === 410) {
  399. // HTTP 410 Gone
  400. Minz_Log::warning('Muting gone feed: ' . $feed->url(false));
  401. $feedDAO->mute($feed->id(), true);
  402. }
  403. $feed->unlock();
  404. continue;
  405. }
  406. $needFeedCacheRefresh = false;
  407. if (count($newGuids) > 0) {
  408. $titlesAsRead = [];
  409. $readWhenSameTitleInFeed = $feed->attributes('read_when_same_title_in_feed');
  410. if ($readWhenSameTitleInFeed == false) {
  411. $readWhenSameTitleInFeed = FreshRSS_Context::$user_conf->mark_when['same_title_in_feed'];
  412. }
  413. if ($readWhenSameTitleInFeed > 0) {
  414. /** @var array<string,bool> $titlesAsRead*/
  415. $titlesAsRead = array_flip($feedDAO->listTitles($feed->id(), (int)$readWhenSameTitleInFeed));
  416. }
  417. $mark_updated_article_unread = $feed->attributes('mark_updated_article_unread') ?? FreshRSS_Context::$user_conf->mark_updated_article_unread;
  418. // For this feed, check existing GUIDs already in database.
  419. $existingHashForGuids = $entryDAO->listHashForFeedGuids($feed->id(), $newGuids) ?: [];
  420. /** @var array<string,bool> $newGuids */
  421. $newGuids = [];
  422. // Add entries in database if possible.
  423. /** @var FreshRSS_Entry $entry */
  424. foreach ($entries as $entry) {
  425. if (isset($newGuids[$entry->guid()])) {
  426. continue; //Skip subsequent articles with same GUID
  427. }
  428. $newGuids[$entry->guid()] = true;
  429. $entry->_lastSeen($mtime);
  430. if (isset($existingHashForGuids[$entry->guid()])) {
  431. $existingHash = $existingHashForGuids[$entry->guid()];
  432. if (strcasecmp($existingHash, $entry->hash()) !== 0) {
  433. //This entry already exists but has been updated
  434. //Minz_Log::debug('Entry with GUID `' . $entry->guid() . '` updated in feed ' . $feed->url(false) .
  435. //', old hash ' . $existingHash . ', new hash ' . $entry->hash());
  436. $entry->_isFavorite(null); // Do not change favourite state
  437. $entry->_isRead($mark_updated_article_unread ? false : null); //Change is_read according to policy.
  438. if ($mark_updated_article_unread) {
  439. Minz_ExtensionManager::callHook('entry_auto_unread', $entry, 'updated_article');
  440. }
  441. $entry = Minz_ExtensionManager::callHook('entry_before_insert', $entry);
  442. if (!($entry instanceof FreshRSS_Entry)) {
  443. // An extension has returned a null value, there is nothing to insert.
  444. continue;
  445. }
  446. if (!$entry->isRead()) {
  447. $needFeedCacheRefresh = true;
  448. $feed->incPendingUnread(); //Maybe
  449. }
  450. // If the entry has changed, there is a good chance for the full content to have changed as well.
  451. $entry->loadCompleteContent(true);
  452. if (!$entryDAO->inTransaction()) {
  453. $entryDAO->beginTransaction();
  454. }
  455. $entryDAO->updateEntry($entry->toArray());
  456. }
  457. } else {
  458. $id = uTimeString();
  459. $entry->_id($id);
  460. $entry->applyFilterActions($titlesAsRead);
  461. if ($readWhenSameTitleInFeed > 0) {
  462. $titlesAsRead[$entry->title()] = true;
  463. }
  464. $entry = Minz_ExtensionManager::callHook('entry_before_insert', $entry);
  465. if (!($entry instanceof FreshRSS_Entry)) {
  466. // An extension has returned a null value, there is nothing to insert.
  467. continue;
  468. }
  469. if ($pubSubHubbubEnabled && !$simplePiePush) { //We use push, but have discovered an article by pull!
  470. $text = 'An article was discovered by pull although we use PubSubHubbub!: Feed ' .
  471. SimplePie_Misc::url_remove_credentials($url) .
  472. ' GUID ' . $entry->guid();
  473. Minz_Log::warning($text, PSHB_LOG);
  474. Minz_Log::warning($text);
  475. $pubSubHubbubEnabled = false;
  476. $feed->pubSubHubbubError(true);
  477. }
  478. if (!$entryDAO->inTransaction()) {
  479. $entryDAO->beginTransaction();
  480. }
  481. $entryDAO->addEntry($entry->toArray(), true);
  482. if (!$entry->isRead()) {
  483. $feed->incPendingUnread();
  484. }
  485. $nb_new_articles++;
  486. }
  487. }
  488. // N.B.: Applies to _entry table and not _entrytmp:
  489. $entryDAO->updateLastSeen($feed->id(), array_keys($newGuids), $mtime);
  490. } elseif ($feedIsUnchanged) {
  491. // Feed cache was unchanged, so mark as seen the same entries as last time
  492. if (!$entryDAO->inTransaction()) {
  493. $entryDAO->beginTransaction();
  494. }
  495. $entryDAO->updateLastSeenUnchanged($feed->id(), $mtime);
  496. }
  497. unset($entries);
  498. if (rand(0, 30) === 1) { // Remove old entries once in 30.
  499. if (!$entryDAO->inTransaction()) {
  500. $entryDAO->beginTransaction();
  501. }
  502. $nb = $feed->cleanOldEntries();
  503. if ($nb > 0) {
  504. $needFeedCacheRefresh = true;
  505. }
  506. }
  507. $feedDAO->updateLastUpdate($feed->id(), false, $mtime);
  508. $needFeedCacheRefresh |= ($feed->keepMaxUnread() != false);
  509. if ($simplePiePush === null) {
  510. // Do not call for WebSub events, as we do not know the list of articles still on the upstream feed.
  511. $needFeedCacheRefresh |= ($feed->markAsReadUponGone($feedIsEmpty, $mtime) != false);
  512. }
  513. if ($needFeedCacheRefresh) {
  514. $feedDAO->updateCachedValues($feed->id());
  515. }
  516. if ($entryDAO->inTransaction()) {
  517. $entryDAO->commit();
  518. }
  519. $feedProperties = [];
  520. if ($pubsubhubbubEnabledGeneral && $feed->hubUrl() && $feed->selfUrl()) { //selfUrl has priority for WebSub
  521. if ($feed->selfUrl() !== $url) { // https://github.com/pubsubhubbub/PubSubHubbub/wiki/Moving-Feeds-or-changing-Hubs
  522. $selfUrl = checkUrl($feed->selfUrl());
  523. if ($selfUrl) {
  524. Minz_Log::debug('WebSub unsubscribe ' . $feed->url(false));
  525. if (!$feed->pubSubHubbubSubscribe(false)) { //Unsubscribe
  526. Minz_Log::warning('Error while WebSub unsubscribing from ' . $feed->url(false));
  527. }
  528. $feed->_url($selfUrl, false);
  529. Minz_Log::notice('Feed ' . $url . ' canonical address moved to ' . $feed->url(false));
  530. $feedDAO->updateFeed($feed->id(), ['url' => $feed->url()]);
  531. }
  532. }
  533. } elseif ($feed->url() !== $url) { // HTTP 301 Moved Permanently
  534. Minz_Log::notice('Feed ' . SimplePie_Misc::url_remove_credentials($url) .
  535. ' moved permanently to ' . SimplePie_Misc::url_remove_credentials($feed->url(false)));
  536. $feedProperties['url'] = $feed->url();
  537. }
  538. if ($simplePie != null) {
  539. if ($feed->name(true) === '') {
  540. //HTML to HTML-PRE //ENT_COMPAT except '&'
  541. $name = strtr(html_only_entity_decode($simplePie->get_title()), ['<' => '&lt;', '>' => '&gt;', '"' => '&quot;']);
  542. $feed->_name($name);
  543. $feedProperties['name'] = $feed->name(false);
  544. }
  545. if (trim($feed->website()) === '') {
  546. $website = html_only_entity_decode($simplePie->get_link());
  547. $feed->_website($website == '' ? $feed->url() : $website);
  548. $feedProperties['website'] = $feed->website();
  549. $feed->faviconPrepare();
  550. }
  551. if (trim($feed->description()) === '') {
  552. $description = html_only_entity_decode($simplePie->get_description());
  553. if ($description !== '') {
  554. $feed->_description($description);
  555. $feedProperties['description'] = $feed->description();
  556. }
  557. }
  558. }
  559. if (!empty($feedProperties)) {
  560. $ok = $feedDAO->updateFeed($feed->id(), $feedProperties);
  561. if (!$ok && $feedIsNew) {
  562. //Cancel adding new feed in case of database error at first actualize
  563. $feedDAO->deleteFeed($feed->id());
  564. $feed->unlock();
  565. break;
  566. }
  567. }
  568. $feed->faviconPrepare();
  569. if ($pubsubhubbubEnabledGeneral && $feed->pubSubHubbubPrepare()) {
  570. Minz_Log::notice('WebSub subscribe ' . $feed->url(false));
  571. if (!$feed->pubSubHubbubSubscribe(true)) { //Subscribe
  572. Minz_Log::warning('Error while WebSub subscribing to ' . $feed->url(false));
  573. }
  574. }
  575. $feed->unlock();
  576. $updated_feeds++;
  577. unset($feed);
  578. gc_collect_cycles();
  579. // No more than $maxFeeds feeds unless $force is true to avoid overloading
  580. // the server.
  581. if ($updated_feeds >= $maxFeeds && !$force) {
  582. break;
  583. }
  584. }
  585. if (!$noCommit && ($nb_new_articles > 0 || $updated_feeds > 0)) {
  586. if (!$entryDAO->inTransaction()) {
  587. $entryDAO->beginTransaction();
  588. }
  589. $entryDAO->commitNewEntries();
  590. $feedDAO->updateCachedValues();
  591. if ($entryDAO->inTransaction()) {
  592. $entryDAO->commit();
  593. }
  594. $databaseDAO = FreshRSS_Factory::createDatabaseDAO();
  595. $databaseDAO->minorDbMaintenance();
  596. }
  597. return [$updated_feeds, reset($feeds), $nb_new_articles];
  598. }
  599. /**
  600. * This action actualizes entries from one or several feeds.
  601. *
  602. * Parameters are:
  603. * - id (default: false): Feed ID
  604. * - url (default: false): Feed URL
  605. * - force (default: false)
  606. * - noCommit (default: 0): Set to 1 to prevent committing the new articles to the main database
  607. * If id and url are not specified, all the feeds are actualized. But if force is
  608. * false, process stops at 10 feeds to avoid time execution problem.
  609. */
  610. public function actualizeAction(): int {
  611. Minz_Session::_param('actualize_feeds', false);
  612. $id = Minz_Request::paramInt('id');
  613. $url = Minz_Request::paramString('url');
  614. $force = Minz_Request::paramBoolean('force');
  615. $maxFeeds = Minz_Request::paramInt('maxFeeds');
  616. $noCommit = ($_POST['noCommit'] ?? 0) == 1;
  617. $feed = null;
  618. if ($id == -1 && !$noCommit) { //Special request only to commit & refresh DB cache
  619. $updated_feeds = 0;
  620. $entryDAO = FreshRSS_Factory::createEntryDao();
  621. $feedDAO = FreshRSS_Factory::createFeedDao();
  622. $entryDAO->beginTransaction();
  623. $entryDAO->commitNewEntries();
  624. $feedDAO->updateCachedValues();
  625. $entryDAO->commit();
  626. $databaseDAO = FreshRSS_Factory::createDatabaseDAO();
  627. $databaseDAO->minorDbMaintenance();
  628. } else {
  629. FreshRSS_category_Controller::refreshDynamicOpmls();
  630. [$updated_feeds, $feed] = self::actualizeFeed($id, $url, $force, null, $noCommit, $maxFeeds);
  631. }
  632. if (Minz_Request::paramBoolean('ajax')) {
  633. // Most of the time, ajax request is for only one feed. But since
  634. // there are several parallel requests, we should return that there
  635. // are several updated feeds.
  636. Minz_Request::setGoodNotification(_t('feedback.sub.feed.actualizeds'));
  637. // No layout in ajax request.
  638. $this->view->_layout(null);
  639. } elseif ($feed instanceof FreshRSS_Feed) {
  640. // Redirect to the main page with correct notification.
  641. if ($updated_feeds === 1) {
  642. Minz_Request::good(_t('feedback.sub.feed.actualized', $feed->name()), [
  643. 'params' => ['get' => 'f_' . $feed->id()]
  644. ]);
  645. } elseif ($updated_feeds > 1) {
  646. Minz_Request::good(_t('feedback.sub.feed.n_actualized', $updated_feeds), []);
  647. } else {
  648. Minz_Request::good(_t('feedback.sub.feed.no_refresh'), []);
  649. }
  650. }
  651. return $updated_feeds;
  652. }
  653. /**
  654. * @throws Minz_ConfigurationNamespaceException
  655. * @throws JsonException
  656. * @throws Minz_PDOConnectionException
  657. */
  658. public static function renameFeed(int $feed_id, string $feed_name): bool {
  659. if ($feed_id <= 0 || $feed_name === '') {
  660. return false;
  661. }
  662. FreshRSS_UserDAO::touch();
  663. $feedDAO = FreshRSS_Factory::createFeedDao();
  664. return $feedDAO->updateFeed($feed_id, ['name' => $feed_name]) === 1;
  665. }
  666. public static function moveFeed(int $feed_id, int $cat_id, string $new_cat_name = ''): bool {
  667. if ($feed_id <= 0 || ($cat_id <= 0 && $new_cat_name === '')) {
  668. return false;
  669. }
  670. FreshRSS_UserDAO::touch();
  671. $catDAO = FreshRSS_Factory::createCategoryDao();
  672. if ($cat_id > 0) {
  673. $cat = $catDAO->searchById($cat_id);
  674. $cat_id = $cat === null ? 0 : $cat->id();
  675. }
  676. if ($cat_id <= 1 && $new_cat_name != '') {
  677. $cat_id = $catDAO->addCategory(['name' => $new_cat_name]);
  678. }
  679. if ($cat_id <= 1) {
  680. $catDAO->checkDefault();
  681. $cat_id = FreshRSS_CategoryDAO::DEFAULTCATEGORYID;
  682. }
  683. $feedDAO = FreshRSS_Factory::createFeedDao();
  684. return $feedDAO->updateFeed($feed_id, ['category' => $cat_id]) === 1;
  685. }
  686. /**
  687. * This action changes the category of a feed.
  688. *
  689. * This page must be reached by a POST request.
  690. *
  691. * Parameters are:
  692. * - f_id (default: false)
  693. * - c_id (default: false)
  694. * If c_id is false, default category is used.
  695. *
  696. * @todo should handle order of the feed inside the category.
  697. */
  698. public function moveAction(): void {
  699. if (!Minz_Request::isPost()) {
  700. Minz_Request::forward(['c' => 'subscription'], true);
  701. }
  702. $feed_id = Minz_Request::paramInt('f_id');
  703. $cat_id = Minz_Request::paramInt('c_id');
  704. if (self::moveFeed($feed_id, $cat_id)) {
  705. // TODO: return something useful
  706. // Log a notice to prevent "Empty IF statement" warning in PHP_CodeSniffer
  707. Minz_Log::notice('Moved feed `' . $feed_id . '` in the category `' . $cat_id . '`');
  708. } else {
  709. Minz_Log::warning('Cannot move feed `' . $feed_id . '` in the category `' . $cat_id . '`');
  710. Minz_Error::error(404);
  711. }
  712. }
  713. public static function deleteFeed(int $feed_id): bool {
  714. FreshRSS_UserDAO::touch();
  715. $feedDAO = FreshRSS_Factory::createFeedDao();
  716. if ($feedDAO->deleteFeed($feed_id)) {
  717. // TODO: Delete old favicon
  718. // Remove related queries
  719. FreshRSS_Context::$user_conf->queries = remove_query_by_get(
  720. 'f_' . $feed_id, FreshRSS_Context::$user_conf->queries);
  721. FreshRSS_Context::$user_conf->save();
  722. return true;
  723. }
  724. return false;
  725. }
  726. /**
  727. * This action deletes a feed.
  728. *
  729. * This page must be reached by a POST request.
  730. * If there are related queries, they are deleted too.
  731. *
  732. * Parameters are:
  733. * - id (default: false)
  734. */
  735. public function deleteAction(): void {
  736. $from = Minz_Request::paramString('from');
  737. $id = Minz_Request::paramInt('id');
  738. switch ($from) {
  739. case 'stats':
  740. $redirect_url = ['c' => 'stats', 'a' => 'idle'];
  741. break;
  742. case 'normal':
  743. $get = Minz_Request::paramString('get');
  744. if ($get) {
  745. $redirect_url = ['c' => 'index', 'a' => 'normal', 'params' => ['get' => $get]];
  746. } else {
  747. $redirect_url = ['c' => 'index', 'a' => 'normal'];
  748. }
  749. break;
  750. default:
  751. $redirect_url = ['c' => 'subscription', 'a' => 'index'];
  752. if (!Minz_Request::isPost()) {
  753. Minz_Request::forward($redirect_url, true);
  754. }
  755. }
  756. if (self::deleteFeed($id)) {
  757. Minz_Request::good(_t('feedback.sub.feed.deleted'), $redirect_url);
  758. } else {
  759. Minz_Request::bad(_t('feedback.sub.feed.error'), $redirect_url);
  760. }
  761. }
  762. /**
  763. * This action force clears the cache of a feed.
  764. *
  765. * Parameters are:
  766. * - id (mandatory - no default): Feed ID
  767. *
  768. */
  769. public function clearCacheAction(): void {
  770. //Get Feed.
  771. $id = Minz_Request::paramInt('id');
  772. $feedDAO = FreshRSS_Factory::createFeedDao();
  773. $feed = $feedDAO->searchById($id);
  774. if ($feed === null) {
  775. Minz_Request::bad(_t('feedback.sub.feed.not_found'), []);
  776. return;
  777. }
  778. $feed->clearCache();
  779. Minz_Request::good(_t('feedback.sub.feed.cache_cleared', $feed->name()), [
  780. 'params' => ['get' => 'f_' . $feed->id()],
  781. ]);
  782. }
  783. /**
  784. * This action forces reloading the articles of a feed.
  785. *
  786. * Parameters are:
  787. * - id (mandatory - no default): Feed ID
  788. *
  789. * @throws FreshRSS_BadUrl_Exception
  790. */
  791. public function reloadAction(): void {
  792. @set_time_limit(300);
  793. //Get Feed ID.
  794. $feed_id = Minz_Request::paramInt('id');
  795. $limit = Minz_Request::paramInt('reload_limit') ?: 10;
  796. $feedDAO = FreshRSS_Factory::createFeedDao();
  797. $entryDAO = FreshRSS_Factory::createEntryDao();
  798. $feed = $feedDAO->searchById($feed_id);
  799. if ($feed === null) {
  800. Minz_Request::bad(_t('feedback.sub.feed.not_found'), []);
  801. return;
  802. }
  803. //Re-fetch articles as if the feed was new.
  804. $feedDAO->updateFeed($feed->id(), [ 'lastUpdate' => 0 ]);
  805. self::actualizeFeed($feed_id, '', false);
  806. //Extract all feed entries from database, load complete content and store them back in database.
  807. $entries = $entryDAO->listWhere('f', $feed_id, FreshRSS_Entry::STATE_ALL, 'DESC', $limit);
  808. //We need another DB connection in parallel for unbuffered streaming
  809. Minz_ModelPdo::$usesSharedPdo = false;
  810. if (FreshRSS_Context::$system_conf->db['type'] === 'mysql') {
  811. // Second parallel connection for unbuffered streaming: MySQL
  812. $entryDAO2 = FreshRSS_Factory::createEntryDao();
  813. } else {
  814. // Single connection for buffered queries (in memory): SQLite, PostgreSQL
  815. //TODO: Consider an unbuffered query for PostgreSQL
  816. $entryDAO2 = $entryDAO;
  817. }
  818. foreach ($entries as $entry) {
  819. if ($entry->loadCompleteContent(true)) {
  820. $entryDAO2->updateEntry($entry->toArray());
  821. }
  822. }
  823. Minz_ModelPdo::$usesSharedPdo = true;
  824. //Give feedback to user.
  825. Minz_Request::good(_t('feedback.sub.feed.reloaded', $feed->name()), [
  826. 'params' => ['get' => 'f_' . $feed->id()]
  827. ]);
  828. }
  829. /**
  830. * This action creates a preview of a content-selector.
  831. *
  832. * Parameters are:
  833. * - id (mandatory - no default): Feed ID
  834. * - selector (mandatory - no default): Selector to preview
  835. *
  836. */
  837. public function contentSelectorPreviewAction(): void {
  838. //Configure.
  839. $this->view->fatalError = '';
  840. $this->view->selectorSuccess = false;
  841. $this->view->htmlContent = '';
  842. $this->view->_layout(null);
  843. $this->_csp([
  844. 'default-src' => "'self'",
  845. 'frame-src' => '*',
  846. 'img-src' => '* data:',
  847. 'media-src' => '*',
  848. ]);
  849. //Get parameters.
  850. $feed_id = Minz_Request::paramInt('id');
  851. $content_selector = Minz_Request::paramString('selector');
  852. if (!$content_selector) {
  853. $this->view->fatalError = _t('feedback.sub.feed.selector_preview.selector_empty');
  854. return;
  855. }
  856. //Check Feed ID validity.
  857. $entryDAO = FreshRSS_Factory::createEntryDao();
  858. $entries = $entryDAO->listWhere('f', $feed_id);
  859. $entry = null;
  860. //Get first entry (syntax robust for Generator or Array)
  861. foreach ($entries as $myEntry) {
  862. $entry = $myEntry;
  863. }
  864. if ($entry == null) {
  865. $this->view->fatalError = _t('feedback.sub.feed.selector_preview.no_entries');
  866. return;
  867. }
  868. //Get feed.
  869. $feed = $entry->feed();
  870. if ($feed === null) {
  871. $this->view->fatalError = _t('feedback.sub.feed.selector_preview.no_feed');
  872. return;
  873. }
  874. $attributes = $feed->attributes();
  875. $attributes['path_entries_filter'] = Minz_Request::paramString('selector_filter', true);
  876. //Fetch & select content.
  877. try {
  878. $fullContent = FreshRSS_Entry::getContentByParsing(
  879. htmlspecialchars_decode($entry->link(), ENT_QUOTES),
  880. htmlspecialchars_decode($content_selector, ENT_QUOTES),
  881. $attributes
  882. );
  883. if ($fullContent != '') {
  884. $this->view->selectorSuccess = true;
  885. $this->view->htmlContent = $fullContent;
  886. } else {
  887. $this->view->selectorSuccess = false;
  888. $this->view->htmlContent = $entry->content(false);
  889. }
  890. } catch (Exception $e) {
  891. $this->view->fatalError = _t('feedback.sub.feed.selector_preview.http_error');
  892. }
  893. }
  894. }