Feed.php 34 KB

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