Feed.php 34 KB

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