Feed.php 33 KB

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