feedController.php 31 KB

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