Feed.php 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493
  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_DOTNOTATION = 30;
  32. /** JSON embedded in HTML */
  33. public const KIND_HTML_XPATH_JSON_DOTNOTATION = 35;
  34. public const PRIORITY_IMPORTANT = 20;
  35. public const PRIORITY_MAIN_STREAM = 10;
  36. public const PRIORITY_CATEGORY = 0;
  37. public const PRIORITY_FEED = -5;
  38. public const PRIORITY_HIDDEN = -10;
  39. #[Deprecated('Use PRIORITY_HIDDEN instead')]
  40. public const PRIORITY_ARCHIVED = -10;
  41. public const TTL_DEFAULT = 0;
  42. public const ARCHIVING_RETENTION_COUNT_LIMIT = 10000;
  43. public const ARCHIVING_RETENTION_PERIOD = 'P3M';
  44. private int $id = 0;
  45. private string $url = '';
  46. private int $kind = 0;
  47. private int $categoryId = 0;
  48. private ?FreshRSS_Category $category = null;
  49. private int $nbEntries = -1;
  50. private int $nbNotRead = -1;
  51. private string $name = '';
  52. private string $website = '';
  53. private string $description = '';
  54. private int $lastUpdate = 0;
  55. private int $priority = self::PRIORITY_MAIN_STREAM;
  56. private string $pathEntries = '';
  57. private string $httpAuth = '';
  58. private int $error = 0;
  59. private int $ttl = self::TTL_DEFAULT;
  60. private bool $mute = false;
  61. private string $hash = '';
  62. private string $hashFavicon = '';
  63. private string $lockPath = '';
  64. private string $hubUrl = '';
  65. private string $selfUrl = '';
  66. /**
  67. * @throws FreshRSS_BadUrl_Exception
  68. */
  69. public function __construct(string $url, bool $validate = true) {
  70. if ($validate) {
  71. $this->_url($url);
  72. } else {
  73. $this->url = $url;
  74. }
  75. }
  76. public static function default(): FreshRSS_Feed {
  77. $f = new FreshRSS_Feed('http://example.net/', false);
  78. $f->faviconPrepare();
  79. return $f;
  80. }
  81. public function id(): int {
  82. return $this->id;
  83. }
  84. public function hash(): string {
  85. if ($this->hash == '') {
  86. $salt = FreshRSS_Context::systemConf()->salt;
  87. $params = $this->url . $this->proxyParam();
  88. $this->hash = sha1($salt . $params);
  89. }
  90. return $this->hash;
  91. }
  92. public function resetFaviconHash(): void {
  93. $this->hashFavicon(skipCache: true);
  94. }
  95. public function proxyParam(): string {
  96. $curl_params = FreshRSS_http_Util::sanitizeCurlParams($this->attributeArray('curl_params') ?? []);
  97. return is_string($curl_params[CURLOPT_PROXY] ?? null) ? $curl_params[CURLOPT_PROXY] : '';
  98. }
  99. /**
  100. * Resets the custom favicon to the default one. Also deletes the favicon when allowed by extension.
  101. *
  102. * @param array{'url'?:string,'kind'?:int,'category'?:int,'name'?:string,'website'?:string,'description'?:string,'lastUpdate'?:int,'priority'?:int,
  103. * 'pathEntries'?:string,'httpAuth'?:string,'error'?:int,'ttl'?:int,'attributes'?:string|array<string,mixed>} &$values &$values
  104. *
  105. * @param bool $updateFeed Whether `updateFeed()` should be called immediately. If false, it must be handled manually.
  106. *
  107. * @return void
  108. *
  109. * @throws FreshRSS_Feed_Exception
  110. */
  111. public function resetCustomFavicon(?array &$values = null, bool $updateFeed = true) {
  112. if (!$this->customFavicon()) {
  113. return;
  114. }
  115. if (!$this->attributeBoolean('customFaviconDisallowDel')) {
  116. FreshRSS_Feed::faviconDelete($this->hashFavicon());
  117. }
  118. $this->_attribute('customFavicon', false);
  119. $this->_attribute('customFaviconExt', null);
  120. $this->_attribute('customFaviconDisallowDel', false);
  121. if ($values !== null) {
  122. $values['attributes'] = $this->attributes();
  123. $feedDAO = FreshRSS_Factory::createFeedDao();
  124. if ($updateFeed && !$feedDAO->updateFeed($this->id(), $values)) {
  125. throw new FreshRSS_Feed_Exception();
  126. }
  127. }
  128. $this->resetFaviconHash();
  129. }
  130. /**
  131. * Set a custom favicon for the feed.
  132. *
  133. * @param string $contents Contents of the favicon file. Optional if $tmpPath is set.
  134. * @param string $tmpPath Use only when handling file uploads. (value from `tmp_name` goes here)
  135. *
  136. * @param array{'url'?:string,'kind'?:int,'category'?:int,'name'?:string,'website'?:string,'description'?:string,'lastUpdate'?:int,'priority'?:int,
  137. * 'pathEntries'?:string,'httpAuth'?:string,'error'?:int,'ttl'?:int,'attributes'?:string|array<string,mixed>} &$values &$values
  138. *
  139. * @param bool $updateFeed Whether `updateFeed()` should be called immediately. If false, it must be handled manually.
  140. * @param string $extName The extension name of the calling extension.
  141. * @param bool $disallowDelete Whether the icon can be later deleted when it's being reset. Intended for use by extensions.
  142. * @param bool $overrideCustomIcon Whether a custom favicon set by a user can be overridden.
  143. *
  144. * @return string|null Path where the favicon can be found. Useful for checking if the favicon already exists, before downloading it for example.
  145. *
  146. * @throws FreshRSS_UnsupportedImageFormat_Exception
  147. * @throws FreshRSS_Feed_Exception
  148. */
  149. public function setCustomFavicon(
  150. ?string $contents = null,
  151. string $tmpPath = '',
  152. ?array &$values = null,
  153. bool $updateFeed = true,
  154. ?string $extName = null,
  155. bool $disallowDelete = false,
  156. bool $overrideCustomIcon = false
  157. ): ?string {
  158. if ($contents === null && $tmpPath !== '') {
  159. $contents = file_get_contents($tmpPath);
  160. }
  161. $attributesOnly = $contents === null && $tmpPath === '';
  162. require_once LIB_PATH . '/favicons.php';
  163. if (!$attributesOnly && !isImgMime(is_string($contents) ? $contents : '')) {
  164. throw new FreshRSS_UnsupportedImageFormat_Exception();
  165. }
  166. $oldHash = '';
  167. $oldDisallowDelete = false;
  168. if ($this->customFavicon()) {
  169. /* If $overrideCustomFavicon is true, custom favicons set by extensions can be overridden,
  170. * but not ones explicitly set by the user */
  171. if (!$overrideCustomIcon && $this->customFaviconExt() === null) {
  172. return null;
  173. }
  174. $oldHash = $this->hashFavicon(skipCache: true);
  175. $oldDisallowDelete = $this->attributeBoolean('customFaviconDisallowDel');
  176. }
  177. $this->_attribute('customFavicon', true);
  178. $this->_attribute('customFaviconExt', $extName);
  179. $this->_attribute('customFaviconDisallowDel', $disallowDelete);
  180. $newPath = FAVICONS_DIR . $this->hashFavicon(skipCache: true) . '.ico';
  181. if ($attributesOnly && !file_exists($newPath)) {
  182. $updateFeed = false;
  183. }
  184. if ($values !== null) {
  185. $values['attributes'] = $this->attributes();
  186. $feedDAO = FreshRSS_Factory::createFeedDao();
  187. if ($updateFeed && !$feedDAO->updateFeed($this->id(), $values)) {
  188. throw new FreshRSS_Feed_Exception();
  189. }
  190. }
  191. if ($tmpPath !== '') {
  192. move_uploaded_file($tmpPath, $newPath);
  193. } elseif ($contents !== null) {
  194. file_put_contents($newPath, $contents);
  195. }
  196. if ($oldHash !== '' && !$oldDisallowDelete) {
  197. FreshRSS_Feed::faviconDelete($oldHash);
  198. }
  199. return $newPath;
  200. }
  201. /**
  202. * Checks if the feed has a custom favicon set by an extension.
  203. * Additionally, it also checks if the extension that set the icon is still enabled
  204. * And if not, it resets attributes related to custom favicons.
  205. *
  206. * @return string|null The name of the extension that set the icon.
  207. */
  208. public function customFaviconExt(): ?string {
  209. $customFaviconExt = $this->attributeString('customFaviconExt');
  210. if ($customFaviconExt !== null && !Minz_ExtensionManager::isExtensionEnabled($customFaviconExt)) {
  211. $this->_attribute('customFavicon', false);
  212. $this->_attribute('customFaviconExt', null);
  213. $this->_attribute('customFaviconDisallowDel', false);
  214. $customFaviconExt = null;
  215. }
  216. return $customFaviconExt;
  217. }
  218. public function customFavicon(): bool {
  219. $this->customFaviconExt();
  220. return $this->attributeBoolean('customFavicon') ?? false;
  221. }
  222. public function hashFavicon(bool $skipCache = false): string {
  223. if ($this->hashFavicon == '' || $skipCache) {
  224. $salt = FreshRSS_Context::systemConf()->salt;
  225. $params = '';
  226. if ($this->customFavicon()) {
  227. $current = $this->id . Minz_User::name();
  228. $hookParams = Minz_ExtensionManager::callHook(Minz_HookType::CustomFaviconHash, $this);
  229. $params = $hookParams !== null ? $hookParams : $current;
  230. } else {
  231. $feedIconUrl = $this->attributeString('feedIconUrl') ?? '';
  232. $params = $feedIconUrl !== '' ? $feedIconUrl . $this->proxyParam()
  233. : $this->website(fallback: true) . $this->proxyParam();
  234. }
  235. $this->hashFavicon = hash('crc32b', $salt . (is_string($params) ? $params : ''));
  236. }
  237. return $this->hashFavicon;
  238. }
  239. public function url(bool $includeCredentials = true): string {
  240. return $includeCredentials ? $this->url : \SimplePie\Misc::url_remove_credentials($this->url);
  241. }
  242. public function selfUrl(): string {
  243. return $this->selfUrl;
  244. }
  245. public function kind(): int {
  246. return $this->kind;
  247. }
  248. public function hubUrl(): string {
  249. return $this->hubUrl;
  250. }
  251. public function category(): ?FreshRSS_Category {
  252. if ($this->category === null && $this->categoryId > 0) {
  253. $catDAO = FreshRSS_Factory::createCategoryDao();
  254. $this->category = $catDAO->searchById($this->categoryId);
  255. }
  256. return $this->category;
  257. }
  258. public function categoryId(): int {
  259. return $this->category?->id() ?: $this->categoryId;
  260. }
  261. public function name(bool $raw = false): string {
  262. return $raw || $this->name != '' ? $this->name : (preg_replace('%^https?://(www[.])?%i', '', $this->url) ?? '');
  263. }
  264. /**
  265. * @param bool $fallback true to return the URL of the feed if the Web site is blank
  266. * @return string HTML-encoded URL of the Web site of the feed
  267. */
  268. public function website(bool $fallback = false): string {
  269. $url = $this->website;
  270. if ($fallback && !preg_match('%^https?://.%i', $url)) {
  271. $url = $this->url;
  272. }
  273. return $url;
  274. }
  275. public function description(): string {
  276. return $this->description;
  277. }
  278. public function lastUpdate(): int {
  279. return $this->lastUpdate;
  280. }
  281. public function priority(): int {
  282. return $this->priority;
  283. }
  284. public function showUnreadCount(): bool {
  285. $sucGlobal = FreshRSS_Context::userConf()->show_unread_count;
  286. $isImportant = $this->priority >= self::PRIORITY_IMPORTANT;
  287. if ($isImportant && $sucGlobal !== 'none') {
  288. return true;
  289. }
  290. return $this->attributeBoolean('show_unread_count') ??
  291. $this->category()?->attributeBoolean('show_unread_count') ??
  292. ($sucGlobal === 'all' || ($sucGlobal === 'important' && $isImportant));
  293. }
  294. /** @return string HTML-encoded CSS selector */
  295. public function pathEntries(): string {
  296. return $this->pathEntries;
  297. }
  298. /**
  299. * @phpstan-return ($raw is true ? string : array{'username':string,'password':string})
  300. * @return array{'username':string,'password':string}|string
  301. */
  302. public function httpAuth(bool $raw = true): array|string {
  303. if ($raw) {
  304. return $this->httpAuth;
  305. } else {
  306. $pos_colon = strpos($this->httpAuth, ':');
  307. if ($pos_colon !== false) {
  308. $user = substr($this->httpAuth, 0, $pos_colon);
  309. $pass = substr($this->httpAuth, $pos_colon + 1);
  310. } else {
  311. $user = '';
  312. $pass = '';
  313. }
  314. return [
  315. 'username' => $user,
  316. 'password' => $pass,
  317. ];
  318. }
  319. }
  320. /** @return array<int,mixed> */
  321. public function curlOptions(): array {
  322. $curl_options = [];
  323. if ($this->httpAuth !== '') {
  324. $curl_options[CURLOPT_USERPWD] = htmlspecialchars_decode($this->httpAuth, ENT_QUOTES);
  325. }
  326. return $curl_options;
  327. }
  328. /**
  329. * Timestamp of last update error.
  330. * Legacy: may return 1 if the feed has an error but the timestamp is not available.
  331. */
  332. public function lastError(): int {
  333. return $this->error;
  334. }
  335. /**
  336. * If the feed has an error
  337. */
  338. public function inError(): bool {
  339. return $this->error > 0;
  340. }
  341. /**
  342. * @param bool $raw true for database version combined with mute information, false otherwise
  343. */
  344. public function ttl(bool $raw = false): int {
  345. if ($raw) {
  346. $ttl = $this->ttl;
  347. if ($this->mute && FreshRSS_Feed::TTL_DEFAULT === $ttl) {
  348. $ttl = FreshRSS_Context::userConf()->ttl_default;
  349. }
  350. return $ttl * ($this->mute ? -1 : 1);
  351. }
  352. if ($this->mute && $this->ttl === FreshRSS_Context::userConf()->ttl_default) {
  353. return FreshRSS_Feed::TTL_DEFAULT;
  354. }
  355. return $this->ttl;
  356. }
  357. public function mute(): bool {
  358. return $this->mute;
  359. }
  360. public function nbEntries(): int {
  361. if ($this->nbEntries < 0) {
  362. $feedDAO = FreshRSS_Factory::createFeedDao();
  363. $this->nbEntries = $feedDAO->countEntries($this->id());
  364. }
  365. return $this->nbEntries;
  366. }
  367. public function nbNotRead(): int {
  368. if ($this->nbNotRead < 0) {
  369. $feedDAO = FreshRSS_Factory::createFeedDao();
  370. $this->nbNotRead = $feedDAO->countNotRead($this->id());
  371. }
  372. return $this->nbNotRead;
  373. }
  374. /** @return int Timestamp of the newest article received for this feed, or 0 if none */
  375. public function newestArticleReceivedDate(): int {
  376. static $newestArticleReceivedDate = null;
  377. if (!is_int($newestArticleReceivedDate)) {
  378. $feedDAO = FreshRSS_Factory::createFeedDao();
  379. $newestArticleReceivedDate = $feedDAO->newestArticleReceivedDate($this->id());
  380. }
  381. return $newestArticleReceivedDate;
  382. }
  383. /** @return int Timestamp of the Last article published for this feed, or 0 if none */
  384. public function newestArticlePublicationDate(): int {
  385. static $newestArticlePublicationDate = null;
  386. if (!is_int($newestArticlePublicationDate)) {
  387. $feedDAO = FreshRSS_Factory::createFeedDao();
  388. $newestArticlePublicationDate = $feedDAO->newestArticlePublicationDate($this->id());
  389. }
  390. return $newestArticlePublicationDate;
  391. }
  392. public function faviconPrepare(bool $force = false): void {
  393. require_once LIB_PATH . '/favicons.php';
  394. if ($this->customFavicon()) {
  395. return;
  396. }
  397. $feedIconUrl = $this->attributeString('feedIconUrl') ?? '';
  398. $websiteUrl = $this->website(fallback: false);
  399. if ($websiteUrl === '' || $websiteUrl === $this->url) {
  400. // Get root URL from the feed URL
  401. $websiteUrl = preg_replace('%^(https?://[^/]+).*$%i', '$1/', $this->url) ?? $this->url;
  402. }
  403. $url = $feedIconUrl !== '' ? $feedIconUrl : $websiteUrl;
  404. $txt = FAVICONS_DIR . $this->hashFavicon() . '.txt';
  405. if (@file_get_contents($txt) !== $url) {
  406. file_put_contents($txt, $url);
  407. }
  408. if (FreshRSS_Context::$isCli || $force) {
  409. $ico = FAVICONS_DIR . $this->hashFavicon() . '.ico';
  410. $ico_mtime = @filemtime($ico);
  411. $txt_mtime = @filemtime($txt);
  412. if ($txt_mtime != false &&
  413. ($ico_mtime == false || $ico_mtime < $txt_mtime || ($ico_mtime < time() - (14 * 86400)))) {
  414. // no ico file or we should download a new one.
  415. if ($feedIconUrl !== '' && download_favicon_from_image_url($feedIconUrl, $ico)) {
  416. return;
  417. }
  418. // Fall back to website favicon search
  419. if (!download_favicon($websiteUrl, $ico)) {
  420. touch($ico);
  421. }
  422. }
  423. }
  424. }
  425. public static function faviconDelete(string $hash): void {
  426. if (!ctype_xdigit($hash)) {
  427. return;
  428. }
  429. $path = DATA_PATH . '/favicons/' . $hash;
  430. @unlink($path . '.ico');
  431. @unlink($path . '.txt');
  432. }
  433. public function favicon(bool $absolute = false): string {
  434. $hash = $this->hashFavicon();
  435. $url = '/f.php?h=' . $hash;
  436. if ($this->customFavicon()
  437. // when the below attribute is set, icon won't be changing frequently so cache buster is not needed
  438. && !$this->attributeBoolean('customFaviconDisallowDel')) {
  439. $url .= '&t=' . @filemtime(DATA_PATH . '/favicons/' . $hash . '.ico');
  440. }
  441. return Minz_Url::display($url, absolute: $absolute);
  442. }
  443. public function _id(int $value): void {
  444. $this->id = $value;
  445. }
  446. /**
  447. * @throws FreshRSS_BadUrl_Exception
  448. */
  449. public function _url(string $value, bool $validate = true): void {
  450. $this->hash = '';
  451. $this->hashFavicon = '';
  452. $url = $value;
  453. if ($validate) {
  454. $url = FreshRSS_http_Util::checkUrl($url);
  455. }
  456. if ($url == false) {
  457. throw new FreshRSS_BadUrl_Exception($value);
  458. }
  459. $this->url = $url;
  460. }
  461. public function _selfUrl(string $value): void {
  462. $this->selfUrl = $value;
  463. }
  464. public function _kind(int $value): void {
  465. $this->kind = $value;
  466. }
  467. public function _category(?FreshRSS_Category $cat): void {
  468. $this->category = $cat;
  469. $this->categoryId = $this->category == null ? 0 : $this->category->id();
  470. }
  471. /** @param int|numeric-string $id */
  472. public function _categoryId(int|string $id): void {
  473. $this->category = null;
  474. $this->categoryId = (int)$id;
  475. }
  476. public function _name(string $value): void {
  477. $this->name = $value == '' ? '' : trim($value);
  478. }
  479. public function _website(string $value, bool $validate = true): void {
  480. $this->hashFavicon = '';
  481. if ($validate) {
  482. $value = FreshRSS_http_Util::checkUrl($value);
  483. }
  484. if ($value == false) {
  485. $value = '';
  486. }
  487. $this->website = $value;
  488. }
  489. public function _description(string $value): void {
  490. $this->description = $value == '' ? '' : $value;
  491. }
  492. /**
  493. * @param int|numeric-string $value
  494. * 32-bit systems provide a string and will fail in year 2038
  495. */
  496. public function _lastUpdate(int|string $value): void {
  497. $this->lastUpdate = (int)$value;
  498. }
  499. public function _priority(int $value): void {
  500. $this->priority = $value;
  501. }
  502. /** @param string $value HTML-encoded CSS selector */
  503. public function _pathEntries(string $value): void {
  504. $this->pathEntries = $value;
  505. }
  506. public function _httpAuth(string $value): void {
  507. $this->httpAuth = $value;
  508. }
  509. public function _error(int $value): void {
  510. $this->error = $value;
  511. }
  512. public function _mute(bool $value): void {
  513. $this->mute = $value;
  514. }
  515. public function _ttl(int $value): void {
  516. $value = min($value, 100_000_000);
  517. $this->ttl = abs($value);
  518. $this->mute = $value < self::TTL_DEFAULT;
  519. }
  520. public function _nbNotRead(int $value): void {
  521. $this->nbNotRead = $value;
  522. }
  523. public function _nbEntries(int $value): void {
  524. $this->nbEntries = $value;
  525. }
  526. public function defaultSort(): ?string {
  527. return $this->attributeString('defaultSort');
  528. }
  529. public function defaultOrder(): ?string {
  530. return $this->attributeString('defaultOrder');
  531. }
  532. /**
  533. * @throws Minz_FileNotExistException
  534. * @throws FreshRSS_Feed_Exception
  535. */
  536. public function load(bool $loadDetails = false, bool $noCache = false): ?FreshRSS_SimplePieCustom {
  537. if ($this->url != '') {
  538. /**
  539. * @throws Minz_FileNotExistException
  540. */
  541. if (trim(CACHE_PATH) === '') {
  542. throw new Minz_FileNotExistException(
  543. 'CACHE_PATH',
  544. Minz_Exception::ERROR
  545. );
  546. } else {
  547. if (($retryAfter = FreshRSS_http_Util::getRetryAfter($this->url, $this->proxyParam())) > 0) {
  548. throw new FreshRSS_Feed_Exception('For that domain, will first retry after ' . date('c', $retryAfter) .
  549. '. ' . $this->url(includeCredentials: false), code: 503);
  550. }
  551. $simplePie = new FreshRSS_SimplePieCustom($this->attributes(), $this->curlOptions());
  552. $url = htmlspecialchars_decode($this->url, ENT_QUOTES);
  553. if (str_ends_with($url, '#force_feed')) {
  554. $simplePie->force_feed(true);
  555. $url = substr($url, 0, -11);
  556. }
  557. $simplePie->set_feed_url($url);
  558. if (!$loadDetails) { //Only activates auto-discovery when adding a new feed
  559. $simplePie->set_autodiscovery_level(\SimplePie\SimplePie::LOCATOR_NONE);
  560. }
  561. if ($this->attributeBoolean('clear_cache')) {
  562. // Do not use `$simplePie->enable_cache(false);` as it would prevent caching in multiuser context
  563. $this->clearCache();
  564. }
  565. Minz_ExtensionManager::callHook(Minz_HookType::SimplepieBeforeInit, $simplePie, $this);
  566. $simplePieResult = $simplePie->init();
  567. Minz_ExtensionManager::callHook(Minz_HookType::SimplepieAfterInit, $simplePie, $this, $simplePieResult);
  568. if ($simplePieResult === false || $simplePie->get_hash() === '' || !empty($simplePie->error())) {
  569. if ($simplePie->status_code() === 429) {
  570. $errorMessage = 'HTTP 429 Too Many Requests!';
  571. } elseif ($simplePie->status_code() === 503) {
  572. $errorMessage = 'HTTP 503 Service Unavailable!';
  573. } else {
  574. $errorMessage = $simplePie->error();
  575. if (empty($errorMessage)) {
  576. $errorMessage = '';
  577. } elseif (is_array($errorMessage)) {
  578. $errorMessage = json_encode($errorMessage, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_LINE_TERMINATORS) ?: '';
  579. }
  580. }
  581. throw new FreshRSS_Feed_Exception(
  582. ($errorMessage == '' ? 'Unknown error for feed' : $errorMessage) .
  583. ' [' . $this->url(includeCredentials: false) . ']',
  584. $simplePie->status_code()
  585. );
  586. }
  587. $links = $simplePie->get_links('self');
  588. $this->selfUrl = empty($links[0]) ? '' : (FreshRSS_http_Util::checkUrl($links[0]) ?: '');
  589. $links = $simplePie->get_links('hub');
  590. $this->hubUrl = empty($links[0]) ? '' : (FreshRSS_http_Util::checkUrl($links[0]) ?: '');
  591. if ($loadDetails) {
  592. // si on a utilisé l’auto-discover, notre url va avoir changé
  593. $subscribe_url = $simplePie->subscribe_url(false) ?? '';
  594. if ($this->name(true) === '') {
  595. //HTML to HTML-PRE //ENT_COMPAT except '&'
  596. $title = strtr(html_only_entity_decode($simplePie->get_title()), ['<' => '&lt;', '>' => '&gt;', '"' => '&quot;']);
  597. $this->_name($title == '' ? $this->url : $title);
  598. }
  599. if ($this->website() === '') {
  600. $this->_website(html_only_entity_decode($simplePie->get_link()));
  601. }
  602. if ($this->description() === '') {
  603. $this->_description(html_only_entity_decode($simplePie->get_description()));
  604. }
  605. } else {
  606. //The case of HTTP 301 Moved Permanently
  607. $subscribe_url = $simplePie->subscribe_url(true) ?? '';
  608. }
  609. $clean_url = \SimplePie\Misc::url_remove_credentials($subscribe_url);
  610. if ($subscribe_url !== '' && $subscribe_url !== $url) {
  611. $this->_url($clean_url);
  612. }
  613. if ($noCache || $simplePie->get_hash() !== $this->attributeString('SimplePieHash')) {
  614. // syslog(LOG_DEBUG, 'FreshRSS no cache ' . $simplePie->get_hash() . ' !== ' . $this->attributeString('SimplePieHash') . ' for ' . $clean_url);
  615. $this->_attribute('SimplePieHash', $simplePie->get_hash());
  616. return $simplePie;
  617. }
  618. syslog(LOG_DEBUG, 'FreshRSS SimplePie uses cache for ' . $clean_url);
  619. }
  620. }
  621. return null;
  622. }
  623. /**
  624. * Decide the GUID of an entry based on the feed’s policy.
  625. * @param \SimplePie\Item $item The item to decide the GUID for.
  626. * @param bool $fallback Whether to automatically switch to the next policy in case of blank GUID.
  627. * @return string The decided GUID for the entry.
  628. */
  629. protected function decideEntryGuid(\SimplePie\Item $item, bool $fallback = false): string {
  630. $unicityCriteria = $this->attributeString('unicityCriteria');
  631. if ($this->attributeBoolean('hasBadGuids')) { // Legacy
  632. $unicityCriteria = 'link';
  633. }
  634. $entryId = safe_ascii($item->get_id(false, false));
  635. $guid = match ($unicityCriteria) {
  636. null => $entryId,
  637. 'link' => $item->get_permalink() ?? '',
  638. 'sha1:link_published' => sha1($item->get_permalink() . $item->get_date('U')),
  639. 'sha1:link_published_title' => sha1($item->get_permalink() . $item->get_date('U') . $item->get_title()),
  640. 'sha1:link_published_title_content' => sha1($item->get_permalink() . $item->get_date('U') . $item->get_title() . $item->get_content()),
  641. 'sha1:title' => sha1($item->get_title() ?? ''),
  642. 'sha1:title_published' => sha1($item->get_title() . $item->get_date('U')),
  643. 'sha1:title_published_content' => sha1($item->get_title() . $item->get_date('U') . $item->get_content()),
  644. 'sha1:content' => sha1($item->get_content() ?? ''),
  645. 'sha1:content_published' => sha1($item->get_content() . $item->get_date('U')),
  646. 'sha1:published' => sha1((string)($item->get_date('U') ?? '')),
  647. default => $entryId,
  648. };
  649. $blankHash = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'; // sha1('')
  650. if ($guid === $blankHash) {
  651. $guid = '';
  652. }
  653. if ($fallback && $guid === '') {
  654. if ($entryId !== '') {
  655. $guid = $entryId;
  656. } elseif (($item->get_permalink() ?? '') !== '') {
  657. $guid = sha1($item->get_permalink() . $item->get_date('U'));
  658. } elseif (($item->get_title() ?? '') !== '') {
  659. $guid = sha1($item->get_permalink() . $item->get_date('U') . $item->get_title());
  660. } else {
  661. $guid = sha1($item->get_permalink() . $item->get_date('U') . $item->get_title() . $item->get_content());
  662. }
  663. if ($guid === $blankHash) {
  664. $guid = '';
  665. }
  666. }
  667. return $guid;
  668. }
  669. /**
  670. * @param float $invalidGuidsTolerance (default 0.05) The maximum ratio (rounded) of invalid GUIDs to tolerate before degrading the unicity criteria.
  671. * Example for 0.05 (5% rounded): tolerate 0 invalid GUIDs for up to 9 articles, 1 for 10, 2 for 30, 3 for 50, 4 for 70, 5 for 90, 6 for 110, etc.
  672. * The default value of 5% rounded was chosen to allow 1 invalid GUID for feeds of 10 articles, which is a frequently observed amount of articles.
  673. * @return list<string>
  674. */
  675. public function loadGuids(FreshRSS_SimplePieCustom $simplePie, float $invalidGuidsTolerance = 0.05): array {
  676. $invalidGuids = 0;
  677. $testGuids = [];
  678. $guids = [];
  679. $items = $simplePie->get_items();
  680. if (empty($items)) {
  681. return $guids;
  682. }
  683. for ($i = count($items) - 1; $i >= 0; $i--) {
  684. $item = $items[$i];
  685. if ($item == null) {
  686. continue;
  687. }
  688. $guid = $this->decideEntryGuid($item, fallback: true);
  689. if ($guid === '' || !empty($testGuids['_' . $guid])) {
  690. $invalidGuids++;
  691. Minz_Log::debug('Invalid GUID [' . $guid . '] for feed ' . $this->url);
  692. }
  693. $testGuids['_' . $guid] = true;
  694. $guids[] = $guid;
  695. }
  696. if ($invalidGuids > 0) {
  697. Minz_Log::warning("Feed has {$invalidGuids} invalid GUIDs: " . $this->url(includeCredentials: false));
  698. if (!$this->attributeBoolean('unicityCriteriaForced') && $invalidGuids > round($invalidGuidsTolerance * count($items))) {
  699. $unicityCriteria = $this->attributeString('unicityCriteria');
  700. if ($this->attributeBoolean('hasBadGuids')) { // Legacy
  701. $unicityCriteria = 'link';
  702. }
  703. // Automatic fallback to next (degraded) unicity criteria
  704. $newUnicityCriteria = match ($unicityCriteria) {
  705. null => 'sha1:link_published',
  706. 'link' => 'sha1:link_published',
  707. 'sha1:link_published' => 'sha1:link_published_title',
  708. default => $unicityCriteria,
  709. };
  710. if ($newUnicityCriteria !== $unicityCriteria) {
  711. $this->_attribute('hasBadGuids', null); // Remove legacy
  712. $this->_attribute('unicityCriteria', $newUnicityCriteria);
  713. Minz_Log::warning('Feed unicity policy degraded (' . ($unicityCriteria ?: 'id') . ' → ' . $newUnicityCriteria . '): ' .
  714. $this->url(includeCredentials: false));
  715. return $this->loadGuids($simplePie, $invalidGuidsTolerance);
  716. }
  717. }
  718. $this->_error(time());
  719. }
  720. return $guids;
  721. }
  722. /** @return Traversable<FreshRSS_Entry> */
  723. public function loadEntries(FreshRSS_SimplePieCustom $simplePie): Traversable {
  724. $items = $simplePie->get_items();
  725. if (empty($items)) {
  726. return;
  727. }
  728. // We want chronological order and SimplePie uses reverse order.
  729. for ($i = count($items) - 1; $i >= 0; $i--) {
  730. $item = $items[$i];
  731. if ($item == null) {
  732. continue;
  733. }
  734. $title = html_only_entity_decode(strip_tags($item->get_title() ?? ''));
  735. $authors = $item->get_authors();
  736. $link = $item->get_permalink();
  737. $date = $item->get_date('U');
  738. if (!is_numeric($date)) {
  739. $date = 0;
  740. }
  741. //Tag processing (tag == category)
  742. $categories = $item->get_categories();
  743. $tags = [];
  744. if (is_array($categories)) {
  745. foreach ($categories as $category) {
  746. $text = html_only_entity_decode($category->get_label());
  747. //Some feeds use a single category with comma-separated tags
  748. $labels = explode(',', $text);
  749. if (!empty($labels)) {
  750. foreach ($labels as $label) {
  751. $tags[] = trim($label);
  752. }
  753. }
  754. }
  755. $tags = array_unique($tags);
  756. }
  757. $content = html_only_entity_decode($item->get_content());
  758. $attributeThumbnail = $item->get_thumbnail() ?? [];
  759. if (empty($attributeThumbnail['url'])) {
  760. $attributeThumbnail['url'] = '';
  761. }
  762. $attributeEnclosures = [];
  763. if (!empty($item->get_enclosures())) {
  764. foreach ($item->get_enclosures() as $enclosure) {
  765. $elink = $enclosure->get_link();
  766. if ($elink != '') {
  767. $etitle = $enclosure->get_title() ?? '';
  768. $credits = $enclosure->get_credits() ?? null;
  769. $description = $enclosure->get_description() ?? '';
  770. $mime = strtolower($enclosure->get_type() ?? '');
  771. $medium = strtolower($enclosure->get_medium() ?? '');
  772. $height = $enclosure->get_height();
  773. $width = $enclosure->get_width();
  774. $length = $enclosure->get_length();
  775. $attributeEnclosure = [
  776. 'url' => $elink,
  777. ];
  778. if ($etitle != '') {
  779. $attributeEnclosure['title'] = $etitle;
  780. }
  781. if (is_array($credits)) {
  782. $attributeEnclosure['credit'] = [];
  783. foreach ($credits as $credit) {
  784. $attributeEnclosure['credit'][] = $credit->get_name();
  785. }
  786. }
  787. if ($description != '') {
  788. $attributeEnclosure['description'] = $description;
  789. }
  790. if ($mime != '') {
  791. $attributeEnclosure['type'] = $mime;
  792. }
  793. if ($medium != '') {
  794. $attributeEnclosure['medium'] = $medium;
  795. }
  796. if ($length != '') {
  797. $attributeEnclosure['length'] = (int)$length;
  798. }
  799. if ($height != '') {
  800. $attributeEnclosure['height'] = (int)$height;
  801. }
  802. if ($width != '') {
  803. $attributeEnclosure['width'] = (int)$width;
  804. }
  805. if (!empty($enclosure->get_thumbnails())) {
  806. foreach ($enclosure->get_thumbnails() as $thumbnail) {
  807. if ($thumbnail !== $attributeThumbnail['url']) {
  808. $attributeEnclosure['thumbnails'][] = $thumbnail;
  809. }
  810. }
  811. }
  812. $attributeEnclosures[] = $attributeEnclosure;
  813. }
  814. }
  815. }
  816. $guid = $this->decideEntryGuid($item, fallback: true);
  817. unset($item);
  818. $authorNames = '';
  819. if (is_array($authors)) {
  820. foreach ($authors as $author) {
  821. $authorName = $author->name != '' ? $author->name : $author->email;
  822. if (is_string($authorName) && $authorName !== '') {
  823. $authorNames .= html_only_entity_decode(strip_tags($authorName)) . '; ';
  824. }
  825. }
  826. }
  827. $authorNames = substr($authorNames, 0, -2) ?: '';
  828. $entry = new FreshRSS_Entry(
  829. $this->id(),
  830. $guid,
  831. $title == '' ? '' : $title,
  832. $authorNames,
  833. $content == '' ? '' : $content,
  834. $link == null ? '' : $link,
  835. $date ?: time()
  836. );
  837. $entry->_tags($tags);
  838. $entry->_feed($this);
  839. if (!empty($attributeThumbnail['url'])) {
  840. $entry->_attribute('thumbnail', $attributeThumbnail);
  841. }
  842. $entry->_attribute('enclosures', $attributeEnclosures);
  843. $entry->hash(); //Must be computed before loading full content
  844. $entry->loadCompleteContent(); // Optionally load full content for truncated feeds
  845. yield $entry;
  846. }
  847. }
  848. /**
  849. * Given a feed content generated from a FreshRSS_View
  850. * returns a SimplePie initialized already with that content
  851. * @param string $feedContent the content of the feed, typically generated via FreshRSS_View::renderToString()
  852. */
  853. private function simplePieFromContent(string $feedContent): FreshRSS_SimplePieCustom {
  854. $simplePie = new FreshRSS_SimplePieCustom();
  855. $simplePie->enable_cache(false);
  856. $simplePie->set_raw_data($feedContent);
  857. $simplePie->init();
  858. return $simplePie;
  859. }
  860. /** @return array<string,string> */
  861. private function dotNotationForStandardJsonFeed(): array {
  862. return [
  863. 'feedTitle' => 'title',
  864. 'feedImage' => 'icon',
  865. 'feedImageFallback' => 'favicon',
  866. 'item' => 'items',
  867. 'itemTitle' => 'title',
  868. 'itemContent' => 'content_text',
  869. 'itemContentHTML' => 'content_html',
  870. 'itemUri' => 'url',
  871. 'itemTimestamp' => 'date_published',
  872. 'itemTimeFormat' => DateTimeInterface::RFC3339_EXTENDED,
  873. 'itemThumbnail' => 'image',
  874. 'itemCategories' => 'tags',
  875. 'itemUid' => 'id',
  876. 'itemAttachment' => 'attachments',
  877. 'itemAttachmentUrl' => 'url',
  878. 'itemAttachmentType' => 'mime_type',
  879. 'itemAttachmentLength' => 'size_in_bytes',
  880. ];
  881. }
  882. private function extractJsonFromHtml(string $html): ?string {
  883. $xPathToJson = $this->attributeString('xPathToJson') ?? '';
  884. if ($xPathToJson === '') {
  885. return null;
  886. }
  887. $doc = new DOMDocument();
  888. $doc->recover = true;
  889. $doc->strictErrorChecking = false;
  890. if (!$doc->loadHTML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING)) {
  891. return null;
  892. }
  893. $xpath = new DOMXPath($doc);
  894. $jsonFragments = @$xpath->evaluate($xPathToJson);
  895. if ($jsonFragments === false) {
  896. return null;
  897. }
  898. if (is_string($jsonFragments)) {
  899. return $jsonFragments;
  900. }
  901. if ($jsonFragments instanceof DOMNodeList && $jsonFragments->length > 0) {
  902. // If the result is a list, then aggregate as a JSON array
  903. $result = [];
  904. foreach ($jsonFragments as $node) {
  905. if (!($node instanceof DOMNode)) {
  906. continue;
  907. }
  908. $json = json_decode($node->textContent, true);
  909. if (json_last_error() === JSON_ERROR_NONE && is_array($json)) {
  910. $result[] = $json;
  911. }
  912. }
  913. return json_encode($result, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?: null;
  914. }
  915. return null;
  916. }
  917. public function loadJson(): ?FreshRSS_SimplePieCustom {
  918. if ($this->url == '') {
  919. return null;
  920. }
  921. $feedSourceUrl = htmlspecialchars_decode($this->url, ENT_QUOTES);
  922. if ($feedSourceUrl == null) {
  923. return null;
  924. }
  925. $httpAccept = $this->kind() === FreshRSS_Feed::KIND_HTML_XPATH_JSON_DOTNOTATION ? 'html' : 'json';
  926. $content = FreshRSS_http_Util::httpGet($feedSourceUrl, $this->cacheFilename(), $httpAccept, $this->attributes(), $this->curlOptions())['body'];
  927. if (strlen($content) <= 0) {
  928. return null;
  929. }
  930. if ($this->kind() === FreshRSS_Feed::KIND_HTML_XPATH_JSON_DOTNOTATION) {
  931. $content = $this->extractJsonFromHtml($content);
  932. if ($content == null) {
  933. return null;
  934. }
  935. }
  936. //check if the content is actual JSON
  937. $jf = json_decode($content, true);
  938. if (json_last_error() !== JSON_ERROR_NONE || !is_array($jf)) {
  939. return null;
  940. }
  941. /** @var array<string,string> $json_dotnotation */
  942. $json_dotnotation = $this->attributeArray('json_dotnotation') ?? [];
  943. $dotnotations = $this->kind() === FreshRSS_Feed::KIND_JSONFEED ? $this->dotNotationForStandardJsonFeed() : $json_dotnotation;
  944. $feedContent = FreshRSS_dotNotation_Util::convertJsonToRss($jf, $feedSourceUrl, $dotnotations, $this->name());
  945. if ($feedContent == null) {
  946. return null;
  947. }
  948. return $this->simplePieFromContent($feedContent);
  949. }
  950. public function loadHtmlXpath(): ?FreshRSS_SimplePieCustom {
  951. if ($this->url == '') {
  952. return null;
  953. }
  954. $feedSourceUrl = htmlspecialchars_decode($this->url, ENT_QUOTES);
  955. if ($feedSourceUrl == null) {
  956. return null;
  957. }
  958. // Same naming conventions than https://rss-bridge.github.io/rss-bridge/Bridge_API/XPathAbstract.html
  959. // https://rss-bridge.github.io/rss-bridge/Bridge_API/BridgeAbstract.html#collectdata
  960. /** @var array<string,string> $xPathSettings */
  961. $xPathSettings = $this->attributeArray('xpath');
  962. $xPathFeedTitle = $xPathSettings['feedTitle'] ?? '';
  963. $xPathItem = $xPathSettings['item'] ?? '';
  964. $xPathItemTitle = $xPathSettings['itemTitle'] ?? '';
  965. $xPathItemContent = $xPathSettings['itemContent'] ?? '';
  966. $xPathItemUri = $xPathSettings['itemUri'] ?? '';
  967. $xPathItemAuthor = $xPathSettings['itemAuthor'] ?? '';
  968. $xPathItemTimestamp = $xPathSettings['itemTimestamp'] ?? '';
  969. $xPathItemTimeFormat = $xPathSettings['itemTimeFormat'] ?? '';
  970. $xPathItemThumbnail = $xPathSettings['itemThumbnail'] ?? '';
  971. $xPathItemCategories = $xPathSettings['itemCategories'] ?? '';
  972. $xPathItemUid = $xPathSettings['itemUid'] ?? '';
  973. if ($xPathItem == '') {
  974. return null;
  975. }
  976. $httpAccept = $this->kind() === FreshRSS_Feed::KIND_XML_XPATH ? 'xml' : 'html';
  977. $html = FreshRSS_http_Util::httpGet($feedSourceUrl, $this->cacheFilename(), $httpAccept, $this->attributes(), $this->curlOptions())['body'];
  978. if (strlen($html) <= 0) {
  979. return null;
  980. }
  981. $view = new FreshRSS_View();
  982. $view->_path('index/rss.phtml');
  983. $view->internal_rendering = true;
  984. $view->rss_url = htmlspecialchars($feedSourceUrl, ENT_COMPAT, 'UTF-8');
  985. $view->html_url = $view->rss_url;
  986. $view->entries = [];
  987. try {
  988. $doc = new DOMDocument();
  989. $doc->recover = true;
  990. $doc->strictErrorChecking = false;
  991. $ok = false;
  992. switch ($this->kind()) {
  993. case FreshRSS_Feed::KIND_HTML_XPATH:
  994. $ok = $doc->loadHTML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING) !== false;
  995. break;
  996. case FreshRSS_Feed::KIND_XML_XPATH:
  997. $ok = $doc->loadXML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING) !== false;
  998. break;
  999. }
  1000. if (!$ok) {
  1001. return null;
  1002. }
  1003. $xpath = new DOMXPath($doc);
  1004. $xpathEvaluateString = function (string $expression, ?DOMNode $contextNode = null) use ($xpath): string {
  1005. $result = @$xpath->evaluate('normalize-space(' . $expression . ')', $contextNode);
  1006. return is_string($result) ? $result : '';
  1007. };
  1008. $view->rss_title = $xPathFeedTitle == '' ? $this->name() :
  1009. htmlspecialchars($xpathEvaluateString($xPathFeedTitle), ENT_COMPAT, 'UTF-8');
  1010. $view->rss_base = htmlspecialchars(trim($xpathEvaluateString('//base/@href')), ENT_COMPAT, 'UTF-8');
  1011. $nodes = $xpath->query($xPathItem);
  1012. if ($nodes === false || $nodes->length === 0) {
  1013. return null;
  1014. }
  1015. foreach ($nodes as $node) {
  1016. if (!($node instanceof DOMNode)) {
  1017. continue;
  1018. }
  1019. $item = [];
  1020. $item['title'] = $xPathItemTitle == '' ? '' : $xpathEvaluateString($xPathItemTitle, $node);
  1021. $item['content'] = '';
  1022. if ($xPathItemContent != '') {
  1023. $result = @$xpath->evaluate($xPathItemContent, $node);
  1024. if ($result instanceof DOMNodeList) {
  1025. // List of nodes, save as HTML
  1026. $content = '';
  1027. foreach ($result as $child) {
  1028. if ($child instanceof DOMNode) {
  1029. $content .= $doc->saveHTML($child) . "\n";
  1030. }
  1031. }
  1032. $item['content'] = $content;
  1033. } elseif (is_string($result) || is_int($result) || is_bool($result)) {
  1034. // Typed expression, save as-is
  1035. $item['content'] = (string)$result;
  1036. }
  1037. }
  1038. $item['link'] = $xPathItemUri == '' ? '' : $xpathEvaluateString($xPathItemUri, $node);
  1039. $item['author'] = $xPathItemAuthor == '' ? '' : $xpathEvaluateString($xPathItemAuthor, $node);
  1040. $item['timestamp'] = $xPathItemTimestamp == '' ? '' : $xpathEvaluateString($xPathItemTimestamp, $node);
  1041. if ($xPathItemTimeFormat != '') {
  1042. if ($xPathItemTimeFormat === 'U' && strlen($item['timestamp']) > 10) {
  1043. // Compatibility with Unix timestamp in milliseconds
  1044. $item['timestamp'] = substr($item['timestamp'], 0, -3);
  1045. }
  1046. $dateTime = DateTime::createFromFormat($xPathItemTimeFormat, $item['timestamp']);
  1047. if ($dateTime != false) {
  1048. $item['timestamp'] = $dateTime->format(DateTime::ATOM);
  1049. }
  1050. }
  1051. $item['thumbnail'] = $xPathItemThumbnail == '' ? '' : $xpathEvaluateString($xPathItemThumbnail, $node);
  1052. if ($xPathItemCategories != '') {
  1053. $itemCategories = @$xpath->evaluate($xPathItemCategories, $node);
  1054. if (is_string($itemCategories) && $itemCategories !== '') {
  1055. $item['tags'] = [$itemCategories];
  1056. } elseif ($itemCategories instanceof DOMNodeList && $itemCategories->length > 0) {
  1057. $item['tags'] = [];
  1058. foreach ($itemCategories as $itemCategory) {
  1059. if ($itemCategory instanceof DOMNode) {
  1060. $item['tags'][] = $itemCategory->textContent;
  1061. }
  1062. }
  1063. }
  1064. }
  1065. if ($xPathItemUid != '') {
  1066. $item['guid'] = $xpathEvaluateString($xPathItemUid, $node);
  1067. }
  1068. if (empty($item['guid'])) {
  1069. $item['guid'] = 'urn:sha1:' . sha1($item['title'] . $item['content'] . $item['link']);
  1070. }
  1071. if ($item['title'] != '' || $item['content'] != '' || $item['link'] != '') {
  1072. // HTML-encoding/escaping of the relevant fields (all except 'content')
  1073. foreach (['author', 'guid', 'link', 'thumbnail', 'timestamp', 'title'] as $key) {
  1074. if (isset($item[$key])) {
  1075. $item[$key] = htmlspecialchars($item[$key], ENT_COMPAT, 'UTF-8');
  1076. }
  1077. }
  1078. if (isset($item['tags'])) {
  1079. $item['tags'] = Minz_Helper::htmlspecialchars_utf8($item['tags']);
  1080. }
  1081. // CDATA protection
  1082. $item['content'] = str_replace(']]>', ']]&gt;', $item['content']);
  1083. $view->entries[] = FreshRSS_Entry::fromArray($item);
  1084. }
  1085. }
  1086. } catch (Exception $ex) {
  1087. Minz_Log::warning($ex->getMessage());
  1088. return null;
  1089. }
  1090. return $this->simplePieFromContent($view->renderToString());
  1091. }
  1092. /**
  1093. * @return int|null The max number of unread articles to keep, or null if disabled.
  1094. */
  1095. public function keepMaxUnread(): ?int {
  1096. $keepMaxUnread = $this->attributeInt('keep_max_n_unread');
  1097. if ($keepMaxUnread === null) {
  1098. $keepMaxUnread = FreshRSS_Context::userConf()->mark_when['max_n_unread'];
  1099. }
  1100. return is_int($keepMaxUnread) && $keepMaxUnread >= 0 ? $keepMaxUnread : null;
  1101. }
  1102. /**
  1103. * @return int|false The number of articles marked as read, of false if error
  1104. */
  1105. public function markAsReadMaxUnread(): int|false {
  1106. $keepMaxUnread = $this->keepMaxUnread();
  1107. if ($keepMaxUnread === null) {
  1108. return false;
  1109. }
  1110. $feedDAO = FreshRSS_Factory::createFeedDao();
  1111. $affected = $feedDAO->markAsReadMaxUnread($this->id(), $keepMaxUnread);
  1112. return $affected;
  1113. }
  1114. /**
  1115. * Applies the *mark as read upon gone* policy, if enabled.
  1116. * Remember to call `updateCachedValues($id_feed)` or `updateCachedValues()` just after.
  1117. * @return int|false the number of lines affected, or false if not applicable
  1118. */
  1119. public function markAsReadUponGone(bool $upstreamIsEmpty, int $minLastSeen = 0): int|false {
  1120. $readUponGone = $this->attributeBoolean('read_upon_gone');
  1121. if ($readUponGone === null) {
  1122. $readUponGone = FreshRSS_Context::userConf()->mark_when['gone'];
  1123. }
  1124. if (!$readUponGone) {
  1125. return false;
  1126. }
  1127. if ($upstreamIsEmpty) {
  1128. if ($minLastSeen <= 0) {
  1129. $minLastSeen = time();
  1130. }
  1131. $entryDAO = FreshRSS_Factory::createEntryDao();
  1132. $affected = $entryDAO->markReadFeed($this->id(), $minLastSeen . '000000');
  1133. } else {
  1134. $feedDAO = FreshRSS_Factory::createFeedDao();
  1135. $affected = $feedDAO->markAsReadNotSeen($this->id(), $minLastSeen);
  1136. }
  1137. if ($affected > 0) {
  1138. Minz_Log::debug(__METHOD__ . " $affected items" . ($upstreamIsEmpty ? ' (all)' : '') . ' [' . $this->url(includeCredentials: false) . ']');
  1139. }
  1140. return $affected;
  1141. }
  1142. /**
  1143. * Remember to call `updateCachedValues($id_feed)` or `updateCachedValues()` just after
  1144. */
  1145. public function cleanOldEntries(): int|false {
  1146. /** @var array<string,bool|int|string>|null $archiving */
  1147. $archiving = $this->attributeArray('archiving');
  1148. if ($archiving === null) {
  1149. $catDAO = FreshRSS_Factory::createCategoryDao();
  1150. $category = $catDAO->searchById($this->categoryId);
  1151. $archiving = $category === null ? null : $category->attributeArray('archiving');
  1152. /** @var array<string,bool|int|string>|null $archiving */
  1153. if ($archiving === null) {
  1154. $archiving = FreshRSS_Context::userConf()->archiving;
  1155. }
  1156. }
  1157. if (is_array($archiving)) {
  1158. $entryDAO = FreshRSS_Factory::createEntryDao();
  1159. $nb = $entryDAO->cleanOldEntries($this->id(), $archiving);
  1160. if ($nb > 0) {
  1161. Minz_Log::debug($nb . ' entries cleaned in feed [' . $this->url(false) . '] with: ' . json_encode($archiving));
  1162. }
  1163. return $nb;
  1164. }
  1165. return false;
  1166. }
  1167. /**
  1168. * @param string $url Overridden URL. Will default to the feed URL.
  1169. * @throws FreshRSS_Context_Exception
  1170. */
  1171. public function cacheFilename(string $url = ''): string {
  1172. $simplePie = new FreshRSS_SimplePieCustom($this->attributes(), $this->curlOptions());
  1173. if ($url !== '') {
  1174. $filename = $simplePie->get_cache_filename($url);
  1175. return CACHE_PATH . '/' . $filename . '.html';
  1176. }
  1177. $url = htmlspecialchars_decode($this->url);
  1178. $filename = $simplePie->get_cache_filename($url);
  1179. switch ($this->kind) {
  1180. case FreshRSS_Feed::KIND_HTML_XPATH:
  1181. return CACHE_PATH . '/' . $filename . '.html';
  1182. case FreshRSS_Feed::KIND_XML_XPATH:
  1183. return CACHE_PATH . '/' . $filename . '.xml';
  1184. case FreshRSS_Feed::KIND_JSON_DOTNOTATION:
  1185. case FreshRSS_Feed::KIND_JSON_XPATH:
  1186. case FreshRSS_Feed::KIND_JSONFEED:
  1187. return CACHE_PATH . '/' . $filename . '.json';
  1188. case FreshRSS_Feed::KIND_RSS:
  1189. case FreshRSS_Feed::KIND_RSS_FORCED:
  1190. default:
  1191. return CACHE_PATH . '/' . $filename . '.spc';
  1192. }
  1193. }
  1194. private function faviconRebuild(): void {
  1195. if ($this->customFavicon()) {
  1196. return;
  1197. }
  1198. FreshRSS_Feed::faviconDelete($this->hashFavicon());
  1199. $this->faviconPrepare(true);
  1200. }
  1201. public function clearCache(): bool {
  1202. $this->faviconRebuild();
  1203. return @unlink($this->cacheFilename());
  1204. }
  1205. /** @return int|false */
  1206. public function cacheModifiedTime(): int|false {
  1207. $filename = $this->cacheFilename();
  1208. clearstatcache(true, $filename);
  1209. return @filemtime($filename);
  1210. }
  1211. public function lock(): bool {
  1212. $this->lockPath = TMP_PATH . '/' . $this->hash() . '.freshrss.lock';
  1213. if (file_exists($this->lockPath) && ((time() - (@filemtime($this->lockPath) ?: 0)) > 3600)) {
  1214. @unlink($this->lockPath);
  1215. }
  1216. if (($handle = @fopen($this->lockPath, 'x')) === false) {
  1217. return false;
  1218. }
  1219. //register_shutdown_function('unlink', $this->lockPath);
  1220. @fclose($handle);
  1221. return true;
  1222. }
  1223. public function unlock(): bool {
  1224. return @unlink($this->lockPath);
  1225. }
  1226. //<WebSub>
  1227. public function pubSubHubbubEnabled(): bool {
  1228. $url = $this->selfUrl ?: $this->url;
  1229. $hubFilename = PSHB_PATH . '/feeds/' . sha1($url) . '/!hub.json';
  1230. if (($hubFile = @file_get_contents($hubFilename)) != false) {
  1231. $hubJson = json_decode($hubFile, true);
  1232. if (is_array($hubJson) && empty($hubJson['error']) &&
  1233. (empty($hubJson['lease_end']) || $hubJson['lease_end'] > time())) {
  1234. return true;
  1235. }
  1236. }
  1237. return false;
  1238. }
  1239. public function pubSubHubbubError(bool $error = true): bool {
  1240. $url = $this->selfUrl ?: $this->url;
  1241. $hubFilename = PSHB_PATH . '/feeds/' . sha1($url) . '/!hub.json';
  1242. $hubFile = @file_get_contents($hubFilename);
  1243. $hubJson = is_string($hubFile) ? json_decode($hubFile, true) : null;
  1244. if (is_array($hubJson) && (!isset($hubJson['error']) || $hubJson['error'] !== $error)) {
  1245. $hubJson['error'] = $error;
  1246. file_put_contents($hubFilename, json_encode($hubJson));
  1247. Minz_Log::warning('Set error to ' . ($error ? 1 : 0) . ' for ' . $url, PSHB_LOG);
  1248. }
  1249. return false;
  1250. }
  1251. private static function isSameHost(string $url1, string $url2): bool {
  1252. $hubHost = parse_url($url1, PHP_URL_HOST);
  1253. $baseHost = parse_url($url2, PHP_URL_HOST);
  1254. return ($hubHost != null && $baseHost != null && strcasecmp($hubHost, $baseHost) === 0);
  1255. }
  1256. public function pubSubHubbubPrepare(): string|false {
  1257. $key = '';
  1258. $baseUrl = FreshRSS_Context::systemConf()->base_url;
  1259. // If they have the same host, they can reach each other (e.g., localhost to localhost)
  1260. if ((Minz_Request::serverIsPublic($baseUrl) || self::isSameHost($this->hubUrl, $baseUrl)) &&
  1261. $this->hubUrl !== '' && $this->selfUrl !== '' && @is_dir(PSHB_PATH)) {
  1262. $path = PSHB_PATH . '/feeds/' . sha1($this->selfUrl);
  1263. $hubFilename = $path . '/!hub.json';
  1264. if (($hubFile = @file_get_contents($hubFilename)) != false) {
  1265. $hubJson = json_decode($hubFile, true);
  1266. if (!is_array($hubJson) || empty($hubJson['key']) || !is_string($hubJson['key']) || !ctype_xdigit($hubJson['key'])) {
  1267. $text = 'Invalid JSON for WebSub: ' . $this->url;
  1268. Minz_Log::warning($text);
  1269. Minz_Log::warning($text, PSHB_LOG);
  1270. return false;
  1271. }
  1272. if (!empty($hubJson['lease_end']) && is_int($hubJson['lease_end']) && $hubJson['lease_end'] < (time() + (3600 * 23))) { //TODO: Make a better policy
  1273. $text = 'WebSub lease ends at '
  1274. . date('c', empty($hubJson['lease_end']) ? time() : $hubJson['lease_end'])
  1275. . ' and needs renewal: ' . $this->url;
  1276. Minz_Log::warning($text);
  1277. Minz_Log::warning($text, PSHB_LOG);
  1278. $key = $hubJson['key']; //To renew our lease
  1279. } elseif (((!empty($hubJson['error'])) || empty($hubJson['lease_end'])) &&
  1280. (empty($hubJson['lease_start']) || $hubJson['lease_start'] < time() - (3600 * 23))) { //Do not renew too often
  1281. $key = $hubJson['key']; //To renew our lease
  1282. }
  1283. } else {
  1284. @mkdir($path, 0770, true);
  1285. $key = sha1($path . FreshRSS_Context::systemConf()->salt);
  1286. $hubJson = [
  1287. 'hub' => $this->hubUrl,
  1288. 'key' => $key,
  1289. ];
  1290. file_put_contents($hubFilename, json_encode($hubJson));
  1291. @mkdir(PSHB_PATH . '/keys/', 0770, true);
  1292. file_put_contents(PSHB_PATH . '/keys/' . $key . '.txt', $this->selfUrl);
  1293. $text = 'WebSub prepared for ' . $this->url;
  1294. Minz_Log::debug($text);
  1295. Minz_Log::debug($text, PSHB_LOG);
  1296. }
  1297. $currentUser = Minz_User::name() ?? '';
  1298. if (FreshRSS_user_Controller::checkUsername($currentUser) && !file_exists($path . '/' . $currentUser . '.txt')) {
  1299. touch($path . '/' . $currentUser . '.txt');
  1300. }
  1301. }
  1302. return $key;
  1303. }
  1304. //Parameter true to subscribe, false to unsubscribe.
  1305. public function pubSubHubbubSubscribe(bool $state): bool {
  1306. if ($state) {
  1307. $url = $this->selfUrl ?: $this->url;
  1308. } else {
  1309. $url = $this->url; //Always use current URL during unsubscribe
  1310. }
  1311. $baseUrl = FreshRSS_Context::systemConf()->base_url;
  1312. // If they have the same host, they can reach each other (e.g., localhost to localhost)
  1313. if ($url !== '' && (Minz_Request::serverIsPublic($baseUrl) || self::isSameHost($url, $baseUrl) || !$state)) {
  1314. $hubFilename = PSHB_PATH . '/feeds/' . sha1($url) . '/!hub.json';
  1315. $hubFile = @file_get_contents($hubFilename);
  1316. if ($hubFile === false) {
  1317. Minz_Log::warning('JSON not found for WebSub: ' . $this->url);
  1318. return false;
  1319. }
  1320. $hubJson = json_decode($hubFile, true);
  1321. if (!is_array($hubJson) || empty($hubJson['key']) || !is_string($hubJson['key']) || !ctype_xdigit($hubJson['key']) ||
  1322. empty($hubJson['hub']) || !is_string($hubJson['hub'])) {
  1323. Minz_Log::warning('Invalid JSON for WebSub: ' . $this->url);
  1324. return false;
  1325. }
  1326. $callbackUrl = FreshRSS_http_Util::checkUrl(Minz_Request::getBaseUrl() . '/api/pshb.php?k=' . $hubJson['key']);
  1327. if ($callbackUrl == '') {
  1328. Minz_Log::warning('Invalid callback for WebSub: ' . $this->url);
  1329. return false;
  1330. }
  1331. if (!$state) { //unsubscribe
  1332. $hubJson['lease_end'] = time() - 60;
  1333. file_put_contents($hubFilename, json_encode($hubJson));
  1334. }
  1335. $response = FreshRSS_http_Util::httpGet($hubJson['hub'], null, 'html', [], [
  1336. CURLOPT_POSTFIELDS => http_build_query([
  1337. 'hub.verify' => 'sync',
  1338. 'hub.mode' => $state ? 'subscribe' : 'unsubscribe',
  1339. 'hub.topic' => $url,
  1340. 'hub.callback' => $callbackUrl,
  1341. ]),
  1342. CURLOPT_MAXREDIRS => 10,
  1343. ]);
  1344. Minz_Log::warning('WebSub ' . ($state ? 'subscribe' : 'unsubscribe') . ' to ' . $url .
  1345. ' via hub ' . $hubJson['hub'] .
  1346. ' with callback ' . $callbackUrl . ': ' . $response['status'] . ' ' . $response['body'], PSHB_LOG);
  1347. if (str_starts_with('' . $response['status'], '2')) {
  1348. return true;
  1349. } else {
  1350. $hubJson['lease_start'] = time(); //Prevent trying again too soon
  1351. $hubJson['error'] = true;
  1352. file_put_contents($hubFilename, json_encode($hubJson));
  1353. return false;
  1354. }
  1355. }
  1356. return false;
  1357. }
  1358. //</WebSub>
  1359. }