Feed.php 33 KB

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