Feed.php 33 KB

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