feedController.php 32 KB

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