feedController.php 25 KB

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