4
0

Feed.php 49 KB

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