Feed.php 34 KB

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