feedController.php 28 KB

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