Feed.php 34 KB

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