Feed.php 32 KB

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