Feed.php 46 KB

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