Feed.php 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  1. <?php
  2. class FreshRSS_Feed extends Minz_Model {
  3. /**
  4. * Normal RSS or Atom feed
  5. * @var int
  6. */
  7. const KIND_RSS = 0;
  8. /**
  9. * Invalid RSS or Atom feed
  10. * @var int
  11. */
  12. const KIND_RSS_FORCED = 2;
  13. /**
  14. * Normal HTML with XPath scraping
  15. * @var int
  16. */
  17. const KIND_HTML_XPATH = 10;
  18. /**
  19. * Normal JSON with XPath scraping
  20. * @var int
  21. */
  22. const KIND_JSON_XPATH = 20;
  23. const PRIORITY_MAIN_STREAM = 10;
  24. const PRIORITY_NORMAL = 0;
  25. const PRIORITY_ARCHIVED = -10;
  26. const TTL_DEFAULT = 0;
  27. const ARCHIVING_RETENTION_COUNT_LIMIT = 10000;
  28. const ARCHIVING_RETENTION_PERIOD = 'P3M';
  29. /** @var int */
  30. private $id = 0;
  31. /** @var string */
  32. private $url = '';
  33. /** @var int */
  34. private $kind = 0;
  35. /** @var int */
  36. private $categoryId = 1;
  37. /** @var FreshRSS_Category|null */
  38. private $category;
  39. /** @var int */
  40. private $nbEntries = -1;
  41. /** @var int */
  42. private $nbNotRead = -1;
  43. /** @var int */
  44. private $nbPendingNotRead = 0;
  45. /** @var string */
  46. private $name = '';
  47. /** @var string */
  48. private $website = '';
  49. /** @var string */
  50. private $description = '';
  51. /** @var int */
  52. private $lastUpdate = 0;
  53. /** @var int */
  54. private $priority = self::PRIORITY_MAIN_STREAM;
  55. /** @var string */
  56. private $pathEntries = '';
  57. /** @var string */
  58. private $httpAuth = '';
  59. /** @var bool */
  60. private $error = false;
  61. /** @var int */
  62. private $ttl = self::TTL_DEFAULT;
  63. private $attributes = [];
  64. /** @var bool */
  65. private $mute = false;
  66. /** @var string */
  67. private $hash = '';
  68. /** @var string */
  69. private $lockPath = '';
  70. /** @var string */
  71. private $hubUrl = '';
  72. /** @var string */
  73. private $selfUrl = '';
  74. /** @var array<FreshRSS_FilterAction> $filterActions */
  75. private $filterActions = null;
  76. public function __construct(string $url, bool $validate = true) {
  77. if ($validate) {
  78. $this->_url($url);
  79. } else {
  80. $this->url = $url;
  81. }
  82. }
  83. /**
  84. * @return FreshRSS_Feed
  85. */
  86. public static function example() {
  87. $f = new FreshRSS_Feed('http://example.net/', false);
  88. $f->faviconPrepare();
  89. return $f;
  90. }
  91. public function id(): int {
  92. return $this->id;
  93. }
  94. public function hash(): string {
  95. if ($this->hash == '') {
  96. $salt = FreshRSS_Context::$system_conf->salt;
  97. $this->hash = hash('crc32b', $salt . $this->url);
  98. }
  99. return $this->hash;
  100. }
  101. public function url(bool $includeCredentials = true): string {
  102. return $includeCredentials ? $this->url : SimplePie_Misc::url_remove_credentials($this->url);
  103. }
  104. public function selfUrl(): string {
  105. return $this->selfUrl;
  106. }
  107. public function kind(): int {
  108. return $this->kind;
  109. }
  110. public function hubUrl(): string {
  111. return $this->hubUrl;
  112. }
  113. /**
  114. * @return FreshRSS_Category|null|false
  115. */
  116. public function category() {
  117. if ($this->category === null) {
  118. $catDAO = FreshRSS_Factory::createCategoryDao();
  119. $this->category = $catDAO->searchById($this->categoryId);
  120. }
  121. return $this->category;
  122. }
  123. public function categoryId(): int {
  124. return $this->categoryId;
  125. }
  126. public function entries() {
  127. Minz_Log::warning(__method__ . ' is deprecated since FreshRSS 1.16.1!');
  128. $simplePie = $this->load(false, true);
  129. return $simplePie == null ? [] : iterator_to_array($this->loadEntries($simplePie));
  130. }
  131. public function name($raw = false): string {
  132. return $raw || $this->name != '' ? $this->name : preg_replace('%^https?://(www[.])?%i', '', $this->url);
  133. }
  134. /** @return string HTML-encoded URL of the Web site of the feed */
  135. public function website(): string {
  136. return $this->website;
  137. }
  138. public function description(): string {
  139. return $this->description;
  140. }
  141. public function lastUpdate(): int {
  142. return $this->lastUpdate;
  143. }
  144. public function priority(): int {
  145. return $this->priority;
  146. }
  147. /** @return string HTML-encoded CSS selector */
  148. public function pathEntries(): string {
  149. return $this->pathEntries;
  150. }
  151. public function httpAuth($raw = true) {
  152. if ($raw) {
  153. return $this->httpAuth;
  154. } else {
  155. $pos_colon = strpos($this->httpAuth, ':');
  156. $user = substr($this->httpAuth, 0, $pos_colon);
  157. $pass = substr($this->httpAuth, $pos_colon + 1);
  158. return array(
  159. 'username' => $user,
  160. 'password' => $pass
  161. );
  162. }
  163. }
  164. public function inError(): bool {
  165. return $this->error;
  166. }
  167. /**
  168. * @param bool $raw true for database version combined with mute information, false otherwise
  169. */
  170. public function ttl(bool $raw = false): int {
  171. if ($raw) {
  172. $ttl = $this->ttl;
  173. if ($this->mute && FreshRSS_Feed::TTL_DEFAULT === $ttl) {
  174. $ttl = FreshRSS_Context::$user_conf ? FreshRSS_Context::$user_conf->ttl_default : 3600;
  175. }
  176. return $ttl * ($this->mute ? -1 : 1);
  177. }
  178. return $this->ttl;
  179. }
  180. /** @return mixed attribute (if $key is not blank) or array of attributes, not HTML-encoded */
  181. public function attributes($key = '') {
  182. if ($key == '') {
  183. return $this->attributes;
  184. } else {
  185. return isset($this->attributes[$key]) ? $this->attributes[$key] : null;
  186. }
  187. }
  188. public function mute(): bool {
  189. return $this->mute;
  190. }
  191. public function nbEntries(): int {
  192. if ($this->nbEntries < 0) {
  193. $feedDAO = FreshRSS_Factory::createFeedDao();
  194. $this->nbEntries = $feedDAO->countEntries($this->id());
  195. }
  196. return $this->nbEntries;
  197. }
  198. public function nbNotRead($includePending = false): int {
  199. if ($this->nbNotRead < 0) {
  200. $feedDAO = FreshRSS_Factory::createFeedDao();
  201. $this->nbNotRead = $feedDAO->countNotRead($this->id());
  202. }
  203. return $this->nbNotRead + ($includePending ? $this->nbPendingNotRead : 0);
  204. }
  205. public function faviconPrepare() {
  206. require_once(LIB_PATH . '/favicons.php');
  207. $url = $this->website;
  208. if ($url == '') {
  209. $url = $this->url;
  210. }
  211. $txt = FAVICONS_DIR . $this->hash() . '.txt';
  212. if (@file_get_contents($txt) !== $url) {
  213. file_put_contents($txt, $url);
  214. }
  215. if (FreshRSS_Context::$isCli) {
  216. $ico = FAVICONS_DIR . $this->hash() . '.ico';
  217. $ico_mtime = @filemtime($ico);
  218. $txt_mtime = @filemtime($txt);
  219. if ($txt_mtime != false &&
  220. ($ico_mtime == false || $ico_mtime < $txt_mtime || ($ico_mtime < time() - (14 * 86400)))) {
  221. // no ico file or we should download a new one.
  222. $url = file_get_contents($txt);
  223. download_favicon($url, $ico) || touch($ico);
  224. }
  225. }
  226. }
  227. public static function faviconDelete($hash) {
  228. $path = DATA_PATH . '/favicons/' . $hash;
  229. @unlink($path . '.ico');
  230. @unlink($path . '.txt');
  231. }
  232. public function favicon(): string {
  233. return Minz_Url::display('/f.php?' . $this->hash());
  234. }
  235. public function _id($value) {
  236. $this->id = intval($value);
  237. }
  238. public function _url(string $value, bool $validate = true) {
  239. $this->hash = '';
  240. if ($validate) {
  241. $value = checkUrl($value);
  242. }
  243. if ($value == '') {
  244. throw new FreshRSS_BadUrl_Exception($value);
  245. }
  246. $this->url = $value;
  247. }
  248. public function _kind(int $value) {
  249. $this->kind = $value;
  250. }
  251. /** @param FreshRSS_Category|null $cat */
  252. public function _category($cat) {
  253. $this->category = $cat;
  254. $this->categoryId = $this->category == null ? 0 : $this->category->id();
  255. }
  256. /** @param int|string $id */
  257. public function _categoryId($id) {
  258. $this->category = null;
  259. $this->categoryId = intval($id);
  260. }
  261. public function _name(string $value) {
  262. $this->name = $value == '' ? '' : trim($value);
  263. }
  264. public function _website(string $value, bool $validate = true) {
  265. if ($validate) {
  266. $value = checkUrl($value);
  267. }
  268. if ($value == '') {
  269. $value = '';
  270. }
  271. $this->website = $value;
  272. }
  273. public function _description(string $value) {
  274. $this->description = $value == '' ? '' : $value;
  275. }
  276. public function _lastUpdate($value) {
  277. $this->lastUpdate = intval($value);
  278. }
  279. public function _priority($value) {
  280. $this->priority = intval($value);
  281. }
  282. /** @param string $value HTML-encoded CSS selector */
  283. public function _pathEntries(string $value) {
  284. $this->pathEntries = $value;
  285. }
  286. public function _httpAuth(string $value) {
  287. $this->httpAuth = $value;
  288. }
  289. public function _error($value) {
  290. $this->error = (bool)$value;
  291. }
  292. public function _mute(bool $value) {
  293. $this->mute = $value;
  294. }
  295. public function _ttl($value) {
  296. $value = intval($value);
  297. $value = min($value, 100000000);
  298. $this->ttl = abs($value);
  299. $this->mute = $value < self::TTL_DEFAULT;
  300. }
  301. /** @param mixed $value Value, not HTML-encoded */
  302. public function _attributes(string $key, $value) {
  303. if ($key == '') {
  304. if (is_string($value)) {
  305. $value = json_decode($value, true);
  306. }
  307. if (is_array($value)) {
  308. $this->attributes = $value;
  309. }
  310. } elseif ($value === null) {
  311. unset($this->attributes[$key]);
  312. } else {
  313. $this->attributes[$key] = $value;
  314. }
  315. }
  316. public function _nbNotRead($value) {
  317. $this->nbNotRead = intval($value);
  318. }
  319. public function _nbEntries($value) {
  320. $this->nbEntries = intval($value);
  321. }
  322. /**
  323. * @return SimplePie|null
  324. */
  325. public function load(bool $loadDetails = false, bool $noCache = false) {
  326. if ($this->url != '') {
  327. // @phpstan-ignore-next-line
  328. if (CACHE_PATH === false) {
  329. throw new Minz_FileNotExistException(
  330. 'CACHE_PATH',
  331. Minz_Exception::ERROR
  332. );
  333. } else {
  334. $url = htmlspecialchars_decode($this->url, ENT_QUOTES);
  335. if ($this->httpAuth != '') {
  336. $url = preg_replace('#((.+)://)(.+)#', '${1}' . $this->httpAuth . '@${3}', $url);
  337. }
  338. $simplePie = customSimplePie($this->attributes());
  339. if (substr($url, -11) === '#force_feed') {
  340. $simplePie->force_feed(true);
  341. $url = substr($url, 0, -11);
  342. }
  343. $simplePie->set_feed_url($url);
  344. if (!$loadDetails) { //Only activates auto-discovery when adding a new feed
  345. $simplePie->set_autodiscovery_level(SIMPLEPIE_LOCATOR_NONE);
  346. }
  347. if ($this->attributes('clear_cache')) {
  348. // Do not use `$simplePie->enable_cache(false);` as it would prevent caching in multiuser context
  349. $this->clearCache();
  350. }
  351. Minz_ExtensionManager::callHook('simplepie_before_init', $simplePie, $this);
  352. $mtime = $simplePie->init();
  353. if ((!$mtime) || $simplePie->error()) {
  354. $errorMessage = $simplePie->error();
  355. throw new FreshRSS_Feed_Exception(
  356. ($errorMessage == '' ? 'Unknown error for feed' : $errorMessage) . ' [' . $this->url . ']',
  357. $simplePie->status_code()
  358. );
  359. }
  360. $links = $simplePie->get_links('self');
  361. $this->selfUrl = empty($links[0]) ? '' : checkUrl($links[0]);
  362. if ($this->selfUrl == false) {
  363. $this->selfUrl = '';
  364. }
  365. $links = $simplePie->get_links('hub');
  366. $this->hubUrl = empty($links[0]) ? '' : checkUrl($links[0]);
  367. if ($this->hubUrl == false) {
  368. $this->hubUrl = '';
  369. }
  370. if ($loadDetails) {
  371. // si on a utilisé l’auto-discover, notre url va avoir changé
  372. $subscribe_url = $simplePie->subscribe_url(false);
  373. //HTML to HTML-PRE //ENT_COMPAT except '&'
  374. $title = strtr(html_only_entity_decode($simplePie->get_title()), array('<' => '&lt;', '>' => '&gt;', '"' => '&quot;'));
  375. $this->_name($title == '' ? $this->url : $title);
  376. $this->_website(html_only_entity_decode($simplePie->get_link()));
  377. $this->_description(html_only_entity_decode($simplePie->get_description()));
  378. } else {
  379. //The case of HTTP 301 Moved Permanently
  380. $subscribe_url = $simplePie->subscribe_url(true);
  381. }
  382. $clean_url = SimplePie_Misc::url_remove_credentials($subscribe_url);
  383. if ($subscribe_url !== null && $subscribe_url !== $url) {
  384. $this->_url($clean_url);
  385. }
  386. if (($mtime === true) || ($mtime > $this->lastUpdate) || $noCache) {
  387. //Minz_Log::debug('FreshRSS no cache ' . $mtime . ' > ' . $this->lastUpdate . ' for ' . $clean_url);
  388. return $simplePie;
  389. }
  390. //Minz_Log::debug('FreshRSS use cache for ' . $clean_url);
  391. }
  392. }
  393. return null;
  394. }
  395. /**
  396. * @return array<string>
  397. */
  398. public function loadGuids(SimplePie $simplePie) {
  399. $hasUniqueGuids = true;
  400. $testGuids = [];
  401. $guids = [];
  402. $hasBadGuids = $this->attributes('hasBadGuids');
  403. $items = $simplePie->get_items();
  404. if (empty($items)) {
  405. return $guids;
  406. }
  407. for ($i = count($items) - 1; $i >= 0; $i--) {
  408. $item = $items[$i];
  409. if ($item == null) {
  410. continue;
  411. }
  412. $guid = safe_ascii($item->get_id(false, false));
  413. $hasUniqueGuids &= empty($testGuids['_' . $guid]);
  414. $testGuids['_' . $guid] = true;
  415. $guids[] = $guid;
  416. }
  417. if ($hasBadGuids != !$hasUniqueGuids) {
  418. $hasBadGuids = !$hasUniqueGuids;
  419. if ($hasBadGuids) {
  420. Minz_Log::warning('Feed has invalid GUIDs: ' . $this->url);
  421. } else {
  422. Minz_Log::warning('Feed has valid GUIDs again: ' . $this->url);
  423. }
  424. $feedDAO = FreshRSS_Factory::createFeedDao();
  425. $feedDAO->updateFeedAttribute($this, 'hasBadGuids', $hasBadGuids);
  426. }
  427. return $guids;
  428. }
  429. public function loadEntries(SimplePie $simplePie) {
  430. $hasBadGuids = $this->attributes('hasBadGuids');
  431. $items = $simplePie->get_items();
  432. if (empty($items)) {
  433. return;
  434. }
  435. // We want chronological order and SimplePie uses reverse order.
  436. for ($i = count($items) - 1; $i >= 0; $i--) {
  437. $item = $items[$i];
  438. if ($item == null) {
  439. continue;
  440. }
  441. $title = html_only_entity_decode(strip_tags($item->get_title() ?? ''));
  442. $authors = $item->get_authors();
  443. $link = $item->get_permalink();
  444. $date = @strtotime($item->get_date() ?? '');
  445. //Tag processing (tag == category)
  446. $categories = $item->get_categories();
  447. $tags = array();
  448. if (is_array($categories)) {
  449. foreach ($categories as $category) {
  450. $text = html_only_entity_decode($category->get_label());
  451. //Some feeds use a single category with comma-separated tags
  452. $labels = explode(',', $text);
  453. if (is_array($labels)) {
  454. foreach ($labels as $label) {
  455. $tags[] = trim($label);
  456. }
  457. }
  458. }
  459. $tags = array_unique($tags);
  460. }
  461. $content = html_only_entity_decode($item->get_content());
  462. if ($item->get_enclosures() != null) {
  463. $elinks = array();
  464. foreach ($item->get_enclosures() as $enclosure) {
  465. $elink = $enclosure->get_link();
  466. if ($elink != '' && empty($elinks[$elink])) {
  467. $content .= '<div class="enclosure">';
  468. if ($enclosure->get_title() != '') {
  469. $content .= '<p class="enclosure-title">' . $enclosure->get_title() . '</p>';
  470. }
  471. $enclosureContent = '';
  472. $elinks[$elink] = true;
  473. $mime = strtolower($enclosure->get_type() ?? '');
  474. $medium = strtolower($enclosure->get_medium() ?? '');
  475. $height = $enclosure->get_height();
  476. $width = $enclosure->get_width();
  477. $length = $enclosure->get_length();
  478. if ($medium === 'image' || strpos($mime, 'image') === 0 ||
  479. ($mime == '' && $length == null && ($width != 0 || $height != 0 || preg_match('/[.](avif|gif|jpe?g|png|svg|webp)$/i', $elink)))) {
  480. $enclosureContent .= '<p class="enclosure-content"><img src="' . $elink . '" alt="" /></p>';
  481. } elseif ($medium === 'audio' || strpos($mime, 'audio') === 0) {
  482. $enclosureContent .= '<p class="enclosure-content"><audio preload="none" src="' . $elink
  483. . ($length == null ? '' : '" data-length="' . intval($length))
  484. . ($mime == '' ? '' : '" data-type="' . htmlspecialchars($mime, ENT_COMPAT, 'UTF-8'))
  485. . '" controls="controls"></audio> <a download="" href="' . $elink . '">💾</a></p>';
  486. } elseif ($medium === 'video' || strpos($mime, 'video') === 0) {
  487. $enclosureContent .= '<p class="enclosure-content"><video preload="none" src="' . $elink
  488. . ($length == null ? '' : '" data-length="' . intval($length))
  489. . ($mime == '' ? '' : '" data-type="' . htmlspecialchars($mime, ENT_COMPAT, 'UTF-8'))
  490. . '" controls="controls"></video> <a download="" href="' . $elink . '">💾</a></p>';
  491. } else { //e.g. application, text, unknown
  492. $enclosureContent .= '<p class="enclosure-content"><a download="" href="' . $elink
  493. . ($mime == '' ? '' : '" data-type="' . htmlspecialchars($mime, ENT_COMPAT, 'UTF-8'))
  494. . ($medium == '' ? '' : '" data-medium="' . htmlspecialchars($medium, ENT_COMPAT, 'UTF-8'))
  495. . '">💾</a></p>';
  496. }
  497. $thumbnailContent = '';
  498. if ($enclosure->get_thumbnails() != null) {
  499. foreach ($enclosure->get_thumbnails() as $thumbnail) {
  500. if (empty($elinks[$thumbnail])) {
  501. $elinks[$thumbnail] = true;
  502. $thumbnailContent .= '<p><img class="enclosure-thumbnail" src="' . $thumbnail . '" alt="" /></p>';
  503. }
  504. }
  505. }
  506. $content .= $thumbnailContent;
  507. $content .= $enclosureContent;
  508. if ($enclosure->get_description() != '') {
  509. $content .= '<p class="enclosure-description">' . $enclosure->get_description() . '</p>';
  510. }
  511. $content .= "</div>\n";
  512. }
  513. }
  514. }
  515. $guid = safe_ascii($item->get_id(false, false));
  516. unset($item);
  517. $authorNames = '';
  518. if (is_array($authors)) {
  519. foreach ($authors as $author) {
  520. $authorName = $author->name != '' ? $author->name : $author->email;
  521. if ($authorName != '') {
  522. $authorNames .= escapeToUnicodeAlternative(strip_tags($authorName), true) . '; ';
  523. }
  524. }
  525. }
  526. $authorNames = substr($authorNames, 0, -2);
  527. $entry = new FreshRSS_Entry(
  528. $this->id(),
  529. $hasBadGuids ? '' : $guid,
  530. $title == '' ? '' : $title,
  531. $authorNames,
  532. $content == '' ? '' : $content,
  533. $link == '' ? '' : $link,
  534. $date ? $date : time()
  535. );
  536. $entry->_tags($tags);
  537. $entry->_feed($this);
  538. $entry->hash(); //Must be computed before loading full content
  539. $entry->loadCompleteContent(); // Optionally load full content for truncated feeds
  540. yield $entry;
  541. }
  542. }
  543. /**
  544. * @return SimplePie|null
  545. */
  546. public function loadHtmlXpath(bool $loadDetails = false, bool $noCache = false) {
  547. if ($this->url == '') {
  548. return null;
  549. }
  550. $feedSourceUrl = htmlspecialchars_decode($this->url, ENT_QUOTES);
  551. if ($this->httpAuth != '') {
  552. $feedSourceUrl = preg_replace('#((.+)://)(.+)#', '${1}' . $this->httpAuth . '@${3}', $feedSourceUrl);
  553. }
  554. // Same naming conventions than https://rss-bridge.github.io/rss-bridge/Bridge_API/XPathAbstract.html
  555. // https://rss-bridge.github.io/rss-bridge/Bridge_API/BridgeAbstract.html#collectdata
  556. /** @var array<string,string> */
  557. $xPathSettings = $this->attributes('xpath');
  558. $xPathFeedTitle = $xPathSettings['feedTitle'] ?? '';
  559. $xPathItem = $xPathSettings['item'] ?? '';
  560. $xPathItemTitle = $xPathSettings['itemTitle'] ?? '';
  561. $xPathItemContent = $xPathSettings['itemContent'] ?? '';
  562. $xPathItemUri = $xPathSettings['itemUri'] ?? '';
  563. $xPathItemAuthor = $xPathSettings['itemAuthor'] ?? '';
  564. $xPathItemTimestamp = $xPathSettings['itemTimestamp'] ?? '';
  565. $xPathItemTimeFormat = $xPathSettings['itemTimeFormat'] ?? '';
  566. $xPathItemThumbnail = $xPathSettings['itemThumbnail'] ?? '';
  567. $xPathItemCategories = $xPathSettings['itemCategories'] ?? '';
  568. $xPathItemUid = $xPathSettings['itemUid'] ?? '';
  569. if ($xPathItem == '') {
  570. return null;
  571. }
  572. $cachePath = FreshRSS_Feed::cacheFilename($feedSourceUrl, $this->attributes(), FreshRSS_Feed::KIND_HTML_XPATH);
  573. $html = httpGet($feedSourceUrl, $cachePath, 'html', $this->attributes());
  574. if (strlen($html) <= 0) {
  575. return null;
  576. }
  577. $view = new FreshRSS_View();
  578. $view->_path('index/rss.phtml');
  579. $view->internal_rendering = true;
  580. $view->rss_url = $feedSourceUrl;
  581. $view->entries = [];
  582. try {
  583. $doc = new DOMDocument();
  584. $doc->recover = true;
  585. $doc->strictErrorChecking = false;
  586. $doc->loadHTML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING);
  587. $xpath = new DOMXPath($doc);
  588. $view->rss_title = $xPathFeedTitle == '' ? $this->name() :
  589. htmlspecialchars(@$xpath->evaluate('normalize-space(' . $xPathFeedTitle . ')'), ENT_COMPAT, 'UTF-8');
  590. $view->rss_base = htmlspecialchars(trim($xpath->evaluate('normalize-space(//base/@href)')), ENT_COMPAT, 'UTF-8');
  591. $nodes = $xpath->query($xPathItem);
  592. if (empty($nodes)) {
  593. return null;
  594. }
  595. foreach ($nodes as $node) {
  596. $item = [];
  597. $item['title'] = $xPathItemTitle == '' ? '' : @$xpath->evaluate('normalize-space(' . $xPathItemTitle . ')', $node);
  598. $item['content'] = '';
  599. if ($xPathItemContent != '') {
  600. $result = @$xpath->evaluate($xPathItemContent, $node);
  601. if ($result instanceof DOMNodeList) {
  602. // List of nodes, save as HTML
  603. $content = '';
  604. foreach ($result as $child) {
  605. $content .= $doc->saveHTML($child) . "\n";
  606. }
  607. $item['content'] = $content;
  608. } else {
  609. // Typed expression, save as-is
  610. $item['content'] = strval($result);
  611. }
  612. }
  613. $item['link'] = $xPathItemUri == '' ? '' : @$xpath->evaluate('normalize-space(' . $xPathItemUri . ')', $node);
  614. $item['author'] = $xPathItemAuthor == '' ? '' : @$xpath->evaluate('normalize-space(' . $xPathItemAuthor . ')', $node);
  615. $item['timestamp'] = $xPathItemTimestamp == '' ? '' : @$xpath->evaluate('normalize-space(' . $xPathItemTimestamp . ')', $node);
  616. if ($xPathItemTimeFormat != '') {
  617. $dateTime = DateTime::createFromFormat($xPathItemTimeFormat, $item['timestamp'] ?? '');
  618. if ($dateTime != false) {
  619. $item['timestamp'] = $dateTime->format(DateTime::ATOM);
  620. }
  621. }
  622. $item['thumbnail'] = $xPathItemThumbnail == '' ? '' : @$xpath->evaluate('normalize-space(' . $xPathItemThumbnail . ')', $node);
  623. if ($xPathItemCategories != '') {
  624. $itemCategories = @$xpath->query($xPathItemCategories, $node);
  625. if ($itemCategories) {
  626. foreach ($itemCategories as $itemCategory) {
  627. $item['categories'][] = $itemCategory->textContent;
  628. }
  629. }
  630. }
  631. if ($xPathItemUid != '') {
  632. $item['guid'] = @$xpath->evaluate('normalize-space(' . $xPathItemUid . ')', $node);
  633. }
  634. if (empty($item['guid'])) {
  635. $item['guid'] = 'urn:sha1:' . sha1($item['title'] . $item['content'] . $item['link']);
  636. }
  637. if ($item['title'] != '' || $item['content'] != '' || $item['link'] != '') {
  638. // HTML-encoding/escaping of the relevant fields (all except 'content')
  639. foreach (['author', 'categories', 'guid', 'link', 'thumbnail', 'timestamp', 'title'] as $key) {
  640. if (!empty($item[$key])) {
  641. $item[$key] = Minz_Helper::htmlspecialchars_utf8($item[$key]);
  642. }
  643. }
  644. // CDATA protection
  645. $item['content'] = str_replace(']]>', ']]&gt;', $item['content']);
  646. $view->entries[] = FreshRSS_Entry::fromArray($item);
  647. }
  648. }
  649. } catch (Exception $ex) {
  650. Minz_Log::warning($ex->getMessage());
  651. return null;
  652. }
  653. $simplePie = customSimplePie();
  654. $simplePie->set_raw_data($view->renderToString());
  655. $simplePie->init();
  656. return $simplePie;
  657. }
  658. /**
  659. * To keep track of some new potentially unread articles since last commit+fetch from database
  660. */
  661. public function incPendingUnread(int $n = 1) {
  662. $this->nbPendingNotRead += $n;
  663. }
  664. /**
  665. * Remember to call updateCachedValue($id_feed) or updateCachedValues() just after.
  666. * @return int|false the number of lines affected, or false if not applicable
  667. */
  668. public function keepMaxUnread() {
  669. $keepMaxUnread = $this->attributes('keep_max_n_unread');
  670. if ($keepMaxUnread === null) {
  671. $keepMaxUnread = FreshRSS_Context::$user_conf->mark_when['max_n_unread'];
  672. }
  673. if ($keepMaxUnread > 0 && $this->nbNotRead(false) + $this->nbPendingNotRead > $keepMaxUnread) {
  674. $feedDAO = FreshRSS_Factory::createFeedDao();
  675. return $feedDAO->keepMaxUnread($this->id(), max(0, $keepMaxUnread - $this->nbPendingNotRead));
  676. }
  677. return false;
  678. }
  679. /**
  680. * Applies the *mark as read upon gone* policy, if enabled.
  681. * Remember to call updateCachedValue($id_feed) or updateCachedValues() just after.
  682. * @return int|false the number of lines affected, or false if not applicable
  683. */
  684. public function markAsReadUponGone() {
  685. $readUponGone = $this->attributes('read_upon_gone');
  686. if ($readUponGone === null) {
  687. $readUponGone = FreshRSS_Context::$user_conf->mark_when['gone'];
  688. }
  689. if ($readUponGone) {
  690. $feedDAO = FreshRSS_Factory::createFeedDao();
  691. return $feedDAO->markAsReadUponGone($this->id());
  692. }
  693. return false;
  694. }
  695. /**
  696. * Remember to call updateCachedValue($id_feed) or updateCachedValues() just after
  697. */
  698. public function cleanOldEntries() {
  699. $archiving = $this->attributes('archiving');
  700. if ($archiving == null) {
  701. $catDAO = FreshRSS_Factory::createCategoryDao();
  702. $category = $catDAO->searchById($this->categoryId);
  703. $archiving = $category == null ? null : $category->attributes('archiving');
  704. if ($archiving == null) {
  705. $archiving = FreshRSS_Context::$user_conf->archiving;
  706. }
  707. }
  708. if (is_array($archiving)) {
  709. $entryDAO = FreshRSS_Factory::createEntryDao();
  710. $nb = $entryDAO->cleanOldEntries($this->id(), $archiving);
  711. if ($nb > 0) {
  712. $needFeedCacheRefresh = true;
  713. Minz_Log::debug($nb . ' entries cleaned in feed [' . $this->url(false) . '] with: ' . json_encode($archiving));
  714. }
  715. return $nb;
  716. }
  717. return false;
  718. }
  719. public static function cacheFilename(string $url, array $attributes, int $kind = FreshRSS_Feed::KIND_RSS): string {
  720. $simplePie = customSimplePie($attributes);
  721. $filename = $simplePie->get_cache_filename($url);
  722. if ($kind == FreshRSS_Feed::KIND_HTML_XPATH) {
  723. return CACHE_PATH . '/' . $filename . '.html';
  724. } else {
  725. return CACHE_PATH . '/' . $filename . '.spc';
  726. }
  727. }
  728. public function clearCache(): bool {
  729. return @unlink(FreshRSS_Feed::cacheFilename($this->url, $this->attributes(), $this->kind));
  730. }
  731. /** @return int|false */
  732. public function cacheModifiedTime() {
  733. return @filemtime(FreshRSS_Feed::cacheFilename($this->url, $this->attributes(), $this->kind));
  734. }
  735. public function lock(): bool {
  736. $this->lockPath = TMP_PATH . '/' . $this->hash() . '.freshrss.lock';
  737. if (file_exists($this->lockPath) && ((time() - @filemtime($this->lockPath)) > 3600)) {
  738. @unlink($this->lockPath);
  739. }
  740. if (($handle = @fopen($this->lockPath, 'x')) === false) {
  741. return false;
  742. }
  743. //register_shutdown_function('unlink', $this->lockPath);
  744. @fclose($handle);
  745. return true;
  746. }
  747. public function unlock(): bool {
  748. return @unlink($this->lockPath);
  749. }
  750. /**
  751. * @return array<FreshRSS_FilterAction>
  752. */
  753. public function filterActions(): array {
  754. if (empty($this->filterActions)) {
  755. $this->filterActions = array();
  756. $filters = $this->attributes('filters');
  757. if (is_array($filters)) {
  758. foreach ($filters as $filter) {
  759. $filterAction = FreshRSS_FilterAction::fromJSON($filter);
  760. if ($filterAction != null) {
  761. $this->filterActions[] = $filterAction;
  762. }
  763. }
  764. }
  765. }
  766. return $this->filterActions;
  767. }
  768. /**
  769. * @param array<FreshRSS_FilterAction> $filterActions
  770. */
  771. private function _filterActions($filterActions) {
  772. $this->filterActions = $filterActions;
  773. if (is_array($this->filterActions) && !empty($this->filterActions)) {
  774. $this->_attributes('filters', array_map(function ($af) {
  775. return $af == null ? null : $af->toJSON();
  776. }, $this->filterActions));
  777. } else {
  778. $this->_attributes('filters', null);
  779. }
  780. }
  781. /** @return array<FreshRSS_BooleanSearch> */
  782. public function filtersAction(string $action): array {
  783. $action = trim($action);
  784. if ($action == '') {
  785. return array();
  786. }
  787. $filters = array();
  788. $filterActions = $this->filterActions();
  789. for ($i = count($filterActions) - 1; $i >= 0; $i--) {
  790. $filterAction = $filterActions[$i];
  791. if ($filterAction != null && $filterAction->booleanSearch() != null &&
  792. $filterAction->actions() != null && in_array($action, $filterAction->actions(), true)) {
  793. $filters[] = $filterAction->booleanSearch();
  794. }
  795. }
  796. return $filters;
  797. }
  798. /**
  799. * @param array<string> $filters
  800. */
  801. public function _filtersAction(string $action, $filters) {
  802. $action = trim($action);
  803. if ($action == '' || !is_array($filters)) {
  804. return false;
  805. }
  806. $filters = array_unique(array_map('trim', $filters));
  807. $filterActions = $this->filterActions();
  808. //Check existing filters
  809. for ($i = count($filterActions) - 1; $i >= 0; $i--) {
  810. $filterAction = $filterActions[$i];
  811. if ($filterAction == null || !is_array($filterAction->actions()) ||
  812. $filterAction->booleanSearch() == null || trim($filterAction->booleanSearch()->getRawInput()) == '') {
  813. array_splice($filterActions, $i, 1);
  814. continue;
  815. }
  816. $actions = $filterAction->actions();
  817. //Remove existing rules with same action
  818. for ($j = count($actions) - 1; $j >= 0; $j--) {
  819. if ($actions[$j] === $action) {
  820. array_splice($actions, $j, 1);
  821. }
  822. }
  823. //Update existing filter with new action
  824. for ($k = count($filters) - 1; $k >= 0; $k --) {
  825. $filter = $filters[$k];
  826. if ($filter === $filterAction->booleanSearch()->getRawInput()) {
  827. $actions[] = $action;
  828. array_splice($filters, $k, 1);
  829. }
  830. }
  831. //Save result
  832. if (empty($actions)) {
  833. array_splice($filterActions, $i, 1);
  834. } else {
  835. $filterAction->_actions($actions);
  836. }
  837. }
  838. //Add new filters
  839. for ($k = count($filters) - 1; $k >= 0; $k --) {
  840. $filter = $filters[$k];
  841. if ($filter != '') {
  842. $filterAction = FreshRSS_FilterAction::fromJSON(array(
  843. 'search' => $filter,
  844. 'actions' => array($action),
  845. ));
  846. if ($filterAction != null) {
  847. $filterActions[] = $filterAction;
  848. }
  849. }
  850. }
  851. if (empty($filterActions)) {
  852. $filterActions = null;
  853. }
  854. $this->_filterActions($filterActions);
  855. }
  856. //<WebSub>
  857. public function pubSubHubbubEnabled(): bool {
  858. $url = $this->selfUrl ? $this->selfUrl : $this->url;
  859. $hubFilename = PSHB_PATH . '/feeds/' . sha1($url) . '/!hub.json';
  860. if ($hubFile = @file_get_contents($hubFilename)) {
  861. $hubJson = json_decode($hubFile, true);
  862. if ($hubJson && empty($hubJson['error']) &&
  863. (empty($hubJson['lease_end']) || $hubJson['lease_end'] > time())) {
  864. return true;
  865. }
  866. }
  867. return false;
  868. }
  869. public function pubSubHubbubError(bool $error = true): bool {
  870. $url = $this->selfUrl ? $this->selfUrl : $this->url;
  871. $hubFilename = PSHB_PATH . '/feeds/' . sha1($url) . '/!hub.json';
  872. $hubFile = @file_get_contents($hubFilename);
  873. $hubJson = $hubFile ? json_decode($hubFile, true) : array();
  874. if (!isset($hubJson['error']) || $hubJson['error'] !== (bool)$error) {
  875. $hubJson['error'] = (bool)$error;
  876. file_put_contents($hubFilename, json_encode($hubJson));
  877. Minz_Log::warning('Set error to ' . ($error ? 1 : 0) . ' for ' . $url, PSHB_LOG);
  878. }
  879. return false;
  880. }
  881. /**
  882. * @return string|false
  883. */
  884. public function pubSubHubbubPrepare() {
  885. $key = '';
  886. if (Minz_Request::serverIsPublic(FreshRSS_Context::$system_conf->base_url) &&
  887. $this->hubUrl && $this->selfUrl && @is_dir(PSHB_PATH)) {
  888. $path = PSHB_PATH . '/feeds/' . sha1($this->selfUrl);
  889. $hubFilename = $path . '/!hub.json';
  890. if ($hubFile = @file_get_contents($hubFilename)) {
  891. $hubJson = json_decode($hubFile, true);
  892. if (!$hubJson || empty($hubJson['key']) || !ctype_xdigit($hubJson['key'])) {
  893. $text = 'Invalid JSON for WebSub: ' . $this->url;
  894. Minz_Log::warning($text);
  895. Minz_Log::warning($text, PSHB_LOG);
  896. return false;
  897. }
  898. if ((!empty($hubJson['lease_end'])) && ($hubJson['lease_end'] < (time() + (3600 * 23)))) { //TODO: Make a better policy
  899. $text = 'WebSub lease ends at '
  900. . date('c', empty($hubJson['lease_end']) ? time() : $hubJson['lease_end'])
  901. . ' and needs renewal: ' . $this->url;
  902. Minz_Log::warning($text);
  903. Minz_Log::warning($text, PSHB_LOG);
  904. $key = $hubJson['key']; //To renew our lease
  905. } elseif (((!empty($hubJson['error'])) || empty($hubJson['lease_end'])) &&
  906. (empty($hubJson['lease_start']) || $hubJson['lease_start'] < time() - (3600 * 23))) { //Do not renew too often
  907. $key = $hubJson['key']; //To renew our lease
  908. }
  909. } else {
  910. @mkdir($path, 0777, true);
  911. $key = sha1($path . FreshRSS_Context::$system_conf->salt);
  912. $hubJson = array(
  913. 'hub' => $this->hubUrl,
  914. 'key' => $key,
  915. );
  916. file_put_contents($hubFilename, json_encode($hubJson));
  917. @mkdir(PSHB_PATH . '/keys/');
  918. file_put_contents(PSHB_PATH . '/keys/' . $key . '.txt', $this->selfUrl);
  919. $text = 'WebSub prepared for ' . $this->url;
  920. Minz_Log::debug($text);
  921. Minz_Log::debug($text, PSHB_LOG);
  922. }
  923. $currentUser = Minz_Session::param('currentUser');
  924. if (FreshRSS_user_Controller::checkUsername($currentUser) && !file_exists($path . '/' . $currentUser . '.txt')) {
  925. touch($path . '/' . $currentUser . '.txt');
  926. }
  927. }
  928. return $key;
  929. }
  930. //Parameter true to subscribe, false to unsubscribe.
  931. public function pubSubHubbubSubscribe(bool $state): bool {
  932. if ($state) {
  933. $url = $this->selfUrl ? $this->selfUrl : $this->url;
  934. } else {
  935. $url = $this->url; //Always use current URL during unsubscribe
  936. }
  937. if ($url && (Minz_Request::serverIsPublic(FreshRSS_Context::$system_conf->base_url) || !$state)) {
  938. $hubFilename = PSHB_PATH . '/feeds/' . sha1($url) . '/!hub.json';
  939. $hubFile = @file_get_contents($hubFilename);
  940. if ($hubFile === false) {
  941. Minz_Log::warning('JSON not found for WebSub: ' . $this->url);
  942. return false;
  943. }
  944. $hubJson = json_decode($hubFile, true);
  945. if (!$hubJson || empty($hubJson['key']) || !ctype_xdigit($hubJson['key']) || empty($hubJson['hub'])) {
  946. Minz_Log::warning('Invalid JSON for WebSub: ' . $this->url);
  947. return false;
  948. }
  949. $callbackUrl = checkUrl(Minz_Request::getBaseUrl() . '/api/pshb.php?k=' . $hubJson['key']);
  950. if ($callbackUrl == '') {
  951. Minz_Log::warning('Invalid callback for WebSub: ' . $this->url);
  952. return false;
  953. }
  954. if (!$state) { //unsubscribe
  955. $hubJson['lease_end'] = time() - 60;
  956. file_put_contents($hubFilename, json_encode($hubJson));
  957. }
  958. $ch = curl_init();
  959. curl_setopt_array($ch, [
  960. CURLOPT_URL => $hubJson['hub'],
  961. CURLOPT_RETURNTRANSFER => true,
  962. CURLOPT_POSTFIELDS => http_build_query(array(
  963. 'hub.verify' => 'sync',
  964. 'hub.mode' => $state ? 'subscribe' : 'unsubscribe',
  965. 'hub.topic' => $url,
  966. 'hub.callback' => $callbackUrl,
  967. )),
  968. CURLOPT_USERAGENT => FRESHRSS_USERAGENT,
  969. CURLOPT_MAXREDIRS => 10,
  970. CURLOPT_FOLLOWLOCATION => true,
  971. CURLOPT_ENCODING => '', //Enable all encodings
  972. ]);
  973. $response = curl_exec($ch);
  974. $info = curl_getinfo($ch);
  975. Minz_Log::warning('WebSub ' . ($state ? 'subscribe' : 'unsubscribe') . ' to ' . $url .
  976. ' via hub ' . $hubJson['hub'] .
  977. ' with callback ' . $callbackUrl . ': ' . $info['http_code'] . ' ' . $response, PSHB_LOG);
  978. if (substr('' . $info['http_code'], 0, 1) == '2') {
  979. return true;
  980. } else {
  981. $hubJson['lease_start'] = time(); //Prevent trying again too soon
  982. $hubJson['error'] = true;
  983. file_put_contents($hubFilename, json_encode($hubJson));
  984. return false;
  985. }
  986. }
  987. return false;
  988. }
  989. //</WebSub>
  990. }