aboutsummaryrefslogtreecommitdiffstats
path: root/src/Sanitize.php
diff options
context:
space:
mode:
Diffstat (limited to 'src/Sanitize.php')
-rw-r--r--src/Sanitize.php414
1 files changed, 294 insertions, 120 deletions
diff --git a/src/Sanitize.php b/src/Sanitize.php
index 1f15bb9..c8aa2dc 100644
--- a/src/Sanitize.php
+++ b/src/Sanitize.php
@@ -1,56 +1,27 @@
<?php
+// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
+// SPDX-License-Identifier: BSD-3-Clause
+
declare(strict_types=1);
-/**
- * SimplePie
- *
- * A PHP-Based RSS and Atom Feed Framework.
- * Takes the hard work out of managing a complete RSS/Atom solution.
- *
- * Copyright (c) 2004-2022, Ryan Parman, Sam Sneddon, Ryan McCue, and contributors
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without modification, are
- * permitted provided that the following conditions are met:
- *
- * * Redistributions of source code must retain the above copyright notice, this list of
- * conditions and the following disclaimer.
- *
- * * Redistributions in binary form must reproduce the above copyright notice, this list
- * of conditions and the following disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * * Neither the name of the SimplePie Team nor the names of its contributors may be used
- * to endorse or promote products derived from this software without specific prior
- * written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS
- * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- *
- * @package SimplePie
- * @copyright 2004-2016 Ryan Parman, Sam Sneddon, Ryan McCue
- * @author Ryan Parman
- * @author Sam Sneddon
- * @author Ryan McCue
- * @link http://simplepie.org/ SimplePie
- * @license http://www.opensource.org/licenses/bsd-license.php BSD License
- */
namespace SimplePie;
+use DOMDocument;
+use DOMXPath;
use InvalidArgumentException;
+use Psr\Http\Client\ClientInterface;
+use Psr\Http\Message\RequestFactoryInterface;
+use Psr\Http\Message\UriFactoryInterface;
use SimplePie\Cache\Base;
use SimplePie\Cache\BaseDataCache;
use SimplePie\Cache\CallableNameFilter;
use SimplePie\Cache\DataCache;
use SimplePie\Cache\NameFilter;
+use SimplePie\HTTP\Client;
+use SimplePie\HTTP\ClientException;
+use SimplePie\HTTP\FileClient;
+use SimplePie\HTTP\Psr18Client;
/**
* Used for data cleanup and post-processing
@@ -58,36 +29,59 @@ use SimplePie\Cache\NameFilter;
*
* This class can be overloaded with {@see \SimplePie\SimplePie::set_sanitize_class()}
*
- * @package SimplePie
* @todo Move to using an actual HTML parser (this will allow tags to be properly stripped, and to switch between HTML and XHTML), this will also make it easier to shorten a string while preserving HTML tags
*/
class Sanitize implements RegistryAware
{
// Private vars
- public $base;
+ /** @var string */
+ public $base = '';
// Options
+ /** @var bool */
public $remove_div = true;
+ /** @var string */
public $image_handler = '';
+ /** @var string[] */
public $strip_htmltags = ['base', 'blink', 'body', 'doctype', 'embed', 'font', 'form', 'frame', 'frameset', 'html', 'iframe', 'input', 'marquee', 'meta', 'noscript', 'object', 'param', 'script', 'style'];
+ /** @var bool */
public $encode_instead_of_strip = false;
+ /** @var string[] */
public $strip_attributes = ['bgsound', 'expr', 'id', 'style', 'onclick', 'onerror', 'onfinish', 'onmouseover', 'onmouseout', 'onfocus', 'onblur', 'lowsrc', 'dynsrc'];
+ /** @var string[] */
public $rename_attributes = [];
+ /** @var array<string, array<string, string>> */
public $add_attributes = ['audio' => ['preload' => 'none'], 'iframe' => ['sandbox' => 'allow-scripts allow-same-origin'], 'video' => ['preload' => 'none']];
+ /** @var bool */
public $strip_comments = false;
+ /** @var string */
public $output_encoding = 'UTF-8';
+ /** @var bool */
public $enable_cache = true;
+ /** @var string */
public $cache_location = './cache';
+ /** @var string&(callable(string): string) */
public $cache_name_function = 'md5';
/**
* @var NameFilter
*/
private $cache_namefilter;
+ /** @var int */
public $timeout = 10;
+ /** @var string */
public $useragent = '';
+ /** @var bool */
public $force_fsockopen = false;
- public $replace_url_attributes = null;
+ /** @var array<string, string|string[]> */
+ public $replace_url_attributes = [];
+ /**
+ * @var array<int, mixed> Custom curl options
+ * @see SimplePie::set_curl_options()
+ */
+ private $curl_options = [];
+
+ /** @var Registry */
public $registry;
/**
@@ -105,45 +99,65 @@ class Sanitize implements RegistryAware
* @see \SimplePie\Sanitize::set_https_domains()
* Array is a tree split at DNS levels. Example:
* array('biz' => true, 'com' => array('example' => true), 'net' => array('example' => array('www' => true)))
+ * @var true|array<string, true|array<string, true|array<string, array<string, true|array<string, true|array<string, true>>>>>>
*/
public $https_domains = [];
+ /**
+ * @var Client|null
+ */
+ private $http_client = null;
+
public function __construct()
{
// Set defaults
$this->set_url_replacements(null);
}
- public function remove_div($enable = true)
+ /**
+ * @return void
+ */
+ public function remove_div(bool $enable = true)
{
$this->remove_div = (bool) $enable;
}
+ /**
+ * @param string|false $page
+ * @return void
+ */
public function set_image_handler($page = false)
{
if ($page) {
$this->image_handler = (string) $page;
} else {
- $this->image_handler = false;
+ $this->image_handler = '';
}
}
- public function set_registry(\SimplePie\Registry $registry)/* : void */
+ /**
+ * @return void
+ */
+ public function set_registry(\SimplePie\Registry $registry)
{
$this->registry = $registry;
}
- public function pass_cache_data($enable_cache = true, $cache_location = './cache', $cache_name_function = 'md5', $cache_class = 'SimplePie\Cache', DataCache $cache = null)
+ /**
+ * @param (string&(callable(string): string))|NameFilter $cache_name_function
+ * @param class-string<Cache> $cache_class
+ * @return void
+ */
+ public function pass_cache_data(bool $enable_cache = true, string $cache_location = './cache', $cache_name_function = 'md5', string $cache_class = Cache::class, ?DataCache $cache = null)
{
- if (isset($enable_cache)) {
- $this->enable_cache = (bool) $enable_cache;
- }
+ $this->enable_cache = $enable_cache;
if ($cache_location) {
- $this->cache_location = (string) $cache_location;
+ $this->cache_location = $cache_location;
}
- if (! is_string($cache_name_function) && ! is_object($cache_name_function) && ! $cache_name_function instanceof NameFilter) {
+ // @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',
__METHOD__,
@@ -154,7 +168,7 @@ class Sanitize implements RegistryAware
// BC: $cache_name_function could be a callable as string
if (is_string($cache_name_function)) {
// trigger_error(sprintf('Providing $cache_name_function as string in "%s()" is deprecated since SimplePie 1.8.0, provide as "%s" instead.', __METHOD__, NameFilter::class), \E_USER_DEPRECATED);
- $this->cache_name_function = (string) $cache_name_function;
+ $this->cache_name_function = $cache_name_function;
$cache_name_function = new CallableNameFilter($cache_name_function);
}
@@ -166,21 +180,49 @@ class Sanitize implements RegistryAware
}
}
- public function pass_file_data($file_class = 'SimplePie\File', $timeout = 10, $useragent = '', $force_fsockopen = false)
+ /**
+ * Set a PSR-18 client and PSR-17 factories
+ *
+ * Allows you to use your own HTTP client implementations.
+ */
+ final public function set_http_client(
+ ClientInterface $http_client,
+ RequestFactoryInterface $request_factory,
+ UriFactoryInterface $uri_factory
+ ): void {
+ $this->http_client = new Psr18Client($http_client, $request_factory, $uri_factory);
+ }
+
+ /**
+ * @deprecated since SimplePie 1.9.0, use \SimplePie\Sanitize::set_http_client() instead.
+ * @param class-string<File> $file_class
+ * @param array<int, mixed> $curl_options
+ * @return void
+ */
+ public function pass_file_data(string $file_class = File::class, int $timeout = 10, string $useragent = '', bool $force_fsockopen = false, array $curl_options = [])
{
+ // trigger_error(sprintf('SimplePie\Sanitize::pass_file_data() is deprecated since SimplePie 1.9.0, please use "SimplePie\Sanitize::set_http_client()" instead.'), \E_USER_DEPRECATED);
if ($timeout) {
- $this->timeout = (string) $timeout;
+ $this->timeout = $timeout;
}
if ($useragent) {
- $this->useragent = (string) $useragent;
+ $this->useragent = $useragent;
}
if ($force_fsockopen) {
- $this->force_fsockopen = (string) $force_fsockopen;
+ $this->force_fsockopen = $force_fsockopen;
}
+
+ $this->curl_options = $curl_options;
+ // Invalidate the registered client.
+ $this->http_client = null;
}
+ /**
+ * @param string[]|string|false $tags Set a list of tags to strip, or set empty string to use default tags, or false to strip nothing.
+ * @return void
+ */
public function strip_htmltags($tags = ['base', 'blink', 'body', 'doctype', 'embed', 'font', 'form', 'frame', 'frameset', 'html', 'iframe', 'input', 'marquee', 'meta', 'noscript', 'object', 'param', 'script', 'style'])
{
if ($tags) {
@@ -190,15 +232,22 @@ class Sanitize implements RegistryAware
$this->strip_htmltags = explode(',', $tags);
}
} else {
- $this->strip_htmltags = false;
+ $this->strip_htmltags = [];
}
}
- public function encode_instead_of_strip($encode = false)
+ /**
+ * @return void
+ */
+ public function encode_instead_of_strip(bool $encode = false)
{
- $this->encode_instead_of_strip = (bool) $encode;
+ $this->encode_instead_of_strip = $encode;
}
+ /**
+ * @param string[]|string $attribs
+ * @return void
+ */
public function rename_attributes($attribs = [])
{
if ($attribs) {
@@ -208,10 +257,14 @@ class Sanitize implements RegistryAware
$this->rename_attributes = explode(',', $attribs);
}
} else {
- $this->rename_attributes = false;
+ $this->rename_attributes = [];
}
}
+ /**
+ * @param string[]|string $attribs
+ * @return void
+ */
public function strip_attributes($attribs = ['bgsound', 'expr', 'id', 'style', 'onclick', 'onerror', 'onfinish', 'onmouseover', 'onmouseout', 'onfocus', 'onblur', 'lowsrc', 'dynsrc'])
{
if ($attribs) {
@@ -221,31 +274,33 @@ class Sanitize implements RegistryAware
$this->strip_attributes = explode(',', $attribs);
}
} else {
- $this->strip_attributes = false;
+ $this->strip_attributes = [];
}
}
- public function add_attributes($attribs = ['audio' => ['preload' => 'none'], 'iframe' => ['sandbox' => 'allow-scripts allow-same-origin'], 'video' => ['preload' => 'none']])
+ /**
+ * @param array<string, array<string, string>> $attribs
+ * @return void
+ */
+ public function add_attributes(array $attribs = ['audio' => ['preload' => 'none'], 'iframe' => ['sandbox' => 'allow-scripts allow-same-origin'], 'video' => ['preload' => 'none']])
{
- if ($attribs) {
- if (is_array($attribs)) {
- $this->add_attributes = $attribs;
- } else {
- $this->add_attributes = explode(',', $attribs);
- }
- } else {
- $this->add_attributes = false;
- }
+ $this->add_attributes = $attribs;
}
- public function strip_comments($strip = false)
+ /**
+ * @return void
+ */
+ public function strip_comments(bool $strip = false)
{
- $this->strip_comments = (bool) $strip;
+ $this->strip_comments = $strip;
}
- public function set_output_encoding($encoding = 'UTF-8')
+ /**
+ * @return void
+ */
+ public function set_output_encoding(string $encoding = 'UTF-8')
{
- $this->output_encoding = (string) $encoding;
+ $this->output_encoding = $encoding;
}
/**
@@ -257,9 +312,10 @@ class Sanitize implements RegistryAware
* |ins|@cite, |q|@cite, |source|@src, |video|@src
*
* @since 1.0
- * @param array|null $element_attribute Element/attribute key/value pairs, null for default
+ * @param array<string, string|string[]>|null $element_attribute Element/attribute key/value pairs, null for default
+ * @return void
*/
- public function set_url_replacements($element_attribute = null)
+ public function set_url_replacements(?array $element_attribute = null)
{
if ($element_attribute === null) {
$element_attribute = [
@@ -283,21 +339,26 @@ class Sanitize implements RegistryAware
]
];
}
- $this->replace_url_attributes = (array) $element_attribute;
+ $this->replace_url_attributes = $element_attribute;
}
/**
* Set the list of domains for which to force HTTPS.
* @see \SimplePie\Misc::https_url()
* Example array('biz', 'example.com', 'example.org', 'www.example.net');
+ *
+ * @param string[] $domains list of domain names ['biz', 'example.com', 'example.org', 'www.example.net']
+ *
+ * @return void
*/
- public function set_https_domains($domains)
+ public function set_https_domains(array $domains)
{
$this->https_domains = [];
foreach ($domains as $domain) {
$domain = trim($domain, ". \t\n\r\0\x0B");
$segments = array_reverse(explode('.', $domain));
- $node =& $this->https_domains;
+ /** @var true|array<string, true|array<string, true|array<string, array<string, true|array<string, true|array<string, true>>>>>> */ // Needed for PHPStan.
+ $node = &$this->https_domains;
foreach ($segments as $segment) {//Build a tree
if ($node === true) {
break;
@@ -305,7 +366,7 @@ class Sanitize implements RegistryAware
if (!isset($node[$segment])) {
$node[$segment] = [];
}
- $node =& $node[$segment];
+ $node = &$node[$segment];
}
$node = true;
}
@@ -313,15 +374,17 @@ class Sanitize implements RegistryAware
/**
* Check if the domain is in the list of forced HTTPS.
+ *
+ * @return bool
*/
- protected function is_https_domain($domain)
+ protected function is_https_domain(string $domain)
{
$domain = trim($domain, '. ');
$segments = array_reverse(explode('.', $domain));
- $node =& $this->https_domains;
+ $node = &$this->https_domains;
foreach ($segments as $segment) {//Explore the tree
if (isset($node[$segment])) {
- $node =& $node[$segment];
+ $node = &$node[$segment];
} else {
break;
}
@@ -331,16 +394,26 @@ class Sanitize implements RegistryAware
/**
* Force HTTPS for selected Web sites.
+ *
+ * @return string
*/
- public function https_url($url)
+ public function https_url(string $url)
{
- return (strtolower(substr($url, 0, 7)) === 'http://') &&
- $this->is_https_domain(parse_url($url, PHP_URL_HOST)) ?
- substr_replace($url, 's', 4, 0) : //Add the 's' to HTTPS
- $url;
+ return (
+ strtolower(substr($url, 0, 7)) === 'http://'
+ && ($parsed = parse_url($url, PHP_URL_HOST)) !== false // Malformed URL
+ && $parsed !== null // Missing host
+ && $this->is_https_domain($parsed) // Should be forced?
+ ) ? substr_replace($url, 's', 4, 0) // Add the 's' to HTTPS
+ : $url;
}
- public function sanitize($data, $type, $base = '')
+ /**
+ * @param int-mask-of<SimplePie::CONSTRUCT_*> $type
+ * @param string $base
+ * @return string Sanitized data; false if output encoding is changed to something other than UTF-8 and conversion fails
+ */
+ public function sanitize(string $data, int $type, string $base = '')
{
$data = trim($data);
if ($data !== '' || $type & \SimplePie\SimplePie::CONSTRUCT_IRI) {
@@ -363,9 +436,13 @@ class Sanitize implements RegistryAware
$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(['SimplePie\Misc', 'silence_errors']);
+ set_error_handler([Misc::class, 'silence_errors']);
$document->loadHTML($data);
restore_error_handler();
@@ -373,16 +450,19 @@ class Sanitize implements RegistryAware
// Strip comments
if ($this->strip_comments) {
+ /** @var \DOMNodeList<\DOMComment> */
$comments = $xpath->query('//comment()');
foreach ($comments as $comment) {
- $comment->parentNode->removeChild($comment);
+ $parentNode = $comment->parentNode;
+ assert($parentNode !== null, 'For PHPStan, comment must have a parent');
+ $parentNode->removeChild($comment);
}
}
// Strip out HTML tags and attributes that might cause various security problems.
// Based on recommendations by Mark Pilgrim at:
- // http://diveintomark.org/archives/2003/06/12/how_to_consume_rss_safely
+ // https://web.archive.org/web/20110902041826/http://diveintomark.org:80/archives/2003/06/12/how_to_consume_rss_safely
if ($this->strip_htmltags) {
foreach ($this->strip_htmltags as $tag) {
$this->strip_tag($tag, $document, $xpath, $type);
@@ -414,7 +494,7 @@ class Sanitize implements RegistryAware
}
// If image handling (caching, etc.) is enabled, cache and rewrite all the image tags.
- if (isset($this->image_handler) && ((string) $this->image_handler) !== '' && $this->enable_cache) {
+ if ($this->image_handler !== '' && $this->enable_cache) {
$images = $document->getElementsByTagName('img');
foreach ($images as $img) {
@@ -425,11 +505,18 @@ class Sanitize implements RegistryAware
if ($cache->get_data($image_url, false)) {
$img->setAttribute('src', $this->image_handler . $image_url);
} else {
- $file = $this->registry->create(File::class, [$img->getAttribute('src'), $this->timeout, 5, ['X-FORWARDED-FOR' => $_SERVER['REMOTE_ADDR']], $this->useragent, $this->force_fsockopen]);
- $headers = $file->headers;
+ try {
+ $file = $this->get_http_client()->request(
+ Client::METHOD_GET,
+ $img->getAttribute('src'),
+ ['X-FORWARDED-FOR' => $_SERVER['REMOTE_ADDR']]
+ );
+ } catch (ClientException $th) {
+ continue;
+ }
- if ($file->success && ($file->method & \SimplePie\SimplePie::FILE_SOURCE_REMOTE === 0 || ($file->status_code === 200 || $file->status_code > 206 && $file->status_code < 300))) {
- if ($cache->set_data($image_url, ['headers' => $file->headers, 'body' => $file->body], $this->cache_duration)) {
+ if ((!Misc::is_remote_uri($file->get_final_requested_uri()) || ($file->get_status_code() === 200 || $file->get_status_code() > 206 && $file->get_status_code() < 300))) {
+ if ($cache->set_data($image_url, ['headers' => $file->get_headers(), 'body' => $file->get_body_content()], $this->cache_duration)) {
$img->setAttribute('src', $this->image_handler . $image_url);
} else {
trigger_error("$this->cache_location is not writable. Make sure you've set the correct relative or absolute path, and that the location is server-writable.", E_USER_WARNING);
@@ -441,18 +528,23 @@ class Sanitize implements RegistryAware
}
// Get content node
- $div = $document->getElementsByTagName('body')->item(0)->firstChild;
+ $div = null;
+ if (($item = $document->getElementsByTagName('body')->item(0)) !== null) {
+ $div = $item->firstChild;
+ }
// Finally, convert to a HTML string
- $data = trim($document->saveHTML($div));
+ $data = trim((string) $document->saveHTML($div));
if ($this->remove_div) {
$data = preg_replace('/^<div' . \SimplePie\SimplePie::PCRE_XML_ATTRIBUTE . '>/', '', $data);
- $data = preg_replace('/<\/div>$/', '', $data);
+ // Cast for PHPStan, it is unable to validate a non-literal regex above.
+ $data = preg_replace('/<\/div>$/', '', (string) $data);
} else {
$data = preg_replace('/^<div' . \SimplePie\SimplePie::PCRE_XML_ATTRIBUTE . '>/', '<div>', $data);
}
- $data = str_replace('</source>', '', $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) {
@@ -467,13 +559,19 @@ class Sanitize implements RegistryAware
}
if ($this->output_encoding !== 'UTF-8') {
+ // This really returns string|false but changing encoding is uncommon and we are going to deprecate it, so let’s just lie to PHPStan in the interest of cleaner annotations.
+ /** @var string */
$data = $this->registry->call(Misc::class, 'change_encoding', [$data, 'UTF-8', $this->output_encoding]);
}
}
return $data;
}
- protected function preprocess($html, $type)
+ /**
+ * @param int-mask-of<SimplePie::CONSTRUCT_*> $type
+ * @return string
+ */
+ protected function preprocess(string $html, int $type)
{
$ret = '';
$html = preg_replace('%</?(?:html|body)[^>]*?'.'>%is', '', $html);
@@ -494,7 +592,11 @@ class Sanitize implements RegistryAware
return $ret;
}
- public function replace_urls($document, $tag, $attributes)
+ /**
+ * @param array<string>|string $attributes
+ * @return void
+ */
+ public function replace_urls(DOMDocument $document, string $tag, $attributes)
{
if (!is_array($attributes)) {
$attributes = [$attributes];
@@ -516,7 +618,11 @@ class Sanitize implements RegistryAware
}
}
- public function do_strip_htmltags($match)
+ /**
+ * @param array<int, string> $match
+ * @return string
+ */
+ public function do_strip_htmltags(array $match)
{
if ($this->encode_instead_of_strip) {
if (isset($match[4]) && !in_array(strtolower($match[1]), ['script', 'style'])) {
@@ -533,9 +639,21 @@ class Sanitize implements RegistryAware
}
}
- protected function strip_tag($tag, $document, $xpath, $type)
+ /**
+ * @param int-mask-of<SimplePie::CONSTRUCT_*> $type
+ * @return void
+ */
+ protected function strip_tag(string $tag, DOMDocument $document, DOMXPath $xpath, int $type)
{
$elements = $xpath->query('body//' . $tag);
+
+ if ($elements === false) {
+ throw new \SimplePie\Exception(sprintf(
+ '%s(): Possibly malformed expression, check argument #1 ($tag)',
+ __METHOD__
+ ), 1);
+ }
+
if ($this->encode_instead_of_strip) {
foreach ($elements as $element) {
$fragment = $document->createDocumentFragment();
@@ -543,7 +661,7 @@ 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->hasAttributes()) {
+ if ($element->attributes !== null) {
$attrs = [];
foreach ($element->attributes as $name => $attr) {
$value = $attr->value;
@@ -569,21 +687,26 @@ class Sanitize implements RegistryAware
$number = $element->childNodes->length;
for ($i = $number; $i > 0; $i--) {
- $child = $element->childNodes->item(0);
- $fragment->appendChild($child);
+ if (($child = $element->childNodes->item(0)) !== null) {
+ $fragment->appendChild($child);
+ }
}
if (!in_array($tag, ['script', 'style'])) {
$fragment->appendChild(new \DOMText('</' . $tag . '>'));
}
- $element->parentNode->replaceChild($fragment, $element);
+ if (($parentNode = $element->parentNode) !== null) {
+ $parentNode->replaceChild($fragment, $element);
+ }
}
return;
} elseif (in_array($tag, ['script', 'style'])) {
foreach ($elements as $element) {
- $element->parentNode->removeChild($element);
+ if (($parentNode = $element->parentNode) !== null) {
+ $parentNode->removeChild($element);
+ }
}
return;
@@ -592,37 +715,67 @@ class Sanitize implements RegistryAware
$fragment = $document->createDocumentFragment();
$number = $element->childNodes->length;
for ($i = $number; $i > 0; $i--) {
- $child = $element->childNodes->item(0);
- $fragment->appendChild($child);
+ if (($child = $element->childNodes->item(0)) !== null) {
+ $fragment->appendChild($child);
+ }
}
- $element->parentNode->replaceChild($fragment, $element);
+ if (($parentNode = $element->parentNode) !== null) {
+ $parentNode->replaceChild($fragment, $element);
+ }
}
}
}
- protected function strip_attr($attrib, $xpath)
+ /**
+ * @return void
+ */
+ protected function strip_attr(string $attrib, DOMXPath $xpath)
{
$elements = $xpath->query('//*[@' . $attrib . ']');
+ if ($elements === false) {
+ throw new \SimplePie\Exception(sprintf(
+ '%s(): Possibly malformed expression, check argument #1 ($attrib)',
+ __METHOD__
+ ), 1);
+ }
+
+ /** @var \DOMElement $element */
foreach ($elements as $element) {
$element->removeAttribute($attrib);
}
}
- protected function rename_attr($attrib, $xpath)
+ /**
+ * @return void
+ */
+ protected function rename_attr(string $attrib, DOMXPath $xpath)
{
$elements = $xpath->query('//*[@' . $attrib . ']');
+ if ($elements === false) {
+ throw new \SimplePie\Exception(sprintf(
+ '%s(): Possibly malformed expression, check argument #1 ($attrib)',
+ __METHOD__
+ ), 1);
+ }
+
+ /** @var \DOMElement $element */
foreach ($elements as $element) {
$element->setAttribute('data-sanitized-' . $attrib, $element->getAttribute($attrib));
$element->removeAttribute($attrib);
}
}
- protected function add_attr($tag, $valuePairs, $document)
+ /**
+ * @param array<string, string> $valuePairs
+ * @return void
+ */
+ protected function add_attr(string $tag, array $valuePairs, DOMDocument $document)
{
$elements = $document->getElementsByTagName($tag);
+ /** @var \DOMElement $element */
foreach ($elements as $element) {
foreach ($valuePairs as $attrib => $value) {
$element->setAttribute($attrib, $value);
@@ -637,7 +790,7 @@ class Sanitize implements RegistryAware
*
* @return DataCache
*/
- private function get_cache($image_url = '')
+ private function get_cache(string $image_url = ''): DataCache
{
if ($this->cache === null) {
// @trigger_error(sprintf('Not providing as PSR-16 cache implementation is deprecated since SimplePie 1.8.0, please use "SimplePie\SimplePie::set_cache()".'), \E_USER_DEPRECATED);
@@ -652,6 +805,27 @@ class Sanitize implements RegistryAware
return $this->cache;
}
+
+ /**
+ * Get a HTTP client
+ */
+ private function get_http_client(): Client
+ {
+ if ($this->http_client === null) {
+ $this->http_client = new FileClient(
+ $this->registry,
+ [
+ 'timeout' => $this->timeout,
+ 'redirects' => 5,
+ 'useragent' => $this->useragent,
+ 'force_fsockopen' => $this->force_fsockopen,
+ 'curl_options' => $this->curl_options,
+ ]
+ );
+ }
+
+ return $this->http_client;
+ }
}
class_alias('SimplePie\Sanitize', 'SimplePie_Sanitize');