Feed.php 34 KB

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