feedController.php 32 KB

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