Feed.php 50 KB

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