Feed.php 47 KB

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