Feed.php 34 KB

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