Feed.php 33 KB

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