Feed.php 40 KB

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