Feed.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  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::$system_conf->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::$user_conf ? FreshRSS_Context::$user_conf->ttl_default : 3600;
  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->attributes('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 !== null && $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->attributes('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. $links[] = $item->get_permalink();
  392. }
  393. if ($hadBadGuids != !$hasUniqueGuids) {
  394. if ($hadBadGuids) {
  395. Minz_Log::warning('Feed has invalid GUIDs: ' . $this->url);
  396. } else {
  397. Minz_Log::warning('Feed has valid GUIDs again: ' . $this->url);
  398. }
  399. $feedDAO = FreshRSS_Factory::createFeedDao();
  400. $feedDAO->updateFeedAttribute($this, 'hasBadGuids', !$hasUniqueGuids);
  401. }
  402. return $hasUniqueGuids ? $guids : $links;
  403. }
  404. /** @return Traversable<FreshRSS_Entry> */
  405. public function loadEntries(SimplePie $simplePie): Traversable {
  406. $hasBadGuids = $this->attributes('hasBadGuids');
  407. $items = $simplePie->get_items();
  408. if (empty($items)) {
  409. return;
  410. }
  411. // We want chronological order and SimplePie uses reverse order.
  412. for ($i = count($items) - 1; $i >= 0; $i--) {
  413. $item = $items[$i];
  414. if ($item == null) {
  415. continue;
  416. }
  417. $title = html_only_entity_decode(strip_tags($item->get_title() ?? ''));
  418. $authors = $item->get_authors();
  419. $link = $item->get_permalink();
  420. $date = @strtotime((string)($item->get_date() ?? '')) ?: 0;
  421. //Tag processing (tag == category)
  422. $categories = $item->get_categories();
  423. $tags = array();
  424. if (is_array($categories)) {
  425. foreach ($categories as $category) {
  426. $text = html_only_entity_decode($category->get_label());
  427. //Some feeds use a single category with comma-separated tags
  428. $labels = explode(',', $text);
  429. if (!empty($labels)) {
  430. foreach ($labels as $label) {
  431. $tags[] = trim($label);
  432. }
  433. }
  434. }
  435. $tags = array_unique($tags);
  436. }
  437. $content = html_only_entity_decode($item->get_content());
  438. $attributeThumbnail = $item->get_thumbnail() ?? [];
  439. if (empty($attributeThumbnail['url'])) {
  440. $attributeThumbnail['url'] = '';
  441. }
  442. $attributeEnclosures = [];
  443. if (!empty($item->get_enclosures())) {
  444. foreach ($item->get_enclosures() as $enclosure) {
  445. $elink = $enclosure->get_link();
  446. if ($elink != '') {
  447. $etitle = $enclosure->get_title() ?? '';
  448. $credit = $enclosure->get_credit() ?? null;
  449. $description = $enclosure->get_description() ?? '';
  450. $mime = strtolower($enclosure->get_type() ?? '');
  451. $medium = strtolower($enclosure->get_medium() ?? '');
  452. $height = $enclosure->get_height();
  453. $width = $enclosure->get_width();
  454. $length = $enclosure->get_length();
  455. $attributeEnclosure = [
  456. 'url' => $elink,
  457. ];
  458. if ($etitle != '') {
  459. $attributeEnclosure['title'] = $etitle;
  460. }
  461. if ($credit != null) {
  462. $attributeEnclosure['credit'] = $credit->get_name();
  463. }
  464. if ($description != '') {
  465. $attributeEnclosure['description'] = $description;
  466. }
  467. if ($mime != '') {
  468. $attributeEnclosure['type'] = $mime;
  469. }
  470. if ($medium != '') {
  471. $attributeEnclosure['medium'] = $medium;
  472. }
  473. if ($length != '') {
  474. $attributeEnclosure['length'] = intval($length);
  475. }
  476. if ($height != '') {
  477. $attributeEnclosure['height'] = intval($height);
  478. }
  479. if ($width != '') {
  480. $attributeEnclosure['width'] = intval($width);
  481. }
  482. if (!empty($enclosure->get_thumbnails())) {
  483. foreach ($enclosure->get_thumbnails() as $thumbnail) {
  484. if ($thumbnail !== $attributeThumbnail['url']) {
  485. $attributeEnclosure['thumbnails'][] = $thumbnail;
  486. }
  487. }
  488. }
  489. $attributeEnclosures[] = $attributeEnclosure;
  490. }
  491. }
  492. }
  493. $guid = safe_ascii($item->get_id(false, false));
  494. unset($item);
  495. $authorNames = '';
  496. if (is_array($authors)) {
  497. foreach ($authors as $author) {
  498. $authorName = $author->name != '' ? $author->name : $author->email;
  499. if ($authorName != '') {
  500. $authorNames .= escapeToUnicodeAlternative(strip_tags($authorName), true) . '; ';
  501. }
  502. }
  503. }
  504. $authorNames = substr($authorNames, 0, -2) ?: '';
  505. $entry = new FreshRSS_Entry(
  506. $this->id(),
  507. $hasBadGuids ? '' : $guid,
  508. $title == '' ? '' : $title,
  509. $authorNames,
  510. $content == '' ? '' : $content,
  511. $link == '' ? '' : $link,
  512. $date ?: time()
  513. );
  514. $entry->_tags($tags);
  515. $entry->_feed($this);
  516. if (!empty($attributeThumbnail['url'])) {
  517. $entry->_attributes('thumbnail', $attributeThumbnail);
  518. }
  519. $entry->_attributes('enclosures', $attributeEnclosures);
  520. $entry->hash(); //Must be computed before loading full content
  521. $entry->loadCompleteContent(); // Optionally load full content for truncated feeds
  522. yield $entry;
  523. }
  524. }
  525. /**
  526. * @throws FreshRSS_Context_Exception
  527. */
  528. public function loadHtmlXpath(): ?SimplePie {
  529. if ($this->url == '') {
  530. return null;
  531. }
  532. $feedSourceUrl = htmlspecialchars_decode($this->url, ENT_QUOTES);
  533. if ($this->httpAuth != '') {
  534. $feedSourceUrl = preg_replace('#((.+)://)(.+)#', '${1}' . $this->httpAuth . '@${3}', $feedSourceUrl);
  535. }
  536. // Same naming conventions than https://rss-bridge.github.io/rss-bridge/Bridge_API/XPathAbstract.html
  537. // https://rss-bridge.github.io/rss-bridge/Bridge_API/BridgeAbstract.html#collectdata
  538. /** @var array<string,string> $xPathSettings */
  539. $xPathSettings = $this->attributes('xpath');
  540. $xPathFeedTitle = $xPathSettings['feedTitle'] ?? '';
  541. $xPathItem = $xPathSettings['item'] ?? '';
  542. $xPathItemTitle = $xPathSettings['itemTitle'] ?? '';
  543. $xPathItemContent = $xPathSettings['itemContent'] ?? '';
  544. $xPathItemUri = $xPathSettings['itemUri'] ?? '';
  545. $xPathItemAuthor = $xPathSettings['itemAuthor'] ?? '';
  546. $xPathItemTimestamp = $xPathSettings['itemTimestamp'] ?? '';
  547. $xPathItemTimeFormat = $xPathSettings['itemTimeFormat'] ?? '';
  548. $xPathItemThumbnail = $xPathSettings['itemThumbnail'] ?? '';
  549. $xPathItemCategories = $xPathSettings['itemCategories'] ?? '';
  550. $xPathItemUid = $xPathSettings['itemUid'] ?? '';
  551. if ($xPathItem == '') {
  552. return null;
  553. }
  554. $cachePath = FreshRSS_Feed::cacheFilename($feedSourceUrl, $this->attributes(), $this->kind());
  555. $html = httpGet($feedSourceUrl, $cachePath,
  556. $this->kind() === FreshRSS_Feed::KIND_XML_XPATH ? 'xml' : 'html', $this->attributes());
  557. if (strlen($html) <= 0) {
  558. return null;
  559. }
  560. $view = new FreshRSS_View();
  561. $view->_path('index/rss.phtml');
  562. $view->internal_rendering = true;
  563. $view->rss_url = $feedSourceUrl;
  564. $view->entries = [];
  565. try {
  566. $doc = new DOMDocument();
  567. $doc->recover = true;
  568. $doc->strictErrorChecking = false;
  569. $ok = false;
  570. switch ($this->kind()) {
  571. case FreshRSS_Feed::KIND_HTML_XPATH:
  572. $ok = $doc->loadHTML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING) !== false;
  573. break;
  574. case FreshRSS_Feed::KIND_XML_XPATH:
  575. $ok = $doc->loadXML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING) !== false;
  576. break;
  577. }
  578. if (!$ok) {
  579. return null;
  580. }
  581. $xpath = new DOMXPath($doc);
  582. $view->rss_title = $xPathFeedTitle == '' ? $this->name() :
  583. htmlspecialchars(@$xpath->evaluate('normalize-space(' . $xPathFeedTitle . ')'), ENT_COMPAT, 'UTF-8');
  584. $view->rss_base = htmlspecialchars(trim($xpath->evaluate('normalize-space(//base/@href)')), ENT_COMPAT, 'UTF-8');
  585. $nodes = $xpath->query($xPathItem);
  586. if ($nodes === false || $nodes->length === 0) {
  587. return null;
  588. }
  589. foreach ($nodes as $node) {
  590. $item = [];
  591. $item['title'] = $xPathItemTitle == '' ? '' : @$xpath->evaluate('normalize-space(' . $xPathItemTitle . ')', $node);
  592. $item['content'] = '';
  593. if ($xPathItemContent != '') {
  594. $result = @$xpath->evaluate($xPathItemContent, $node);
  595. if ($result instanceof DOMNodeList) {
  596. // List of nodes, save as HTML
  597. $content = '';
  598. foreach ($result as $child) {
  599. $content .= $doc->saveHTML($child) . "\n";
  600. }
  601. $item['content'] = $content;
  602. } else {
  603. // Typed expression, save as-is
  604. $item['content'] = (string)$result;
  605. }
  606. }
  607. $item['link'] = $xPathItemUri == '' ? '' : @$xpath->evaluate('normalize-space(' . $xPathItemUri . ')', $node);
  608. $item['author'] = $xPathItemAuthor == '' ? '' : @$xpath->evaluate('normalize-space(' . $xPathItemAuthor . ')', $node);
  609. $item['timestamp'] = $xPathItemTimestamp == '' ? '' : @$xpath->evaluate('normalize-space(' . $xPathItemTimestamp . ')', $node);
  610. if ($xPathItemTimeFormat != '') {
  611. $dateTime = DateTime::createFromFormat($xPathItemTimeFormat, $item['timestamp'] ?? '');
  612. if ($dateTime != false) {
  613. $item['timestamp'] = $dateTime->format(DateTime::ATOM);
  614. }
  615. }
  616. $item['thumbnail'] = $xPathItemThumbnail == '' ? '' : @$xpath->evaluate('normalize-space(' . $xPathItemThumbnail . ')', $node);
  617. if ($xPathItemCategories != '') {
  618. $itemCategories = @$xpath->evaluate($xPathItemCategories, $node);
  619. if (is_string($itemCategories) && $itemCategories !== '') {
  620. $item['tags'] = [$itemCategories];
  621. } elseif ($itemCategories instanceof DOMNodeList && $itemCategories->length > 0) {
  622. $item['tags'] = [];
  623. /** @var DOMNode $itemCategory */
  624. foreach ($itemCategories as $itemCategory) {
  625. $item['tags'][] = $itemCategory->textContent;
  626. }
  627. }
  628. }
  629. if ($xPathItemUid != '') {
  630. $item['guid'] = @$xpath->evaluate('normalize-space(' . $xPathItemUid . ')', $node);
  631. }
  632. if (empty($item['guid'])) {
  633. $item['guid'] = 'urn:sha1:' . sha1($item['title'] . $item['content'] . $item['link']);
  634. }
  635. if ($item['title'] != '' || $item['content'] != '' || $item['link'] != '') {
  636. // HTML-encoding/escaping of the relevant fields (all except 'content')
  637. foreach (['author', 'guid', 'link', 'thumbnail', 'timestamp', 'tags', 'title'] as $key) {
  638. if (!empty($item[$key]) && is_string($item[$key])) {
  639. $item[$key] = Minz_Helper::htmlspecialchars_utf8($item[$key]);
  640. }
  641. }
  642. // CDATA protection
  643. $item['content'] = str_replace(']]>', ']]&gt;', $item['content']);
  644. $view->entries[] = FreshRSS_Entry::fromArray($item);
  645. }
  646. }
  647. } catch (Exception $ex) {
  648. Minz_Log::warning($ex->getMessage());
  649. return null;
  650. }
  651. $simplePie = customSimplePie();
  652. $simplePie->set_raw_data($view->renderToString());
  653. $simplePie->init();
  654. return $simplePie;
  655. }
  656. /**
  657. * @return int|null The max number of unread articles to keep, or null if disabled.
  658. * @throws JsonException
  659. */
  660. public function keepMaxUnread() {
  661. $keepMaxUnread = $this->attributes('keep_max_n_unread');
  662. if ($keepMaxUnread === null) {
  663. $keepMaxUnread = FreshRSS_Context::$user_conf->mark_when['max_n_unread'];
  664. }
  665. return is_int($keepMaxUnread) && $keepMaxUnread >= 0 ? $keepMaxUnread : null;
  666. }
  667. /**
  668. * @return int|false The number of articles marked as read, of false if error
  669. */
  670. public function markAsReadMaxUnread() {
  671. $keepMaxUnread = $this->keepMaxUnread();
  672. if ($keepMaxUnread === null) {
  673. return false;
  674. }
  675. $feedDAO = FreshRSS_Factory::createFeedDao();
  676. $affected = $feedDAO->markAsReadMaxUnread($this->id(), $keepMaxUnread);
  677. if ($affected > 0) {
  678. Minz_Log::debug(__METHOD__ . " $affected items [" . $this->url(false) . ']');
  679. }
  680. return $affected;
  681. }
  682. /**
  683. * Applies the *mark as read upon gone* policy, if enabled.
  684. * Remember to call `updateCachedValue($id_feed)` or `updateCachedValues()` just after.
  685. * @return int|false the number of lines affected, or false if not applicable
  686. */
  687. public function markAsReadUponGone(bool $upstreamIsEmpty, int $maxTimestamp = 0) {
  688. $readUponGone = $this->attributes('read_upon_gone');
  689. if ($readUponGone === null) {
  690. $readUponGone = FreshRSS_Context::$user_conf->mark_when['gone'];
  691. }
  692. if (!$readUponGone) {
  693. return false;
  694. }
  695. if ($upstreamIsEmpty) {
  696. if ($maxTimestamp <= 0) {
  697. $maxTimestamp = time();
  698. }
  699. $entryDAO = FreshRSS_Factory::createEntryDao();
  700. $affected = $entryDAO->markReadFeed($this->id(), $maxTimestamp . '000000');
  701. } else {
  702. $feedDAO = FreshRSS_Factory::createFeedDao();
  703. $affected = $feedDAO->markAsReadUponGone($this->id());
  704. }
  705. if ($affected > 0) {
  706. Minz_Log::debug(__METHOD__ . " $affected items" . ($upstreamIsEmpty ? ' (all)' : '') . ' [' . $this->url(false) . ']');
  707. }
  708. return $affected;
  709. }
  710. /**
  711. * Remember to call `updateCachedValue($id_feed)` or `updateCachedValues()` just after
  712. * @return int|false
  713. */
  714. public function cleanOldEntries() {
  715. $archiving = $this->attributes('archiving');
  716. if ($archiving == null) {
  717. $catDAO = FreshRSS_Factory::createCategoryDao();
  718. $category = $catDAO->searchById($this->categoryId);
  719. $archiving = $category == null ? null : $category->attributes('archiving');
  720. if ($archiving == null) {
  721. $archiving = FreshRSS_Context::$user_conf->archiving;
  722. }
  723. }
  724. if (is_array($archiving)) {
  725. $entryDAO = FreshRSS_Factory::createEntryDao();
  726. $nb = $entryDAO->cleanOldEntries($this->id(), $archiving);
  727. if ($nb > 0) {
  728. Minz_Log::debug($nb . ' entries cleaned in feed [' . $this->url(false) . '] with: ' . json_encode($archiving));
  729. }
  730. return $nb;
  731. }
  732. return false;
  733. }
  734. /** @param array<string,mixed> $attributes */
  735. public static function cacheFilename(string $url, array $attributes, int $kind = FreshRSS_Feed::KIND_RSS): string {
  736. $simplePie = customSimplePie($attributes);
  737. $filename = $simplePie->get_cache_filename($url);
  738. if ($kind === FreshRSS_Feed::KIND_HTML_XPATH) {
  739. return CACHE_PATH . '/' . $filename . '.html';
  740. } elseif ($kind === FreshRSS_Feed::KIND_XML_XPATH) {
  741. return CACHE_PATH . '/' . $filename . '.xml';
  742. } else {
  743. return CACHE_PATH . '/' . $filename . '.spc';
  744. }
  745. }
  746. public function clearCache(): bool {
  747. return @unlink(FreshRSS_Feed::cacheFilename($this->url, $this->attributes(), $this->kind));
  748. }
  749. /** @return int|false */
  750. public function cacheModifiedTime() {
  751. $filename = FreshRSS_Feed::cacheFilename($this->url, $this->attributes(), $this->kind);
  752. clearstatcache(true, $filename);
  753. return @filemtime($filename);
  754. }
  755. public function lock(): bool {
  756. $this->lockPath = TMP_PATH . '/' . $this->hash() . '.freshrss.lock';
  757. if (file_exists($this->lockPath) && ((time() - (@filemtime($this->lockPath) ?: 0)) > 3600)) {
  758. @unlink($this->lockPath);
  759. }
  760. if (($handle = @fopen($this->lockPath, 'x')) === false) {
  761. return false;
  762. }
  763. //register_shutdown_function('unlink', $this->lockPath);
  764. @fclose($handle);
  765. return true;
  766. }
  767. public function unlock(): bool {
  768. return @unlink($this->lockPath);
  769. }
  770. //<WebSub>
  771. public function pubSubHubbubEnabled(): bool {
  772. $url = $this->selfUrl ?: $this->url;
  773. $hubFilename = PSHB_PATH . '/feeds/' . sha1($url) . '/!hub.json';
  774. if ($hubFile = @file_get_contents($hubFilename)) {
  775. $hubJson = json_decode($hubFile, true);
  776. if ($hubJson && empty($hubJson['error']) &&
  777. (empty($hubJson['lease_end']) || $hubJson['lease_end'] > time())) {
  778. return true;
  779. }
  780. }
  781. return false;
  782. }
  783. public function pubSubHubbubError(bool $error = true): bool {
  784. $url = $this->selfUrl ?: $this->url;
  785. $hubFilename = PSHB_PATH . '/feeds/' . sha1($url) . '/!hub.json';
  786. $hubFile = @file_get_contents($hubFilename);
  787. $hubJson = $hubFile ? json_decode($hubFile, true) : [];
  788. if (!isset($hubJson['error']) || $hubJson['error'] !== $error) {
  789. $hubJson['error'] = $error;
  790. file_put_contents($hubFilename, json_encode($hubJson));
  791. Minz_Log::warning('Set error to ' . ($error ? 1 : 0) . ' for ' . $url, PSHB_LOG);
  792. }
  793. return false;
  794. }
  795. /**
  796. * @return string|false
  797. */
  798. public function pubSubHubbubPrepare() {
  799. $key = '';
  800. if (Minz_Request::serverIsPublic(FreshRSS_Context::$system_conf->base_url) &&
  801. $this->hubUrl && $this->selfUrl && @is_dir(PSHB_PATH)) {
  802. $path = PSHB_PATH . '/feeds/' . sha1($this->selfUrl);
  803. $hubFilename = $path . '/!hub.json';
  804. if ($hubFile = @file_get_contents($hubFilename)) {
  805. $hubJson = json_decode($hubFile, true);
  806. if (!$hubJson || empty($hubJson['key']) || !ctype_xdigit($hubJson['key'])) {
  807. $text = 'Invalid JSON for WebSub: ' . $this->url;
  808. Minz_Log::warning($text);
  809. Minz_Log::warning($text, PSHB_LOG);
  810. return false;
  811. }
  812. if ((!empty($hubJson['lease_end'])) && ($hubJson['lease_end'] < (time() + (3600 * 23)))) { //TODO: Make a better policy
  813. $text = 'WebSub lease ends at '
  814. . date('c', empty($hubJson['lease_end']) ? time() : $hubJson['lease_end'])
  815. . ' and needs renewal: ' . $this->url;
  816. Minz_Log::warning($text);
  817. Minz_Log::warning($text, PSHB_LOG);
  818. $key = $hubJson['key']; //To renew our lease
  819. } elseif (((!empty($hubJson['error'])) || empty($hubJson['lease_end'])) &&
  820. (empty($hubJson['lease_start']) || $hubJson['lease_start'] < time() - (3600 * 23))) { //Do not renew too often
  821. $key = $hubJson['key']; //To renew our lease
  822. }
  823. } else {
  824. @mkdir($path, 0770, true);
  825. $key = sha1($path . FreshRSS_Context::$system_conf->salt);
  826. $hubJson = [
  827. 'hub' => $this->hubUrl,
  828. 'key' => $key,
  829. ];
  830. file_put_contents($hubFilename, json_encode($hubJson));
  831. @mkdir(PSHB_PATH . '/keys/', 0770, true);
  832. file_put_contents(PSHB_PATH . '/keys/' . $key . '.txt', $this->selfUrl);
  833. $text = 'WebSub prepared for ' . $this->url;
  834. Minz_Log::debug($text);
  835. Minz_Log::debug($text, PSHB_LOG);
  836. }
  837. $currentUser = Minz_User::name();
  838. if (FreshRSS_user_Controller::checkUsername($currentUser) && !file_exists($path . '/' . $currentUser . '.txt')) {
  839. touch($path . '/' . $currentUser . '.txt');
  840. }
  841. }
  842. return $key;
  843. }
  844. //Parameter true to subscribe, false to unsubscribe.
  845. public function pubSubHubbubSubscribe(bool $state): bool {
  846. if ($state) {
  847. $url = $this->selfUrl ?: $this->url;
  848. } else {
  849. $url = $this->url; //Always use current URL during unsubscribe
  850. }
  851. if ($url && (Minz_Request::serverIsPublic(FreshRSS_Context::$system_conf->base_url) || !$state)) {
  852. $hubFilename = PSHB_PATH . '/feeds/' . sha1($url) . '/!hub.json';
  853. $hubFile = @file_get_contents($hubFilename);
  854. if ($hubFile === false) {
  855. Minz_Log::warning('JSON not found for WebSub: ' . $this->url);
  856. return false;
  857. }
  858. $hubJson = json_decode($hubFile, true);
  859. if (!$hubJson || empty($hubJson['key']) || !ctype_xdigit($hubJson['key']) || empty($hubJson['hub'])) {
  860. Minz_Log::warning('Invalid JSON for WebSub: ' . $this->url);
  861. return false;
  862. }
  863. $callbackUrl = checkUrl(Minz_Request::getBaseUrl() . '/api/pshb.php?k=' . $hubJson['key']);
  864. if ($callbackUrl == '') {
  865. Minz_Log::warning('Invalid callback for WebSub: ' . $this->url);
  866. return false;
  867. }
  868. if (!$state) { //unsubscribe
  869. $hubJson['lease_end'] = time() - 60;
  870. file_put_contents($hubFilename, json_encode($hubJson));
  871. }
  872. $ch = curl_init();
  873. curl_setopt_array($ch, [
  874. CURLOPT_URL => $hubJson['hub'],
  875. CURLOPT_RETURNTRANSFER => true,
  876. CURLOPT_POSTFIELDS => http_build_query([
  877. 'hub.verify' => 'sync',
  878. 'hub.mode' => $state ? 'subscribe' : 'unsubscribe',
  879. 'hub.topic' => $url,
  880. 'hub.callback' => $callbackUrl,
  881. ]),
  882. CURLOPT_USERAGENT => FRESHRSS_USERAGENT,
  883. CURLOPT_MAXREDIRS => 10,
  884. CURLOPT_FOLLOWLOCATION => true,
  885. CURLOPT_ENCODING => '', //Enable all encodings
  886. ]);
  887. $response = curl_exec($ch);
  888. $info = curl_getinfo($ch);
  889. Minz_Log::warning('WebSub ' . ($state ? 'subscribe' : 'unsubscribe') . ' to ' . $url .
  890. ' via hub ' . $hubJson['hub'] .
  891. ' with callback ' . $callbackUrl . ': ' . $info['http_code'] . ' ' . $response, PSHB_LOG);
  892. if (substr('' . $info['http_code'], 0, 1) == '2') {
  893. return true;
  894. } else {
  895. $hubJson['lease_start'] = time(); //Prevent trying again too soon
  896. $hubJson['error'] = true;
  897. file_put_contents($hubFilename, json_encode($hubJson));
  898. return false;
  899. }
  900. }
  901. return false;
  902. }
  903. //</WebSub>
  904. }