Feed.php 31 KB

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