feedController.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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::$conf->token;
  17. $token_param = Minz_Request::param('token', '');
  18. $token_is_ok = ($token != '' && $token == $token_param);
  19. $action = Minz_Request::actionName();
  20. if ($action !== 'actualize' ||
  21. !(Minz_Configuration::allowAnonymousRefresh() || $token_is_ok)) {
  22. Minz_Error::error(403);
  23. }
  24. }
  25. }
  26. /**
  27. * This action subscribes to a feed.
  28. *
  29. * It can be reached by both GET and POST requests.
  30. *
  31. * GET request displays a form to add and configure a feed.
  32. * Request parameter is:
  33. * - url_rss (default: false)
  34. *
  35. * POST request adds a feed in database.
  36. * Parameters are:
  37. * - url_rss (default: false)
  38. * - category (default: false)
  39. * - new_category (required if category == 'nc')
  40. * - http_user (default: false)
  41. * - http_pass (default: false)
  42. * It tries to get website information from RSS feed.
  43. * If no category is given, feed is added to the default one.
  44. *
  45. * If url_rss is false, nothing happened.
  46. */
  47. public function addAction() {
  48. $url = Minz_Request::param('url_rss');
  49. if ($url === false) {
  50. // No url, do nothing
  51. Minz_Request::forward(array(
  52. 'c' => 'subscription',
  53. 'a' => 'index'
  54. ), true);
  55. }
  56. $feedDAO = FreshRSS_Factory::createFeedDao();
  57. $this->catDAO = new FreshRSS_CategoryDAO();
  58. $url_redirect = array(
  59. 'c' => 'subscription',
  60. 'a' => 'index',
  61. 'params' => array(),
  62. );
  63. $limits = Minz_Configuration::limits();
  64. $this->view->feeds = $feedDAO->listFeeds();
  65. if (count($this->view->feeds) >= $limits['max_feeds']) {
  66. Minz_Request::bad(_t('sub.feeds.over_max', $limits['max_feeds']),
  67. $url_redirect);
  68. }
  69. if (Minz_Request::isPost()) {
  70. @set_time_limit(300);
  71. $cat = Minz_Request::param('category');
  72. if ($cat === 'nc') {
  73. // User want to create a new category, new_category parameter
  74. // must exist
  75. $new_cat = Minz_Request::param('new_category');
  76. if (empty($new_cat['name'])) {
  77. $cat = false;
  78. } else {
  79. $cat = $this->catDAO->addCategory($new_cat);
  80. }
  81. }
  82. if ($cat === false) {
  83. // If category was not given or if creating new category failed,
  84. // get the default category
  85. $this->catDAO->checkDefault();
  86. $def_cat = $this->catDAO->getDefault();
  87. $cat = $def_cat->id();
  88. }
  89. // HTTP information are useful if feed is protected behind a
  90. // HTTP authentication
  91. $user = Minz_Request::param('http_user');
  92. $pass = Minz_Request::param('http_pass');
  93. $http_auth = '';
  94. if ($user != '' || $pass != '') {
  95. $http_auth = $user . ':' . $pass;
  96. }
  97. $transaction_started = false;
  98. try {
  99. $feed = new FreshRSS_Feed($url);
  100. } catch (FreshRSS_BadUrl_Exception $e) {
  101. // Given url was not a valid url!
  102. Minz_Log::warning($e->getMessage());
  103. Minz_Request::bad(_t('invalid_url', $url), $url_redirect);
  104. }
  105. try {
  106. $feed->load(true);
  107. } catch (FreshRSS_Feed_Exception $e) {
  108. // Something went bad (timeout, server not found, etc.)
  109. Minz_Log::warning($e->getMessage());
  110. Minz_Request::bad(
  111. _t('internal_problem_feed', _url('index', 'logs')),
  112. $url_redirect
  113. );
  114. } catch (Minz_FileNotExistException $e) {
  115. // Cache directory doesn't exist!
  116. Minz_Log::error($e->getMessage());
  117. Minz_Request::bad(
  118. _t('internal_problem_feed', _url('index', 'logs')),
  119. $url_redirect
  120. );
  121. }
  122. if ($feedDAO->searchByUrl($feed->url())) {
  123. Minz_Request::bad(_t('already_subscribed', $feed->name()), $url_redirect);
  124. }
  125. $feed->_category($cat);
  126. $feed->_httpAuth($http_auth);
  127. // Call the extension hook
  128. $feed = Minz_ExtensionManager::callHook('feed_before_insert', $feed);
  129. if (is_null($feed)) {
  130. Minz_Request::bad(_t('feed_not_added', $feed->name()), $url_redirect);
  131. }
  132. $values = array(
  133. 'url' => $feed->url(),
  134. 'category' => $feed->category(),
  135. 'name' => $feed->name(),
  136. 'website' => $feed->website(),
  137. 'description' => $feed->description(),
  138. 'lastUpdate' => time(),
  139. 'httpAuth' => $feed->httpAuth(),
  140. );
  141. $id = $feedDAO->addFeed($values);
  142. if (!$id) {
  143. // There was an error in database... we cannot say what here.
  144. Minz_Request::bad(_t('feed_not_added', $feed->name()), $url_redirect);
  145. }
  146. // Ok, feed has been added in database. Now we have to refresh entries.
  147. $feed->_id($id);
  148. $feed->faviconPrepare();
  149. $is_read = FreshRSS_Context::$conf->mark_when['reception'] ? 1 : 0;
  150. $entryDAO = FreshRSS_Factory::createEntryDao();
  151. // We want chronological order and SimplePie uses reverse order.
  152. $entries = array_reverse($feed->entries());
  153. // Calculate date of oldest entries we accept in DB.
  154. $nb_month_old = FreshRSS_Context::$conf->old_entries;
  155. $date_min = time() - (3600 * 24 * 30 * $nb_month_old);
  156. // Use a shared statement and a transaction to improve a LOT the
  157. // performances.
  158. $prepared_statement = $entryDAO->addEntryPrepare();
  159. $feedDAO->beginTransaction();
  160. foreach ($entries as $entry) {
  161. // Entries are added without any verification.
  162. $entry->_feed($feed->id());
  163. $entry->_id(min(time(), $entry->date(true)) . uSecString());
  164. $entry->_isRead($is_read);
  165. $entry = Minz_ExtensionManager::callHook('entry_before_insert', $entry);
  166. if (is_null($entry)) {
  167. // An extension has returned a null value, there is nothing to insert.
  168. continue;
  169. }
  170. $values = $entry->toArray();
  171. $entryDAO->addEntry($values, $prepared_statement);
  172. }
  173. $feedDAO->updateLastUpdate($feed->id());
  174. $feedDAO->commit();
  175. // Entries are in DB, we redirect to feed configuration page.
  176. $url_redirect['params']['id'] = $feed->id();
  177. Minz_Request::good(_t('feed_added', $feed->name()), $url_redirect);
  178. } else {
  179. // GET request: we must ask confirmation to user before adding feed.
  180. Minz_View::prependTitle(_t('add_rss_feed') . ' · ');
  181. $this->view->categories = $this->catDAO->listCategories(false);
  182. $this->view->feed = new FreshRSS_Feed($url);
  183. try {
  184. // We try to get more information about the feed.
  185. $this->view->feed->load(true);
  186. $this->view->load_ok = true;
  187. } catch (Exception $e) {
  188. $this->view->load_ok = false;
  189. }
  190. $feed = $feedDAO->searchByUrl($this->view->feed->url());
  191. if ($feed) {
  192. // Already subscribe so we redirect to the feed configuration page.
  193. $url_redirect['params']['id'] = $feed->id();
  194. Minz_Request::good(_t('already_subscribed', $feed->name()), $url_redirect);
  195. }
  196. }
  197. }
  198. /**
  199. * This action remove entries from a given feed.
  200. *
  201. * It should be reached by a POST action.
  202. *
  203. * Parameter is:
  204. * - id (default: false)
  205. */
  206. public function truncateAction() {
  207. $id = Minz_Request::param('id');
  208. $url_redirect = array(
  209. 'c' => 'subscription',
  210. 'a' => 'index',
  211. 'params' => array('id' => $id)
  212. );
  213. if (!Minz_Request::isPost()) {
  214. Minz_Request::forward($url_redirect, true);
  215. }
  216. $feedDAO = FreshRSS_Factory::createFeedDao();
  217. $n = $feedDAO->truncate($id);
  218. invalidateHttpCache();
  219. if ($n === false) {
  220. Minz_Request::bad(_t('error_occurred'), $url_redirect);
  221. } else {
  222. Minz_Request::good(_t('n_entries_deleted', $n), $url_redirect);
  223. }
  224. }
  225. /**
  226. * This action actualizes entries from one or several feeds.
  227. *
  228. * Parameters are:
  229. * - id (default: false)
  230. * - force (default: false)
  231. * If id is not specified, all the feeds are actualized. But if force is
  232. * false, process stops at 10 feeds to avoid time execution problem.
  233. */
  234. public function actualizeAction() {
  235. @set_time_limit(300);
  236. $feedDAO = FreshRSS_Factory::createFeedDao();
  237. $entryDAO = FreshRSS_Factory::createEntryDao();
  238. Minz_Session::_param('actualize_feeds', false);
  239. $id = Minz_Request::param('id');
  240. $force = Minz_Request::param('force');
  241. // Create a list of feeds to actualize.
  242. // If id is set and valid, corresponding feed is added to the list but
  243. // alone in order to automatize further process.
  244. $feeds = array();
  245. if ($id) {
  246. $feed = $feedDAO->searchById($id);
  247. if ($feed) {
  248. $feeds[] = $feed;
  249. }
  250. } else {
  251. $feeds = $feedDAO->listFeedsOrderUpdate(FreshRSS_Context::$conf->ttl_default);
  252. }
  253. // Calculate date of oldest entries we accept in DB.
  254. $nb_month_old = max(FreshRSS_Context::$conf->old_entries, 1);
  255. $date_min = time() - (3600 * 24 * 30 * $nb_month_old);
  256. $updated_feeds = 0;
  257. $is_read = FreshRSS_Context::$conf->mark_when['reception'] ? 1 : 0;
  258. foreach ($feeds as $feed) {
  259. if (!$feed->lock()) {
  260. Minz_Log::notice('Feed already being actualized: ' . $feed->url());
  261. continue;
  262. }
  263. try {
  264. // Load entries
  265. $feed->load(false);
  266. } catch (FreshRSS_Feed_Exception $e) {
  267. Minz_Log::notice($e->getMessage());
  268. $feedDAO->updateLastUpdate($feed->id(), 1);
  269. $feed->unlock();
  270. continue;
  271. }
  272. $url = $feed->url();
  273. $feed_history = $feed->keepHistory();
  274. if ($feed_history == -2) {
  275. // TODO: -2 must be a constant!
  276. // -2 means we take the default value from configuration
  277. $feed_history = FreshRSS_Context::$conf->keep_history_default;
  278. }
  279. // We want chronological order and SimplePie uses reverse order.
  280. $entries = array_reverse($feed->entries());
  281. if (count($entries) > 0) {
  282. // For this feed, check last n entry GUIDs already in database.
  283. $existing_guids = array_fill_keys($entryDAO->listLastGuidsByFeed(
  284. $feed->id(), count($entries) + 10
  285. ), 1);
  286. $use_declared_date = empty($existing_guids);
  287. // Add entries in database if possible.
  288. $prepared_statement = $entryDAO->addEntryPrepare();
  289. $feedDAO->beginTransaction();
  290. foreach ($entries as $entry) {
  291. $entry_date = $entry->date(true);
  292. if (isset($existing_guids[$entry->guid()]) ||
  293. ($feed_history == 0 && $entry_date < $date_min)) {
  294. // This entry already exists in DB or should not be added
  295. // considering configuration and date.
  296. continue;
  297. }
  298. $id = uTimeString();
  299. if ($use_declared_date || $entry_date < $date_min) {
  300. // Use declared date at first import.
  301. $id = min(time(), $entry_date) . uSecString();
  302. }
  303. $entry->_id($id);
  304. $entry->_isRead($is_read);
  305. $entry = Minz_ExtensionManager::callHook('entry_before_insert', $entry);
  306. if (is_null($entry)) {
  307. // An extension has returned a null value, there is nothing to insert.
  308. continue;
  309. }
  310. $values = $entry->toArray();
  311. $entryDAO->addEntry($values, $prepared_statement);
  312. }
  313. }
  314. if ($feed_history >= 0 && rand(0, 30) === 1) {
  315. // TODO: move this function in web cron when available (see entry::purge)
  316. // Remove old entries once in 30.
  317. if (!$feedDAO->hasTransaction()) {
  318. $feedDAO->beginTransaction();
  319. }
  320. $nb = $feedDAO->cleanOldEntries($feed->id(),
  321. $date_min,
  322. max($feed_history, count($entries) + 10));
  323. if ($nb > 0) {
  324. Minz_Log::debug($nb . ' old entries cleaned in feed [' .
  325. $feed->url() . ']');
  326. }
  327. }
  328. $feedDAO->updateLastUpdate($feed->id(), 0, $feedDAO->hasTransaction());
  329. if ($feedDAO->hasTransaction()) {
  330. $feedDAO->commit();
  331. }
  332. if ($feed->url() !== $url) {
  333. // HTTP 301 Moved Permanently
  334. Minz_Log::notice('Feed ' . $url . ' moved permanently to ' . $feed->url());
  335. $feedDAO->updateFeed($feed->id(), array('url' => $feed->url()));
  336. }
  337. $feed->faviconPrepare();
  338. $feed->unlock();
  339. $updated_feeds++;
  340. unset($feed);
  341. // No more than 10 feeds unless $force is true to avoid overloading
  342. // the server.
  343. if ($updated_feeds >= 10 && !$force) {
  344. break;
  345. }
  346. }
  347. if (Minz_Request::param('ajax')) {
  348. // Most of the time, ajax request is for only one feed. But since
  349. // there are several parallel requests, we should return that there
  350. // are several updated feeds.
  351. $notif = array(
  352. 'type' => 'good',
  353. 'content' => _t('feeds_actualized')
  354. );
  355. Minz_Session::_param('notification', $notif);
  356. // No layout in ajax request.
  357. $this->view->_useLayout(false);
  358. return;
  359. }
  360. // Redirect to the main page with correct notification.
  361. if ($updated_feeds === 1) {
  362. $feed = reset($feeds);
  363. Minz_Request::good(_t('feed_actualized', $feed->name()),
  364. array('get' => 'f_' . $feed->id()));
  365. } elseif ($updated_feeds > 1) {
  366. Minz_Request::good(_t('n_feeds_actualized', $updated_feeds), array());
  367. } else {
  368. Minz_Request::good(_t('no_feed_to_refresh'), array());
  369. }
  370. }
  371. /**
  372. * This action changes the category of a feed.
  373. *
  374. * This page must be reached by a POST request.
  375. *
  376. * Parameters are:
  377. * - f_id (default: false)
  378. * - c_id (default: false)
  379. * If c_id is false, default category is used.
  380. *
  381. * @todo should handle order of the feed inside the category.
  382. */
  383. public function moveAction() {
  384. if (!Minz_Request::isPost()) {
  385. Minz_Request::forward(array('c' => 'subscription'), true);
  386. }
  387. $feed_id = Minz_Request::param('f_id');
  388. $cat_id = Minz_Request::param('c_id');
  389. if ($cat_id === false) {
  390. // If category was not given get the default one.
  391. $catDAO = new FreshRSS_CategoryDAO();
  392. $catDAO->checkDefault();
  393. $def_cat = $catDAO->getDefault();
  394. $cat_id = $def_cat->id();
  395. }
  396. $feedDAO = FreshRSS_Factory::createFeedDao();
  397. $values = array('category' => $cat_id);
  398. $feed = $feedDAO->searchById($feed_id);
  399. if ($feed && ($feed->category() == $cat_id ||
  400. $feedDAO->updateFeed($feed_id, $values))) {
  401. // TODO: return something useful
  402. } else {
  403. Minz_Log::warning('Cannot move feed `' . $feed_id . '` ' .
  404. 'in the category `' . $cat_id . '`');
  405. Minz_Error::error(404);
  406. }
  407. }
  408. /**
  409. * This action deletes a feed.
  410. *
  411. * This page must be reached by a POST request.
  412. * If there are related queries, they are deleted too.
  413. *
  414. * Parameters are:
  415. * - id (default: false)
  416. * - r (default: false)
  417. * r permits to redirect to a given page at the end of this action.
  418. *
  419. * @todo handle "r" redirection in Minz_Request::forward()?
  420. */
  421. public function deleteAction() {
  422. $redirect_url = Minz_Request::param('r', false, true);
  423. if (!$redirect_url) {
  424. $redirect_url = array('c' => 'subscription', 'a' => 'index');
  425. }
  426. if (!Minz_Request::isPost()) {
  427. Minz_Request::forward($redirect_url, true);
  428. }
  429. $id = Minz_Request::param('id');
  430. $feedDAO = FreshRSS_Factory::createFeedDao();
  431. if ($feedDAO->deleteFeed($id)) {
  432. // TODO: Delete old favicon
  433. // Remove related queries
  434. FreshRSS_Context::$conf->remove_query_by_get('f_' . $id);
  435. FreshRSS_Context::$conf->save();
  436. Minz_Request::good(_t('feed_deleted'), $redirect_url);
  437. } else {
  438. Minz_Request::bad(_t('error_occurred'), $redirect_url);
  439. }
  440. }
  441. }