Feed.php 35 KB

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