feedController.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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('feedback.sub.feed.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('feedback.sub.feed.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('feedback.sub.feed.internal_problem', _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('feedback.sub.feed.internal_problem', _url('index', 'logs')),
  119. $url_redirect
  120. );
  121. }
  122. if ($feedDAO->searchByUrl($feed->url())) {
  123. Minz_Request::bad(
  124. _t('feedback.sub.feed.already_subscribed', $feed->name()),
  125. $url_redirect
  126. );
  127. }
  128. $feed->_category($cat);
  129. $feed->_httpAuth($http_auth);
  130. $values = array(
  131. 'url' => $feed->url(),
  132. 'category' => $feed->category(),
  133. 'name' => $feed->name(),
  134. 'website' => $feed->website(),
  135. 'description' => $feed->description(),
  136. 'lastUpdate' => time(),
  137. 'httpAuth' => $feed->httpAuth(),
  138. );
  139. $id = $feedDAO->addFeed($values);
  140. if (!$id) {
  141. // There was an error in database... we cannot say what here.
  142. Minz_Request::bad(_t('feedback.sub.feed.not_added', $feed->name()), $url_redirect);
  143. }
  144. // Ok, feed has been added in database. Now we have to refresh entries.
  145. $feed->_id($id);
  146. $feed->faviconPrepare();
  147. $is_read = FreshRSS_Context::$conf->mark_when['reception'] ? 1 : 0;
  148. $entryDAO = FreshRSS_Factory::createEntryDao();
  149. // We want chronological order and SimplePie uses reverse order.
  150. $entries = array_reverse($feed->entries());
  151. // Calculate date of oldest entries we accept in DB.
  152. $nb_month_old = FreshRSS_Context::$conf->old_entries;
  153. $date_min = time() - (3600 * 24 * 30 * $nb_month_old);
  154. // Use a shared statement and a transaction to improve a LOT the
  155. // performances.
  156. $prepared_statement = $entryDAO->addEntryPrepare();
  157. $feedDAO->beginTransaction();
  158. foreach ($entries as $entry) {
  159. // Entries are added without any verification.
  160. $values = $entry->toArray();
  161. $values['id_feed'] = $feed->id();
  162. $values['id'] = min(time(), $entry->date(true)) . uSecString();
  163. $values['is_read'] = $is_read;
  164. $entryDAO->addEntry($values, $prepared_statement);
  165. }
  166. $feedDAO->updateLastUpdate($feed->id());
  167. $feedDAO->commit();
  168. // Entries are in DB, we redirect to feed configuration page.
  169. $url_redirect['params']['id'] = $feed->id();
  170. Minz_Request::good(_t('feedback.sub.feed.added', $feed->name()), $url_redirect);
  171. } else {
  172. // GET request: we must ask confirmation to user before adding feed.
  173. Minz_View::prependTitle(_t('sub.feed.title_add') . ' · ');
  174. $this->view->categories = $this->catDAO->listCategories(false);
  175. $this->view->feed = new FreshRSS_Feed($url);
  176. try {
  177. // We try to get more information about the feed.
  178. $this->view->feed->load(true);
  179. $this->view->load_ok = true;
  180. } catch (Exception $e) {
  181. $this->view->load_ok = false;
  182. }
  183. $feed = $feedDAO->searchByUrl($this->view->feed->url());
  184. if ($feed) {
  185. // Already subscribe so we redirect to the feed configuration page.
  186. $url_redirect['params']['id'] = $feed->id();
  187. Minz_Request::good(_t('feedback.sub.feed.already_subscribed', $feed->name()), $url_redirect);
  188. }
  189. }
  190. }
  191. /**
  192. * This action remove entries from a given feed.
  193. *
  194. * It should be reached by a POST action.
  195. *
  196. * Parameter is:
  197. * - id (default: false)
  198. */
  199. public function truncateAction() {
  200. $id = Minz_Request::param('id');
  201. $url_redirect = array(
  202. 'c' => 'subscription',
  203. 'a' => 'index',
  204. 'params' => array('id' => $id)
  205. );
  206. if (!Minz_Request::isPost()) {
  207. Minz_Request::forward($url_redirect, true);
  208. }
  209. $feedDAO = FreshRSS_Factory::createFeedDao();
  210. $n = $feedDAO->truncate($id);
  211. invalidateHttpCache();
  212. if ($n === false) {
  213. Minz_Request::bad(_t('feedback.sub.feed.error'), $url_redirect);
  214. } else {
  215. Minz_Request::good(_t('feedback.sub.feed.n_entries_deleted', $n), $url_redirect);
  216. }
  217. }
  218. /**
  219. * This action actualizes entries from one or several feeds.
  220. *
  221. * Parameters are:
  222. * - id (default: false)
  223. * - force (default: false)
  224. * If id is not specified, all the feeds are actualized. But if force is
  225. * false, process stops at 10 feeds to avoid time execution problem.
  226. */
  227. public function actualizeAction() {
  228. @set_time_limit(300);
  229. $feedDAO = FreshRSS_Factory::createFeedDao();
  230. $entryDAO = FreshRSS_Factory::createEntryDao();
  231. Minz_Session::_param('actualize_feeds', false);
  232. $id = Minz_Request::param('id');
  233. $force = Minz_Request::param('force');
  234. // Create a list of feeds to actualize.
  235. // If 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 ($id) {
  239. $feed = $feedDAO->searchById($id);
  240. if ($feed) {
  241. $feeds[] = $feed;
  242. }
  243. } else {
  244. $feeds = $feedDAO->listFeedsOrderUpdate(FreshRSS_Context::$conf->ttl_default);
  245. }
  246. // Calculate date of oldest entries we accept in DB.
  247. $nb_month_old = max(FreshRSS_Context::$conf->old_entries, 1);
  248. $date_min = time() - (3600 * 24 * 30 * $nb_month_old);
  249. $updated_feeds = 0;
  250. $is_read = FreshRSS_Context::$conf->mark_when['reception'] ? 1 : 0;
  251. foreach ($feeds as $feed) {
  252. if (!$feed->lock()) {
  253. Minz_Log::notice('Feed already being actualized: ' . $feed->url());
  254. continue;
  255. }
  256. try {
  257. // Load entries
  258. $feed->load(false);
  259. } catch (FreshRSS_Feed_Exception $e) {
  260. Minz_Log::notice($e->getMessage());
  261. $feedDAO->updateLastUpdate($feed->id(), 1);
  262. $feed->unlock();
  263. continue;
  264. }
  265. $url = $feed->url();
  266. $feed_history = $feed->keepHistory();
  267. if ($feed_history == -2) {
  268. // TODO: -2 must be a constant!
  269. // -2 means we take the default value from configuration
  270. $feed_history = FreshRSS_Context::$conf->keep_history_default;
  271. }
  272. // We want chronological order and SimplePie uses reverse order.
  273. $entries = array_reverse($feed->entries());
  274. if (count($entries) > 0) {
  275. // For this feed, check last n entry GUIDs already in database.
  276. $existing_guids = array_fill_keys($entryDAO->listLastGuidsByFeed(
  277. $feed->id(), count($entries) + 10
  278. ), 1);
  279. $use_declared_date = empty($existing_guids);
  280. // Add entries in database if possible.
  281. $prepared_statement = $entryDAO->addEntryPrepare();
  282. $feedDAO->beginTransaction();
  283. foreach ($entries as $entry) {
  284. $entry_date = $entry->date(true);
  285. if (isset($existing_guids[$entry->guid()]) ||
  286. ($feed_history == 0 && $entry_date < $date_min)) {
  287. // This entry already exists in DB or should not be added
  288. // considering configuration and date.
  289. continue;
  290. }
  291. $id = uTimeString();
  292. if ($use_declared_date || $entry_date < $date_min) {
  293. // Use declared date at first import.
  294. $id = min(time(), $entry_date) . uSecString();
  295. }
  296. $values = $entry->toArray();
  297. $values['id'] = $id;
  298. $values['is_read'] = $is_read;
  299. $entryDAO->addEntry($values, $prepared_statement);
  300. }
  301. }
  302. if ($feed_history >= 0 && rand(0, 30) === 1) {
  303. // TODO: move this function in web cron when available (see entry::purge)
  304. // Remove old entries once in 30.
  305. if (!$feedDAO->hasTransaction()) {
  306. $feedDAO->beginTransaction();
  307. }
  308. $nb = $feedDAO->cleanOldEntries($feed->id(),
  309. $date_min,
  310. max($feed_history, count($entries) + 10));
  311. if ($nb > 0) {
  312. Minz_Log::debug($nb . ' old entries cleaned in feed [' .
  313. $feed->url() . ']');
  314. }
  315. }
  316. $feedDAO->updateLastUpdate($feed->id(), 0, $feedDAO->hasTransaction());
  317. if ($feedDAO->hasTransaction()) {
  318. $feedDAO->commit();
  319. }
  320. if ($feed->url() !== $url) {
  321. // HTTP 301 Moved Permanently
  322. Minz_Log::notice('Feed ' . $url . ' moved permanently to ' . $feed->url());
  323. $feedDAO->updateFeed($feed->id(), array('url' => $feed->url()));
  324. }
  325. $feed->faviconPrepare();
  326. $feed->unlock();
  327. $updated_feeds++;
  328. unset($feed);
  329. // No more than 10 feeds unless $force is true to avoid overloading
  330. // the server.
  331. if ($updated_feeds >= 10 && !$force) {
  332. break;
  333. }
  334. }
  335. if (Minz_Request::param('ajax')) {
  336. // Most of the time, ajax request is for only one feed. But since
  337. // there are several parallel requests, we should return that there
  338. // are several updated feeds.
  339. $notif = array(
  340. 'type' => 'good',
  341. 'content' => _t('feedback.sub.feed.actualizeds')
  342. );
  343. Minz_Session::_param('notification', $notif);
  344. // No layout in ajax request.
  345. $this->view->_useLayout(false);
  346. return;
  347. }
  348. // Redirect to the main page with correct notification.
  349. if ($updated_feeds === 1) {
  350. $feed = reset($feeds);
  351. Minz_Request::good(_t('feedback.sub.feed.actualized', $feed->name()), array(
  352. 'params' => array('get' => 'f_' . $feed->id())
  353. ));
  354. } elseif ($updated_feeds > 1) {
  355. Minz_Request::good(_t('feedback.sub.feed.n_actualized', $updated_feeds), array());
  356. } else {
  357. Minz_Request::good(_t('feedback.sub.feed.no_refresh'), array());
  358. }
  359. }
  360. /**
  361. * This action changes the category of a feed.
  362. *
  363. * This page must be reached by a POST request.
  364. *
  365. * Parameters are:
  366. * - f_id (default: false)
  367. * - c_id (default: false)
  368. * If c_id is false, default category is used.
  369. *
  370. * @todo should handle order of the feed inside the category.
  371. */
  372. public function moveAction() {
  373. if (!Minz_Request::isPost()) {
  374. Minz_Request::forward(array('c' => 'subscription'), true);
  375. }
  376. $feed_id = Minz_Request::param('f_id');
  377. $cat_id = Minz_Request::param('c_id');
  378. if ($cat_id === false) {
  379. // If category was not given get the default one.
  380. $catDAO = new FreshRSS_CategoryDAO();
  381. $catDAO->checkDefault();
  382. $def_cat = $catDAO->getDefault();
  383. $cat_id = $def_cat->id();
  384. }
  385. $feedDAO = FreshRSS_Factory::createFeedDao();
  386. $values = array('category' => $cat_id);
  387. $feed = $feedDAO->searchById($feed_id);
  388. if ($feed && ($feed->category() == $cat_id ||
  389. $feedDAO->updateFeed($feed_id, $values))) {
  390. // TODO: return something useful
  391. } else {
  392. Minz_Log::warning('Cannot move feed `' . $feed_id . '` ' .
  393. 'in the category `' . $cat_id . '`');
  394. Minz_Error::error(404);
  395. }
  396. }
  397. /**
  398. * This action deletes a feed.
  399. *
  400. * This page must be reached by a POST request.
  401. * If there are related queries, they are deleted too.
  402. *
  403. * Parameters are:
  404. * - id (default: false)
  405. * - r (default: false)
  406. * r permits to redirect to a given page at the end of this action.
  407. *
  408. * @todo handle "r" redirection in Minz_Request::forward()?
  409. */
  410. public function deleteAction() {
  411. $redirect_url = Minz_Request::param('r', false, true);
  412. if (!$redirect_url) {
  413. $redirect_url = array('c' => 'subscription', 'a' => 'index');
  414. }
  415. if (!Minz_Request::isPost()) {
  416. Minz_Request::forward($redirect_url, true);
  417. }
  418. $id = Minz_Request::param('id');
  419. $feedDAO = FreshRSS_Factory::createFeedDao();
  420. if ($feedDAO->deleteFeed($id)) {
  421. // TODO: Delete old favicon
  422. // Remove related queries
  423. FreshRSS_Context::$conf->remove_query_by_get('f_' . $id);
  424. FreshRSS_Context::$conf->save();
  425. Minz_Request::good(_t('feedback.sub.feed.deleted'), $redirect_url);
  426. } else {
  427. Minz_Request::bad(_t('feedback.sub.feed.error'), $redirect_url);
  428. }
  429. }
  430. }