Feed.php 38 KB

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