diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index 1d42e95a1..2b5a475da 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -7,7 +7,7 @@ RUN apk add --no-cache \ tzdata \ apache2 php-apache2 \ php php-curl php-gmp php-intl php-mbstring php-xml php-zip \ - php-ctype php-dom php-fileinfo php-iconv php-json php-opcache php-openssl php-phar php-session php-simplexml php-xmlreader php-xmlwriter php-xml php-tokenizer php-zlib \ + php-ctype php-dom php-fileinfo php-iconv php-json php-opcache php-openssl php-phar php-session php-simplexml php-xmlwriter php-xml php-tokenizer php-zlib \ php-pdo_sqlite php-pdo_mysql php-pdo_pgsql \ bash composer curl docker-cli-buildx git gpg make nodejs npm shellcheck shfmt sudo diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 1a426d029..0baf7e4dc 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -146,3 +146,41 @@ jobs: - name: Check spelling run: bin/typos + + # https://github.com/shivammathur/setup-php + tests-oldest-php: + name: tests PHP 8.2 + runs-on: ubuntu-26.04 + + steps: + - name: Git checkout source code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Use PHP 8.2 + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 + with: + php-version: '8.2' + + - name: Check PHP syntax + run: composer run-script php-lint + + - name: Check PHTML syntax + run: composer run-script phtml-lint + + - name: Use Composer cache + id: composer-cache + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: vendor + key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }} + restore-keys: | + ${{ runner.os }}-php- + + - name: Run Composer install + run: composer install --prefer-dist --no-progress + if: steps.composer-cache.outputs.cache-hit != 'true' + + - name: Run PHP unit tests + run: composer run-script phpunit -- --no-progress diff --git a/Docker/Dockerfile-Alpine b/Docker/Dockerfile-Alpine index acbd37412..994b2ccf4 100644 --- a/Docker/Dockerfile-Alpine +++ b/Docker/Dockerfile-Alpine @@ -7,7 +7,7 @@ RUN apk add --no-cache \ tzdata \ apache2 php-apache2 \ php php-curl php-gmp php-intl php-mbstring php-xml php-zip \ - php-ctype php-dom php-fileinfo php-iconv php-json php-opcache php-openssl php-phar php-session php-simplexml php-xmlreader php-xmlwriter php-xml php-tokenizer php-zlib \ + php-ctype php-dom php-fileinfo php-iconv php-json php-opcache php-openssl php-phar php-session php-simplexml php-xmlwriter php-xml php-tokenizer php-zlib \ php-pdo_sqlite php-pdo_mysql php-pdo_pgsql RUN mkdir -p /var/www/FreshRSS /run/apache2/ diff --git a/Docker/Dockerfile-Newest b/Docker/Dockerfile-Newest index 9e4a44f58..f5de2cfc5 100644 --- a/Docker/Dockerfile-Newest +++ b/Docker/Dockerfile-Newest @@ -9,7 +9,7 @@ RUN echo 'https://dl-cdn.alpinelinux.org/alpine/edge/testing' >> /etc/apk/reposi apache2 php86-apache2 \ apache-mod-auth-openidc \ php86 php86-curl php86-gmp php86-intl php86-mbstring php86-xml php86-zip \ - php86-ctype php86-dom php86-fileinfo php86-iconv php86-json php86-openssl php86-phar php86-session php86-simplexml php86-xmlreader php86-xmlwriter php86-xml php86-tokenizer php86-zlib \ + php86-ctype php86-dom php86-fileinfo php86-iconv php86-json php86-openssl php86-phar php86-session php86-simplexml php86-xmlwriter php86-xml php86-tokenizer php86-zlib \ php86-pdo_sqlite php86-pdo_mysql php86-pdo_pgsql RUN mkdir -p /var/www/FreshRSS /run/apache2/ diff --git a/Docker/Dockerfile-Oldest b/Docker/Dockerfile-Oldest index ba710d0e8..896d0d99b 100644 --- a/Docker/Dockerfile-Oldest +++ b/Docker/Dockerfile-Oldest @@ -8,7 +8,7 @@ RUN apk add --no-cache \ tzdata \ apache2 php82-apache2 \ php82 php82-curl php82-gmp php82-intl php82-mbstring php82-xml php82-zip \ - php82-ctype php82-dom php82-fileinfo php82-iconv php82-json php82-opcache php82-openssl php82-phar php82-session php82-simplexml php82-xmlreader php82-xmlwriter php82-xml php82-tokenizer php82-zlib \ + php82-ctype php82-dom php82-fileinfo php82-iconv php82-json php82-opcache php82-openssl php82-phar php82-session php82-simplexml php82-xmlwriter php82-xml php82-tokenizer php82-zlib \ php82-pdo_sqlite php82-pdo_mysql php82-pdo_pgsql RUN mkdir -p /var/www/FreshRSS /run/apache2/ diff --git a/README.fr.md b/README.fr.md index 3625df460..1c19fb6c7 100644 --- a/README.fr.md +++ b/README.fr.md @@ -63,7 +63,7 @@ FreshRSS n’est fourni avec aucune garantie. * Serveur modeste, par exemple sous Linux ou Windows * Fonctionne même sur un Raspberry Pi 1 avec des temps de réponse < 1s (testé sur 150 flux, 22k articles) * Serveur Web Apache2.4+ (recommandé), ou nginx, lighttpd (non testé sur les autres) -* PHP 8.2+ +* PHP 8.2+ (8.4+ recommandé) * Extensions requises : [cURL](https://www.php.net/curl), [DOM](https://www.php.net/dom), [JSON](https://www.php.net/json), [XML](https://www.php.net/xml), [session](https://www.php.net/features.sessions), [ctype](https://www.php.net/ctype) * Extensions recommandées : [PDO_SQLite](https://www.php.net/pdo-sqlite) (pour l’export/import), [GMP](https://www.php.net/gmp) (pour accès API sur plateformes < 64 bits), [IDN](https://www.php.net/intl.idn) (pour les noms de domaines internationalisés), [mbstring](https://www.php.net/mbstring) (pour le texte Unicode), [iconv](https://www.php.net/iconv) (pour conversion d’encodages), [ZIP](https://www.php.net/zip) (pour import/export), [zlib](https://www.php.net/zlib) (pour les flux compressés) * Extension pour base de données : [PDO_PGSQL](https://www.php.net/pdo-pgsql) ou [PDO_SQLite](https://www.php.net/pdo-sqlite) ou [PDO_MySQL](https://www.php.net/pdo-mysql) @@ -311,7 +311,7 @@ et [l’API Fever](https://freshrss.github.io/FreshRSS/fr/users/06_Fever_API.htm * [SimplePie](https://simplepie.org/) * [php-http-304](https://alexandre.alapetite.fr/doc-alex/php-http-304/) * [lib_opml](https://framagit.org/marienfressinaud/lib_opml) -* [PhpGt/CssXPath](https://github.com/PhpGt/CssXPath) +* [PhpGt/CssXPath](https://github.com/PhpGt/CssXPath) (seulement pour PHP < 8.4) * [PHPMailer](https://github.com/PHPMailer/PHPMailer) * [Chart.js](https://www.chartjs.org) diff --git a/README.md b/README.md index 0fbdfdc3f..a1871ca49 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ FreshRSS comes with absolutely no warranty. * Light server running Linux or Windows * It even works on Raspberry Pi 1 with response time under a second (tested with 150 feeds, 22k articles) * A Web server: Apache2.4+ (recommended), nginx, lighttpd (not tested on others) -* PHP 8.2+ +* PHP 8.2+ (8.4+ recommended) * Required extensions: [cURL](https://www.php.net/curl), [DOM](https://www.php.net/dom), [JSON](https://www.php.net/json), [XML](https://www.php.net/xml), [session](https://www.php.net/features.sessions), [ctype](https://www.php.net/ctype) * Recommended extensions: [PDO_SQLite](https://www.php.net/pdo-sqlite) (for export/import), [GMP](https://www.php.net/gmp) (for API access on 32-bit platforms), [IDN](https://www.php.net/intl.idn) (for Internationalized Domain Names), [mbstring](https://www.php.net/mbstring) (for Unicode strings), [iconv](https://www.php.net/iconv) (for charset conversion), [ZIP](https://www.php.net/zip) (for import/export), [zlib](https://www.php.net/zlib) (for compressed feeds) * Extension for database: [PDO_PGSQL](https://www.php.net/pdo-pgsql) or [PDO_SQLite](https://www.php.net/pdo-sqlite) or [PDO_MySQL](https://www.php.net/pdo-mysql) @@ -207,7 +207,7 @@ and [Fever API](https://freshrss.github.io/FreshRSS/en/developers/06_Fever_API.h * [SimplePie](https://simplepie.org/) * [php-http-304](https://alexandre.alapetite.fr/doc-alex/php-http-304/) * [lib_opml](https://framagit.org/marienfressinaud/lib_opml) -* [PhpGt/CssXPath](https://github.com/PhpGt/CssXPath) +* [PhpGt/CssXPath](https://github.com/PhpGt/CssXPath) (only for PHP < 8.4) * [PHPMailer](https://github.com/PHPMailer/PHPMailer) * [Chart.js](https://www.chartjs.org) diff --git a/app/Controllers/importExportController.php b/app/Controllers/importExportController.php index b88f8ded4..3a4dd82e4 100644 --- a/app/Controllers/importExportController.php +++ b/app/Controllers/importExportController.php @@ -347,46 +347,59 @@ class FreshRSS_importExport_Controller extends FreshRSS_ActionController { . '' . "\n"; } + /** + * @return string|false JSON, or false if the file is invalid XML + */ private function ttrssXmlToJson(string $xml): string|false { - $table = (array)simplexml_load_string($xml, options: LIBXML_NOBLANKS | LIBXML_NOCDATA); - $table['items'] = $table['article'] ?? []; - if (!is_array($table['items'])) { - $table['items'] = []; + try { + $dom = @Dom\XMLDocument::createFromString($xml, LIBXML_NOERROR); + } catch (Throwable $ex) { // @phpstan-ignore catch.neverThrown (Dom\XMLDocument::createFromString() does throw) + Minz_Log::warning('Error during TT-RSS articles import: ' . $ex->getMessage()); + return false; } - unset($table['article']); - for ($i = count($table['items']) - 1; $i >= 0; $i--) { - $item = (array)($table['items'][$i]); - $item = array_filter($item, static fn($v) => - // Filter out empty properties, potentially reported as empty objects - (is_string($v) && trim($v) !== '') || !empty($v)); - $item['updated'] = is_string($item['updated'] ?? null) ? strtotime($item['updated']) : ''; - $item['published'] = $item['updated']; - $item['content'] = ['content' => $item['content'] ?? '']; - $item['categories'] = is_string($item['tag_cache'] ?? null) ? [$item['tag_cache']] : []; - if (!empty($item['marked'])) { - $item['categories'][] = 'user/-/state/com.google/starred'; - } - if (!empty($item['published'])) { - $item['categories'][] = 'user/-/state/com.google/broadcast'; - } - if (is_string($item['label_cache'] ?? null)) { - $labels_cache = json_decode($item['label_cache'], true); - if (is_array($labels_cache)) { - foreach ($labels_cache as $label_cache) { - if (is_array($label_cache) && !empty($label_cache[1]) && is_string($label_cache[1])) { - $item['categories'][] = 'user/-/label/' . trim($label_cache[1]); + $domElement = $dom->documentElement; + $table = ['items' => []]; + if ($domElement !== null) { + foreach ($domElement->childNodes as $article) { + if (!$article instanceof Dom\Element || $article->nodeName !== 'article') { + continue; + } + $item = []; + foreach ($article->childNodes as $child) { + if ($child instanceof Dom\Element) { + $item[$child->nodeName] = $child->textContent; + } + } + $item = array_filter($item, static fn($v) => trim($v) !== ''); + $item['updated'] = isset($item['updated']) ? strtotime($item['updated']) : ''; + $item['published'] = $item['updated']; + $item['content'] = ['content' => $item['content'] ?? '']; + $item['categories'] = isset($item['tag_cache']) ? [$item['tag_cache']] : []; + if (!empty($item['marked'])) { + $item['categories'][] = 'user/-/state/com.google/starred'; + } + if (!empty($item['published'])) { + $item['categories'][] = 'user/-/state/com.google/broadcast'; + } + if (is_string($item['label_cache'] ?? null)) { + $labels_cache = json_decode($item['label_cache'], true); + if (is_array($labels_cache)) { + foreach ($labels_cache as $label_cache) { + if (is_array($label_cache) && !empty($label_cache[1]) && is_string($label_cache[1])) { + $item['categories'][] = 'user/-/label/' . trim($label_cache[1]); + } } } } + $item['alternate'] = [['href' => $item['link'] ?? '']]; + $item['origin'] = [ + 'title' => $item['feed_title'] ?? '', + 'feedUrl' => $item['feed_url'] ?? '', + ]; + $item['id'] = $item['guid'] ?? ($item['feed_url'] ?? $item['published']); + $item['guid'] = $item['id']; + $table['items'][] = $item; } - $item['alternate'] = [['href' => $item['link'] ?? '']]; - $item['origin'] = [ - 'title' => $item['feed_title'] ?? '', - 'feedUrl' => $item['feed_url'] ?? '', - ]; - $item['id'] = $item['guid'] ?? ($item['feed_url'] ?? $item['published']); - $item['guid'] = $item['id']; - $table['items'][$i] = $item; } return json_encode($table); } diff --git a/app/Models/Entry.php b/app/Models/Entry.php index 1680181d0..936c4d746 100644 --- a/app/Models/Entry.php +++ b/app/Models/Entry.php @@ -324,25 +324,23 @@ class FreshRSS_Entry extends Minz_Model { try { $searchEnclosures = !is_iterable($attributeEnclosures) && (str_contains($this->content, '

' . $this->content, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING); - $xpath = new DOMXPath($dom); + $doc = Dom\HTMLDocument::createFromString($this->content, LIBXML_NOERROR | Dom\HTML_NO_DEFAULT_NS); } - if ($searchEnclosures && $xpath !== null) { + if ($searchEnclosures && $doc !== null) { // Legacy code for database entries < FreshRSS 1.20.1 - $enclosures = $xpath->query('//div[@class="enclosure"]/p[@class="enclosure-content"]/*[@src]'); - if (!empty($enclosures)) { + $enclosures = $doc->querySelectorAll('div.enclosure > p.enclosure-content > [src]'); + if ($enclosures->length > 0) { foreach ($enclosures as $enclosure) { - if (!($enclosure instanceof DOMElement)) { + if (!($enclosure instanceof Dom\Element)) { continue; } $result = [ - 'url' => $enclosure->getAttribute('src'), - 'type' => $enclosure->getAttribute('data-type'), - 'medium' => $enclosure->getAttribute('data-medium'), - 'length' => (int)($enclosure->getAttribute('data-length')), + 'url' => $enclosure->getAttribute('src') ?? '', + 'type' => $enclosure->getAttribute('data-type') ?? '', + 'medium' => $enclosure->getAttribute('data-medium') ?? '', + 'length' => (int)($enclosure->getAttribute('data-length') ?? ''), ]; if (empty($result['medium'])) { switch (strtolower($enclosure->nodeName)) { @@ -355,18 +353,18 @@ class FreshRSS_Entry extends Minz_Model { } } } - if ($searchBodyImages && $xpath !== null) { - $images = $xpath->query('//img'); - if (!empty($images)) { + if ($searchBodyImages && $doc !== null) { + $images = $doc->querySelectorAll('img'); + if ($images->length > 0) { foreach ($images as $img) { - if (!($img instanceof DOMElement)) { + if (!($img instanceof Dom\Element)) { continue; } - $src = $img->getAttribute('src'); - if ($src == null) { - $src = $img->getAttribute('data-src'); + $src = $img->getAttribute('src') ?? ''; + if ($src === '') { + $src = $img->getAttribute('data-src') ?? ''; } - if ($src != null) { + if ($src !== '') { $result = [ 'url' => $src, 'medium' => 'image', @@ -973,19 +971,20 @@ class FreshRSS_Entry extends Minz_Model { $response = FreshRSS_http_Util::httpGet($url, $cachePath, 'html', $feed->attributes(), $feed->curlOptions()); $html = $response['body']; if ($html !== '') { - $doc = new DOMDocument(); - $doc->loadHTML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING); - $xpath = new DOMXPath($doc); + $doc = Dom\HTMLDocument::createFromString($html, LIBXML_NOERROR); // Account for HTTP redirections $url = $response['effective_url'] ?: $url; $maxRedirs -= $response['redirect_count']; if ($maxRedirs > 0) { //Follow any HTML redirection - $metas = $xpath->query('//meta[@content]') ?: []; + $metas = $doc->querySelectorAll('meta[content]'); foreach ($metas as $meta) { - if ($meta instanceof DOMElement && strtolower(trim($meta->getAttribute('http-equiv'))) === 'refresh') { - $refresh = preg_replace('/^[0-9.; ]*\s*(url\s*=)?\s*/i', '', trim($meta->getAttribute('content'))); + if (!$meta instanceof Dom\Element) { + continue; + } + if (strtolower(trim($meta->getAttribute('http-equiv') ?? '')) === 'refresh') { + $refresh = preg_replace('/^[0-9.; ]*\s*(url\s*=)?\s*/i', '', trim($meta->getAttribute('content') ?? '')); $refresh = is_string($refresh) ? \SimplePie\Misc::absolutize_url($refresh, $url) : false; if ($refresh != false && $refresh !== $url) { return $this->getContentByParsing($refresh, $maxRedirs - 1); @@ -994,8 +993,12 @@ class FreshRSS_Entry extends Minz_Model { } } - $base = $xpath->evaluate('normalize-space(//base/@href)'); - if ($base == false || !is_string($base)) { + $base = ''; + $baseNode = $doc->querySelector('base[href]'); + if ($baseNode instanceof Dom\Element) { + $base = trim($baseNode->getAttribute('href') ?? ''); + } + if ($base === '') { $base = $url; } elseif (str_starts_with($base, '//')) { //Protocol-relative URLs "//www.example.net" @@ -1006,75 +1009,55 @@ class FreshRSS_Entry extends Minz_Model { $cssSelector = htmlspecialchars_decode($feed->pathEntries(), ENT_QUOTES); $cssSelector = trim($cssSelector, ', '); $path_entries_filter = trim($feed->attributeString('path_entries_filter') ?? '', ', '); - $nodes = $xpath->query((new GT\CssXPath\Translator($cssSelector, '//'))->asXPath()); - if ($nodes === false || $nodes->length === 0) { + $nodeList = $doc->querySelectorAll($cssSelector); + if ($nodeList->length === 0) { Minz_Log::warning('CSS content retrieval matched no elements for feed “' . $feed->name() . '” and article URL ' . $url . ': ' . $cssSelector); } else { - $filter_xpath = $path_entries_filter === '' ? '' : (new GT\CssXPath\Translator($path_entries_filter, 'descendant-or-self::'))->asXPath(); - foreach ($nodes as $node) { - try { - if (!($node instanceof DOMElement)) { - continue; - } - if ($filter_xpath !== '' && ($filterednodes = $xpath->query($filter_xpath, $node)) !== false) { - // Remove unwanted elements once before sanitizing, for CSS selectors to also match original content - foreach ($filterednodes as $filterednode) { - try { - if ($filterednode === $node) { - continue 2; - } - if (!($filterednode instanceof DOMElement) || $filterednode->ownerDocument !== $doc || $filterednode->parentNode === null) { - continue; - } - $filterednode->remove(); - } catch (Error $e) { // @phpstan-ignore catch.neverThrown - if (!str_contains($e->getMessage(), 'Node no longer exists')) { - throw $e; - } - } + foreach ($nodeList as $node) { + if (!($node instanceof Dom\Element)) { + continue; + } + if ($path_entries_filter !== '' && $node->matches($path_entries_filter)) { + // Remove unwanted elements once before sanitizing, for CSS selectors to also match original content + continue; + } + if ($path_entries_filter !== '') { + $filterednodeList = $node->querySelectorAll($path_entries_filter); + foreach ($filterednodeList as $filterednode) { + if (!($filterednode instanceof Dom\Element) || $filterednode->ownerDocument !== $doc || $filterednode->parentNode === null) { + continue; } - } - if ($node->ownerDocument !== $doc || $node->parentNode === null) { - continue; - } - $html .= $doc->saveHTML($node) . "\n"; - } catch (Error $e) { - if (!str_contains($e->getMessage(), 'Node no longer exists')) { - throw $e; + $filterednode->remove(); } } + if ($node->ownerDocument !== $doc || $node->parentNode === null) { + continue; + } + $html .= $doc->saveHTML($node) . "\n"; } } - unset($xpath, $doc); + unset($doc); $html = FreshRSS_SimplePieCustom::sanitizeHTML($html, $base); - if ($nodes !== false && $nodes->length > 0 && trim($html) === '') { + if ($nodeList->length > 0 && trim($html) === '') { Minz_Log::warning('CSS content retrieval returned no content for feed “' . $feed->name() . '” and article URL ' . $url . ': ' . $cssSelector); } if ($path_entries_filter !== '') { // Remove unwanted elements again after sanitizing, for CSS selectors to also match sanitized content $modified = false; - $doc = new DOMDocument(); - $utf8BOM = "\xEF\xBB\xBF"; - $doc->loadHTML($utf8BOM . $html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING); - $xpath = new DOMXPath($doc); - $filterednodes = $xpath->query((new GT\CssXPath\Translator($path_entries_filter, '//'))->asXPath()) ?: []; - foreach ($filterednodes as $filterednode) { - try { - if (!($filterednode instanceof DOMElement) || $filterednode->ownerDocument !== $doc || $filterednode->parentNode === null) { - continue; - } - $filterednode->remove(); - $modified = true; - } catch (Error $e) { // @phpstan-ignore catch.neverThrown - if (!str_contains($e->getMessage(), 'Node no longer exists')) { - throw $e; - } + $doc = Dom\HTMLDocument::createFromString($html, LIBXML_NOERROR); + $filterednodeList = $doc->querySelectorAll($path_entries_filter); + foreach ($filterednodeList as $filterednode) { + if (!($filterednode instanceof Dom\Element) || $filterednode->ownerDocument !== $doc || $filterednode->parentNode === null) { + continue; } + $filterednode->remove(); + $modified = true; } if ($modified) { - $html = $doc->saveHTML($doc->getElementsByTagName('body')->item(0) ?? $doc->firstElementChild) ?: $html; + $bodyNode = $doc->querySelector('body'); + $html = $doc->saveHTML($bodyNode ?? $doc->firstElementChild) ?: $html; } } @@ -1131,30 +1114,18 @@ class FreshRSS_Entry extends Minz_Model { } } elseif (trim($feed->attributeString('path_entries_filter') ?? '') !== '') { $originalContent = $this->attributeString('original_content') ?? $this->content; - $doc = new DOMDocument(); - $utf8BOM = "\xEF\xBB\xBF"; - if (!$doc->loadHTML($utf8BOM . $originalContent, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING)) { - return false; - } - $xpath = new DOMXPath($doc); - $filterednodes = $xpath->query((new GT\CssXPath\Translator($feed->attributeString('path_entries_filter'), '//'))->asXPath()) ?: []; - foreach ($filterednodes as $filterednode) { - try { - if (!($filterednode instanceof DOMElement) || $filterednode->ownerDocument !== $doc || $filterednode->parentNode === null) { - continue; - } - $filterednode->remove(); - } catch (Error $e) { // @phpstan-ignore catch.neverThrown - if (!str_contains($e->getMessage(), 'Node no longer exists')) { - throw $e; - } + $doc = Dom\HTMLDocument::createFromString($originalContent, LIBXML_NOERROR | Dom\HTML_NO_DEFAULT_NS); + $pathEntriesFilter = $feed->attributeString('path_entries_filter'); + $filterednodeList = $doc->querySelectorAll($pathEntriesFilter); + foreach ($filterednodeList as $filterednode) { + if (!($filterednode instanceof Dom\Element) || $filterednode->ownerDocument !== $doc || $filterednode->parentNode === null) { + continue; } + $filterednode->remove(); } - $html = $doc->saveHTML($doc->getElementsByTagName('body')->item(0) ?? $doc->firstElementChild); - if (!is_string($html)) { - return false; - } - $html = preg_replace('%^\s*\s*|\s*\s*$%i', '', $html); + $bodyNode = $doc->querySelector('body'); + $html = $doc->saveHTML($bodyNode ?? $doc->firstElementChild) ?: ''; + $html = preg_replace('%^\s*\s*|\s*\s*$%i', '', $html) ?? ''; $this->_attribute('original_content'); if (is_string($html) && $this->content !== $html) { $this->_attribute('original_content', $originalContent); diff --git a/app/Models/Feed.php b/app/Models/Feed.php index 94c9cd397..b0718836b 100644 --- a/app/Models/Feed.php +++ b/app/Models/Feed.php @@ -1026,29 +1026,18 @@ class FreshRSS_Feed extends Minz_Model { return null; } - $doc = new DOMDocument(); - $doc->recover = true; - $doc->strictErrorChecking = false; - if (!$doc->loadHTML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING)) { - return null; - } - - $xpath = new DOMXPath($doc); + $doc = Dom\HTMLDocument::createFromString($html, LIBXML_NOERROR | Dom\HTML_NO_DEFAULT_NS); + $xpath = new Dom\XPath($doc); $jsonFragments = @$xpath->evaluate($xPathToJson); - if ($jsonFragments === false) { - return null; - } if (is_string($jsonFragments)) { return $jsonFragments; } - if ($jsonFragments instanceof DOMNodeList && $jsonFragments->length > 0) { + if ($jsonFragments instanceof Dom\NodeList && $jsonFragments->length > 0) { // If the result is a list, then aggregate as a JSON array $result = []; foreach ($jsonFragments as $node) { - if (!($node instanceof DOMNode)) { - continue; - } - $json = json_decode($node->textContent, true); + /** @var \DOMNode $node */ + $json = json_decode((string)$node->textContent, true); if (json_last_error() === JSON_ERROR_NONE && is_array($json)) { $result[] = $json; } @@ -1139,58 +1128,55 @@ class FreshRSS_Feed extends Minz_Model { $view->entries = []; try { - $doc = new DOMDocument(); - $doc->recover = true; - $doc->strictErrorChecking = false; - $ok = false; - switch ($this->kind()) { case FreshRSS_Feed::KIND_HTML_XPATH: - $ok = $doc->loadHTML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING) !== false; + $doc = Dom\HTMLDocument::createFromString($html, LIBXML_NOERROR | Dom\HTML_NO_DEFAULT_NS); break; case FreshRSS_Feed::KIND_XML_XPATH: - $ok = $doc->loadXML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING) !== false; + $doc = @Dom\XMLDocument::createFromString($html, LIBXML_NONET); break; + default: + return null; } - if (!$ok) { - return null; - } + $xpath = new Dom\XPath($doc); + $xPathEvaluate = function (string $expression, Dom\Node|\DOMNode|null $contextNode = null) use ($xpath): mixed { + if ($contextNode === null) { + return @$xpath->evaluate($expression); + } + return @$xpath->evaluate($expression, $contextNode); + }; - $xpath = new DOMXPath($doc); - $xpathEvaluateString = function (string $expression, ?DOMNode $contextNode = null) use ($xpath): string { - $result = @$xpath->evaluate('normalize-space(' . $expression . ')', $contextNode); + $xpathEvaluateString = function (string $expression, Dom\Node|\DOMNode|null $contextNode = null) use ($xPathEvaluate): string { + $result = $xPathEvaluate('normalize-space(' . $expression . ')', $contextNode); return is_string($result) ? $result : ''; }; $view->rss_title = $xPathFeedTitle == '' ? $this->name() : htmlspecialchars($xpathEvaluateString($xPathFeedTitle), ENT_COMPAT, 'UTF-8'); $view->rss_base = htmlspecialchars(trim($xpathEvaluateString('//base/@href')), ENT_COMPAT, 'UTF-8'); - $nodes = $xpath->query($xPathItem); - if ($nodes === false || $nodes->length === 0) { + $nodes = @$xpath->query($xPathItem); + if ($nodes->length === 0) { return null; } foreach ($nodes as $node) { - if (!($node instanceof DOMNode)) { - continue; - } $item = []; $item['title'] = $xPathItemTitle == '' ? '' : $xpathEvaluateString($xPathItemTitle, $node); $item['content'] = ''; if ($xPathItemContent != '') { - $result = @$xpath->evaluate($xPathItemContent, $node); - if ($result instanceof DOMNodeList) { - // List of nodes, save as HTML + $result = $xPathEvaluate($xPathItemContent, $node); + if ($result instanceof Dom\NodeList) { + // List of nodes, serialized as HTML or XML depending on the document $content = ''; foreach ($result as $child) { - if ($child instanceof DOMNode) { - $content .= $doc->saveHTML($child) . "\n"; - } + /** @var \DOMNode $child */ + $content .= ($doc instanceof Dom\HTMLDocument ? $doc->saveHTML($child) : + ($doc->saveXML($child) ?: '')) . "\n"; } $item['content'] = $content; - } elseif (is_string($result) || is_int($result) || is_bool($result)) { + } elseif (is_string($result) || is_bool($result)) { // Typed expression, save as-is $item['content'] = (string)$result; } @@ -1211,15 +1197,14 @@ class FreshRSS_Feed extends Minz_Model { } $item['thumbnail'] = $xPathItemThumbnail == '' ? '' : $xpathEvaluateString($xPathItemThumbnail, $node); if ($xPathItemCategories != '') { - $itemCategories = @$xpath->evaluate($xPathItemCategories, $node); + $itemCategories = $xPathEvaluate($xPathItemCategories, $node); if (is_string($itemCategories) && $itemCategories !== '') { $item['tags'] = [$itemCategories]; - } elseif ($itemCategories instanceof DOMNodeList && $itemCategories->length > 0) { + } elseif ($itemCategories instanceof Dom\NodeList && $itemCategories->length > 0) { $item['tags'] = []; foreach ($itemCategories as $itemCategory) { - if ($itemCategory instanceof DOMNode) { - $item['tags'][] = $itemCategory->textContent; - } + /** @var \DOMNode $itemCategory */ + $item['tags'][] = (string)$itemCategory->textContent; } } } @@ -1245,7 +1230,7 @@ class FreshRSS_Feed extends Minz_Model { $view->entries[] = FreshRSS_Entry::fromArray($item); } } - } catch (Exception $ex) { + } catch (Throwable $ex) { Minz_Log::warning($ex->getMessage()); return null; } diff --git a/app/Utils/httpUtil.php b/app/Utils/httpUtil.php index 3cfe94317..044b4bf4b 100644 --- a/app/Utils/httpUtil.php +++ b/app/Utils/httpUtil.php @@ -180,7 +180,7 @@ final class FreshRSS_http_Util { * Set an XML preamble to enforce the HTML content type charset received by HTTP. * @param string $html the raw downloaded HTML content * @param string $contentType an HTTP Content-Type such as 'text/html; charset=utf-8' - * @return string an HTML string with XML encoding information for DOMDocument::loadHTML() + * @return string an HTML string with Unicode BOM encoding information */ private static function enforceHttpEncoding(string $html, string $contentType = ''): string { $httpCharset = preg_match('/\bcharset=([0-9a-z_-]{2,12})$/i', $contentType, $matches) === 1 ? $matches[1] : ''; @@ -234,56 +234,28 @@ final class FreshRSS_http_Util { * @return string an HTML string */ private static function enforceHtmlBase(string $html, string $href): string { - $doc = new DOMDocument(); - $doc->loadHTML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING); - if ($doc->documentElement === null) { + $doc = Dom\HTMLDocument::createFromString($html, LIBXML_NOERROR); + $documentElement = $doc->documentElement; + if ($documentElement === null) { return ''; } - $xpath = new DOMXPath($doc); - $bases = $xpath->evaluate('//base'); - if (!($bases instanceof DOMNodeList) || $bases->length === 0) { + if ($doc->querySelector('base') === null) { $base = $doc->createElement('base'); - if ($base === false) { - return $html; - } $base->setAttribute('href', $href); - $head = null; - $heads = $xpath->evaluate('//head'); - if ($heads instanceof DOMNodeList && $heads->length > 0) { - $head = $heads->item(0); - } - if ($head instanceof DOMElement) { + $head = $doc->querySelector('head'); + if ($head instanceof Dom\Element) { $head->insertBefore($base, $head->firstChild); } else { - $doc->documentElement->insertBefore($base, $doc->documentElement->firstChild); + $documentElement->insertBefore($base, $documentElement->firstChild); } } - // Save the start of HTML because libxml2 saveHTML() risks scrambling it - $htmlPos = stripos($html, ' 512 ? '' : substr($html, 0, $htmlPos); - - $encoding = strtolower($doc->encoding ?? ''); - $bom = str_starts_with($html, "\xEF\xBB\xBF") ? "\xEF\xBB\xBF" : ''; - if ($encoding === 'utf-8' || ($encoding === '' && $bom !== '')) { - // For a whole document, libxml2 saveHTML() only knows the charset from . - // With or a byte order mark, it writes non-ASCII characters as HTML entities, - // also inside