4
0

feedController.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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. }
  27. /**
  28. * This action subscribes to a feed.
  29. *
  30. * It can be reached by both GET and POST requests.
  31. *
  32. * GET request displays a form to add and configure a feed.
  33. * Request parameter is:
  34. * - url_rss (default: false)
  35. *
  36. * POST request adds a feed in database.
  37. * Parameters are:
  38. * - url_rss (default: false)
  39. * - category (default: false)
  40. * - new_category (required if category == 'nc')
  41. * - http_user (default: false)
  42. * - http_pass (default: false)
  43. * It tries to get website information from RSS feed.
  44. * If no category is given, feed is added to the default one.
  45. *
  46. * If url_rss is false, nothing happened.
  47. */
  48. public function addAction() {
  49. $url = Minz_Request::param('url_rss');
  50. if ($url === false) {
  51. // No url, do nothing
  52. Minz_Request::forward(array(
  53. 'c' => 'subscription',
  54. 'a' => 'index'
  55. ), true);
  56. }
  57. $feedDAO = FreshRSS_Factory::createFeedDao();
  58. $this->catDAO = new FreshRSS_CategoryDAO();
  59. $url_redirect = array(
  60. 'c' => 'subscription',
  61. 'a' => 'index',
  62. 'params' => array(),
  63. );
  64. $limits = FreshRSS_Context::$system_conf->limits;
  65. $this->view->feeds = $feedDAO->listFeeds();
  66. if (count($this->view->feeds) >= $limits['max_feeds']) {
  67. Minz_Request::bad(_t('feedback.sub.feed.over_max', $limits['max_feeds']),
  68. $url_redirect);
  69. }
  70. if (Minz_Request::isPost()) {
  71. @set_time_limit(300);
  72. $cat = Minz_Request::param('category');
  73. if ($cat === 'nc') {
  74. // User want to create a new category, new_category parameter
  75. // must exist
  76. $new_cat = Minz_Request::param('new_category');
  77. if (empty($new_cat['name'])) {
  78. $cat = false;
  79. } else {
  80. $cat = $this->catDAO->addCategory($new_cat);
  81. }
  82. }
  83. if ($cat === false) {
  84. // If category was not given or if creating new category failed,
  85. // get the default category
  86. $this->catDAO->checkDefault();
  87. $def_cat = $this->catDAO->getDefault();
  88. $cat = $def_cat->id();
  89. }
  90. // HTTP information are useful if feed is protected behind a
  91. // HTTP authentication
  92. $user = trim(Minz_Request::param('http_user', ''));
  93. $pass = Minz_Request::param('http_pass', '');
  94. $http_auth = '';
  95. if ($user != '' && $pass != '') { //TODO: Sanitize
  96. $http_auth = $user . ':' . $pass;
  97. }
  98. $transaction_started = false;
  99. try {
  100. $feed = new FreshRSS_Feed($url);
  101. } catch (FreshRSS_BadUrl_Exception $e) {
  102. // Given url was not a valid url!
  103. Minz_Log::warning($e->getMessage());
  104. Minz_Request::bad(_t('feedback.sub.feed.invalid_url', $url), $url_redirect);
  105. }
  106. try {
  107. $feed->load(true);
  108. } catch (FreshRSS_Feed_Exception $e) {
  109. // Something went bad (timeout, server not found, etc.)
  110. Minz_Log::warning($e->getMessage());
  111. Minz_Request::bad(
  112. _t('feedback.sub.feed.internal_problem', _url('index', 'logs')),
  113. $url_redirect
  114. );
  115. } catch (Minz_FileNotExistException $e) {
  116. // Cache directory doesn't exist!
  117. Minz_Log::error($e->getMessage());
  118. Minz_Request::bad(
  119. _t('feedback.sub.feed.internal_problem', _url('index', 'logs')),
  120. $url_redirect
  121. );
  122. }
  123. if ($feedDAO->searchByUrl($feed->url())) {
  124. Minz_Request::bad(
  125. _t('feedback.sub.feed.already_subscribed', $feed->name()),
  126. $url_redirect
  127. );
  128. }
  129. $feed->_category($cat);
  130. $feed->_httpAuth($http_auth);
  131. // Call the extension hook
  132. $name = $feed->name();
  133. $feed = Minz_ExtensionManager::callHook('feed_before_insert', $feed);
  134. if ($feed === null) {
  135. Minz_Request::bad(_t('feedback.sub.feed.not_added', $name), $url_redirect);
  136. }
  137. $values = array(
  138. 'url' => $feed->url(),
  139. 'category' => $feed->category(),
  140. 'name' => $feed->name(),
  141. 'website' => $feed->website(),
  142. 'description' => $feed->description(),
  143. 'lastUpdate' => time(),
  144. 'httpAuth' => $feed->httpAuth(),
  145. );
  146. $id = $feedDAO->addFeed($values);
  147. if (!$id) {
  148. // There was an error in database... we cannot say what here.
  149. Minz_Request::bad(_t('feedback.sub.feed.not_added', $feed->name()), $url_redirect);
  150. }
  151. // Ok, feed has been added in database. Now we have to refresh entries.
  152. $feed->_id($id);
  153. $feed->faviconPrepare();
  154. //$feed->pubSubHubbubPrepare(); //TODO: prepare PubSubHubbub already when adding the feed
  155. $is_read = FreshRSS_Context::$user_conf->mark_when['reception'] ? 1 : 0;
  156. $entryDAO = FreshRSS_Factory::createEntryDao();
  157. // We want chronological order and SimplePie uses reverse order.
  158. $entries = array_reverse($feed->entries());
  159. // Calculate date of oldest entries we accept in DB.
  160. $nb_month_old = FreshRSS_Context::$user_conf->old_entries;
  161. $date_min = time() - (3600 * 24 * 30 * $nb_month_old);
  162. // Use a shared statement and a transaction to improve a LOT the
  163. // performances.
  164. $feedDAO->beginTransaction();
  165. foreach ($entries as $entry) {
  166. // Entries are added without any verification.
  167. $entry->_feed($feed->id());
  168. $entry->_id(min(time(), $entry->date(true)) . uSecString());
  169. $entry->_isRead($is_read);
  170. $entry = Minz_ExtensionManager::callHook('entry_before_insert', $entry);
  171. if ($entry === null) {
  172. // An extension has returned a null value, there is nothing to insert.
  173. continue;
  174. }
  175. $values = $entry->toArray();
  176. $entryDAO->addEntry($values);
  177. }
  178. $feedDAO->updateLastUpdate($feed->id());
  179. $feedDAO->commit();
  180. // Entries are in DB, we redirect to feed configuration page.
  181. $url_redirect['params']['id'] = $feed->id();
  182. Minz_Request::good(_t('feedback.sub.feed.added', $feed->name()), $url_redirect);
  183. } else {
  184. // GET request: we must ask confirmation to user before adding feed.
  185. Minz_View::prependTitle(_t('sub.feed.title_add') . ' · ');
  186. $this->view->categories = $this->catDAO->listCategories(false);
  187. $this->view->feed = new FreshRSS_Feed($url);
  188. try {
  189. // We try to get more information about the feed.
  190. $this->view->feed->load(true);
  191. $this->view->load_ok = true;
  192. } catch (Exception $e) {
  193. $this->view->load_ok = false;
  194. }
  195. $feed = $feedDAO->searchByUrl($this->view->feed->url());
  196. if ($feed) {
  197. // Already subscribe so we redirect to the feed configuration page.
  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. /**
  231. * This action actualizes entries from one or several feeds.
  232. *
  233. * Parameters are:
  234. * - id (default: false): Feed ID
  235. * - url (default: false): Feed URL
  236. * - force (default: false)
  237. * If id and url are not specified, all the feeds are actualized. But if force is
  238. * false, process stops at 10 feeds to avoid time execution problem.
  239. */
  240. public function actualizeAction($simplePiePush = null) {
  241. @set_time_limit(300);
  242. $feedDAO = FreshRSS_Factory::createFeedDao();
  243. $entryDAO = FreshRSS_Factory::createEntryDao();
  244. Minz_Session::_param('actualize_feeds', false);
  245. $id = Minz_Request::param('id');
  246. $url = Minz_Request::param('url');
  247. $force = Minz_Request::param('force');
  248. // Create a list of feeds to actualize.
  249. // If id is set and valid, corresponding feed is added to the list but
  250. // alone in order to automatize further process.
  251. $feeds = array();
  252. if ($id || $url) {
  253. $feed = $id ? $feedDAO->searchById($id) : $feedDAO->searchByUrl($url);
  254. if ($feed) {
  255. $feeds[] = $feed;
  256. }
  257. } else {
  258. $feeds = $feedDAO->listFeedsOrderUpdate(FreshRSS_Context::$user_conf->ttl_default);
  259. }
  260. // Calculate date of oldest entries we accept in DB.
  261. $nb_month_old = max(FreshRSS_Context::$user_conf->old_entries, 1);
  262. $date_min = time() - (3600 * 24 * 30 * $nb_month_old);
  263. $pshbMinAge = time() - (3600 * 24); //TODO: Make a configuration.
  264. $updated_feeds = 0;
  265. $is_read = FreshRSS_Context::$user_conf->mark_when['reception'] ? 1 : 0;
  266. foreach ($feeds as $feed) {
  267. $url = $feed->url(); //For detection of HTTP 301
  268. $pubSubHubbubEnabled = $feed->pubSubHubbubEnabled();
  269. if ((!$simplePiePush) && (!$id) && $pubSubHubbubEnabled && ($feed->lastUpdate() > $pshbMinAge)) {
  270. $text = 'Skip pull of feed using PubSubHubbub: ' . $url;
  271. //Minz_Log::debug($text);
  272. file_put_contents(USERS_PATH . '/_/log_pshb.txt', date('c') . "\t" . $text . "\n", FILE_APPEND);
  273. continue; //When PubSubHubbub is used, do not pull refresh so often
  274. }
  275. if (!$feed->lock()) {
  276. Minz_Log::notice('Feed already being actualized: ' . $feed->url());
  277. continue;
  278. }
  279. try {
  280. if ($simplePiePush) {
  281. $feed->loadEntries($simplePiePush); //Used by PubSubHubbub
  282. } else {
  283. $feed->load(false);
  284. }
  285. } catch (FreshRSS_Feed_Exception $e) {
  286. Minz_Log::notice($e->getMessage());
  287. $feedDAO->updateLastUpdate($feed->id(), true);
  288. $feed->unlock();
  289. continue;
  290. }
  291. $feed_history = $feed->keepHistory();
  292. if ($feed_history == -2) {
  293. // TODO: -2 must be a constant!
  294. // -2 means we take the default value from configuration
  295. $feed_history = FreshRSS_Context::$user_conf->keep_history_default;
  296. }
  297. // We want chronological order and SimplePie uses reverse order.
  298. $entries = array_reverse($feed->entries());
  299. if (count($entries) > 0) {
  300. $newGuids = array();
  301. foreach ($entries as $entry) {
  302. $newGuids[] = $entry->guid();
  303. }
  304. // For this feed, check existing GUIDs already in database.
  305. $existingHashForGuids = $entryDAO->listHashForFeedGuids($feed->id(), $newGuids);
  306. unset($newGuids);
  307. $oldGuids = array();
  308. // Add entries in database if possible.
  309. foreach ($entries as $entry) {
  310. $entry_date = $entry->date(true);
  311. if (isset($existingHashForGuids[$entry->guid()])) {
  312. $existingHash = $existingHashForGuids[$entry->guid()];
  313. if (strcasecmp($existingHash, $entry->hash()) === 0 || $existingHash === '00000000000000000000000000000000') {
  314. //This entry already exists and is unchanged. TODO: Remove the test with the zero'ed hash in FreshRSS v1.3
  315. $oldGuids[] = $entry->guid();
  316. } else { //This entry already exists but has been updated
  317. Minz_Log::debug('Entry with GUID `' . $entry->guid() . '` updated in feed ' . $feed->id() .
  318. ', old hash ' . $existingHash . ', new hash ' . $entry->hash());
  319. //TODO: Make an updated/is_read policy by feed, in addition to the global one.
  320. $entry->_isRead(FreshRSS_Context::$user_conf->mark_updated_article_unread ? false : null); //Change is_read according to policy.
  321. if (!$entryDAO->hasTransaction()) {
  322. $entryDAO->beginTransaction();
  323. }
  324. $entryDAO->updateEntry($entry->toArray());
  325. }
  326. } elseif ($feed_history == 0 && $entry_date < $date_min) {
  327. // This entry should not be added considering configuration and date.
  328. $oldGuids[] = $entry->guid();
  329. } else {
  330. if ($entry_date < $date_min) {
  331. $id = min(time(), $entry_date) . uSecString();
  332. $entry->_isRead(true); //Old article that was not in database. Probably an error, so mark as read
  333. } else {
  334. $id = uTimeString();
  335. $entry->_isRead($is_read);
  336. }
  337. $entry->_id($id);
  338. $entry = Minz_ExtensionManager::callHook('entry_before_insert', $entry);
  339. if ($entry === null) {
  340. // An extension has returned a null value, there is nothing to insert.
  341. continue;
  342. }
  343. if ($pubSubHubbubEnabled && !$simplePiePush) { //We use push, but have discovered an article by pull!
  344. $text = 'An article was discovered by pull although we use PubSubHubbub!: Feed ' . $url . ' GUID ' . $entry->guid();
  345. file_put_contents(USERS_PATH . '/_/log_pshb.txt', date('c') . "\t" . $text . "\n", FILE_APPEND);
  346. Minz_Log::warning($text);
  347. $pubSubHubbubEnabled = false;
  348. $feed->pubSubHubbubError(true);
  349. }
  350. if (!$entryDAO->hasTransaction()) {
  351. $entryDAO->beginTransaction();
  352. }
  353. $entryDAO->addEntry($entry->toArray());
  354. }
  355. }
  356. $entryDAO->updateLastSeen($feed->id(), $oldGuids);
  357. }
  358. if ($feed_history >= 0 && rand(0, 30) === 1) {
  359. // TODO: move this function in web cron when available (see entry::purge)
  360. // Remove old entries once in 30.
  361. if (!$entryDAO->hasTransaction()) {
  362. $entryDAO->beginTransaction();
  363. }
  364. $nb = $feedDAO->cleanOldEntries($feed->id(),
  365. $date_min,
  366. max($feed_history, count($entries) + 10));
  367. if ($nb > 0) {
  368. Minz_Log::debug($nb . ' old entries cleaned in feed [' .
  369. $feed->url() . ']');
  370. }
  371. }
  372. $feedDAO->updateLastUpdate($feed->id(), 0, $entryDAO->hasTransaction());
  373. if ($entryDAO->hasTransaction()) {
  374. $entryDAO->commit();
  375. }
  376. if ($feed->hubUrl() && $feed->selfUrl()) { //selfUrl has priority for PubSubHubbub
  377. if ($feed->selfUrl() !== $url) { //https://code.google.com/p/pubsubhubbub/wiki/MovingFeedsOrChangingHubs
  378. $selfUrl = checkUrl($feed->selfUrl());
  379. if ($selfUrl) {
  380. Minz_Log::debug('PubSubHubbub unsubscribe ' . $feed->url());
  381. if (!$feed->pubSubHubbubSubscribe(false)) { //Unsubscribe
  382. Minz_Log::warning('Error while PubSubHubbub unsubscribing from ' . $feed->url());
  383. }
  384. $feed->_url($selfUrl, false);
  385. Minz_Log::notice('Feed ' . $url . ' canonical address moved to ' . $feed->url());
  386. $feedDAO->updateFeed($feed->id(), array('url' => $feed->url()));
  387. }
  388. }
  389. }
  390. elseif ($feed->url() !== $url) { // HTTP 301 Moved Permanently
  391. Minz_Log::notice('Feed ' . $url . ' moved permanently to ' . $feed->url());
  392. $feedDAO->updateFeed($feed->id(), array('url' => $feed->url()));
  393. }
  394. $feed->faviconPrepare();
  395. if ($feed->pubSubHubbubPrepare()) {
  396. Minz_Log::notice('PubSubHubbub subscribe ' . $feed->url());
  397. if (!$feed->pubSubHubbubSubscribe(true)) { //Subscribe
  398. Minz_Log::warning('Error while PubSubHubbub subscribing to ' . $feed->url());
  399. }
  400. }
  401. $feed->unlock();
  402. $updated_feeds++;
  403. unset($feed);
  404. // No more than 10 feeds unless $force is true to avoid overloading
  405. // the server.
  406. if ($updated_feeds >= 10 && !$force) {
  407. break;
  408. }
  409. }
  410. if (Minz_Request::param('ajax')) {
  411. // Most of the time, ajax request is for only one feed. But since
  412. // there are several parallel requests, we should return that there
  413. // are several updated feeds.
  414. $notif = array(
  415. 'type' => 'good',
  416. 'content' => _t('feedback.sub.feed.actualizeds')
  417. );
  418. Minz_Session::_param('notification', $notif);
  419. // No layout in ajax request.
  420. $this->view->_useLayout(false);
  421. } else {
  422. // Redirect to the main page with correct notification.
  423. if ($updated_feeds === 1) {
  424. $feed = reset($feeds);
  425. Minz_Request::good(_t('feedback.sub.feed.actualized', $feed->name()), array(
  426. 'params' => array('get' => 'f_' . $feed->id())
  427. ));
  428. } elseif ($updated_feeds > 1) {
  429. Minz_Request::good(_t('feedback.sub.feed.n_actualized', $updated_feeds), array());
  430. } else {
  431. Minz_Request::good(_t('feedback.sub.feed.no_refresh'), array());
  432. }
  433. }
  434. return $updated_feeds;
  435. }
  436. /**
  437. * This action changes the category of a feed.
  438. *
  439. * This page must be reached by a POST request.
  440. *
  441. * Parameters are:
  442. * - f_id (default: false)
  443. * - c_id (default: false)
  444. * If c_id is false, default category is used.
  445. *
  446. * @todo should handle order of the feed inside the category.
  447. */
  448. public function moveAction() {
  449. if (!Minz_Request::isPost()) {
  450. Minz_Request::forward(array('c' => 'subscription'), true);
  451. }
  452. $feed_id = Minz_Request::param('f_id');
  453. $cat_id = Minz_Request::param('c_id');
  454. if ($cat_id === false) {
  455. // If category was not given get the default one.
  456. $catDAO = new FreshRSS_CategoryDAO();
  457. $catDAO->checkDefault();
  458. $def_cat = $catDAO->getDefault();
  459. $cat_id = $def_cat->id();
  460. }
  461. $feedDAO = FreshRSS_Factory::createFeedDao();
  462. $values = array('category' => $cat_id);
  463. $feed = $feedDAO->searchById($feed_id);
  464. if ($feed && ($feed->category() == $cat_id ||
  465. $feedDAO->updateFeed($feed_id, $values))) {
  466. // TODO: return something useful
  467. } else {
  468. Minz_Log::warning('Cannot move feed `' . $feed_id . '` ' .
  469. 'in the category `' . $cat_id . '`');
  470. Minz_Error::error(404);
  471. }
  472. }
  473. /**
  474. * This action deletes a feed.
  475. *
  476. * This page must be reached by a POST request.
  477. * If there are related queries, they are deleted too.
  478. *
  479. * Parameters are:
  480. * - id (default: false)
  481. * - r (default: false)
  482. * r permits to redirect to a given page at the end of this action.
  483. *
  484. * @todo handle "r" redirection in Minz_Request::forward()?
  485. */
  486. public function deleteAction() {
  487. $redirect_url = Minz_Request::param('r', false, true);
  488. if (!$redirect_url) {
  489. $redirect_url = array('c' => 'subscription', 'a' => 'index');
  490. }
  491. if (!Minz_Request::isPost()) {
  492. Minz_Request::forward($redirect_url, true);
  493. }
  494. $id = Minz_Request::param('id');
  495. $feedDAO = FreshRSS_Factory::createFeedDao();
  496. if ($feedDAO->deleteFeed($id)) {
  497. // TODO: Delete old favicon
  498. // Remove related queries
  499. FreshRSS_Context::$user_conf->queries = remove_query_by_get(
  500. 'f_' . $id, FreshRSS_Context::$user_conf->queries);
  501. FreshRSS_Context::$user_conf->save();
  502. Minz_Request::good(_t('feedback.sub.feed.deleted'), $redirect_url);
  503. } else {
  504. Minz_Request::bad(_t('feedback.sub.feed.error'), $redirect_url);
  505. }
  506. }
  507. }