Feed.php 39 KB

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