Feed.php 52 KB

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