feedController.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  1. <?php
  2. /**
  3. * Controller to handle every feed actions.
  4. */
  5. class FreshRSS_feed_Controller extends FreshRSS_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. * @param string $url
  29. * @param string $title
  30. * @param int $cat_id
  31. * @param string $new_cat_name
  32. * @param string $http_auth
  33. * @return FreshRSS_Feed
  34. * @throws FreshRSS_AlreadySubscribed_Exception
  35. * @throws FreshRSS_FeedNotAdded_Exception
  36. * @throws FreshRSS_Feed_Exception
  37. * @throws Minz_FileNotExistException
  38. */
  39. public static function addFeed($url, $title = '', $cat_id = 0, $new_cat_name = '', $http_auth = '', $attributes = array(), $kind = FreshRSS_Feed::KIND_RSS) {
  40. FreshRSS_UserDAO::touch();
  41. @set_time_limit(300);
  42. $catDAO = FreshRSS_Factory::createCategoryDao();
  43. $url = trim($url);
  44. /** @var string|null $url */
  45. $url = Minz_ExtensionManager::callHook('check_url_before_add', $url);
  46. if (null === $url) {
  47. throw new FreshRSS_FeedNotAdded_Exception($url);
  48. }
  49. $cat = null;
  50. if ($cat_id > 0) {
  51. $cat = $catDAO->searchById($cat_id);
  52. }
  53. if ($cat == null && $new_cat_name != '') {
  54. $new_cat_id = $catDAO->addCategory(array('name' => $new_cat_name));
  55. $cat_id = $new_cat_id > 0 ? $new_cat_id : $cat_id;
  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. $title = trim($title);
  64. if ($title != '') {
  65. $feed->_name($title);
  66. }
  67. $feed->_kind($kind);
  68. $feed->_attributes('', $attributes);
  69. $feed->_httpAuth($http_auth);
  70. $feed->_categoryId($cat_id);
  71. switch ($kind) {
  72. case FreshRSS_Feed::KIND_RSS:
  73. case FreshRSS_Feed::KIND_RSS_FORCED:
  74. $feed->load(true); //Throws FreshRSS_Feed_Exception, Minz_FileNotExistException
  75. break;
  76. case FreshRSS_Feed::KIND_HTML_XPATH:
  77. $feed->_website($url);
  78. break;
  79. }
  80. $feedDAO = FreshRSS_Factory::createFeedDao();
  81. if ($feedDAO->searchByUrl($feed->url())) {
  82. throw new FreshRSS_AlreadySubscribed_Exception($url, $feed->name());
  83. }
  84. /** @var FreshRSS_Feed|null $feed */
  85. $feed = Minz_ExtensionManager::callHook('feed_before_insert', $feed);
  86. if ($feed === null) {
  87. throw new FreshRSS_FeedNotAdded_Exception($url);
  88. }
  89. $id = $feedDAO->addFeedObject($feed);
  90. if (!$id) {
  91. // There was an error in database… we cannot say what here.
  92. throw new FreshRSS_FeedNotAdded_Exception($url);
  93. }
  94. $feed->_id($id);
  95. // Ok, feed has been added in database. Now we have to refresh entries.
  96. self::actualizeFeed($id, $url, false, null);
  97. return $feed;
  98. }
  99. /**
  100. * This action subscribes to a feed.
  101. *
  102. * It can be reached by both GET and POST requests.
  103. *
  104. * GET request displays a form to add and configure a feed.
  105. * Request parameter is:
  106. * - url_rss (default: false)
  107. *
  108. * POST request adds a feed in database.
  109. * Parameters are:
  110. * - url_rss (default: false)
  111. * - category (default: false)
  112. * - http_user (default: false)
  113. * - http_pass (default: false)
  114. * It tries to get website information from RSS feed.
  115. * If no category is given, feed is added to the default one.
  116. *
  117. * If url_rss is false, nothing happened.
  118. */
  119. public function addAction() {
  120. $url = Minz_Request::param('url_rss');
  121. if ($url === false) {
  122. // No url, do nothing
  123. Minz_Request::forward(array(
  124. 'c' => 'subscription',
  125. 'a' => 'index'
  126. ), true);
  127. }
  128. $feedDAO = FreshRSS_Factory::createFeedDao();
  129. $url_redirect = array(
  130. 'c' => 'subscription',
  131. 'a' => 'add',
  132. 'params' => array(),
  133. );
  134. $limits = FreshRSS_Context::$system_conf->limits;
  135. $this->view->feeds = $feedDAO->listFeeds();
  136. if (count($this->view->feeds) >= $limits['max_feeds']) {
  137. Minz_Request::bad(_t('feedback.sub.feed.over_max', $limits['max_feeds']), $url_redirect);
  138. }
  139. if (Minz_Request::isPost()) {
  140. $cat = Minz_Request::param('category');
  141. // HTTP information are useful if feed is protected behind a
  142. // HTTP authentication
  143. $user = trim(Minz_Request::param('http_user', ''));
  144. $pass = trim(Minz_Request::param('http_pass', ''));
  145. $http_auth = '';
  146. if ($user != '' && $pass != '') { //TODO: Sanitize
  147. $http_auth = $user . ':' . $pass;
  148. }
  149. $useragent = Minz_Request::param('curl_params_useragent', '');
  150. $proxy_address = Minz_Request::param('curl_params', '');
  151. $proxy_type = Minz_Request::param('proxy_type', '');
  152. $opts = [];
  153. if ($proxy_address !== '' && $proxy_type !== '' && in_array($proxy_type, [0, 2, 4, 5, 6, 7])) {
  154. $opts[CURLOPT_PROXY] = $proxy_address;
  155. $opts[CURLOPT_PROXYTYPE] = intval($proxy_type);
  156. }
  157. if ($useragent !== '') {
  158. $opts[CURLOPT_USERAGENT] = $useragent;
  159. }
  160. $attributes = array(
  161. 'ssl_verify' => null,
  162. 'timeout' => null,
  163. 'curl_params' => empty($opts) ? null : $opts,
  164. );
  165. $attributes['ssl_verify'] = Minz_Request::paramTernary('ssl_verify');
  166. $timeout = intval(Minz_Request::param('timeout', 0));
  167. $attributes['timeout'] = $timeout > 0 ? $timeout : null;
  168. $feed_kind = Minz_Request::param('feed_kind', FreshRSS_Feed::KIND_RSS);
  169. if ($feed_kind == FreshRSS_Feed::KIND_HTML_XPATH) {
  170. $xPathSettings = [];
  171. if (Minz_Request::param('xPathFeedTitle', '') != '') $xPathSettings['feedTitle'] = Minz_Request::param('xPathFeedTitle', '', true);
  172. if (Minz_Request::param('xPathItem', '') != '') $xPathSettings['item'] = Minz_Request::param('xPathItem', '', true);
  173. if (Minz_Request::param('xPathItemTitle', '') != '') $xPathSettings['itemTitle'] = Minz_Request::param('xPathItemTitle', '', true);
  174. if (Minz_Request::param('xPathItemContent', '') != '') $xPathSettings['itemContent'] = Minz_Request::param('xPathItemContent', '', true);
  175. if (Minz_Request::param('xPathItemUri', '') != '') $xPathSettings['itemUri'] = Minz_Request::param('xPathItemUri', '', true);
  176. if (Minz_Request::param('xPathItemAuthor', '') != '') $xPathSettings['itemAuthor'] = Minz_Request::param('xPathItemAuthor', '', true);
  177. if (Minz_Request::param('xPathItemTimestamp', '') != '') $xPathSettings['itemTimestamp'] = Minz_Request::param('xPathItemTimestamp', '', true);
  178. if (Minz_Request::param('xPathItemThumbnail', '') != '') $xPathSettings['itemThumbnail'] = Minz_Request::param('xPathItemThumbnail', '', true);
  179. if (Minz_Request::param('xPathItemCategories', '') != '') $xPathSettings['itemCategories'] = Minz_Request::param('xPathItemCategories', '', true);
  180. if (Minz_Request::param('xPathItemUid', '') != '') $xPathSettings['itemUid'] = Minz_Request::param('xPathItemUid', '', true);
  181. if (!empty($xPathSettings)) {
  182. $attributes['xpath'] = $xPathSettings;
  183. }
  184. }
  185. try {
  186. $feed = self::addFeed($url, '', $cat, '', $http_auth, $attributes, $feed_kind);
  187. } catch (FreshRSS_BadUrl_Exception $e) {
  188. // Given url was not a valid url!
  189. Minz_Log::warning($e->getMessage());
  190. return Minz_Request::bad(_t('feedback.sub.feed.invalid_url', $url), $url_redirect);
  191. } catch (FreshRSS_Feed_Exception $e) {
  192. // Something went bad (timeout, server not found, etc.)
  193. Minz_Log::warning($e->getMessage());
  194. return Minz_Request::bad(_t('feedback.sub.feed.internal_problem', _url('index', 'logs')), $url_redirect);
  195. } catch (Minz_FileNotExistException $e) {
  196. // Cache directory doesn’t exist!
  197. Minz_Log::error($e->getMessage());
  198. return Minz_Request::bad(_t('feedback.sub.feed.internal_problem', _url('index', 'logs')), $url_redirect);
  199. } catch (FreshRSS_AlreadySubscribed_Exception $e) {
  200. return Minz_Request::bad(_t('feedback.sub.feed.already_subscribed', $e->feedName()), $url_redirect);
  201. } catch (FreshRSS_FeedNotAdded_Exception $e) {
  202. return Minz_Request::bad(_t('feedback.sub.feed.not_added', $e->url()), $url_redirect);
  203. }
  204. // Entries are in DB, we redirect to feed configuration page.
  205. $url_redirect['a'] = 'index';
  206. $url_redirect['params']['id'] = '' . $feed->id();
  207. Minz_Request::good(_t('feedback.sub.feed.added', $feed->name()), $url_redirect);
  208. } else {
  209. // GET request: we must ask confirmation to user before adding feed.
  210. FreshRSS_View::prependTitle(_t('sub.feed.title_add') . ' · ');
  211. $catDAO = FreshRSS_Factory::createCategoryDao();
  212. $this->view->categories = $catDAO->listCategories(false);
  213. $this->view->feed = new FreshRSS_Feed($url);
  214. try {
  215. // We try to get more information about the feed.
  216. $this->view->feed->load(true);
  217. $this->view->load_ok = true;
  218. } catch (Exception $e) {
  219. $this->view->load_ok = false;
  220. }
  221. $feed = $feedDAO->searchByUrl($this->view->feed->url());
  222. if ($feed) {
  223. // Already subscribe so we redirect to the feed configuration page.
  224. $url_redirect['a'] = 'index';
  225. $url_redirect['params']['id'] = $feed->id();
  226. Minz_Request::good(_t('feedback.sub.feed.already_subscribed', $feed->name()), $url_redirect);
  227. }
  228. }
  229. }
  230. /**
  231. * This action remove entries from a given feed.
  232. *
  233. * It should be reached by a POST action.
  234. *
  235. * Parameter is:
  236. * - id (default: false)
  237. */
  238. public function truncateAction() {
  239. $id = Minz_Request::param('id');
  240. $url_redirect = array(
  241. 'c' => 'subscription',
  242. 'a' => 'index',
  243. 'params' => array('id' => $id)
  244. );
  245. if (!Minz_Request::isPost()) {
  246. Minz_Request::forward($url_redirect, true);
  247. }
  248. $feedDAO = FreshRSS_Factory::createFeedDao();
  249. $n = $feedDAO->truncate($id);
  250. invalidateHttpCache();
  251. if ($n === false) {
  252. Minz_Request::bad(_t('feedback.sub.feed.error'), $url_redirect);
  253. } else {
  254. Minz_Request::good(_t('feedback.sub.feed.n_entries_deleted', $n), $url_redirect);
  255. }
  256. }
  257. /**
  258. * @param int $feed_id
  259. * @param string $feed_url
  260. * @param bool $force
  261. * @param SimplePie|null $simplePiePush
  262. * @param bool $noCommit
  263. * @param int $maxFeeds
  264. */
  265. public static function actualizeFeed($feed_id, $feed_url, $force, $simplePiePush = null, $noCommit = false, $maxFeeds = 10) {
  266. @set_time_limit(300);
  267. $feedDAO = FreshRSS_Factory::createFeedDao();
  268. $entryDAO = FreshRSS_Factory::createEntryDao();
  269. // Create a list of feeds to actualize.
  270. // If feed_id is set and valid, corresponding feed is added to the list but
  271. // alone in order to automatize further process.
  272. $feeds = array();
  273. if ($feed_id > 0 || $feed_url) {
  274. $feed = $feed_id > 0 ? $feedDAO->searchById($feed_id) : $feedDAO->searchByUrl($feed_url);
  275. if ($feed) {
  276. $feeds[] = $feed;
  277. }
  278. } else {
  279. $feeds = $feedDAO->listFeedsOrderUpdate(-1);
  280. }
  281. // Set maxFeeds to a minimum of 10
  282. if (!is_int($maxFeeds) || $maxFeeds < 10) {
  283. $maxFeeds = 10;
  284. }
  285. // WebSub (PubSubHubbub) support
  286. $pubsubhubbubEnabledGeneral = FreshRSS_Context::$system_conf->pubsubhubbub_enabled;
  287. $pshbMinAge = time() - (3600 * 24); //TODO: Make a configuration.
  288. $updated_feeds = 0;
  289. $nb_new_articles = 0;
  290. foreach ($feeds as $feed) {
  291. /** @var FreshRSS_Feed|null $feed */
  292. $feed = Minz_ExtensionManager::callHook('feed_before_actualize', $feed);
  293. if (null === $feed) {
  294. continue;
  295. }
  296. $url = $feed->url(); //For detection of HTTP 301
  297. $pubSubHubbubEnabled = $pubsubhubbubEnabledGeneral && $feed->pubSubHubbubEnabled();
  298. if ((!$simplePiePush) && (!$feed_id) && $pubSubHubbubEnabled && ($feed->lastUpdate() > $pshbMinAge)) {
  299. //$text = 'Skip pull of feed using PubSubHubbub: ' . $url;
  300. //Minz_Log::debug($text);
  301. //Minz_Log::debug($text, PSHB_LOG);
  302. continue; //When PubSubHubbub is used, do not pull refresh so often
  303. }
  304. $mtime = 0;
  305. if ($feed->mute()) {
  306. continue; //Feed refresh is disabled
  307. }
  308. $ttl = $feed->ttl();
  309. if ((!$simplePiePush) && (!$feed_id) &&
  310. ($feed->lastUpdate() + 10 >= time() - (
  311. $ttl == FreshRSS_Feed::TTL_DEFAULT ? FreshRSS_Context::$user_conf->ttl_default : $ttl))) {
  312. //Too early to refresh from source, but check whether the feed was updated by another user
  313. $mtime = $feed->cacheModifiedTime();
  314. if ($feed->lastUpdate() + 10 >= $mtime) {
  315. continue; //Nothing newer from other users
  316. }
  317. //Minz_Log::debug($feed->url(false) . ' was updated at ' . date('c', $mtime) . ' by another user');
  318. //Will take advantage of the newer cache
  319. } else {
  320. $mtime = time();
  321. }
  322. if (!$feed->lock()) {
  323. Minz_Log::notice('Feed already being actualized: ' . $feed->url(false));
  324. continue;
  325. }
  326. $isNewFeed = $feed->lastUpdate() <= 0;
  327. try {
  328. if ($simplePiePush) {
  329. $simplePie = $simplePiePush; //Used by WebSub
  330. } elseif ($feed->kind() === FreshRSS_Feed::KIND_HTML_XPATH) {
  331. $simplePie = $feed->loadHtmlXpath(false, $isNewFeed);
  332. if ($simplePie == null) {
  333. throw new FreshRSS_Feed_Exception('HTML+XPath Web scraping failed for [' . $feed->url(false) . ']');
  334. }
  335. } else {
  336. $simplePie = $feed->load(false, $isNewFeed);
  337. }
  338. $newGuids = $simplePie == null ? [] : $feed->loadGuids($simplePie);
  339. $entries = $simplePie == null ? [] : $feed->loadEntries($simplePie);
  340. } catch (FreshRSS_Feed_Exception $e) {
  341. Minz_Log::warning($e->getMessage());
  342. $feedDAO->updateLastUpdate($feed->id(), true);
  343. if ($e->getCode() === 410) {
  344. // HTTP 410 Gone
  345. Minz_Log::warning('Muting gone feed: ' . $feed->url(false));
  346. $feedDAO->mute($feed->id(), true);
  347. }
  348. $feed->unlock();
  349. continue;
  350. }
  351. $needFeedCacheRefresh = false;
  352. if (count($newGuids) > 0) {
  353. $titlesAsRead = [];
  354. $readWhenSameTitleInFeed = $feed->attributes('read_when_same_title_in_feed');
  355. if ($readWhenSameTitleInFeed == false) {
  356. $readWhenSameTitleInFeed = FreshRSS_Context::$user_conf->mark_when['same_title_in_feed'];
  357. }
  358. if ($readWhenSameTitleInFeed > 0) {
  359. $titlesAsRead = array_flip($feedDAO->listTitles($feed->id(), intval($readWhenSameTitleInFeed)));
  360. }
  361. $mark_updated_article_unread = $feed->attributes('mark_updated_article_unread') !== null ? (
  362. $feed->attributes('mark_updated_article_unread')
  363. ) : FreshRSS_Context::$user_conf->mark_updated_article_unread;
  364. // For this feed, check existing GUIDs already in database.
  365. $existingHashForGuids = $entryDAO->listHashForFeedGuids($feed->id(), $newGuids);
  366. /** @var array<string,bool> */
  367. $newGuids = [];
  368. // Add entries in database if possible.
  369. /** @var FreshRSS_Entry $entry */
  370. foreach ($entries as $entry) {
  371. if (isset($newGuids[$entry->guid()])) {
  372. continue; //Skip subsequent articles with same GUID
  373. }
  374. $newGuids[$entry->guid()] = true;
  375. if (isset($existingHashForGuids[$entry->guid()])) {
  376. $existingHash = $existingHashForGuids[$entry->guid()];
  377. if (strcasecmp($existingHash, $entry->hash()) !== 0) {
  378. //This entry already exists but has been updated
  379. //Minz_Log::debug('Entry with GUID `' . $entry->guid() . '` updated in feed ' . $feed->url(false) .
  380. //', old hash ' . $existingHash . ', new hash ' . $entry->hash());
  381. $entry->_isRead($mark_updated_article_unread ? false : null); //Change is_read according to policy.
  382. $entry->_isFavorite(null); // Do not change favourite state
  383. /** @var FreshRSS_Entry|null */
  384. $entry = Minz_ExtensionManager::callHook('entry_before_insert', $entry);
  385. if ($entry === null) {
  386. // An extension has returned a null value, there is nothing to insert.
  387. continue;
  388. }
  389. if (!$entry->isRead()) {
  390. $needFeedCacheRefresh = true;
  391. $feed->incPendingUnread(); //Maybe
  392. }
  393. // If the entry has changed, there is a good chance for the full content to have changed as well.
  394. $entry->loadCompleteContent(true);
  395. if (!$entryDAO->inTransaction()) {
  396. $entryDAO->beginTransaction();
  397. }
  398. $entryDAO->updateEntry($entry->toArray());
  399. }
  400. } else {
  401. $id = uTimeString();
  402. $entry->_id($id);
  403. $entry->applyFilterActions($titlesAsRead);
  404. if ($readWhenSameTitleInFeed > 0) {
  405. $titlesAsRead[$entry->title()] = true;
  406. }
  407. /** @var FreshRSS_Entry|null */
  408. $entry = Minz_ExtensionManager::callHook('entry_before_insert', $entry);
  409. if ($entry === null) {
  410. // An extension has returned a null value, there is nothing to insert.
  411. continue;
  412. }
  413. if ($pubSubHubbubEnabled && !$simplePiePush) { //We use push, but have discovered an article by pull!
  414. $text = 'An article was discovered by pull although we use PubSubHubbub!: Feed ' .
  415. SimplePie_Misc::url_remove_credentials($url) .
  416. ' GUID ' . $entry->guid();
  417. Minz_Log::warning($text, PSHB_LOG);
  418. Minz_Log::warning($text);
  419. $pubSubHubbubEnabled = false;
  420. $feed->pubSubHubbubError(true);
  421. }
  422. if (!$entryDAO->inTransaction()) {
  423. $entryDAO->beginTransaction();
  424. }
  425. $entryDAO->addEntry($entry->toArray());
  426. if (!$entry->isRead()) {
  427. $feed->incPendingUnread();
  428. }
  429. $nb_new_articles++;
  430. }
  431. }
  432. $entryDAO->updateLastSeen($feed->id(), array_keys($newGuids), $mtime);
  433. }
  434. unset($entries);
  435. if (mt_rand(0, 30) === 1) { // Remove old entries once in 30.
  436. if (!$entryDAO->inTransaction()) {
  437. $entryDAO->beginTransaction();
  438. }
  439. $nb = $feed->cleanOldEntries();
  440. if ($nb > 0) {
  441. $needFeedCacheRefresh = true;
  442. }
  443. }
  444. $feedDAO->updateLastUpdate($feed->id(), false, $mtime);
  445. $needFeedCacheRefresh |= ($feed->keepMaxUnread() != false);
  446. $needFeedCacheRefresh |= ($feed->markAsReadUponGone() != false);
  447. if ($needFeedCacheRefresh) {
  448. $feedDAO->updateCachedValues($feed->id());
  449. }
  450. if ($entryDAO->inTransaction()) {
  451. $entryDAO->commit();
  452. }
  453. $feedProperties = [];
  454. if ($pubsubhubbubEnabledGeneral && $feed->hubUrl() && $feed->selfUrl()) { //selfUrl has priority for WebSub
  455. if ($feed->selfUrl() !== $url) { // https://github.com/pubsubhubbub/PubSubHubbub/wiki/Moving-Feeds-or-changing-Hubs
  456. $selfUrl = checkUrl($feed->selfUrl());
  457. if ($selfUrl) {
  458. Minz_Log::debug('WebSub unsubscribe ' . $feed->url(false));
  459. if (!$feed->pubSubHubbubSubscribe(false)) { //Unsubscribe
  460. Minz_Log::warning('Error while WebSub unsubscribing from ' . $feed->url(false));
  461. }
  462. $feed->_url($selfUrl, false);
  463. Minz_Log::notice('Feed ' . $url . ' canonical address moved to ' . $feed->url(false));
  464. $feedDAO->updateFeed($feed->id(), array('url' => $feed->url()));
  465. }
  466. }
  467. } elseif ($feed->url() !== $url) { // HTTP 301 Moved Permanently
  468. Minz_Log::notice('Feed ' . SimplePie_Misc::url_remove_credentials($url) .
  469. ' moved permanently to ' . SimplePie_Misc::url_remove_credentials($feed->url(false)));
  470. $feedProperties['url'] = $feed->url();
  471. }
  472. if ($simplePie != null) {
  473. if ($feed->name(true) == '') {
  474. //HTML to HTML-PRE //ENT_COMPAT except '&'
  475. $name = strtr(html_only_entity_decode($simplePie->get_title()), array('<' => '&lt;', '>' => '&gt;', '"' => '&quot;'));
  476. $feed->_name($name);
  477. $feedProperties['name'] = $feed->name(false);
  478. }
  479. if (trim($feed->website()) == '') {
  480. $website = html_only_entity_decode($simplePie->get_link());
  481. $feed->_website($website == '' ? $feed->url() : $website);
  482. $feedProperties['website'] = $feed->website();
  483. $feed->faviconPrepare();
  484. }
  485. if (trim($feed->description()) == '') {
  486. $description = html_only_entity_decode($simplePie->get_description());
  487. if ($description != '') {
  488. $feed->_description($description);
  489. $feedProperties['description'] = $feed->description();
  490. }
  491. }
  492. }
  493. if (!empty($feedProperties)) {
  494. $ok = $feedDAO->updateFeed($feed->id(), $feedProperties);
  495. if (!$ok && $isNewFeed) {
  496. //Cancel adding new feed in case of database error at first actualize
  497. $feedDAO->deleteFeed($feed->id());
  498. $feed->unlock();
  499. break;
  500. }
  501. }
  502. $feed->faviconPrepare();
  503. if ($pubsubhubbubEnabledGeneral && $feed->pubSubHubbubPrepare()) {
  504. Minz_Log::notice('WebSub subscribe ' . $feed->url(false));
  505. if (!$feed->pubSubHubbubSubscribe(true)) { //Subscribe
  506. Minz_Log::warning('Error while WebSub subscribing to ' . $feed->url(false));
  507. }
  508. }
  509. $feed->unlock();
  510. $updated_feeds++;
  511. unset($feed);
  512. gc_collect_cycles();
  513. // No more than $maxFeeds feeds unless $force is true to avoid overloading
  514. // the server.
  515. if ($updated_feeds >= $maxFeeds && !$force) {
  516. break;
  517. }
  518. }
  519. if (!$noCommit && ($nb_new_articles > 0 || $updated_feeds > 0)) {
  520. if (!$entryDAO->inTransaction()) {
  521. $entryDAO->beginTransaction();
  522. }
  523. $entryDAO->commitNewEntries();
  524. $feedDAO->updateCachedValues();
  525. if ($entryDAO->inTransaction()) {
  526. $entryDAO->commit();
  527. }
  528. $databaseDAO = FreshRSS_Factory::createDatabaseDAO();
  529. $databaseDAO->minorDbMaintenance();
  530. }
  531. return array($updated_feeds, reset($feeds), $nb_new_articles);
  532. }
  533. /**
  534. * This action actualizes entries from one or several feeds.
  535. *
  536. * Parameters are:
  537. * - id (default: false): Feed ID
  538. * - url (default: false): Feed URL
  539. * - force (default: false)
  540. * - noCommit (default: 0): Set to 1 to prevent committing the new articles to the main database
  541. * If id and url are not specified, all the feeds are actualized. But if force is
  542. * false, process stops at 10 feeds to avoid time execution problem.
  543. */
  544. public function actualizeAction() {
  545. Minz_Session::_param('actualize_feeds', false);
  546. $id = Minz_Request::param('id');
  547. $url = Minz_Request::param('url');
  548. $force = Minz_Request::param('force');
  549. $maxFeeds = (int)Minz_Request::param('maxFeeds');
  550. $noCommit = ($_POST['noCommit'] ?? 0) == 1;
  551. $feed = null;
  552. if ($id == -1 && !$noCommit) { //Special request only to commit & refresh DB cache
  553. $updated_feeds = 0;
  554. $entryDAO = FreshRSS_Factory::createEntryDao();
  555. $feedDAO = FreshRSS_Factory::createFeedDao();
  556. $entryDAO->beginTransaction();
  557. $entryDAO->commitNewEntries();
  558. $feedDAO->updateCachedValues();
  559. $entryDAO->commit();
  560. $databaseDAO = FreshRSS_Factory::createDatabaseDAO();
  561. $databaseDAO->minorDbMaintenance();
  562. } else {
  563. FreshRSS_category_Controller::refreshDynamicOpmls();
  564. list($updated_feeds, $feed, $nb_new_articles) = self::actualizeFeed($id, $url, $force, null, $noCommit, $maxFeeds);
  565. }
  566. if (Minz_Request::param('ajax')) {
  567. // Most of the time, ajax request is for only one feed. But since
  568. // there are several parallel requests, we should return that there
  569. // are several updated feeds.
  570. Minz_Request::setGoodNotification(_t('feedback.sub.feed.actualizeds'));
  571. // No layout in ajax request.
  572. $this->view->_layout(false);
  573. } else {
  574. // Redirect to the main page with correct notification.
  575. if ($updated_feeds === 1) {
  576. Minz_Request::good(_t('feedback.sub.feed.actualized', $feed->name()), array(
  577. 'params' => array('get' => 'f_' . $feed->id())
  578. ));
  579. } elseif ($updated_feeds > 1) {
  580. Minz_Request::good(_t('feedback.sub.feed.n_actualized', $updated_feeds), array());
  581. } else {
  582. Minz_Request::good(_t('feedback.sub.feed.no_refresh'), array());
  583. }
  584. }
  585. return $updated_feeds;
  586. }
  587. public static function renameFeed($feed_id, $feed_name) {
  588. if ($feed_id <= 0 || $feed_name == '') {
  589. return false;
  590. }
  591. FreshRSS_UserDAO::touch();
  592. $feedDAO = FreshRSS_Factory::createFeedDao();
  593. return $feedDAO->updateFeed($feed_id, array('name' => $feed_name));
  594. }
  595. public static function moveFeed($feed_id, $cat_id, $new_cat_name = '') {
  596. if ($feed_id <= 0 || ($cat_id <= 0 && $new_cat_name == '')) {
  597. return false;
  598. }
  599. FreshRSS_UserDAO::touch();
  600. $catDAO = FreshRSS_Factory::createCategoryDao();
  601. if ($cat_id > 0) {
  602. $cat = $catDAO->searchById($cat_id);
  603. $cat_id = $cat == null ? 0 : $cat->id();
  604. }
  605. if ($cat_id <= 1 && $new_cat_name != '') {
  606. $cat_id = $catDAO->addCategory(array('name' => $new_cat_name));
  607. }
  608. if ($cat_id <= 1) {
  609. $catDAO->checkDefault();
  610. $cat_id = FreshRSS_CategoryDAO::DEFAULTCATEGORYID;
  611. }
  612. $feedDAO = FreshRSS_Factory::createFeedDao();
  613. return $feedDAO->updateFeed($feed_id, array('category' => $cat_id));
  614. }
  615. /**
  616. * This action changes the category of a feed.
  617. *
  618. * This page must be reached by a POST request.
  619. *
  620. * Parameters are:
  621. * - f_id (default: false)
  622. * - c_id (default: false)
  623. * If c_id is false, default category is used.
  624. *
  625. * @todo should handle order of the feed inside the category.
  626. */
  627. public function moveAction() {
  628. if (!Minz_Request::isPost()) {
  629. Minz_Request::forward(array('c' => 'subscription'), true);
  630. }
  631. $feed_id = Minz_Request::param('f_id');
  632. $cat_id = Minz_Request::param('c_id');
  633. if (self::moveFeed($feed_id, $cat_id)) {
  634. // TODO: return something useful
  635. // Log a notice to prevent "Empty IF statement" warning in PHP_CodeSniffer
  636. Minz_Log::notice('Moved feed `' . $feed_id . '` in the category `' . $cat_id . '`');
  637. } else {
  638. Minz_Log::warning('Cannot move feed `' . $feed_id . '` in the category `' . $cat_id . '`');
  639. Minz_Error::error(404);
  640. }
  641. }
  642. public static function deleteFeed($feed_id) {
  643. FreshRSS_UserDAO::touch();
  644. $feedDAO = FreshRSS_Factory::createFeedDao();
  645. if ($feedDAO->deleteFeed($feed_id)) {
  646. // TODO: Delete old favicon
  647. // Remove related queries
  648. FreshRSS_Context::$user_conf->queries = remove_query_by_get(
  649. 'f_' . $feed_id, FreshRSS_Context::$user_conf->queries);
  650. FreshRSS_Context::$user_conf->save();
  651. return true;
  652. }
  653. return false;
  654. }
  655. /**
  656. * This action deletes a feed.
  657. *
  658. * This page must be reached by a POST request.
  659. * If there are related queries, they are deleted too.
  660. *
  661. * Parameters are:
  662. * - id (default: false)
  663. * - r (default: false)
  664. * r permits to redirect to a given page at the end of this action.
  665. *
  666. * @todo handle "r" redirection in Minz_Request::forward()?
  667. */
  668. public function deleteAction() {
  669. $from = Minz_Request::param('from');
  670. $id = Minz_Request::param('id');
  671. switch ($from) {
  672. case 'stats':
  673. $redirect_url = array('c' => 'stats', 'a' => 'idle');
  674. break;
  675. case 'normal':
  676. $get = Minz_Request::param('get');
  677. if ($get) {
  678. $redirect_url = array('c' => 'index', 'a' => 'normal', 'params' => array('get' => $get));
  679. } else {
  680. $redirect_url = array('c' => 'index', 'a' => 'normal');
  681. }
  682. break;
  683. default:
  684. $redirect_url = Minz_Request::param('r', false, true);
  685. if (!$redirect_url) {
  686. $redirect_url = array('c' => 'subscription', 'a' => 'index');
  687. }
  688. if (!Minz_Request::isPost()) {
  689. Minz_Request::forward($redirect_url, true);
  690. }
  691. }
  692. if (self::deleteFeed($id)) {
  693. Minz_Request::good(_t('feedback.sub.feed.deleted'), $redirect_url);
  694. } else {
  695. Minz_Request::bad(_t('feedback.sub.feed.error'), $redirect_url);
  696. }
  697. }
  698. /**
  699. * This action force clears the cache of a feed.
  700. *
  701. * Parameters are:
  702. * - id (mandatory - no default): Feed ID
  703. *
  704. */
  705. public function clearCacheAction() {
  706. //Get Feed.
  707. $id = Minz_Request::param('id');
  708. $feedDAO = FreshRSS_Factory::createFeedDao();
  709. $feed = $feedDAO->searchById($id);
  710. if (!$feed) {
  711. Minz_Request::bad(_t('feedback.sub.feed.not_found'), array());
  712. return;
  713. }
  714. $feed->clearCache();
  715. Minz_Request::good(_t('feedback.sub.feed.cache_cleared', $feed->name()), array(
  716. 'params' => array('get' => 'f_' . $feed->id())
  717. ));
  718. }
  719. /**
  720. * This action forces reloading the articles of a feed.
  721. *
  722. * Parameters are:
  723. * - id (mandatory - no default): Feed ID
  724. *
  725. */
  726. public function reloadAction() {
  727. @set_time_limit(300);
  728. //Get Feed ID.
  729. $feed_id = intval(Minz_Request::param('id', 0));
  730. $limit = intval(Minz_Request::param('reload_limit', 10));
  731. $feedDAO = FreshRSS_Factory::createFeedDao();
  732. $entryDAO = FreshRSS_Factory::createEntryDao();
  733. $feed = $feedDAO->searchById($feed_id);
  734. if (!$feed) {
  735. Minz_Request::bad(_t('feedback.sub.feed.not_found'), array());
  736. return;
  737. }
  738. //Re-fetch articles as if the feed was new.
  739. $feedDAO->updateFeed($feed->id(), [ 'lastUpdate' => 0 ]);
  740. self::actualizeFeed($feed_id, '', false);
  741. //Extract all feed entries from database, load complete content and store them back in database.
  742. $entries = $entryDAO->listWhere('f', $feed_id, FreshRSS_Entry::STATE_ALL, 'DESC', $limit);
  743. //We need another DB connection in parallel for unbuffered streaming
  744. Minz_ModelPdo::$usesSharedPdo = false;
  745. if (FreshRSS_Context::$system_conf->db['type'] === 'mysql') {
  746. // Second parallel connection for unbuffered streaming: MySQL
  747. $entryDAO2 = FreshRSS_Factory::createEntryDao();
  748. } else {
  749. // Single connection for buffered queries (in memory): SQLite, PostgreSQL
  750. //TODO: Consider an unbuffered query for PostgreSQL
  751. $entryDAO2 = $entryDAO;
  752. }
  753. foreach ($entries as $entry) {
  754. if ($entry->loadCompleteContent(true)) {
  755. $entryDAO2->updateEntry($entry->toArray());
  756. }
  757. }
  758. Minz_ModelPdo::$usesSharedPdo = true;
  759. //Give feedback to user.
  760. Minz_Request::good(_t('feedback.sub.feed.reloaded', $feed->name()), array(
  761. 'params' => array('get' => 'f_' . $feed->id())
  762. ));
  763. }
  764. /**
  765. * This action creates a preview of a content-selector.
  766. *
  767. * Parameters are:
  768. * - id (mandatory - no default): Feed ID
  769. * - selector (mandatory - no default): Selector to preview
  770. *
  771. */
  772. public function contentSelectorPreviewAction() {
  773. //Configure.
  774. $this->view->fatalError = '';
  775. $this->view->selectorSuccess = false;
  776. $this->view->htmlContent = '';
  777. $this->view->_layout(false);
  778. $this->_csp([
  779. 'default-src' => "'self'",
  780. 'frame-src' => '*',
  781. 'img-src' => '* data:',
  782. 'media-src' => '*',
  783. ]);
  784. //Get parameters.
  785. $feed_id = Minz_Request::param('id');
  786. $content_selector = trim(Minz_Request::param('selector'));
  787. if (!$content_selector) {
  788. $this->view->fatalError = _t('feedback.sub.feed.selector_preview.selector_empty');
  789. return;
  790. }
  791. //Check Feed ID validity.
  792. $entryDAO = FreshRSS_Factory::createEntryDao();
  793. $entries = $entryDAO->listWhere('f', $feed_id);
  794. $entry = null;
  795. //Get first entry (syntax robust for Generator or Array)
  796. foreach ($entries as $myEntry) {
  797. if ($entry == null) {
  798. $entry = $myEntry;
  799. }
  800. }
  801. if ($entry == null) {
  802. $this->view->fatalError = _t('feedback.sub.feed.selector_preview.no_entries');
  803. return;
  804. }
  805. //Get feed.
  806. $feed = $entry->feed();
  807. if (!$feed) {
  808. $this->view->fatalError = _t('feedback.sub.feed.selector_preview.no_feed');
  809. return;
  810. }
  811. $attributes = $feed->attributes();
  812. $attributes['path_entries_filter'] = trim(Minz_Request::param('selector_filter', ''));
  813. //Fetch & select content.
  814. try {
  815. $fullContent = FreshRSS_Entry::getContentByParsing(
  816. htmlspecialchars_decode($entry->link(), ENT_QUOTES),
  817. $content_selector,
  818. $attributes
  819. );
  820. if ($fullContent != '') {
  821. $this->view->selectorSuccess = true;
  822. $this->view->htmlContent = $fullContent;
  823. } else {
  824. $this->view->selectorSuccess = false;
  825. $this->view->htmlContent = $entry->content();
  826. }
  827. } catch (Exception $e) {
  828. $this->view->fatalError = _t('feedback.sub.feed.selector_preview.http_error');
  829. }
  830. }
  831. }