feedController.php 31 KB

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