Feed.php 47 KB

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