feedController.php 27 KB

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