]> git.mxchange.org Git - friendica.git/blobdiff - src/Content/Text/HTML.php
Merge pull request #10493 from annando/api
[friendica.git] / src / Content / Text / HTML.php
index 7b8153b8a8e735df5b7813834ed83437b8e0fa67..51515137e56ddd00f3d576e93f4998b7652bf025 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /**
- * @copyright Copyright (C) 2020, Friendica
+ * @copyright Copyright (C) 2010-2021, the Friendica project
  *
  * @license GNU AGPL version 3 or any later version
  *
@@ -36,27 +36,6 @@ use League\HTMLToMarkdown\HtmlConverter;
 
 class HTML
 {
-       public static function sanitizeCSS($input)
-       {
-               $cleaned = "";
-
-               $input = strtolower($input);
-
-               for ($i = 0; $i < strlen($input); $i++) {
-                       $char = substr($input, $i, 1);
-
-                       if (($char >= "a") && ($char <= "z")) {
-                               $cleaned .= $char;
-                       }
-
-                       if (!(strpos(" #;:0123456789-_.%", $char) === false)) {
-                               $cleaned .= $char;
-                       }
-               }
-
-               return $cleaned;
-       }
-
        /**
         * Search all instances of a specific HTML tag node in the provided DOM document and replaces them with BBCode text nodes.
         *
@@ -188,6 +167,10 @@ class HTML
 
                        $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
 
+                       if (empty($message)) {
+                               return '';
+                       }
+
                        @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
 
                        XML::deleteNode($doc, 'style');
@@ -209,6 +192,10 @@ class HTML
                        $message = str_replace(["\n<", ">\n", "\r", "\n", "\xC3\x82\xC2\xA0"], ["<", ">", "<br />", " ", ""], $message);
                        $message = preg_replace('= [\s]*=i', " ", $message);
 
+                       if (empty($message)) {
+                               return '';
+                       }
+
                        @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
 
                        self::tagToBBCode($doc, 'html', [], "", "");
@@ -311,7 +298,8 @@ class HTML
 
                        self::tagToBBCode($doc, 'video', ['src' => '/(.+)/'], '[video]$1', '[/video]', true);
                        self::tagToBBCode($doc, 'audio', ['src' => '/(.+)/'], '[audio]$1', '[/audio]', true);
-                       self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], '[iframe]$1', '[/iframe]', true);
+                       // Backward compatibility, [iframe] support has been removed in version 2020.12
+                       self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], '[url]$1', '[/url]', true);
 
                        self::tagToBBCode($doc, 'key', [], '[code]', '[/code]');
                        self::tagToBBCode($doc, 'code', [], '[code]', '[/code]');
@@ -604,6 +592,10 @@ class HTML
 
                $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
 
+               if (empty($message)) {
+                       return '';
+               }
+
                @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
 
                $message = $doc->saveHTML();
@@ -613,6 +605,10 @@ class HTML
                // Collecting all links
                $urls = self::collectURLs($message);
 
+               if (empty($message)) {
+                       return '';
+               }
+
                @$doc->loadHTML($message, LIBXML_HTML_NODEFDTD);
 
                self::tagToBBCode($doc, 'html', [], '', '');
@@ -651,6 +647,7 @@ class HTML
                        self::tagToBBCode($doc, 'img', ['src' => '/(.+)/'], ' ', ' ');
                }
 
+               // Backward compatibility, [iframe] support has been removed in version 2020.12
                self::tagToBBCode($doc, 'iframe', ['src' => '/(.+)/'], ' $1 ', '');
 
                $message = $doc->saveHTML();
@@ -852,7 +849,7 @@ class HTML
                $redir = false;
 
                if ($redirect) {
-                       $url = Contact::magicLink($contact['url']);
+                       $url = Contact::magicLinkByContact($contact);
                        if (strpos($url, 'redir/') === 0) {
                                $sparkle = ' sparkle';
                        }
@@ -968,4 +965,69 @@ class HTML
        {
                return str_replace('&amp;', '&', $s);
        }
+
+       /**
+        * 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,
+               ]);
+               $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;
+       }
 }