+
+ /**
+ * Clean an HTML text for potentially harmful code
+ *
+ * @param string $text
+ * @param array $allowedIframeDomains List of allowed iframe source domains without the scheme
+ * @return string
+ */
+ public static function purify(string $text, array $allowedIframeDomains = []): string
+ {
+ // Allows cid: URL scheme
+ \HTMLPurifier_URISchemeRegistry::instance()->register('cid', new HTMLPurifier_URIScheme_cid());
+
+ $config = \HTMLPurifier_HTML5Config::createDefault();
+ $config->set('HTML.Doctype', 'HTML5');
+
+ // Used to remove iframe with src attribute filtered out
+ $config->set('AutoFormat.RemoveEmpty', true);
+
+ $config->set('HTML.SafeIframe', true);
+
+ array_walk($allowedIframeDomains, function (&$domain) {
+ // Allow the domain and all its eventual sub-domains
+ $domain = '(?:(?!-)[A-Za-z0-9-]{1,63}(?<!-)\.)*' . preg_quote(trim($domain, '/'), '%');
+ });
+
+ $config->set('URI.SafeIframeRegexp',
+ '%^https://(?:
+ ' . implode('|', $allowedIframeDomains) . '
+ )
+ (?:/|$) # Prevents bogus domains like youtube.com.fake.tld
+ %xi'
+ );
+
+ $config->set('Attr.AllowedRel', [
+ 'noreferrer' => true,
+ 'noopener' => true,
+ 'tag' => true,
+ ]);
+ $config->set('Attr.AllowedFrameTargets', [
+ '_blank' => true,
+ ]);
+
+ $config->set('AutoFormat.RemoveEmpty.Predicate', [
+ 'colgroup' => [], // |
+ 'th' => [], // |
+ 'td' => [], // |
+ 'iframe' => ['src'], // ↳ Default HTMLPurify values
+ 'i' => ['class'], // Allows forkawesome icons
+ ]);
+
+ // Uncomment to debug HTMLPurifier behavior
+ //$config->set('Core.CollectErrors', true);
+ //$config->set('Core.MaintainLineNumbers', true);
+
+ $HTMLPurifier = new \HTMLPurifier($config);
+
+ $text = $HTMLPurifier->purify($text);
+
+ /** @var \HTMLPurifier_ErrorCollector $errorCollector */
+ // Uncomment to debug HTML Purifier behavior
+ //$errorCollector = $HTMLPurifier->context->get('ErrorCollector');
+ //var_dump($errorCollector->getRaw());
+
+ return $text;
+ }
+
+ /**
+ * XPath arbitrary string quoting
+ *
+ * @see https://stackoverflow.com/a/45228168
+ * @param string $value
+ * @return string
+ */
+ public static function xpathQuote(string $value): string
+ {
+ if (false === strpos($value, '"')) {
+ return '"' . $value . '"';
+ }
+
+ if (false === strpos($value, "'")) {
+ return "'" . $value . "'";
+ }
+
+ // if the value contains both single and double quotes, construct an
+ // expression that concatenates all non-double-quote substrings with
+ // the quotes, e.g.:
+ //
+ // concat("'foo'", '"', "bar")
+ return 'concat(' . implode(', \'"\', ', array_map([self::class, 'xpathQuote'], explode('"', $value))) . ')';
+ }
+
+ /**
+ * Checks if the provided URL is present in the DOM document in an element with the rel="me" attribute
+ *
+ * XHTML Friends Network http://gmpg.org/xfn/
+ *
+ * @param DOMDocument $doc
+ * @param UriInterface $meUrl
+ * @return bool
+ */
+ public static function checkRelMeLink(DOMDocument $doc, UriInterface $meUrl): bool
+ {
+ $xpath = new \DOMXpath($doc);
+
+ // This expression checks that "me" is among the space-delimited values of the "rel" attribute.
+ // And that the href attribute contains exactly the provided URL
+ $expression = "//*[contains(concat(' ', normalize-space(@rel), ' '), ' me ')][@href = " . self::xpathQuote($meUrl) . "]";
+
+ $result = $xpath->query($expression);
+
+ return $result !== false && $result->length > 0;
+ }
+
+ /**
+ * @param DOMDocument $doc
+ * @return string|null Lowercase charset
+ */
+ public static function extractCharset(DOMDocument $doc): ?string
+ {
+ $xpath = new DOMXPath($doc);
+
+ $expression = "string(//meta[@charset]/@charset)";
+ if ($charset = $xpath->evaluate($expression)) {
+ return strtolower($charset);
+ }
+
+ try {
+ // This expression looks for a meta tag with the http-equiv attribute set to "content-type" ignoring case
+ // whose content attribute contains a "charset" string and returns its value
+ $expression = "string(//meta[@http-equiv][translate(@http-equiv, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') = 'content-type'][contains(translate(@content, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'charset')]/@content)";
+ $mediaType = MediaType::fromContentType($xpath->evaluate($expression));
+ if (isset($mediaType->parameters['charset'])) {
+ return strtolower($mediaType->parameters['charset']);
+ }
+ } catch(\InvalidArgumentException $e) {}
+
+ return null;
+ }