Feed.php 51 KB

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