Forráskód Böngészése

Use PHP 8.4+ \Dom classes and functions (#9567)

Currently, SimplePie uses legacy DOMDocument parsing, which outputs potentially problematic HTML, not correctly sanitised.
This breaks the assumption that one can use something like `<div><!-- some HTML sanitized from SimplePie --></div>`.

```
--- Expected
+++ Actual
@@ @@
 '<ul>
-    <li><div></div></li>
+    <li><div>
     <li>Item</li>
-</ul>'
+</div></li></ul>'
```

When shown in a compliant Web browser, several tags will be wrongly closed, breaking the layout of the client.

This PR patches SimplePie to use the modern parser and code syntax, while maintaining a best-effort polyfill for legacy PHP versions < 8.4.

Depends on:

SimplePie: Upgrade to PHPStan 2
* https://github.com/FreshRSS/simplepie/pull/97
* https://github.com/simplepie/simplepie/pull/939
* https://github.com/simplepie/simplepie/pull/1019

SimplePie: Use PHP 8.4+ \Dom classes and functions
* https://github.com/FreshRSS/simplepie/pull/98
* https://github.com/simplepie/simplepie/issues/1021

SimplePie: Add unit test for HTML5 sanitizing compliance
* https://github.com/simplepie/simplepie/pull/1022

SimplePie: Remove obsolete xml_is_sane and XMLReader fallback
* https://github.com/simplepie/simplepie/pull/1023

CssXPath: Add support for case insensitivity
* https://github.com/phpgt/CssXPath/pull/256

fix https://github.com/FreshRSS/FreshRSS/issues/5201
fix https://github.com/FreshRSS/FreshRSS/issues/6830
fix https://github.com/FreshRSS/FreshRSS/issues/6831

~5% faster for HTML sanitising.
Remove SimpleXML. Remove XMLReader.
Alexandre Alapetite 7 órája
szülő
commit
ea646d2bde
44 módosított fájl, 1007 hozzáadás és 618 törlés
  1. 1 1
      .devcontainer/Dockerfile
  2. 38 0
      .github/workflows/tests.yml
  3. 1 1
      Docker/Dockerfile-Alpine
  4. 1 1
      Docker/Dockerfile-Newest
  5. 1 1
      Docker/Dockerfile-Oldest
  6. 2 2
      README.fr.md
  7. 2 2
      README.md
  8. 48 35
      app/Controllers/importExportController.php
  9. 72 101
      app/Models/Entry.php
  10. 32 47
      app/Models/Feed.php
  11. 13 41
      app/Utils/httpUtil.php
  12. 1 2
      composer.json
  13. 3 4
      composer.lock
  14. 1 1
      docs/en/admins/02_Prerequisites.md
  15. 1 1
      docs/en/admins/09_AccessControl.md
  16. 1 1
      docs/en/developers/02_First_steps.md
  17. 1 1
      docs/fr/users/01_Installation.md
  18. 1 1
      docs/i18n/freshrss.fr.po
  19. 1 1
      docs/i18n/templates/freshrss.pot
  20. 6 2
      lib/composer.json
  21. 7 14
      lib/favicons.php
  22. 8 0
      lib/lib_rss.php
  23. 73 35
      lib/phpgt/cssxpath/src/AttributeSelectorConverter.php
  24. 334 0
      lib/simplepie/simplepie/compat/dom-polyfill.php
  25. 12 0
      lib/simplepie/simplepie/compat/dom.php
  26. 17 45
      lib/simplepie/simplepie/phpstan.dist.neon
  27. 1 0
      lib/simplepie/simplepie/src/Cache/Psr16.php
  28. 1 0
      lib/simplepie/simplepie/src/Enclosure.php
  29. 11 3
      lib/simplepie/simplepie/src/File.php
  30. 0 1
      lib/simplepie/simplepie/src/HTTP/FileClient.php
  31. 25 30
      lib/simplepie/simplepie/src/Locator.php
  32. 1 1
      lib/simplepie/simplepie/src/Misc.php
  33. 48 100
      lib/simplepie/simplepie/src/Parser.php
  34. 1 0
      lib/simplepie/simplepie/src/Registry.php
  35. 112 97
      lib/simplepie/simplepie/src/Sanitize.php
  36. 8 25
      lib/simplepie/simplepie/src/SimplePie.php
  37. 9 0
      phpstan.dist.neon
  38. 10 1
      phpunit.xml
  39. 51 0
      tests/app/Models/SimplePieCustomTest.php
  40. 12 2
      tests/app/Utils/dotNotationUtilTest.php
  41. 6 8
      tests/app/Views/entryHeaderTest.php
  42. 4 5
      tests/app/Views/headerTest.php
  43. 5 5
      tests/app/Views/streamFooterTest.php
  44. 24 0
      tests/lib/CssXPath/CssXPathTest.php

+ 1 - 1
.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
 

+ 38 - 0
.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

+ 1 - 1
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/

+ 1 - 1
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/

+ 1 - 1
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/

+ 2 - 2
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)
 

+ 2 - 2
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)
 

+ 48 - 35
app/Controllers/importExportController.php

@@ -347,46 +347,59 @@ class FreshRSS_importExport_Controller extends FreshRSS_ActionController {
 			. '</body></opml>' . "\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'] = [];
-		}
-		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]);
+		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;
+		}
+		$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);
 	}

+ 72 - 101
app/Models/Entry.php

@@ -324,25 +324,23 @@ class FreshRSS_Entry extends Minz_Model {
 		try {
 			$searchEnclosures = !is_iterable($attributeEnclosures) && (str_contains($this->content, '<p class="enclosure-content'));
 			$searchBodyImages &= (stripos($this->content, '<img') !== false);
-			$xpath = null;
+			$doc = null;
 			if ($searchEnclosures || $searchBodyImages) {
-				$dom = new DOMDocument();
-				$dom->loadHTML('<?xml version="1.0" encoding="UTF-8" ?>' . $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;
 							}
+							$filterednode->remove();
 						}
-						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;
-						}
 					}
+					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*<body>\s*|\s*</body>\s*$%i', '', $html);
+			$bodyNode = $doc->querySelector('body');
+			$html = $doc->saveHTML($bodyNode ?? $doc->firstElementChild) ?: '';
+			$html = preg_replace('%^\s*<body>\s*|\s*</body>\s*$%i', '', $html) ?? '';
 			$this->_attribute('original_content');
 			if (is_string($html) && $this->content !== $html) {
 				$this->_attribute('original_content', $originalContent);

+ 32 - 47
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;
 		}

+ 13 - 41
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, '<html');
-		$htmlStart = $htmlPos === false || $htmlPos > 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 <meta http-equiv="Content-Type">.
-			// With <meta charset="UTF-8"> or a byte order mark, it writes non-ASCII characters as HTML entities,
-			// also inside <script>, where they are not decoded, which corrupts e.g. JSON data. Node by node, it writes UTF-8.
-			$utf8 = '';
-			foreach ($doc->childNodes as $node) {
-				$utf8 .= $doc->saveHTML($node) ?: '';
-			}
-			$html = $utf8 !== '' ? $bom . $utf8 : $html;
-		} else {
-			$html = $doc->saveHTML() ?: $html;
-		}
-		if ($htmlStart !== '' && !str_starts_with($html, $htmlStart)) {
-			// libxml2 saveHTML() risks removing Unicode BOM and XML declaration,
-			// which affects future detection of charset encoding, so manually restore it
-			$htmlPos = stripos($html, '<html');
-			$html = $htmlPos === false || $htmlPos > 512 ? $html : $htmlStart . substr($html, $htmlPos);
+		$saved = $doc->saveHTML();
+		if ($saved === '') {
+			return $html;
 		}
-		return $html;
+		// Re-add the Unicode byte order mark, for downstream charset detection
+		return (str_starts_with($html, "\xEF\xBB\xBF") ? "\xEF\xBB\xBF" : '') . $saved;
 	}
 
 	public static function compareURLOrigins(string $url1, string $url2): bool {

+ 1 - 2
composer.json

@@ -32,9 +32,7 @@
 		"ext-pdo": "*",
 		"ext-pdo_sqlite": "*",
 		"ext-session": "*",
-		"ext-simplexml": "*",
 		"ext-xml": "*",
-		"ext-xmlreader": "*",
 		"ext-zend-opcache": "*",
 		"ext-zip": "*",
 		"ext-zlib": "*"
@@ -55,6 +53,7 @@
 	"require-dev": {
 		"php": ">=8.2",
 		"ext-phar": "*",
+		"ext-simplexml": "*",
 		"ext-tokenizer": "*",
 		"ext-xmlwriter": "*",
 		"phpstan/phpstan": "^2.2",

+ 3 - 4
composer.lock

@@ -4,7 +4,7 @@
         "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
         "This file is @generated automatically"
     ],
-    "content-hash": "a98d34205a998ade47ad94d4e7c2ed09",
+    "content-hash": "98e7aca4fad3cf4ebfe82427ff8cc73f",
     "packages": [],
     "packages-dev": [
         {
@@ -2102,9 +2102,7 @@
         "ext-pdo": "*",
         "ext-pdo_sqlite": "*",
         "ext-session": "*",
-        "ext-simplexml": "*",
         "ext-xml": "*",
-        "ext-xmlreader": "*",
         "ext-zend-opcache": "*",
         "ext-zip": "*",
         "ext-zlib": "*"
@@ -2112,11 +2110,12 @@
     "platform-dev": {
         "php": ">=8.2",
         "ext-phar": "*",
+        "ext-simplexml": "*",
         "ext-tokenizer": "*",
         "ext-xmlwriter": "*"
     },
     "platform-overrides": {
         "php": "8.2"
     },
-    "plugin-api-version": "2.9.0"
+    "plugin-api-version": "2.11.0"
 }

+ 1 - 1
docs/en/admins/02_Prerequisites.md

@@ -7,7 +7,7 @@ You need to verify that your server can run FreshRSS before installing it. If yo
 | Software      | Recommended             | Also Works With         |
 | ------------- | ----------------------- | ----------------------- |
 | Web server    | **Apache 2.4**          | nginx, lighttpd |
-| PHP           | **PHP 8.2+**            | FreshRSS 1.30.4: PHP 8.1+ |
+| PHP           | **PHP 8.4+**            | PHP 8.2+; FreshRSS 1.30.4: PHP 8.1+ |
 | PHP modules   | Required: libxml, cURL, JSON, PDO_MySQL, PCRE and ctype.<br />Required (32-bit only): GMP <br />Recommended: Zlib, mbstring, iconv, ZipArchive<br />*For the whole modules list see [Dockerfile](https://github.com/FreshRSS/FreshRSS/blob/edge/Docker/Dockerfile-Alpine#L9-L11)* | |
 | Database      | **PostgreSQL 10+**      | SQLite, MariaDB 10.6+, MySQL 8.0+ |
 | Browser       | **Firefox**             | Chrome, Opera, Safari, or Edge       |

+ 1 - 1
docs/en/admins/09_AccessControl.md

@@ -40,7 +40,7 @@ These steps are not necessary for trusted, single-user deployments, but are stro
 
 ## Form Authentication
 
-Form Authentication is using a standard HTML form, it does not require any JavaScript since FreshRSS v1.31.0. It will work on any supported version of PHP (>=8.2).
+Form Authentication is using a standard HTML form, it does not require any JavaScript since FreshRSS v1.31.0. It will work on any supported version of PHP.
 
 This option requires nothing more than selecting Form Authentication during installation, and properly configured PHP sessions.
 

+ 1 - 1
docs/en/developers/02_First_steps.md

@@ -102,7 +102,7 @@ yum install -y git make npm php-cli php-curl php-mbstring php-xml php-pdo unzip
 ### Alpine Linux
 
 ```sh
-apk add git make npm php-cli php-curl php-ctype php-dom php-mbstring php-openssl php-phar php-simplexml php-xml php-pdo php-tokenizer php-xmlreader php-xmlwriter unzip wget
+apk add git make npm php-cli php-curl php-ctype php-dom php-mbstring php-openssl php-phar php-simplexml php-xml php-pdo php-tokenizer php-xmlwriter unzip wget
 ```
 
 ### Partial fixes & tests

+ 1 - 1
docs/fr/users/01_Installation.md

@@ -7,7 +7,7 @@ Il est toutefois de votre responsabilité de vérifier que votre hébergement pe
 | Logiciel         | Recommandé         | Fonctionne aussi avec          |
 | --------         | -----------        | ---------------------          |
 | Serveur web      | **Apache 2.4+**    | nginx, lighttpd |
-| PHP              | **PHP 8.2+**       | FreshRSS 1.30.4 : PHP 8.1+ |
+| PHP              | **PHP 8.4+**       | PHP 8.2+ ; FreshRSS 1.30.4 : PHP 8.1+ |
 | Modules PHP      | Requis : libxml, cURL, JSON, PDO_MySQL, PCRE et ctype<br />Requis (32 bits seulement) : GMP<br />Recommandé : Zlib, mbstring et iconv, ZipArchive<br />*Pour une liste complète des modules nécessaires voir le [Dockerfile](https://github.com/FreshRSS/FreshRSS/blob/edge/Docker/Dockerfile-Alpine#L9-L11)* |                                |
 | Base de données  | **PostgreSQL 10+** | SQLite, MariaDB 10.6+, MySQL 8.0+ |
 | Navigateur       | **Firefox**        | Chrome, Opera, Safari, or Edge   |

+ 1 - 1
docs/i18n/freshrss.fr.po

@@ -734,7 +734,7 @@ msgstr ""
 #. type: Fenced code block (sh)
 #: en/./developers/02_First_steps.md:106
 #, no-wrap
-msgid "apk add git make npm php-cli php-curl php-ctype php-dom php-mbstring php-openssl php-phar php-simplexml php-xml php-pdo php-tokenizer php-xmlreader php-xmlwriter unzip wget\n"
+msgid "apk add git make npm php-cli php-curl php-ctype php-dom php-mbstring php-openssl php-phar php-simplexml php-xml php-pdo php-tokenizer php-xmlwriter unzip wget\n"
 msgstr ""
 
 #. type: Title ###

+ 1 - 1
docs/i18n/templates/freshrss.pot

@@ -700,7 +700,7 @@ msgstr ""
 msgid ""
 "apk add git make npm php-cli php-curl php-ctype php-dom php-mbstring "
 "php-openssl php-phar php-simplexml php-xml php-pdo php-tokenizer "
-"php-xmlreader php-xmlwriter unzip wget\n"
+"php-xmlwriter unzip wget\n"
 msgstr ""
 
 #. type: Title ###

+ 6 - 2
lib/composer.json

@@ -12,13 +12,17 @@
 		{
 			"type": "git",
 			"url": "https://framagit.org/marienfressinaud/lib_opml.git"
+		},
+		{
+			"type": "git",
+			"url": "https://github.com/Alkarex/CssXPath.git"
 		}
 	],
 	"require": {
 		"marienfressinaud/lib_opml": "dev-main#f0e850b6394af90b898daf0e65fcc7363457b844",
-		"phpgt/cssxpath": "v1.6.0",
+		"phpgt/cssxpath": "dev-case-insensitivity#4d046c033b348a908be2b049d2ba4f50ee3f9e3a",
 		"phpmailer/phpmailer": "7.1.1",
-		"simplepie/simplepie": "dev-freshrss#366b687cc1a39b76f1563ce9859fb027f85001d2"
+		"simplepie/simplepie": "dev-freshrss#d7467dd6a5e59cc6f4c73d0e8d5cadc5e7c9ecfc"
 	},
 	"config": {
 		"sort-packages": true,

+ 7 - 14
lib/favicons.php

@@ -30,30 +30,23 @@ function searchFavicon(string $url): string {
 	if ($url === '') {
 		return '';
 	}
-	$dom = new DOMDocument();
 	['body' => $html, 'effective_url' => $effective_url, 'fail' => $fail] =
 		FreshRSS_http_Util::httpGet($url, cachePath: CACHE_PATH . '/' . sha1($url) . '.html', type: 'html');
-	if ($fail || $html === '' || !@$dom->loadHTML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING)) {
-		return '';
-	}
-
-	$xpath = new DOMXPath($dom);
-	$links = $xpath->query('//link[@href][translate(@rel, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")="shortcut icon"'
-		. ' or translate(@rel, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")="icon"]');
-	if (!($links instanceof DOMNodeList)) {
+	if ($fail || $html === '') {
 		return '';
 	}
+	$dom = Dom\HTMLDocument::createFromString($html, LIBXML_NOERROR);
+	$links = $dom->querySelectorAll('link[href][rel~="icon" i]');
 
 	// Use the base element for relative paths, if there is one
-	$baseElements = $xpath->query('//base[@href]');
-	$baseElement = ($baseElements !== false && $baseElements->length > 0) ? $baseElements->item(0) : null;
-	$baseUrl = ($baseElement instanceof DOMElement) ? $baseElement->getAttribute('href') : $effective_url;
+	$baseElement = $dom->querySelector('base[href]');
+	$baseUrl = ($baseElement !== null) ? ($baseElement->getAttribute('href') ?? '') : $effective_url;
 
 	foreach ($links as $link) {
-		if (!$link instanceof DOMElement) {
+		if (!$link instanceof Dom\Element) {
 			continue;
 		}
-		$href = trim($link->getAttribute('href'));
+		$href = trim($link->getAttribute('href') ?? '');
 		$urlParts = parse_url($effective_url);
 
 		// Handle protocol-relative URLs by adding the current URL's scheme

+ 8 - 0
lib/lib_rss.php

@@ -1,6 +1,10 @@
 <?php
 declare(strict_types=1);
 
+// Polyfill PHP 8.4+ `Dom\` classes, including the CSS selector API,
+// maintained together with the vendored SimplePie fork:
+require_once LIB_PATH . '/simplepie/simplepie/compat/dom.php';
+
 if (!function_exists('mb_strcut')) {
 	function mb_strcut(string $str, int $start, ?int $length = null, string $encoding = 'UTF-8'): string {
 		return substr($str, $start, $length) ?: '';
@@ -55,6 +59,10 @@ function actualize_mutex_file(string $tmpPath, string $dataPath): string {
 function unregister_unsafe_protocols(): void {
 	$registered_wrappers = stream_get_wrappers();
 	$allowed_wrappers = ['file', 'php'];
+	if (defined('__PHPSTAN_RUNNING__')) {
+		// Needed for PHPStan compatibility PHP < 8.4
+		$allowed_wrappers[] = 'phar';
+	}
 	foreach ($registered_wrappers as $protocol) {
 		if (!in_array($protocol, $allowed_wrappers, true)) {
 			stream_wrapper_unregister($protocol);

+ 73 - 35
lib/phpgt/cssxpath/src/AttributeSelectorConverter.php

@@ -3,6 +3,9 @@
 namespace GT\CssXPath;
 
 class AttributeSelectorConverter {
+	private const UPPER_CASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
+	private const LOWER_CASE = "abcdefghijklmnopqrstuvwxyz";
+
 	/** @param array<string, mixed> $token */
 	public function apply(
 		array $token,
@@ -11,25 +14,8 @@ class AttributeSelectorConverter {
 	):void {
 		$expression->ensureElement();
 
-		$attribute = (string)$token["content"];
-		if($htmlMode) {
-			$attribute = strtolower($attribute);
-		}
-
-		$detail = $token["detail"] ?? null;
-		$detailType = $detail[0] ?? null;
-		$detailValue = $detail[1] ?? null;
-
-		if(!$this->hasEqualsType($detailType)) {
-			$expression->appendFragment("[@{$attribute}]");
-			return;
-		}
-
-		$valueString = trim((string)$detailValue["content"], " '\"");
-		$equalsType = $detailType["content"];
-		$expression->appendFragment(
-			$this->buildExpression($attribute, $valueString, $equalsType)
-		);
+		$condition = $this->buildConditionFromToken($token, $htmlMode);
+		$expression->appendFragment("[{$condition}]");
 	}
 
 	/** @param array<string, mixed> $token */
@@ -55,9 +41,13 @@ class AttributeSelectorConverter {
 			return "@{$attribute}";
 		}
 
-		$valueString = trim((string)$detailValue["content"], " '\"");
+		[$value, $flag] = $this->extractValueAndFlag(
+			(string)$detailValue["content"]
+		);
 		$equalsType = $detailType["content"];
-		return $this->buildCondition($attribute, $valueString, $equalsType);
+		$attributeAccessor = $this->getAttributeAccessor($attribute, $flag);
+		$condition = $this->buildCondition($attributeAccessor, $value, $equalsType);
+		return $this->withExistenceCheck($attribute, $condition, $flag);
 	}
 
 	/**
@@ -94,34 +84,82 @@ class AttributeSelectorConverter {
 		string $equalsType
 	):string {
 		return match($equalsType) {
-			Translator::EQUALS_EXACT => "@{$attribute}=\"{$value}\"",
-			Translator::EQUALS_CONTAINS => "contains(@{$attribute},\"{$value}\")",
+			Translator::EQUALS_EXACT => "{$attribute}=\"{$value}\"",
+			Translator::EQUALS_CONTAINS => "contains({$attribute},\"{$value}\")",
 			Translator::EQUALS_CONTAINS_WORD => ""
-				. "contains(concat(\" \",@{$attribute},\" \"),"
+				. "contains(concat(\" \",{$attribute},\" \"),"
 				. "concat(\" \",\"{$value}\",\" \"))"
 				. "",
 			Translator::EQUALS_OR_STARTS_WITH_HYPHENATED => ""
-				. "@{$attribute}=\"{$value}\" or "
-				. "starts-with(@{$attribute}, \"{$value}-\")"
+				. "{$attribute}=\"{$value}\" or "
+				. "starts-with({$attribute}, \"{$value}-\")"
 				. "",
 			Translator::EQUALS_STARTS_WITH => ""
-				. "starts-with(@{$attribute}, \"{$value}\")"
+				. "starts-with({$attribute}, \"{$value}\")"
 				. "",
-				Translator::EQUALS_ENDS_WITH => ""
-				. "substring(@{$attribute},"
-				. "string-length(@{$attribute}) - "
+			Translator::EQUALS_ENDS_WITH => ""
+				. "substring({$attribute},"
+				. "string-length({$attribute}) - "
 				. "string-length(\"{$value}\") + 1)"
 				. "=\"{$value}\""
 				. "",
-			default => "@{$attribute}",
+			default => $attribute,
 		};
 	}
 
-	private function buildExpression(
+	private function withExistenceCheck(
 		string $attribute,
-		string $value,
-		string $equalsType
+		string $condition,
+		?string $flag
+	):string {
+		if($flag !== "i") {
+			return $condition;
+		}
+
+		return "@{$attribute} and ({$condition})";
+	}
+
+	/**
+	 * Splits an attribute selector's value from its trailing case flag, if any.
+	 * E.g. `rel~="icon" i` represents the value "icon" with case-insensitivity.
+	 * @param string $rawValue
+	 * @return array{string, string|null} The attribute value and case flag.
+	 */
+	private function extractValueAndFlag(string $rawValue):array {
+		// A case flag appears either after the closing quote of a quoted value,
+		// or separated by whitespace after an unquoted value.
+		$patternQuoted = "/^(?<quote>['\"])(?<value>.*)(?P=quote)\s*"
+			. "(?<flag>[is])\s*$/i";
+		$patternUnquoted = '/^(?<value>.*\S)\s+(?<flag>[is])\s*$/i';
+
+		if(preg_match($patternQuoted, $rawValue, $matches) === 1
+			|| preg_match($patternUnquoted, $rawValue, $matches) === 1) {
+			$flag = strtolower($matches["flag"]);
+			$value = trim($matches["value"], " '\"");
+			if($flag === "i") {
+				$value = strtolower($value);
+			}
+
+			return [$value, $flag];
+		}
+
+		return [trim($rawValue, " '\""), null];
+	}
+
+	/**
+	 * Rewrites the condition's attribute-name comparison to ignore case,
+	 * using the XPath translate() function.
+	 */
+	private function getAttributeAccessor(
+		string $attribute,
+		?string $flag
 	):string {
-		return "[" . $this->buildCondition($attribute, $value, $equalsType) . "]";
+		if($flag === null || $flag === "s") {
+			return "@" . $attribute;
+		}
+
+		return "translate(@" . $attribute
+			. ",\"" . self::UPPER_CASE . "\","
+			. "\"" . self::LOWER_CASE . "\")";
 	}
 }

+ 334 - 0
lib/simplepie/simplepie/compat/dom-polyfill.php

@@ -0,0 +1,334 @@
+<?php
+
+// SPDX-FileCopyrightText: 2026 Alexandre Alapetite
+// SPDX-License-Identifier: BSD-3-Clause
+
+// Polyfill PHP 8.4+ `Dom\` classes approximated using legacy `DOM*` classes,
+// and optional CSS selector API approximated using `GT\CssXPath` library.
+
+declare(strict_types=1);
+
+namespace Dom;
+
+const HTML_NO_DEFAULT_NS = 2147483648;
+
+// phpcs:disable PSR1.Classes.ClassDeclaration.MultipleClasses -- Polyfilled `Dom\` classes best co-exist in this file.
+
+// Hide from PHPStan to avoid divergent signature shapes of the legacy aliases,
+// and also skip when legacy `ext-dom` is unavailable
+if (!defined('__PHPSTAN_RUNNING__') && class_exists(\DOMDocument::class, false)) {
+    if (\PHP_VERSION_ID >= 80300) {
+        // The polyfilled classes that cannot use `registerNodeClass()`
+        // (aliasing internal classes requires PHP 8.3+):
+        class_alias(\DOMComment::class, 'Dom\Comment', false);
+        class_alias(\DOMDocument::class, 'Dom\Document', false);
+        class_alias(\DOMNode::class, 'Dom\Node', false);
+        class_alias(\DOMNodeList::class, 'Dom\NodeList', false);
+        class_alias(\DOMText::class, 'Dom\Text', false);
+    }
+
+    /**
+     * Optional PHP 8.4+ CSS selector API, requiring `GT\CssXPath` library.
+     */
+    trait CssSelectors
+    {
+        private function cssXPath(): ?XPath
+        {
+            /** @var \DOMDocument|null $document */
+            $document = $this->ownerDocument ?? $this;
+            return $document instanceof \DOMDocument ? new XPath($document) : null;
+        }
+
+        /**
+         * Translates a CSS selector to an XPath expression.
+         *
+         * @param string $selectors CSS selector
+         * @param string $prefix e.g. `.//` to search descendants of the context node
+         * @throws \DOMException if the CSS selector cannot be translated
+         */
+        private function cssToXPath(string $selectors, string $prefix): string
+        {
+            if (!class_exists(\GT\CssXPath\Translator::class)) {
+                // https://github.com/PhpGt/CssXPath
+                throw new \DOMException('CSS selectors are not available: missing the `GT\CssXPath` package');
+            }
+            try {
+                return (new \GT\CssXPath\Translator($selectors, $prefix))->asXPath();
+            } catch (\Throwable $e) {
+                throw new \DOMException('Invalid CSS selector: ' . substr($selectors, 0, 100), 0, $e);
+            }
+        }
+
+        /**
+         * Returns the first descendant element matching the CSS selector, or null.
+         *
+         * @return \Dom\Element|null
+         */
+        public function querySelector(string $selectors)
+        {
+            $result = $this->querySelectorAll($selectors);
+            return $result->length === 0 ? null : $result->item(0);
+        }
+
+        /**
+         * Returns the descendant elements matching the CSS selector.
+         *
+         * @return \Dom\NodeList<\Dom\Element>
+         * @throws \DOMException if the CSS selector cannot be translated
+         */
+        public function querySelectorAll(string $selectors)
+        {
+            $xpath = $this->cssXPath();
+            if ($xpath === null) {
+                // No owner document (e.g. a detached node): empty result
+                return $this->getElementsByTagName('_');
+            }
+            try {
+                return $xpath->query($this->cssToXPath($selectors, './/'), $this);
+            } catch (\Throwable $e) {
+                throw $e instanceof \DOMException ? $e : new \DOMException('Invalid CSS selector: ' . substr($selectors, 0, 100), 0, $e);
+            }
+        }
+
+        /**
+         * Whether this element matches the given CSS selector.
+         *
+         * @throws \DOMException if the CSS selector cannot be translated
+         */
+        public function matches(string $selectors): bool
+        {
+            $xpath = $this->cssXPath();
+            if ($xpath === null) {
+                return false;
+            }
+            try {
+                $result = $xpath->query($this->cssToXPath($selectors, 'descendant-or-self::'));
+            } catch (\Throwable $e) {
+                throw $e instanceof \DOMException ? $e : new \DOMException('Invalid CSS selector: ' . substr($selectors, 0, 100), 0, $e);
+            }
+            for ($i = 0; $i < $result->length; $i++) {
+                $candidate = $result->item($i);
+                if ($candidate !== null && $candidate->isSameNode($this)) {
+                    return true;
+                }
+            }
+            return false;
+        }
+    }
+
+    /**
+     * Equivalent of native `Dom\Element` (PHP 8.4+),
+     * registered as the element class of `HTMLDocument` and `XMLDocument` below.
+     */
+    final class Element extends \DOMElement
+    {
+        use CssSelectors;
+
+        /**
+         * Native `Dom\Element::getAttribute()` return null when the attribute is missing
+         * @return string|null
+         */
+        #[\ReturnTypeWillChange]
+        public function getAttribute($qualifiedName)
+        {
+            return $this->hasAttribute($qualifiedName) ? parent::getAttribute($qualifiedName) : null;
+        }
+    }
+
+    /**
+     * Maps `\Dom\HTMLDocument::createFromString()` onto `\DOMDocument::loadHTML()`.
+     */
+    final class HTMLDocument extends \DOMDocument
+    {
+        use CssSelectors;
+
+        public function __construct()
+        {
+            parent::__construct();
+            $this->registerNodeClass(\DOMElement::class, Element::class);
+        }
+
+        /**
+         * @return static
+         */
+        public static function createFromString(string $source, ?int $options = null, ?string $overrideEncoding = null)
+        {
+            $document = new self();
+            if ($overrideEncoding !== null) {
+                trigger_error('`$overrideEncoding` is not supported by this polyfill', E_USER_WARNING);
+            }
+            $options = ($options ?? 0) | LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_HTML_NODEFDTD;
+
+            // HTML standard encoding sniffing on first 1024 bytes:
+            $probe = substr($source, 0, 1024);
+            // If the source itself declares an encoding, let the parser honour it, otherwise UTF-8.
+            $injectEncoding = $probe !== '' && strncmp($probe, "\xEF\xBB\xBF", 3) !== 0
+                && !preg_match('#<(?:meta|\?xml)[^>]*?(?:charset|encoding)\\s*=#i', $probe);
+            if ($injectEncoding) {
+                $source = '<?xml encoding="UTF-8">' . $source;
+            }
+
+            try {
+                // `HTML_NO_DEFAULT_NS` is unknown to the legacy `loadHTML()`
+                /** @var \DOMDocument $document */
+                $document->loadHTML($source, $options & ~HTML_NO_DEFAULT_NS);
+            } catch (\ValueError $e) {
+                // the native API silently creates an empty document.
+            }
+
+            if ($injectEncoding) {
+                // Remove the injected declaration, which would otherwise be serialised
+                foreach ($document->childNodes as $child) {
+                    if ($child instanceof \DOMProcessingInstruction && $child->target === 'xml') {
+                        $document->removeChild($child);
+                        break;
+                    }
+                }
+            }
+
+            return $document;
+        }
+
+        /**
+         * Normalise to `attr=""` for parity.
+         * It also emits end tags for void elements (e.g. `</source>`).
+         *
+         * Returns `''` instead of `false` in case of error, for parity with the
+         * native `Dom\HTMLDocument::saveHTML()`, which always returns a string.
+         */
+        public function saveHTML(?\DOMNode $node = null): string
+        {
+            if ($node === null && in_array(strtolower($this->encoding ?? 'utf-8'), ['utf-8', 'utf8'], true)) {
+                // For a whole document, the legacy serialiser only knows the charset from `<meta http-equiv="Content-Type">`,
+                // and otherwise writes non-ASCII characters as HTML entities, also inside `<script>`, where they are not decoded.
+                // Node by node, it writes UTF-8, but skips the doctype.
+                $html = '';
+                foreach ($this->childNodes as $child) {
+                    $html .= $child instanceof \DOMDocumentType ? '<!DOCTYPE ' . $child->name . '>' : parent::saveHTML($child);
+                }
+            } else {
+                $html = parent::saveHTML($node);
+            }
+            if ($html === false) {
+                return '';
+            }
+            // Drop void-element end tags emitted for e.g. `<source>`:
+            $html = preg_replace(
+                '#(<(area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)\b[^>]*?>)</\2>#i',
+                '$1',
+                $html
+            ) ?? $html;
+            return (string) preg_replace_callback('#<[\w:-]+[^>]*?>#', static function (array $match): string {
+                $bools = 'allowfullscreen|async|autofocus|autoplay|checked|controls|default|defer|disabled|formnovalidate|hidden|' .
+                    'inert|ismap|itemscope|loop|multiple|muted|nomodule|novalidate|open|playsinline|readonly|required|reversed|selected';
+                // Only scan outside quoted attribute values, which have no raw `"`:
+                $parts = preg_split('#(="[^"]*")#', $match[0], -1, PREG_SPLIT_DELIM_CAPTURE);
+                if ($parts === false) {
+                    return $match[0];
+                }
+                foreach ($parts as $i => $part) {
+                    if ($i % 2 === 0) {
+                        $replaced = preg_replace('#\s(' . $bools . ')(?=[\s/>])#i', ' $1=""', $part);
+                        if ($replaced !== null) {
+                            $parts[$i] = $replaced;
+                        }
+                    }
+                }
+                return implode('', $parts);
+            }, $html) ?: $html;
+        }
+    }
+
+    final class XMLDocument extends \DOMDocument
+    {
+        use CssSelectors;
+
+        public function __construct()
+        {
+            parent::__construct();
+            $this->registerNodeClass(\DOMElement::class, Element::class);
+        }
+
+        /**
+         * Maps `\Dom\XMLDocument::createFromString()` onto `\DOMDocument::loadXML()`.
+         * Like the native implementation, throws upon a malformed XML document.
+         *
+         * @return static
+         */
+        public static function createFromString(string $source, ?int $options = null, ?string $overrideEncoding = null)
+        {
+            $document = new self();
+            if ($overrideEncoding !== null) {
+                // Parity divergence from the native implementation.
+                trigger_error('`$overrideEncoding` is not supported by this polyfill', E_USER_WARNING);
+            }
+            $options = ($options ?? 0) | LIBXML_NOERROR | LIBXML_NOWARNING;
+            if ($source === '') {
+                $message = 'Argument #1 ($source) must not be empty';
+                // `\ValueError` requires PHP 8.0+
+                throw class_exists(\ValueError::class) ? new \ValueError($message) : new \Exception($message);
+            }
+            /** @var \DOMDocument $document */
+            if (@$document->loadXML($source, $options) !== true
+                || $document->documentElement === null) {
+                throw new \DOMException('XML fragment is not well-formed', 12);
+            }
+            return $document;
+        }
+    }
+
+    /**
+     * On the legacy path, the parser never puts elements in any namespace,
+     * so rewrite queries written for the namespaced PHP 8.4 parser (e.g. `xh:body//xh:img`).
+     */
+    final class XPath extends \DOMXPath
+    {
+        /** @var array<string, true> */
+        private $registeredPrefixes = [];
+
+        /**
+         * @param string $prefix
+         * @param string $namespaceURI
+         */
+        public function registerNamespace($prefix, $namespaceURI): bool
+        {
+            $this->registeredPrefixes[$prefix] = true;
+            return parent::registerNamespace($prefix, $namespaceURI);
+        }
+
+        private function translate(string $expression): string
+        {
+            if ($this->registeredPrefixes === []) {
+                return $expression;
+            }
+            foreach (array_keys($this->registeredPrefixes) as $prefix) {
+                // NCName-boundary safe:
+                $translated = preg_replace('/(?<![\\w.\\-])' . preg_quote($prefix, '/') . ':/', '', $expression);
+                if ($translated !== null) {
+                    $expression = $translated;
+                }
+            }
+            return $expression;
+        }
+
+        /**
+         * The native API throws upon an invalid expression, rather than returning `false`.
+         *
+         * @param string $expression
+         * @param \DOMNode|null $contextNode
+         */
+        public function query($expression, $contextNode = null, $registerNodeNS = true): \DOMNodeList
+        {
+            $translated = $this->translate($expression);
+            $result = @parent::query($translated, $contextNode, $registerNodeNS);
+            if ($result === false) {
+                $message = 'Invalid XPath expression: ' . substr($translated, 0, 100);
+                // \ValueError requires PHP 8.0+
+                throw class_exists(\ValueError::class) ? new \ValueError($message) : new \Exception($message);
+            }
+            return $result;
+        }
+    }
+}
+
+// phpcs:enable PSR1.Classes.ClassDeclaration.MultipleClasses

+ 12 - 0
lib/simplepie/simplepie/compat/dom.php

@@ -0,0 +1,12 @@
+<?php
+
+// SPDX-FileCopyrightText: 2026 Alexandre Alapetite
+// SPDX-License-Identifier: BSD-3-Clause
+
+// Loader for the `Dom\` classes polyfill.
+
+declare(strict_types=1);
+
+if (\PHP_VERSION_ID < 80400 && !class_exists(\Dom\HTMLDocument::class, false)) {
+    require_once __DIR__ . '/dom-polyfill.php';
+}

+ 17 - 45
lib/simplepie/simplepie/phpstan.dist.neon

@@ -1,4 +1,8 @@
 parameters:
+    phpVersion:
+        min: 70400 # PHP 7.4
+        max: 80599 # PHP 8.5
+
     level: 8
 
     paths:
@@ -7,54 +11,22 @@ parameters:
         - tests/
         - utils/
 
-    ignoreErrors:
-        # Ignore that only one const exists atm
-        -
-            message: "#^Strict comparison using \\!\\=\\= between 'GET' and 'GET' will always evaluate to false\\.$#"
-            count: 1
-            path: src/HTTP/Psr18Client.php
-
-        # Not used since https://github.com/simplepie/simplepie/commit/b2eb0134d53921e75f0fa70b1cf901ed82b988b1 but cannot be removed due to BC.
-        - '(Constructor of class SimplePie\\Enclosure has an unused parameter \$javascript\.)'
-
-        # Testing legacy dynamic property usage.
-        - '(Access to an undefined property SimplePie.IRI::\$nonexistent_prop\.)'
-
-        -
-            message: '(^Strict comparison using === between string and false will always evaluate to false\.$)'
-            count: 1
-            path: src/HTTP/Parser.php
-            # Only occurs on PHP ≥ 8.0
-            reportUnmatched: false
-
-        -
-            message: '(^Strict comparison using === between string and false will always evaluate to false\.$)'
-            count: 1
-            path: src/IRI.php
-            # Only occurs on PHP ≥ 8.0
-            reportUnmatched: false
-
-        -
-            message: '(^Parameter #1 \$exception of method PHPUnit\\Framework\\TestCase::expectException\(\) expects class-string<Throwable>, string given\.$)'
-
-            count: 3
-            path: tests/Unit/Cache/Psr16Test.php
-            # Only occurs on PHP ≤ 7.4
-            reportUnmatched: false
+    excludePaths:
+        analyseAndScan:
+            - .git/*?
+            - build/*?
+            - vendor/*
 
+    # For PHP < 8.4
+    ignoreErrors:
         -
-            message: '(^Parameter \$parser of method SimplePie\\Parser::(tag_open|cdata|tag_close)\(\) has invalid type XMLParser\.$)'
-
-            count: 3
-            path: src/Parser.php
-            # Only occurs on PHP ≤ 7.4
-            reportUnmatched: false
+            identifier: class.notFound
+            messages:
+                - '#Dom\\\S+#'
 
-        # PHPStan stubs bug https://github.com/phpstan/phpstan/issues/8629
-        -
-            message: '(^Access to an undefined property XMLReader::\$\w+\.$)'
-            # Only occurs on PHP ≥ 8.2
-            reportUnmatched: false
+    treatPhpDocTypesAsCertain: false # TODO: Fix
 
 includes:
     - utils/PHPStan/extension.neon
+    - vendor/phpstan/phpstan-phpunit/extension.neon
+    - vendor/phpstan/phpstan-phpunit/rules.neon

+ 1 - 0
lib/simplepie/simplepie/src/Cache/Psr16.php

@@ -83,6 +83,7 @@ final class Psr16 implements DataCache
      */
     public function set_data(string $key, array $value, ?int $ttl = null): bool
     {
+        // @phpstan-ignore argument.type (mixed is not supported by PHP < 8.0, used by psr/simple-cache >= 2)
         return $this->cache->set($key, $value, $ttl);
     }
 

+ 1 - 0
lib/simplepie/simplepie/src/Enclosure.php

@@ -195,6 +195,7 @@ class Enclosure
      * @param Rating[]|null $ratings
      * @param Restriction[]|null $restrictions
      * @param string[]|null $thumbnails
+     * @phpstan-ignore constructor.unusedParameter
      */
     public function __construct(
         ?string $link = null,

+ 11 - 3
lib/simplepie/simplepie/src/File.php

@@ -645,7 +645,7 @@ class File implements Response
     /**
      * @param array<string, string> $headers
      * @param array<int, mixed> $curl_options
-     * @return \CurlHandle
+     * @return resource
      */
     private static function curlInit(
         string $url,
@@ -656,6 +656,9 @@ class File implements Response
         bool $setAcceptEncoding = true
     ) {
         $fp = curl_init();
+        if ($fp === false) {
+            throw new \SimplePie\Exception('Could not initialize cURL');
+        }
 
         $headers2 = [];
         foreach ($headers as $key => $value) {
@@ -683,8 +686,13 @@ class File implements Response
         curl_setopt($fp, CURLOPT_FAILONERROR, true);
         curl_setopt($fp, CURLOPT_TIMEOUT, $timeout);
         curl_setopt($fp, CURLOPT_CONNECTTIMEOUT, $timeout);
-        // curl_setopt($fp, CURLOPT_REFERER, \SimplePie\Misc::url_remove_credentials($url)); // FreshRSS removed
-        curl_setopt($fp, CURLOPT_USERAGENT, $useragent);
+        // $referer = \SimplePie\Misc::url_remove_credentials($url);
+        // if ($referer !== '') {
+        //     curl_setopt($fp, CURLOPT_REFERER, $referer); // FreshRSS removed
+        // }
+        if ($useragent !== '') {
+            curl_setopt($fp, CURLOPT_USERAGENT, $useragent);
+        }
         curl_setopt($fp, CURLOPT_HTTPHEADER, $headers2);
         foreach ($curl_options as $curl_param => $curl_value) {
             curl_setopt($fp, $curl_param, $curl_value);

+ 0 - 1
lib/simplepie/simplepie/src/HTTP/FileClient.php

@@ -45,7 +45,6 @@ final class FileClient implements Client
      */
     public function request(string $method, string $url, array $headers = []): Response
     {
-        // @phpstan-ignore-next-line Enforce PHPDoc type.
         if ($method !== self::METHOD_GET) {
             throw new InvalidArgumentException(sprintf(
                 '%s(): Argument #1 ($method) only supports method "%s".',

+ 25 - 30
lib/simplepie/simplepie/src/Locator.php

@@ -7,7 +7,6 @@ declare(strict_types=1);
 
 namespace SimplePie;
 
-use DomDocument;
 use Psr\Http\Client\ClientInterface;
 use Psr\Http\Message\RequestFactoryInterface;
 use Psr\Http\Message\UriFactoryInterface;
@@ -51,7 +50,7 @@ class Locator implements RegistryAware
     public $force_fsockopen;
     /** @var array<int, mixed> */
     public $curl_options;
-    /** @var ?\DomDocument */
+    /** @var ?\Dom\HTMLDocument */
     public $dom;
     /** @var ?Registry */
     protected $registry;
@@ -75,18 +74,13 @@ class Locator implements RegistryAware
 
         $body = $this->file->get_body_content();
 
-        if (class_exists('DOMDocument') && $body != '') {
-            $this->dom = new \DOMDocument();
-
-            set_error_handler([Misc::class, 'silence_errors']);
+        if (class_exists(\Dom\HTMLDocument::class) && $body != '') {
+            // NB: Unlike with the legacy DOM API, parsing never fails, but invalid UTF-8 fails gracefully
             try {
-                $this->dom->loadHTML($body);
+                $this->dom = \Dom\HTMLDocument::createFromString($body, LIBXML_NOERROR | \Dom\HTML_NO_DEFAULT_NS);
             } catch (\Throwable $ex) {
                 $this->dom = null;
             }
-            restore_error_handler();
-        } else {
-            $this->dom = null;
         }
     }
 
@@ -193,14 +187,14 @@ class Locator implements RegistryAware
         assert($this->registry !== null);
 
         if ($this->dom === null) {
-            throw new \SimplePie\Exception('DOMDocument not found, unable to use locator');
+            throw new \SimplePie\Exception('\Dom\Document not found, unable to use locator');
         }
         $this->http_base = $this->file->get_final_requested_uri();
         $this->base = $this->http_base;
         $elements = $this->dom->getElementsByTagName('base');
         foreach ($elements as $element) {
             if ($element->hasAttribute('href')) {
-                $base = $this->registry->call(Misc::class, 'absolutize_url', [trim($element->getAttribute('href')), $this->http_base]);
+                $base = $this->registry->call(Misc::class, 'absolutize_url', [trim($element->getAttribute('href') ?? ''), $this->http_base]);
                 if ($base === false) {
                     continue;
                 }
@@ -239,7 +233,7 @@ class Locator implements RegistryAware
         assert($this->registry !== null);
 
         if ($this->dom === null) {
-            throw new \SimplePie\Exception('DOMDocument not found, unable to use locator');
+            throw new \SimplePie\Exception('\Dom\Document not found, unable to use locator');
         }
 
         $links = $this->dom->getElementsByTagName($name);
@@ -248,19 +242,19 @@ class Locator implements RegistryAware
                 break;
             }
             if ($link->hasAttribute('href') && $link->hasAttribute('rel')) {
-                $rel = array_unique($this->registry->call(Misc::class, 'space_separated_tokens', [strtolower($link->getAttribute('rel'))]));
+                $rel = array_unique($this->registry->call(Misc::class, 'space_separated_tokens', [strtolower($link->getAttribute('rel') ?? '')]));
                 $line = $link->getLineNo();
 
                 if ($this->base_location < $line) {
-                    $href = $this->registry->call(Misc::class, 'absolutize_url', [trim($link->getAttribute('href')), $this->base]);
+                    $href = $this->registry->call(Misc::class, 'absolutize_url', [trim($link->getAttribute('href') ?? ''), $this->base]);
                 } else {
-                    $href = $this->registry->call(Misc::class, 'absolutize_url', [trim($link->getAttribute('href')), $this->http_base]);
+                    $href = $this->registry->call(Misc::class, 'absolutize_url', [trim($link->getAttribute('href') ?? ''), $this->http_base]);
                 }
                 if ($href === false) {
                     continue;
                 }
 
-                if (!in_array($href, $done) && in_array('feed', $rel) || (in_array('alternate', $rel) && !in_array('stylesheet', $rel) && $link->hasAttribute('type') && in_array(strtolower($this->registry->call(Misc::class, 'parse_mime', [$link->getAttribute('type')])), ['text/html', 'application/rss+xml', 'application/atom+xml'])) && !isset($feeds[$href])) {
+                if (!in_array($href, $done) && in_array('feed', $rel) || (in_array('alternate', $rel) && !in_array('stylesheet', $rel) && $link->hasAttribute('type') && in_array(strtolower($this->registry->call(Misc::class, 'parse_mime', [$link->getAttribute('type') ?? ''])), ['text/html', 'application/rss+xml', 'application/atom+xml'])) && !isset($feeds[$href])) {
                     $this->checked_feeds++;
                     $headers = [
                         'Accept' => SimplePie::DEFAULT_HTTP_ACCEPT_HEADER,
@@ -291,19 +285,19 @@ class Locator implements RegistryAware
         assert($this->registry !== null);
 
         if ($this->dom === null) {
-            throw new \SimplePie\Exception('DOMDocument not found, unable to use locator');
+            throw new \SimplePie\Exception('\Dom\Document not found, unable to use locator');
         }
 
         $links = $this->dom->getElementsByTagName('a');
         foreach ($links as $link) {
             if ($link->hasAttribute('href')) {
-                $href = trim($link->getAttribute('href'));
+                $href = trim($link->getAttribute('href') ?? '');
                 $parsed = $this->registry->call(Misc::class, 'parse_url', [$href]);
                 if ($parsed['scheme'] === '' || preg_match('/^(https?|feed)?$/i', $parsed['scheme'])) {
                     if ($this->base_location < $link->getLineNo()) {
-                        $href = $this->registry->call(Misc::class, 'absolutize_url', [trim($link->getAttribute('href')), $this->base]);
+                        $href = $this->registry->call(Misc::class, 'absolutize_url', [trim($link->getAttribute('href') ?? ''), $this->base]);
                     } else {
-                        $href = $this->registry->call(Misc::class, 'absolutize_url', [trim($link->getAttribute('href')), $this->http_base]);
+                        $href = $this->registry->call(Misc::class, 'absolutize_url', [trim($link->getAttribute('href') ?? ''), $this->http_base]);
                     }
                     if ($href === false) {
                         continue;
@@ -337,20 +331,21 @@ class Locator implements RegistryAware
         assert($this->registry !== null);
 
         if ($this->dom === null) {
-            throw new \SimplePie\Exception('DOMDocument not found, unable to use '.
+            throw new \SimplePie\Exception('\Dom\Document not found, unable to use '.
                                           'locator');
         }
-        if (!class_exists('DOMXpath')) {
-            throw new \SimplePie\Exception('DOMXpath not found, unable to use '.
+
+        if (!class_exists(\Dom\XPath::class)) {
+            throw new \SimplePie\Exception('\Dom\XPath not found, unable to use '.
                                           'get_rel_link');
         }
 
-        $xpath = new \DOMXpath($this->dom);
+        $xpath = new \Dom\XPath($this->dom);
         $query = '(//head)[1]/link[@rel and @href]';
-        /** @var \DOMNodeList<\DOMElement> */
+        /** @var \Dom\NodeList<\Dom\Element> */
         $queryResult = $xpath->query($query);
         foreach ($queryResult as $link) {
-            $href = trim($link->getAttribute('href'));
+            $href = trim($link->getAttribute('href') ?? '');
             $parsed = $this->registry->call(Misc::class, 'parse_url', [$href]);
             if ($parsed['scheme'] === '' ||
                 preg_match('/^https?$/i', $parsed['scheme'])) {
@@ -358,19 +353,19 @@ class Locator implements RegistryAware
                     $href = $this->registry->call(
                         Misc::class,
                         'absolutize_url',
-                        [trim($link->getAttribute('href')), $this->base]
+                        [trim($link->getAttribute('href') ?? ''), $this->base]
                     );
                 } else {
                     $href = $this->registry->call(
                         Misc::class,
                         'absolutize_url',
-                        [trim($link->getAttribute('href')), $this->http_base]
+                        [trim($link->getAttribute('href') ?? ''), $this->http_base]
                     );
                 }
                 if ($href === false) {
                     return null;
                 }
-                $rel_values = explode(' ', strtolower($link->getAttribute('rel')));
+                $rel_values = explode(' ', strtolower($link->getAttribute('rel') ?? ''));
                 if (in_array($rel, $rel_values)) {
                     return $href;
                 }

+ 1 - 1
lib/simplepie/simplepie/src/Misc.php

@@ -2170,7 +2170,7 @@ JS;
             $info .= "No error found.\n";
         }
         $info .= "Extensions:\n";
-        $extensions = ['pcre', 'curl', 'zlib', 'mbstring', 'iconv', 'xmlreader', 'xml'];
+        $extensions = ['pcre', 'curl', 'zlib', 'mbstring', 'iconv', 'xml'];
         foreach ($extensions as $ext) {
             if (extension_loaded($ext)) {
                 $info .= "    $ext loaded\n";

+ 48 - 100
lib/simplepie/simplepie/src/Parser.php

@@ -69,15 +69,16 @@ class Parser implements RegistryAware
      */
     public function parse(string &$data, string $encoding, string $url = '')
     {
-        if (class_exists('DOMXpath') && function_exists('Mf2\parse')) {
-            $doc = new \DOMDocument();
-            @$doc->loadHTML($data);
-            $xpath = new \DOMXpath($doc);
+        if (class_exists(\Dom\XPath::class) && function_exists('Mf2\parse')) {
+            // NB: Unlike with the legacy DOM API, parsing never fails (no recovery needed),
+            // and errors are swallowed by `LIBXML_NOERROR`.
+            $doc = \Dom\HTMLDocument::createFromString($data, LIBXML_NOERROR);
+            $xpath = new \Dom\XPath($doc);
             // Check for both h-feed and h-entry, as both a feed with no entries
             // and a list of entries without an h-feed wrapper are both valid.
             $query = '//*[contains(concat(" ", @class, " "), " h-feed ") or '.
                 'contains(concat(" ", @class, " "), " h-entry ")]';
-            /** @var \DOMNodeList<\DOMElement> $result */
+            /** @var \Dom\NodeList<\Dom\Element> $result */
             $result = $xpath->query($query);
             if ($result->length !== 0) {
                 return $this->parse_microformats($data, $url);
@@ -94,22 +95,27 @@ class Parser implements RegistryAware
         // Strip BOM:
         // UTF-32 Big Endian BOM
         if (substr($data, 0, 4) === "\x00\x00\xFE\xFF") {
+            /** @phpstan-ignore parameterByRef.type (for PHP < 8.0) */
             $data = substr($data, 4);
         }
         // UTF-32 Little Endian BOM
         elseif (substr($data, 0, 4) === "\xFF\xFE\x00\x00") {
+            /** @phpstan-ignore parameterByRef.type (for PHP < 8.0) */
             $data = substr($data, 4);
         }
         // UTF-16 Big Endian BOM
         elseif (substr($data, 0, 2) === "\xFE\xFF") {
+            /** @phpstan-ignore parameterByRef.type (for PHP < 8.0) */
             $data = substr($data, 2);
         }
         // UTF-16 Little Endian BOM
         elseif (substr($data, 0, 2) === "\xFF\xFE") {
+            /** @phpstan-ignore parameterByRef.type (for PHP < 8.0) */
             $data = substr($data, 2);
         }
         // UTF-8 BOM
         elseif (substr($data, 0, 3) === "\xEF\xBB\xBF") {
+            /** @phpstan-ignore parameterByRef.type (for PHP < 8.0) */
             $data = substr($data, 3);
         }
 
@@ -121,6 +127,7 @@ class Parser implements RegistryAware
         if (substr($data, 0, 5) === '<?xml' && strspn(substr($data, 5, 1), "\x09\x0A\x0D\x20") && ($pos = strpos($data, '?>')) !== false) {
             $declaration = $this->registry->create(DeclarationParser::class, [substr($data, 5, $pos - 5)]);
             if ($declaration->parse()) {
+                /** @phpstan-ignore parameterByRef.type (for PHP < 8.0) */
                 $data = substr($data, $pos + 2);
                 $data = '<?xml version="' . $declaration->version . '" encoding="' . $encoding . '" standalone="' . (($declaration->standalone) ? 'yes' : 'no') . '"?>' . "\n" .
                     self::set_doctype($data);
@@ -134,107 +141,45 @@ class Parser implements RegistryAware
 
         $return = true;
 
-        static $xml_is_sane = null;
-        if ($xml_is_sane === null) {
-            $parser_check = xml_parser_create();
-            xml_parse_into_struct($parser_check, '<foo>&amp;</foo>', $values);
-            if (\PHP_VERSION_ID < 80000) {
-                xml_parser_free($parser_check);
-            }
-            $xml_is_sane = isset($values[0]['value']);
-        }
-
         // Create the parser
-        if ($xml_is_sane) {
-            $xml = xml_parser_create_ns($this->encoding, $this->separator);
-            xml_parser_set_option($xml, XML_OPTION_SKIP_WHITE, 1);
-            xml_parser_set_option($xml, XML_OPTION_CASE_FOLDING, 0);
-            if (defined('XML_OPTION_PARSE_HUGE')) {
-                xml_parser_set_option($xml, XML_OPTION_PARSE_HUGE, 1);
-            }
-            xml_set_character_data_handler($xml, [$this, 'cdata']);
-            xml_set_element_handler($xml, [$this, 'tag_open'], [$this, 'tag_close']);
-
-            // Parse!
-            $wrapper = @is_writable(sys_get_temp_dir()) ? 'php://temp' : 'php://memory';
-            if (($stream = fopen($wrapper, 'r+')) &&
-                fwrite($stream, $data) &&
-                rewind($stream)) {
-                //Parse by chunks not to use too much memory
-                do {
-                    $stream_data = (string) fread($stream, 1048576);
-
-                    if (!xml_parse($xml, $stream_data, feof($stream))) {
-                        $this->error_code = xml_get_error_code($xml);
-                        $this->error_string = xml_error_string($this->error_code) ?: "Unknown";
-                        $return = false;
-                        break;
-                    }
-                } while (!feof($stream));
-                fclose($stream);
-            } else {
-                $return = false;
-            }
-
-            $this->current_line = xml_get_current_line_number($xml);
-            $this->current_column = xml_get_current_column_number($xml);
-            $this->current_byte = xml_get_current_byte_index($xml);
-            if (\PHP_VERSION_ID < 80000) {
-                xml_parser_free($xml);
-            }
-            return $return;
+        $xml = xml_parser_create_ns($this->encoding, $this->separator);
+        xml_parser_set_option($xml, XML_OPTION_SKIP_WHITE, 1);
+        xml_parser_set_option($xml, XML_OPTION_CASE_FOLDING, 0);
+        if (defined('XML_OPTION_PARSE_HUGE')) {
+            xml_parser_set_option($xml, XML_OPTION_PARSE_HUGE, 1);
         }
-
-        libxml_clear_errors();
-        $xml = new \XMLReader();
-        $xml->xml($data);
-        while (@$xml->read()) {
-            switch ($xml->nodeType) {
-                case \XMLReader::END_ELEMENT:
-                    if ($xml->namespaceURI !== '') {
-                        $tagName = $xml->namespaceURI . $this->separator . $xml->localName;
-                    } else {
-                        $tagName = $xml->localName;
-                    }
-                    $this->tag_close(null, $tagName);
-                    break;
-                case \XMLReader::ELEMENT:
-                    $empty = $xml->isEmptyElement;
-                    if ($xml->namespaceURI !== '') {
-                        $tagName = $xml->namespaceURI . $this->separator . $xml->localName;
-                    } else {
-                        $tagName = $xml->localName;
-                    }
-                    $attributes = [];
-                    while ($xml->moveToNextAttribute()) {
-                        if ($xml->namespaceURI !== '') {
-                            $attrName = $xml->namespaceURI . $this->separator . $xml->localName;
-                        } else {
-                            $attrName = $xml->localName;
-                        }
-                        $attributes[$attrName] = $xml->value;
-                    }
-                    $this->tag_open(null, $tagName, $attributes);
-                    if ($empty) {
-                        $this->tag_close(null, $tagName);
-                    }
-                    break;
-                case \XMLReader::TEXT:
-
-                case \XMLReader::CDATA:
-                    $this->cdata(null, $xml->value);
+        xml_set_character_data_handler($xml, [$this, 'cdata']);
+        xml_set_element_handler($xml, [$this, 'tag_open'], [$this, 'tag_close']);
+
+        // Parse!
+        $wrapper = @is_writable(sys_get_temp_dir()) ? 'php://temp' : 'php://memory';
+        if (($stream = fopen($wrapper, 'r+')) &&
+            fwrite($stream, $data) &&
+            rewind($stream)) {
+            //Parse by chunks not to use too much memory
+            do {
+                $stream_data = (string) fread($stream, 1048576);
+
+                if (!xml_parse($xml, $stream_data, feof($stream))) {
+                    $this->error_code = xml_get_error_code($xml);
+                    $this->error_string = xml_error_string($this->error_code) ?: "Unknown";
+                    $return = false;
                     break;
-            }
+                }
+            } while (!feof($stream));
+            fclose($stream);
+        } else {
+            $return = false;
         }
-        if ($error = libxml_get_last_error()) {
-            $this->error_code = $error->code;
-            $this->error_string = $error->message;
-            $this->current_line = $error->line;
-            $this->current_column = $error->column;
-            return false;
+
+        $this->current_line = xml_get_current_line_number($xml);
+        $this->current_column = xml_get_current_column_number($xml);
+        $this->current_byte = xml_get_current_byte_index($xml);
+        if (\PHP_VERSION_ID < 80000) {
+            xml_parser_free($xml);
         }
 
-        return true;
+        return $return;
     }
 
     /**
@@ -289,6 +234,7 @@ class Parser implements RegistryAware
      * @param XMLParser|resource|null $parser
      * @param array<string, string> $attributes
      * @return void
+     * @phpstan-ignore class.notFound (XMLParser requires PHP >= 8.0)
      */
     public function tag_open($parser, string $tag, array $attributes)
     {
@@ -345,6 +291,7 @@ class Parser implements RegistryAware
     /**
      * @param XMLParser|resource|null $parser
      * @return void
+     * @phpstan-ignore class.notFound (XMLParser requires PHP >= 8.0)
      */
     public function cdata($parser, string $cdata)
     {
@@ -358,6 +305,7 @@ class Parser implements RegistryAware
     /**
      * @param XMLParser|resource|null $parser
      * @return void
+     * @phpstan-ignore class.notFound (XMLParser requires PHP >= 8.0)
      */
     public function tag_close($parser, string $tag)
     {

+ 1 - 0
lib/simplepie/simplepie/src/Registry.php

@@ -206,6 +206,7 @@ class Registry
             $instance->set_registry($this);
         } elseif (method_exists($instance, 'set_registry')) {
             trigger_error(sprintf('Using the method "set_registry()" without implementing "%s" is deprecated since SimplePie 1.8.0, implement "%s" in "%s".', RegistryAware::class, RegistryAware::class, $class), \E_USER_DEPRECATED);
+            // @phpstan-ignore method.nonObject
             $instance->set_registry($this);
         }
 

+ 112 - 97
lib/simplepie/simplepie/src/Sanitize.php

@@ -7,8 +7,6 @@ declare(strict_types=1);
 
 namespace SimplePie;
 
-use DOMDocument;
-use DOMXPath;
 use InvalidArgumentException;
 use Psr\Http\Client\ClientInterface;
 use Psr\Http\Message\RequestFactoryInterface;
@@ -166,7 +164,6 @@ class Sanitize implements RegistryAware
             $this->cache_location = $cache_location;
         }
 
-        // @phpstan-ignore-next-line Enforce PHPDoc type.
         if (!is_string($cache_name_function) && !$cache_name_function instanceof NameFilter) {
             throw new InvalidArgumentException(sprintf(
                 '%s(): Argument #3 ($cache_name_function) must be of type %s',
@@ -485,27 +482,30 @@ class Sanitize implements RegistryAware
             }
 
             if ($type & (\SimplePie\SimplePie::CONSTRUCT_HTML | \SimplePie\SimplePie::CONSTRUCT_XHTML)) {
-                if (!class_exists('DOMDocument')) {
-                    throw new \SimplePie\Exception('DOMDocument not found, unable to use sanitizer');
-                }
-                $document = new \DOMDocument();
-                $document->encoding = 'UTF-8';
-
                 // PHPStan seems to have trouble resolving int-mask because bitwise
                 // operators are used when operators are used when passing this parameter.
                 // https://github.com/phpstan/phpstan/issues/9384
                 /** @var int-mask-of<SimplePie::CONSTRUCT_*> $type */
                 $data = $this->preprocess($data, $type);
 
-                set_error_handler([Misc::class, 'silence_errors']);
-                $document->loadHTML($data);
-                restore_error_handler();
-
-                $xpath = new \DOMXPath($document);
+                // NB: Unlike with the legacy DOM API, parsing never fails (no recovery needed).
+                // Without HTML_NO_DEFAULT_NS, elements are parsed into their proper
+                // namespaces (XHTML, SVG, MathML), which makes the HTML5 serialiser
+                // emit void elements correctly ("<img>", no "</img>" end tag), and
+                // allows the XPath queries below to use registered prefixes.
+                $document = \Dom\HTMLDocument::createFromString($data, LIBXML_NOERROR);
+
+                $xpath = new \Dom\XPath($document);
+                // Register the namespaces used by the HTML parser, for the prefixed
+                // XPath queries below. Unprefixed name tests would only match
+                // elements in no namespace, i.e. none.
+                $xpath->registerNamespace('xh', 'http://www.w3.org/1999/xhtml');
+                $xpath->registerNamespace('svg', 'http://www.w3.org/2000/svg');
+                $xpath->registerNamespace('mml', 'http://www.w3.org/1998/Math/MathML');
 
                 // Strip comments
                 if ($this->strip_comments) {
-                    /** @var \DOMNodeList<\DOMComment> */
+                    /** @var \Dom\NodeList<\Dom\Comment> */
                     $comments = $xpath->query('//comment()');
 
                     foreach ($comments as $comment) {
@@ -566,7 +566,8 @@ class Sanitize implements RegistryAware
 
                     foreach ($images as $img) {
                         if ($img->hasAttribute('src')) {
-                            $image_url = $this->cache_namefilter->filter($img->getAttribute('src'));
+                            $src = $img->getAttribute('src') ?? '';
+                            $image_url = $this->cache_namefilter->filter($src);
                             $cache = $this->get_cache($image_url);
 
                             if ($cache->get_data($image_url, false)) {
@@ -575,7 +576,7 @@ class Sanitize implements RegistryAware
                                 try {
                                     $file = $this->get_http_client()->request(
                                         Client::METHOD_GET,
-                                        $img->getAttribute('src'),
+                                        $src,
                                         ['X-FORWARDED-FOR' => $_SERVER['REMOTE_ADDR']]
                                     );
                                 } catch (ClientException $th) {
@@ -600,18 +601,16 @@ class Sanitize implements RegistryAware
                     $div = $item->firstChild;
                 }
                 // Finally, convert to a HTML string
-                $data = trim((string) $document->saveHTML($div));
+                $data = trim($document->saveHtml($div) ?: '');
 
                 if ($this->remove_div) {
-                    $data = preg_replace('/^<div' . \SimplePie\SimplePie::PCRE_XML_ATTRIBUTE . '>/', '', $data);
-                    // Cast for PHPStan, it is unable to validate a non-literal regex above.
-                    $data = preg_replace('/<\/div>$/', '', (string) $data);
+                    // Casts for PHPStan, it is unable to validate a non-literal regex above.
+                    $data = (string) preg_replace('/^<div' . \SimplePie\SimplePie::PCRE_XML_ATTRIBUTE . '>/', '', $data);
+                    $data = (string) preg_replace('/<\/div>$/', '', $data);
                 } else {
-                    $data = preg_replace('/^<div' . \SimplePie\SimplePie::PCRE_XML_ATTRIBUTE . '>/', '<div>', $data);
+                    // Cast for PHPStan, it is unable to validate a non-literal regex above.
+                    $data = (string) preg_replace('/^<div' . \SimplePie\SimplePie::PCRE_XML_ATTRIBUTE . '>/', '<div>', $data);
                 }
-
-                // Cast for PHPStan, it is unable to validate a non-literal regex above.
-                $data = str_replace('</source>', '', (string) $data);
             }
 
             if ($type & \SimplePie\SimplePie::CONSTRUCT_IRI) {
@@ -660,10 +659,11 @@ class Sanitize implements RegistryAware
     }
 
     /**
+     * @param \Dom\Document|\DOMDocument $document
      * @param array<string>|string $attributes
      * @return void
      */
-    public function replace_urls(DOMDocument $document, string $tag, $attributes)
+    public function replace_urls($document, string $tag, $attributes)
     {
         if (!is_array($attributes)) {
             $attributes = [$attributes];
@@ -674,7 +674,7 @@ class Sanitize implements RegistryAware
             foreach ($elements as $element) {
                 foreach ($attributes as $attribute) {
                     if ($element->hasAttribute($attribute)) {
-                        $value = $this->registry->call(Misc::class, 'absolutize_url', [$element->getAttribute($attribute), $this->base]);
+                        $value = $this->registry->call(Misc::class, 'absolutize_url', [$element->getAttribute($attribute) ?? '', $this->base]);
                         if ($value !== false) {
                             // Block disallowed URI protocols (e.g. javascript:), otherwise force HTTPS where applicable
                             $value = ($this->disallowed_uri_schemes !== [] && !$this->is_allowed_uri($tag, $attribute, $value))
@@ -711,11 +711,16 @@ class Sanitize implements RegistryAware
 
     /**
      * Keep only allowed HTML elements (tags) and their allowed attributes.
+     *
+     * @param \Dom\Node|\DOMNode|\DOMElement|\Dom\Element $element
      */
-    protected function enforce_allowed_html_nodes(\DOMNode $element, bool $allow_data_attr = true, bool $allow_aria_attr = true): void
+    protected function enforce_allowed_html_nodes($element, bool $allow_data_attr = true, bool $allow_aria_attr = true): void
     {
-        if ($element instanceof \DOMElement) {
-            $tag = $element->tagName;
+        if ($element instanceof \DOMElement || $element instanceof \Dom\Element) {
+            // NB: `tagName` of namespaced HTML elements is uppercased by libxml.
+            // Use `localName` instead, which is ASCII-lowercased as per HTML,
+            // except for case-adjusted SVG/MathML tag names (e.g. `foreignObject`).
+            $tag = $element->localName;
             $parent = $element->parentNode;
             if (!in_array($tag, ['html', 'head', 'body', 'div'], true)
                 && !isset($this->allowed_html_elements_with_attributes[$tag])) {
@@ -724,7 +729,7 @@ class Sanitize implements RegistryAware
                     $nextSibling = $element->nextSibling;
                     while ($element->firstChild !== null) {
                         $child = $element->firstChild;
-                        if ($child instanceof \DOMText) {
+                        if ($child instanceof \DOMText || $child instanceof \Dom\Text) {
                             $child->nodeValue = htmlspecialchars($child->nodeValue ?? '', ENT_QUOTES, 'UTF-8');
                         }
                         if ($parent !== null) {
@@ -738,25 +743,31 @@ class Sanitize implements RegistryAware
                     }
                 }
                 if ($parent !== null) {
-                    $parent->removeChild($element);
+                    if ($element instanceof \DOMElement) {
+                        $parent->removeChild($element);
+                    } elseif ($parent instanceof \Dom\Element || $parent instanceof \Dom\Document) {
+                        $parent->removeChild($element);
+                    }
                     return;
                 }
             }
             $allowed_attrs = array_merge($this->allowed_html_elements_with_attributes[$tag] ?? [], $this->allowed_html_attributes);
-            for ($i = $element->attributes->length - 1; $i >= 0; $i--) {
-                $attr = $element->attributes[$i]->nodeName;
+            $attributes = $element->attributes ?? [];
+            for ($i = $attributes->length - 1; $i >= 0; $i--) {
+                $attrNode = $attributes[$i];
+                $attr = $attrNode->nodeName;
                 // Skip data-*, aria-* if allowed
-                if (($allow_data_attr && str_starts_with($attr, 'data-'))
-                    || ($allow_aria_attr && str_starts_with($attr, 'aria-'))) {
+                if (($allow_data_attr && substr($attr, 0, 5) === 'data-')
+                    || ($allow_aria_attr && substr($attr, 0, 5) === 'aria-')) {
                     continue;
                 }
 
                 if (!in_array($attr, $allowed_attrs, true)) {
-                    $element->removeAttributeNode($element->attributes[$i]);
+                    $element->removeAttributeNode($attrNode);
                 }
             }
         }
-        if ($element instanceof \DOMElement || $element instanceof \DOMDocument) {
+        if ($element instanceof \DOMElement || $element instanceof \Dom\Element || $element instanceof \DOMDocument || $element instanceof \Dom\Document) {
             for ($i = $element->childNodes->length - 1; $i >= 0; $i--) {
                 $child = $element->childNodes->item($i);
                 if ($child !== null) {
@@ -815,41 +826,44 @@ class Sanitize implements RegistryAware
      * This handles MathML and SVG elements which permit href on arbitrary descendant elements
      * For SVG, also checks xlink:href attribute.
      */
-    private function block_disallowed_schemes_in_descendants(\DOMXPath $xpath): void
+    private function block_disallowed_schemes_in_descendants(\Dom\XPath $xpath): void
     {
-        // Note: content is parsed via loadHTML(), which does not namespace-process attributes
-        $elements = $xpath->query('.//*[self::math or self::svg]/descendant-or-self::*[@href or @*[name()="xlink:href"]]');
-        if ($elements === false) {
-            return;
-        }
+        // NB: SVG and MathML elements are parsed into their own namespaces
+        // (cf. the `registerNamespace()` calls above).
+        // Note: content is parsed via the HTML5 parser, which does not namespace-process attributes
+        $elements = $xpath->query('.//*[self::mml:math or self::svg:svg]/descendant-or-self::*[@href or @*[name()="xlink:href"]]');
         foreach ($elements as $element) {
-            if (!($element instanceof \DOMElement)) {
-                continue;
-            }
-            if ($element->hasAttribute('href')) {
-                $href = $element->getAttribute('href');
-                if (!$this->is_allowed_scheme($href)) {
-                    $element->setAttribute('href', 'unsafe:' . $href);
+            if ($element instanceof \DOMElement || $element instanceof \Dom\Element) {
+                if ($element->hasAttribute('href')) {
+                    $href = $element->getAttribute('href') ?? '';
+                    if (!$this->is_allowed_scheme($href)) {
+                        $element->setAttribute('href', 'unsafe:' . $href);
+                    }
                 }
-            }
-            if ($element->hasAttribute('xlink:href')) {
-                $href = $element->getAttribute('xlink:href');
-                if (!$this->is_allowed_scheme($href)) {
-                    $element->setAttribute('xlink:href', 'unsafe:' . $href);
+                if ($element->hasAttribute('xlink:href')) {
+                    $href = $element->getAttribute('xlink:href') ?? '';
+                    if (!$this->is_allowed_scheme($href)) {
+                        $element->setAttribute('xlink:href', 'unsafe:' . $href);
+                    }
                 }
             }
         }
     }
 
     /**
+     * @param \Dom\Document|\DOMDocument $document
      * @param int-mask-of<SimplePie::CONSTRUCT_*> $type
      * @return void
      */
-    protected function strip_tag(string $tag, DOMDocument $document, DOMXPath $xpath, int $type)
+    protected function strip_tag(string $tag, $document, \Dom\XPath $xpath, int $type)
     {
-        $elements = $xpath->query('body//' . $tag);
-
-        if ($elements === false) {
+        try {
+            // Match the requested tag in any of the namespaces the HTML parser
+            // puts elements in (cf. the three `registerNamespace()` calls above):
+            // mostly the XHTML namespace, but e.g. `image` exists in both
+            // XHTML and SVG.
+            $elements = $xpath->query('xh:body//*[self::xh:' . $tag . ' or self::svg:' . $tag . ' or self::mml:' . $tag . ']');
+        } catch (\Throwable $ex) {
             throw new \SimplePie\Exception(sprintf(
                 '%s(): Possibly malformed expression, check argument #1 ($tag)',
                 __METHOD__
@@ -858,7 +872,7 @@ class Sanitize implements RegistryAware
 
         if ($this->encode_instead_of_strip) {
             foreach ($elements as $element) {
-                if (!($element instanceof \DOMNode)) {
+                if (!$element instanceof \DOMElement && !$element instanceof \Dom\Element) {
                     continue;
                 }
                 $fragment = $document->createDocumentFragment();
@@ -866,28 +880,26 @@ class Sanitize implements RegistryAware
                 // For elements which aren't script or style, include the tag itself
                 if (!in_array($tag, ['script', 'style'])) {
                     $text = '<' . $tag;
-                    if ($element->attributes !== null) {
-                        $attrs = [];
-                        foreach ($element->attributes as $name => $attr) {
-                            $value = $attr->value;
-
-                            // In XHTML, empty values should never exist, so we repeat the value
-                            if (empty($value) && ($type & \SimplePie\SimplePie::CONSTRUCT_XHTML)) {
-                                $value = $name;
-                            }
-                            // For HTML, empty is fine
-                            elseif (empty($value) && ($type & \SimplePie\SimplePie::CONSTRUCT_HTML)) {
-                                $attrs[] = $name;
-                                continue;
-                            }
+                    $attrs = [];
+                    foreach ($element->attributes as $name => $attr) {
+                        $value = $attr->value;
 
-                            // Standard attribute text
-                            $attrs[] = $name . '="' . $attr->value . '"';
+                        // In XHTML, empty values should never exist, so we repeat the value
+                        if (empty($value) && ($type & \SimplePie\SimplePie::CONSTRUCT_XHTML)) {
+                            $value = $name;
+                        }
+                        // For HTML, empty is fine
+                        elseif (empty($value) && ($type & \SimplePie\SimplePie::CONSTRUCT_HTML)) {
+                            $attrs[] = $name;
+                            continue;
                         }
-                        $text .= ' ' . implode(' ', $attrs);
+
+                        // Standard attribute text
+                        $attrs[] = $name . '="' . $attr->value . '"';
                     }
+                    $text .= ' ' . implode(' ', $attrs);
                     $text .= '>';
-                    $fragment->appendChild(new \DOMText($text));
+                    $fragment->appendChild($document->createTextNode($text));
                 }
 
                 $number = $element->childNodes->length;
@@ -898,10 +910,15 @@ class Sanitize implements RegistryAware
                 }
 
                 if (!in_array($tag, ['script', 'style'])) {
-                    $fragment->appendChild(new \DOMText('</' . $tag . '>'));
+                    $fragment->appendChild($document->createTextNode('</' . $tag . '>'));
                 }
 
-                if (($parentNode = $element->parentNode) !== null) {
+                $parentNode = $element->parentNode;
+                if ($element instanceof \DOMElement) {
+                    if ($parentNode !== null) {
+                        $parentNode->replaceChild($fragment, $element);
+                    }
+                } elseif ($parentNode instanceof \Dom\Element || $parentNode instanceof \Dom\Document) {
                     $parentNode->replaceChild($fragment, $element);
                 }
             }
@@ -917,9 +934,6 @@ class Sanitize implements RegistryAware
             return;
         } else {
             foreach ($elements as $element) {
-                if (!($element instanceof \DOMNode)) {
-                    continue;
-                }
                 $fragment = $document->createDocumentFragment();
                 $number = $element->childNodes->length;
                 for ($i = $number; $i > 0; $i--) {
@@ -938,18 +952,18 @@ class Sanitize implements RegistryAware
     /**
      * @return void
      */
-    protected function strip_attr(string $attrib, DOMXPath $xpath)
+    protected function strip_attr(string $attrib, \Dom\XPath $xpath)
     {
-        $elements = $xpath->query('//*[@' . $attrib . ']');
-
-        if ($elements === false) {
+        try {
+            $elements = $xpath->query('//*[@' . $attrib . ']');
+        } catch (\Throwable $ex) {
             throw new \SimplePie\Exception(sprintf(
                 '%s(): Possibly malformed expression, check argument #1 ($attrib)',
                 __METHOD__
             ), 1);
         }
 
-        /** @var \DOMElement $element */
+        /** @var \Dom\Element $element */
         foreach ($elements as $element) {
             $element->removeAttribute($attrib);
         }
@@ -958,32 +972,33 @@ class Sanitize implements RegistryAware
     /**
      * @return void
      */
-    protected function rename_attr(string $attrib, DOMXPath $xpath)
+    protected function rename_attr(string $attrib, \Dom\XPath $xpath)
     {
-        $elements = $xpath->query('//*[@' . $attrib . ']');
-
-        if ($elements === false) {
+        try {
+            $elements = $xpath->query('//*[@' . $attrib . ']');
+        } catch (\Throwable $ex) {
             throw new \SimplePie\Exception(sprintf(
                 '%s(): Possibly malformed expression, check argument #1 ($attrib)',
                 __METHOD__
             ), 1);
         }
 
-        /** @var \DOMElement $element */
+        /** @var \Dom\Element $element */
         foreach ($elements as $element) {
-            $element->setAttribute('data-sanitized-' . $attrib, $element->getAttribute($attrib));
+            $element->setAttribute('data-sanitized-' . $attrib, $element->getAttribute($attrib) ?? '');
             $element->removeAttribute($attrib);
         }
     }
 
     /**
      * @param array<string, string> $valuePairs
+     * @param \Dom\Document|\DOMDocument $document
      * @return void
      */
-    protected function add_attr(string $tag, array $valuePairs, DOMDocument $document)
+    protected function add_attr(string $tag, array $valuePairs, $document)
     {
         $elements = $document->getElementsByTagName($tag);
-        /** @var \DOMElement $element */
+        /** @var \Dom\Element $element */
         foreach ($elements as $element) {
             foreach ($valuePairs as $attrib => $value) {
                 $element->setAttribute($attrib, $value);

+ 8 - 25
lib/simplepie/simplepie/src/SimplePie.php

@@ -1807,21 +1807,6 @@ class SimplePie
             $this->error = 'XML or PCRE extensions not loaded!';
             return false;
         }
-        // Then check the xml extension is sane (i.e., libxml 2.7.x issue on PHP < 5.2.9 and libxml 2.7.0 to 2.7.2 on any version) if we don't have xmlreader.
-        elseif (!extension_loaded('xmlreader')) {
-            static $xml_is_sane = null;
-            if ($xml_is_sane === null) {
-                $parser_check = xml_parser_create();
-                xml_parse_into_struct($parser_check, '<foo>&amp;</foo>', $values);
-                if (\PHP_VERSION_ID < 80000) {
-                    xml_parser_free($parser_check);
-                }
-                $xml_is_sane = isset($values[0]['value']);
-            }
-            if (!$xml_is_sane) {
-                return false;
-            }
-        }
 
         // The default sanitize class gets set in the constructor, check if it has
         // changed.
@@ -2029,7 +2014,6 @@ class SimplePie
             $cache = new BaseDataCache($cache);
         }
 
-        // @phpstan-ignore-next-line Enforce PHPDoc type.
         if ($cache !== false && !$cache instanceof DataCache) {
             throw new InvalidArgumentException(sprintf(
                 '%s(): Argument #1 ($cache) must be of type %s|false',
@@ -2112,7 +2096,7 @@ class SimplePie
                             // Set raw_data to false here too, to signify that the cache
                             // is still valid.
                             $this->raw_data = false;
-                            if (isset($file)) { // FreshRSS
+                            if (isset($file)) { // FreshRSS // @phpstan-ignore isset.variable
                                 $old_cache_control = $this->data['headers']['cache-control'] ?? '';
                                 $old_max_age = \SimplePie\HTTP\Utils::get_http_max_age($this->data['headers']);
 
@@ -2227,16 +2211,17 @@ class SimplePie
                 $copyContentType = $file->get_header_line('content-type');
                 try {
                     $microformats = false;
-                    if (class_exists('DOMXpath') && function_exists('Mf2\parse')) {
-                        $doc = new \DOMDocument();
-                        @$doc->loadHTML($file->get_body_content());
-                        $xpath = new \DOMXpath($doc);
+                    if (class_exists(\Dom\XPath::class) && function_exists('Mf2\parse')) {
+                        // NB: Unlike with the legacy DOM API, parsing never fails (no recovery needed),
+                        // and errors are swallowed by `LIBXML_NOERROR`.
+                        $doc = \Dom\HTMLDocument::createFromString($file->get_body_content(), LIBXML_NOERROR);
+                        $xpath = new \Dom\XPath($doc);
                         // Check for both h-feed and h-entry, as both a feed with no entries
                         // and a list of entries without an h-feed wrapper are both valid.
                         $query = '//*[contains(concat(" ", @class, " "), " h-feed ") or '.
                             'contains(concat(" ", @class, " "), " h-entry ")]';
 
-                        /** @var \DOMNodeList<\DOMElement> $result */
+                        /** @var \Dom\NodeList<\Dom\Element> $result */
                         $result = $xpath->query($query);
                         $microformats = $result->length !== 0;
                     }
@@ -2272,7 +2257,7 @@ class SimplePie
                 } catch (SimplePieException $e) {
                     // We need to unset this so that if SimplePie::set_file() has been called that object is untouched
                     unset($file);
-                    // This is usually because DOMDocument doesn't exist
+                    // This is usually because `\Dom\Document` doesn't exist
                     $this->error = $e->getMessage();
                     $this->registry->call(Misc::class, 'error', [$this->error, E_USER_NOTICE, $e->getFile(), $e->getLine()]);
                     return false;
@@ -3622,8 +3607,6 @@ class SimplePie
             foreach ($urls as $arg) {
                 if ($arg instanceof SimplePie) {
                     $items = array_merge($items, $arg->get_items(0, $limit));
-
-                    // @phpstan-ignore-next-line Enforce PHPDoc type.
                 } else {
                     trigger_error('Arguments must be SimplePie objects', E_USER_WARNING);
                 }

+ 9 - 0
phpstan.dist.neon

@@ -57,6 +57,15 @@ parameters:
 			- 'Minz_Exception'
 	ignoreErrors:
 		- '#Only booleans are allowed in (a negated boolean|a ternary operator condition|an elseif condition|an if condition|&&|\|\|), (bool|false|int(<[0-9, max]+>)?|true|null|\|)+ given.*#'
+		-
+			# For PHP < 8.4, the `Dom\` classes are approximated by `lib/simplepie/simplepie/compat/`
+			identifier: class.notFound
+			messages:
+				- '#Dom\\\S+#'
+		-
+			identifier: argument.type
+			messages:
+				- '#Dom\\\S+#'
 		-
 			message: '#Access to deprecated#'
 			path: app/Models/Context.php

+ 10 - 1
phpunit.xml

@@ -2,8 +2,17 @@
 <phpunit
 	bootstrap="./tests/bootstrap.php"
 	displayDetailsOnAllIssues="true"
-	failOnAllIssues="true"
+	failOnDeprecation="true"
+	failOnEmptyTestSuite="true"
+	failOnIncomplete="true"
+	failOnNotice="true"
+	failOnPhpunitDeprecation="true"
+	failOnPhpunitWarning="true"
+	failOnRisky="true"
+	failOnSkipped="false"
+	failOnWarning="true"
 >
+	<!-- failOnSkipped="false": Skipped tests are legitimate e.g. for PHP < 8.4+ -->
 	<php>
 		<env name="FRESHRSS_ENV" value="silent" force="true"/> <!-- To avoid writing into log files -->
 	</php>

+ 51 - 0
tests/app/Models/SimplePieCustomTest.php

@@ -111,4 +111,55 @@ final class SimplePieCustomTest extends \PHPUnit\Framework\TestCase {
 		$result = FreshRSS_SimplePieCustom::sanitizeHTML('<a href="data:text/html,x">click</a>');
 		self::assertStringContainsString('href="unsafe:data:text/html,x"', $result);
 	}
+
+	/**
+	 * Test malformed HTML.
+	 * Legacy `DOMDocument` cannot properly handle some unclosed tags,
+	 * but PHP 8.4+ native `Dom\HTMLDocument` parser can.
+	 */
+	#[DataProvider('provideUnclosedDivInListItem')]
+	public static function test_sanitizeHTML_whenUnclosedDivInListItem_keepsListItemsAsSiblings(string $input, string $listTag): void {
+		if (PHP_VERSION_ID < 80400 || get_parent_class(\Dom\HTMLDocument::class) === \DOMDocument::class) {
+			self::markTestSkipped('Requires the HTML5 parser of a native `Dom\HTMLDocument` (PHP 8.4+)');
+		}
+		$sanitized = FreshRSS_SimplePieCustom::sanitizeHTML($input);
+		// Embed the result in a minimal page-like context to detect stray closing tags.
+		// Fragment of a page, so prefix with `<!DOCTYPE html>`
+		$document = \Dom\HTMLDocument::createFromString(
+			'<!DOCTYPE html><div class="box">' . $sanitized . '<p id="fragmark">MARK</p></div>',
+			\Dom\HTML_NO_DEFAULT_NS);
+		$list = $document->querySelector($listTag);
+		self::assertNotNull($list, 'The list wrapper must be preserved');
+		$listItems = 0;
+		foreach ($list->childNodes as $child) {
+			if ($child instanceof \Dom\Element && $child->localName === 'li') {
+				$listItems++;
+			}
+		}
+		self::assertSame(2, $listItems, 'Both list items must be direct children of their list');
+		$mark = $document->querySelector('#fragmark');
+		self::assertInstanceOf(\Dom\Element::class, $mark);
+		$markParent = $mark->parentNode;
+		self::assertInstanceOf(\Dom\Element::class, $markParent);
+		self::assertSame('box', $markParent->getAttribute('class'), 'The content after the fragment must stay inside its page container');
+	}
+
+	/** @return Traversable<string,array{string,string}> */
+	public static function provideUnclosedDivInListItem(): Traversable {
+		yield 'Footnote list' => [<<<'HTML'
+			<p>In the end.</p><ol class="footnotes">
+			<li id="footnote_0" class="footnote">First footnote. The full article follows: <hr><div class='footnote'></p>
+			<p><hr></li><li id="footnote_3" class="footnote">Second footnote.</li></ol>
+			HTML, 'ol'];
+		// Unclosed `<div>` inside a list item
+		yield 'Unclosed div in list item' => [<<<'HTML'
+			<ul><li>Text within the first item.<div class="info"></li>
+			<li>Text within the next item.</li></ul>
+			<p>Text after the list.</p>
+			HTML, 'ul'];
+		// In HTML5, an `<li>` start tag must close the previous `<li>`, despite the still-open `<div>`
+		yield 'Minimal unclosed div' => [<<<'HTML'
+			<ul><li>a<div></li><li>b</li></ul>
+			HTML, 'ul'];
+	}
 }

+ 12 - 2
tests/app/Utils/dotNotationUtilTest.php

@@ -70,7 +70,12 @@ final class dotNotationUtilTest extends \PHPUnit\Framework\TestCase {
 		self::assertStringContainsString('<category>News &amp; Politics</category>', $rss);
 		self::assertStringContainsString('<category>Arts &amp; Culture</category>', $rss);
 		self::assertStringContainsString('<category>Science &amp; Tech</category>', $rss);
-		self::assertNotFalse(simplexml_load_string($rss), 'Output must be valid XML');
+		try {
+			$dom = Dom\XMLDocument::createFromString($rss);
+		} catch (Throwable $ex) { // @phpstan-ignore catch.neverThrown (Dom\XMLDocument::createFromString() does throw)
+			self::fail('Output must be valid XML: ' . $ex->getMessage());
+		}
+		self::assertInstanceOf(Dom\XMLDocument::class, $dom);
 	}
 
 	public static function testConvertJsonToRssKeepsAttachments(): void {
@@ -103,6 +108,11 @@ final class dotNotationUtilTest extends \PHPUnit\Framework\TestCase {
 		self::assertIsString($rss);
 		self::assertStringContainsString(
 			'<media:content url="https://example.net/1.mp3?a=1&amp;b=2" type="audio/mpeg" length="1234">', $rss);
-		self::assertNotFalse(simplexml_load_string($rss), 'Output must be valid XML');
+		try {
+			$dom = Dom\XMLDocument::createFromString($rss);
+		} catch (Throwable $ex) { // @phpstan-ignore catch.neverThrown (the XML parser throws on malformed documents, not disclosed in the PHP stubs)
+			self::fail('Output must be valid XML: ' . $ex->getMessage());
+		}
+		self::assertInstanceOf(Dom\XMLDocument::class, $dom);
 	}
 }

+ 6 - 8
tests/app/Views/entryHeaderTest.php

@@ -13,7 +13,7 @@ final class entryHeaderTest extends \PHPUnit\Framework\TestCase {
 	private const ARTICLE_URL = 'https://example.net/article';
 	private const LINK_ITEM = '//li[contains(concat(" ", normalize-space(@class), " "), " link ")]';
 
-	private static function renderEntryHeader(bool $titleOpensWebsite): DOMXPath {
+	private static function renderEntryHeader(bool $titleOpensWebsite): Dom\XPath {
 		FreshRSS_Context::initSystem();
 		Minz_Session::init('FreshRSS', volatile: true);
 		FreshRSS_Context::setUserConf(clone FreshRSS_UserConfiguration::default());
@@ -24,15 +24,13 @@ final class entryHeaderTest extends \PHPUnit\Framework\TestCase {
 		$view->_path('helpers/index/normal/entry_header.phtml');
 		$view->feed = new FreshRSS_Feed('https://example.net/feed.xml', false);
 		$view->entry = new FreshRSS_Entry(1, 'guid', 'Title', '', 'Content', self::ARTICLE_URL, 1700000000);
-		$html = new DOMDocument();
-		self::assertTrue($html->loadHTML($view->renderToString(), LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING));
-		return new DOMXPath($html);
+		// Fragment of a page, so prefix with `<!DOCTYPE html>`
+		$doc = Dom\HTMLDocument::createFromString('<!DOCTYPE html>' . $view->renderToString(), Dom\HTML_NO_DEFAULT_NS);
+		return new Dom\XPath($doc);
 	}
 
-	private static function countNodes(DOMXPath $xpath, string $query): int {
-		$nodes = $xpath->query($query);
-		self::assertNotFalse($nodes);
-		return $nodes->length;
+	private static function countNodes(Dom\XPath $xpath, string $query): int {
+		return $xpath->query($query)->length;
 	}
 
 	public function testLinkIconOpensOriginalWebsiteByDefault(): void {

+ 4 - 5
tests/app/Views/headerTest.php

@@ -37,14 +37,13 @@ final class headerTest extends \PHPUnit\Framework\TestCase {
 		$view = new FreshRSS_View();
 		$view->_path('../layout/header.phtml');
 		$view->html_url = 'https://example.net/';
-		$html = new DOMDocument();
-		self::assertTrue($html->loadHTML($view->renderToString(), LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING));
-		$inputs = (new DOMXPath($html))->query('//form[.//input[@name="search"]]/input[@name="sort"]');
-		self::assertNotFalse($inputs);
+		// Fragment of a page, so prefix with `<!DOCTYPE html>`
+		$doc = Dom\HTMLDocument::createFromString('<!DOCTYPE html>' . $view->renderToString(), Dom\HTML_NO_DEFAULT_NS);
+		$inputs = (new Dom\XPath($doc))->query('//form[.//input[@name="search"]]/input[@name="sort"]');
 		self::assertSame($expectedSort === null ? 0 : 1, $inputs->length);
 		if ($expectedSort !== null) {
 			$input = $inputs->item(0);
-			self::assertInstanceOf(DOMElement::class, $input);
+			self::assertInstanceOf(Dom\Element::class, $input);
 			self::assertSame('hidden', $input->getAttribute('type'));
 			self::assertSame($expectedSort, $input->getAttribute('value'));
 		}

+ 5 - 5
tests/app/Views/streamFooterTest.php

@@ -31,11 +31,11 @@ final class streamFooterTest extends \PHPUnit\Framework\TestCase {
 
 		$view = new FreshRSS_View();
 		$view->_path('helpers/stream-footer.phtml');
-		$html = new DOMDocument();
-		self::assertTrue($html->loadHTML($view->renderToString(), LIBXML_NONET));
-		$button = $html->getElementById('load_more');
-		self::assertInstanceOf(DOMElement::class, $button);
-		$query = parse_url($button->getAttribute('formaction'), PHP_URL_QUERY);
+		// Fragment of a page, so prefix with `<!DOCTYPE html>`
+		$doc = Dom\HTMLDocument::createFromString('<!DOCTYPE html>' . $view->renderToString(), Dom\HTML_NO_DEFAULT_NS);
+		$button = $doc->getElementById('load_more');
+		self::assertInstanceOf(Dom\Element::class, $button);
+		$query = parse_url($button->getAttribute('formaction') ?? '', PHP_URL_QUERY);
 		self::assertIsString($query);
 		parse_str($query, $params);
 		self::assertSame((string)$resolvedState, $params['state'] ?? null);

+ 24 - 0
tests/lib/CssXPath/CssXPathTest.php

@@ -6,4 +6,28 @@ final class CssXPathTest extends \PHPUnit\Framework\TestCase
 	public static function testCssXPathTranslatorClassExists(): void {
 		self::assertTrue(class_exists('GT\\CssXPath\\Translator'));
 	}
+
+	/**
+	 * Test case-insensitive attribute flag, e.g. `link[href][rel~="icon" i]`
+	 */
+	public static function testCssXPathAttributeCaseFlag(): void {
+		$doc = \Dom\HTMLDocument::createFromString(<<<'HTML'
+			<!DOCTYPE html>
+			<html><body>
+				<link rel="ICON" href="a.ico" />
+				<link rel="shortcut icon" href="b.ico" />
+				<link rel="alternate" href="c.xml" />
+			</body></html>
+			HTML, Dom\HTML_NO_DEFAULT_NS);
+		$xpath = new \Dom\XPath($doc);
+
+		$links = $xpath->query((string)new \GT\CssXPath\Translator('link[href][rel~="icon" i]', './/'));
+		self::assertSame(2, $links->length);
+		$link0 = $links->item(0);
+		$link1 = $links->item(1);
+		self::assertInstanceOf(Dom\Element::class, $link0);
+		self::assertInstanceOf(Dom\Element::class, $link1);
+		self::assertSame('a.ico', $link0->getAttribute('href'));
+		self::assertSame('b.ico', $link1->getAttribute('href'));
+	}
 }