Feed.php 55 KB

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