Feed.php 33 KB

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