feedController.php 32 KB

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