Feed.php 38 KB

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