Feed.php 46 KB

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