feedController.php 26 KB

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