feedController.php 34 KB

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