4
0

feedController.php 33 KB

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