4
0

Feed.php 49 KB

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