Feed.php 47 KB

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