Feed.php 52 KB

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