Feed.php 51 KB

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