feedController.php 14 KB

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