feedController.php 32 KB

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