Feed.php 51 KB

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