feedController.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  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->applyFilterActions($titlesAsRead);
  442. if ($readWhenSameTitleInFeed > 0) {
  443. $titlesAsRead[$entry->title()] = true;
  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. @set_time_limit(300);
  797. //Get Feed ID.
  798. $feed_id = Minz_Request::paramInt('id');
  799. $limit = Minz_Request::paramInt('reload_limit') ?: 10;
  800. $feedDAO = FreshRSS_Factory::createFeedDao();
  801. $entryDAO = FreshRSS_Factory::createEntryDao();
  802. $feed = $feedDAO->searchById($feed_id);
  803. if ($feed === null) {
  804. Minz_Request::bad(_t('feedback.sub.feed.not_found'), []);
  805. return;
  806. }
  807. //Re-fetch articles as if the feed was new.
  808. $feedDAO->updateFeed($feed->id(), [ 'lastUpdate' => 0 ]);
  809. self::actualizeFeed($feed_id, '', false);
  810. //Extract all feed entries from database, load complete content and store them back in database.
  811. $entries = $entryDAO->listWhere('f', $feed_id, FreshRSS_Entry::STATE_ALL, 'DESC', $limit);
  812. //We need another DB connection in parallel for unbuffered streaming
  813. Minz_ModelPdo::$usesSharedPdo = false;
  814. if (FreshRSS_Context::$system_conf->db['type'] === 'mysql') {
  815. // Second parallel connection for unbuffered streaming: MySQL
  816. $entryDAO2 = FreshRSS_Factory::createEntryDao();
  817. } else {
  818. // Single connection for buffered queries (in memory): SQLite, PostgreSQL
  819. //TODO: Consider an unbuffered query for PostgreSQL
  820. $entryDAO2 = $entryDAO;
  821. }
  822. foreach ($entries as $entry) {
  823. if ($entry->loadCompleteContent(true)) {
  824. $entryDAO2->updateEntry($entry->toArray());
  825. }
  826. }
  827. Minz_ModelPdo::$usesSharedPdo = true;
  828. //Give feedback to user.
  829. Minz_Request::good(_t('feedback.sub.feed.reloaded', $feed->name()), [
  830. 'params' => ['get' => 'f_' . $feed->id()]
  831. ]);
  832. }
  833. /**
  834. * This action creates a preview of a content-selector.
  835. *
  836. * Parameters are:
  837. * - id (mandatory - no default): Feed ID
  838. * - selector (mandatory - no default): Selector to preview
  839. *
  840. */
  841. public function contentSelectorPreviewAction(): void {
  842. //Configure.
  843. $this->view->fatalError = '';
  844. $this->view->selectorSuccess = false;
  845. $this->view->htmlContent = '';
  846. $this->view->_layout(null);
  847. $this->_csp([
  848. 'default-src' => "'self'",
  849. 'frame-src' => '*',
  850. 'img-src' => '* data:',
  851. 'media-src' => '*',
  852. ]);
  853. //Get parameters.
  854. $feed_id = Minz_Request::paramInt('id');
  855. $content_selector = Minz_Request::paramString('selector');
  856. if (!$content_selector) {
  857. $this->view->fatalError = _t('feedback.sub.feed.selector_preview.selector_empty');
  858. return;
  859. }
  860. //Check Feed ID validity.
  861. $entryDAO = FreshRSS_Factory::createEntryDao();
  862. $entries = $entryDAO->listWhere('f', $feed_id);
  863. $entry = null;
  864. //Get first entry (syntax robust for Generator or Array)
  865. foreach ($entries as $myEntry) {
  866. $entry = $myEntry;
  867. }
  868. if ($entry == null) {
  869. $this->view->fatalError = _t('feedback.sub.feed.selector_preview.no_entries');
  870. return;
  871. }
  872. //Get feed.
  873. $feed = $entry->feed();
  874. if ($feed === null) {
  875. $this->view->fatalError = _t('feedback.sub.feed.selector_preview.no_feed');
  876. return;
  877. }
  878. $attributes = $feed->attributes();
  879. $attributes['path_entries_filter'] = Minz_Request::paramString('selector_filter', true);
  880. //Fetch & select content.
  881. try {
  882. $fullContent = FreshRSS_Entry::getContentByParsing(
  883. htmlspecialchars_decode($entry->link(), ENT_QUOTES),
  884. htmlspecialchars_decode($content_selector, ENT_QUOTES),
  885. $attributes
  886. );
  887. if ($fullContent != '') {
  888. $this->view->selectorSuccess = true;
  889. $this->view->htmlContent = $fullContent;
  890. } else {
  891. $this->view->selectorSuccess = false;
  892. $this->view->htmlContent = $entry->content(false);
  893. }
  894. } catch (Exception $e) {
  895. $this->view->fatalError = _t('feedback.sub.feed.selector_preview.http_error');
  896. }
  897. }
  898. }