Feed.php 31 KB

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