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