feedController.php 28 KB

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