Feed.php 49 KB

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