CVE-2023-0608 (published 2023-02-01T06:15Z)

Cross-site Scripting (XSS) - DOM in GitHub repository microweber/microweber prior to 1.3.2.

CVSS v3 base score: 5.4, MEDIUM (CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N)

Weakness information:
cwe_id: CWE-79
cwe_name: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
description: The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
extended_description: 
            Cross-site scripting (XSS) vulnerabilities occur when:
            
               Untrusted data enters a web application, typically from a web request.
               The web application dynamically generates a web page that contains this untrusted data.
               During page generation, the application does not prevent the data from containing content that is executable by a web browser, such as JavaScript, HTML tags, HTML attributes, mouse events, Flash, ActiveX, etc.
               A victim visits the generated web page through a web browser, which contains malicious script that was injected using the untrusted data.
               Since the script comes from a web page that was sent by the web server, the victim's web browser executes the malicious script in the context of the web server's domain.
               This effectively violates the intention of the web browser's same-origin policy, which states that scripts in one domain should not be able to access resources or run code in a different domain.
            
            There are three main kinds of XSS:
            
               
                  Type 1: Reflected XSS (or Non-Persistent) - 
         			The server reads data directly from the HTTP request and reflects it back in the HTTP response. Reflected XSS exploits occur when an attacker causes a victim to supply dangerous content to a vulnerable web application, which is then reflected back to the victim and executed by the web browser. The most common mechanism for delivering malicious content is to include it as a parameter in a URL that is posted publicly or e-mailed directly to the victim. URLs constructed in this manner constitute the core of many phishing schemes, whereby an attacker convinces a victim to visit a URL that refers to a vulnerable site. After the site reflects the attacker's content back to the victim, the content is executed by the victim's browser.
               
                  Type 2: Stored XSS (or Persistent) - 
               The application stores dangerous data in a database, message forum, visitor log, or other trusted data store. At a later time, the dangerous data is subsequently read back into the application and included in dynamic content. From an attacker's perspective, the optimal place to inject malicious content is in an area that is displayed to either many users or particularly interesting users. Interesting users typically have elevated privileges in the application or interact with sensitive data that is valuable to the attacker. If one of these users executes malicious content, the attacker may be able to perform privileged operations on behalf of the user or gain access to sensitive data belonging to the user. For example, the attacker might inject XSS into a log message, which might not be handled properly when an administrator views the logs.
            
               
                  Type 0: DOM-Based XSS - 
               In DOM-based XSS, the client performs the injection of XSS into the page; in the other types, the server performs the injection. DOM-based XSS generally involves server-controlled, trusted script that is sent to the client, such as Javascript that performs sanity checks on a form before the user submits it. If the server-supplied script processes user-supplied data and then injects it back into the web page (such as with dynamic HTML), then DOM-based XSS is possible.
            
            
            Once the malicious script is injected, the attacker can perform a variety of malicious activities. The attacker could transfer private information, such as cookies that may include session information, from the victim's machine to the attacker. The attacker could send malicious requests to a web site on behalf of the victim, which could be especially dangerous to the site if the victim has administrator privileges to manage that site. Phishing attacks could be used to emulate trusted web sites and trick the victim into entering a password, allowing the attacker to compromise the victim's account on that web site. Finally, the script could exploit a vulnerability in the web browser itself possibly taking over the victim's machine, sometimes referred to as "drive-by hacking."
            In many cases, the attack can be launched without the victim even being aware of it. Even with careful users, attackers frequently use a variety of methods to encode the malicious portion of the attack, such as URL encoding or Unicode, so the request looks less suspicious.
         
         

Fix information:
repo_url: https://github.com/microweber/microweber
commit_details: repo_url: https://github.com/microweber/microweber
author: Peter Ivanov
author_date: 2022-11-29 14:22:23+02:00
msg: update
repository: repo_url: https://github.com/microweber/microweber
repo_name: microweber/microweber
description: Drag and Drop Website Builder and CMS with E-commerce
repo_language: HTML
owner: microweber
file_changes: filename: Parser.php
change_type: ModificationType.MODIFY
diff: @@ -135,10 +135,14 @@ class Parser
 
     public function make_tags($layout, $options = array())
     {
-
-        if ($layout == '') {
+         if ($layout == '') {
             return $layout;
         }
+
+        $layout = str_ireplace('{SITE_URL}','___mw-site-url-temp-replace-on-make-tags___', $layout);
+
+
+
         require_once __DIR__ . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'phpQuery.php';
 
         $pq = \phpQuery::newDocument($layout);
@@ -261,6 +265,10 @@ class Parser
             }
         }
 
+        $layout = str_ireplace('___mw-site-url-temp-replace-on-make-tags___','{SITE_URL}', $layout);
+
+
+
         return $layout;
     }
 

programming_language: PHP
filename: phpQuery.php
change_type: ModificationType.MODIFY
diff: @@ -221,7 +221,14 @@ class DOMDocumentWrapper
         }
         if ($loaded) {
             //			$this->document->formatOutput = true;
+            $this->document->formatOutput = false;
             $this->document->preserveWhiteSpace = true;
+
+            $this->document->validateOnParse=false;
+            $this->document->strictErrorChecking=false;
+            $this->document->recover=false;
+
+
             $this->xpath = new DOMXPath($this->document);
             $this->afterMarkupLoad();
 
@@ -294,11 +301,21 @@ class DOMDocumentWrapper
         if (!$version) {
             $version = '1.0';
         }
+
+        libxml_use_internal_errors(true);
+
         $this->document = new DOMDocument($version, $charset);
         $this->charset = $this->document->encoding;
         //		$this->document->encoding = $charset;
-        $this->document->formatOutput = true;
+       // $this->document->formatOutput = true;
+        $this->document->formatOutput = false;
+       // $this->document->standalone = true;
         $this->document->preserveWhiteSpace = true;
+
+
+        $this->document->validateOnParse=false;
+        $this->document->strictErrorChecking=false;
+        $this->document->recover=false;
     }
 
     protected function loadMarkupHTML($markup, $requestedCharset = null)
@@ -378,7 +395,15 @@ class DOMDocumentWrapper
               ? $this->document->loadHTML($markup)
               : @$this->document->loadHTML($markup); */
 
-            $return = @$this->document->loadHTML($markup);
+         // $return = @$this->document->loadHTML($markup);
+            $return = @$this->document->loadHTML($markup,
+                LIBXML_SCHEMA_CREATE |
+                LIBXML_HTML_NOIMPLIED |
+                LIBXML_HTML_NODEFDTD |
+                LIBXML_NOERROR |
+                LIBXML_NONET |
+                LIBXML_NOWARNING
+            );
 
             if ($return) {
                 $this->root = $this->document;
@@ -763,6 +788,10 @@ class DOMDocumentWrapper
                         .'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" '
                         .'"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
                         .'<fake xmlns="http://www.w3.org/1999/xhtml">'.$markup.'</fake>');
+
+/*                $fragment->loadMarkupXML('<?xml version="1.0" encoding="'.$charset.'"?>'*/
+//                       . phpQuery::$defaultDoctype.''
+//                        .'<fake xmlns="http://www.w3.org/1999/xhtml">'.$markup.'</fake>');
                 $fragment->root = $fragment->document->firstChild->nextSibling;
             } else {
                 $fragment->loadMarkupXML('<?xml version="1.0" encoding="'.$charset.'"?><fake>'.$markup.'</fake>');
@@ -5079,8 +5108,10 @@ abstract class phpQuery
      *
      * @var unknown_type
      */
-    public static $defaultDoctype = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
+    public static $defaultDoctype_old = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">';
+
+    public static $defaultDoctype = '<!doctype html>';
     public static $defaultCharset = 'UTF-8';
 
     /**

programming_language: PHP
filename: ContentManagerCrud.php
change_type: ModificationType.MODIFY
diff: @@ -2,6 +2,7 @@
 namespace MicroweberPackages\Content;
 
 use MicroweberPackages\Content\Repositories\ContentRepository;
+use MicroweberPackages\Content\Models\Content;
 use MicroweberPackages\Database\Crud;
 use Illuminate\Support\Facades\DB;
 use function Opis\Closure\serialize as serializeClosure;

programming_language: PHP
filename: ContentManagerHelpers.php
change_type: ModificationType.MODIFY
diff: @@ -1065,15 +1065,14 @@ class ContentManagerHelpers extends ContentManagerCrud
 
                         $html_to_save = $content =  $this->app->parser->make_tags($html_to_save);
 
-//  AntiXSS makes bug on save convertind comments to htmlentities
-//                        $antixss = new AntiXSS();
-//                        $html_to_save = $content = $antixss->xss_clean($html_to_save);
+                        //\Log::info($html_to_save);
+
 
                         $xssClean = new XSSClean();
                         $html_to_save = $content = $xssClean->clean($html_to_save);
 
 
-
+                      //  \Log::info($html_to_save);
 
                         if ($save_module == false and $save_global == false and $save_layout == false) {
                             if ($content_id) {
@@ -1135,6 +1134,8 @@ class ContentManagerHelpers extends ContentManagerCrud
                                         $cont_table_save[$field]=$html_to_save;
                                     }
                                 }
+
+
                                 $this->app->event_manager->trigger('mw.content.save_edit', $cont_field);
 
                                 $to_save = array();
@@ -1371,6 +1372,7 @@ class ContentManagerHelpers extends ContentManagerCrud
             $table = $table_drafts;
         }
 
+
         $data = $this->app->format->strip_unsafe($data);
 
         if (isset($data['is_draft']) and $data['is_draft'] and isset($data['url'])) {
@@ -1506,6 +1508,8 @@ class ContentManagerHelpers extends ContentManagerCrud
             $data['id'] = $find['id'];
         }
 
+
+
         $save = $this->app->database_manager->save($data);
 
         $this->app->cache_manager->delete('content_fields');

programming_language: PHP
filename: ContentApiControllerLiveEditSaveTest.php
change_type: ModificationType.MODIFY
diff: @@ -1,33 +1,31 @@
 <?php
+
 namespace MicroweberPackages\Content\tests;
 
 use Illuminate\Database\Eloquent\Model;
 use Illuminate\Support\Facades\Auth;
 use MicroweberPackages\Category\Models\Category;
 use MicroweberPackages\Core\tests\TestCase;
+use MicroweberPackages\Helper\XSSClean;
 use MicroweberPackages\Multilanguage\MultilanguageHelpers;
 use MicroweberPackages\Page\Models\Page;
 use MicroweberPackages\User\Models\User;
 
 class ContentApiControllerLiveEditSaveTest extends TestCase
 {
-    public function testSaveContentOnPageLiveEdit()
+    public function testSaveContentOnPageLiveEditSingle()
     {
-        $user = User::where('is_admin', '=', '1')->first();
-        Auth::login($user);
-
-
-        MultilanguageHelpers::setMultilanguageEnabled(0);
+        $this->cleanupAndPrepare();
 
         $unique = uniqid('testSaveContentOnPage');
         $newCleanMlPage = save_content([
             'subtype' => 'static',
             'content_type' => 'page',
             'layout_file' => 'clean.php',
-            'title' => 'pagecontent222'.$unique,
-            'url' => 'pagecontent222'.$unique,
+            'title' => 'pagecontent222' . $unique,
+            'url' => 'pagecontent222' . $unique,
             'preview_layout_file' => 'clean.php',
-            'active_site_template'=> 'new-world',
+            'active_site_template' => 'new-world',
             'is_active' => 1,
         ]);
 
@@ -37,10 +35,10 @@ class ContentApiControllerLiveEditSaveTest extends TestCase
         $this->assertEquals($findPage->id, $newCleanMlPage);
 
         $pageLink = content_link($pageId);
-        $pageLink = '/' . str_replace(site_url(),'', $pageLink);
+        $pageLink = '/' . str_replace(site_url(), '', $pageLink);
 
         $_SERVER['PHP_SELF'] = '/index.php';
-        $_SERVER['REQUEST_URI'] = $pageLink;
+        $_SERVER['REQ`UEST_URI'] = $pageLink;
         $_SERVER['REDIRECT_URL'] = $pageLink;
         $_SERVER['HTTP_REFERER'] = content_link($pageId);
 
@@ -52,26 +50,30 @@ class ContentApiControllerLiveEditSaveTest extends TestCase
 <div class="feature-icon bg-primary bg-gradient">
 <svg class="bi" width="1em" height="1em"><use xlink:href="#collection"></use></svg>
 </div>
+<div class="feature-icon bg-primary bg-gradient">
 <h2>Featured title</h2>
 <p>Paragraph of text beneath the heading to explain the heading. We'll add onto it with another sentence and probably just keep going until we run out of words.</p>
 <a href="#" class="icon-link">
 Call to action
-</a><a class="mb-2" href=""><i class="mdi mdi-arrow-right"></i></a>
+</a>
+<a class="mb-2" href=""><i class="mdi mdi-arrow-right"></i></a>
+<a class="mb-2" href="https://example.com"><i class="mdi mdi-arrow-up"></i>example link</a>
+<a class="mb-3" target="_blank" href="https://example.com/2"><i class="mdi mdi-arrow-left-bold-box"></i>link 2</a>
+</div>
 HTML;
 
 
         $fieldsData = [
-            'field_data_0'=>[
-                'attributes'=>[
-                    'class'=>'container edit',
-                    'rel'=>'content',
-                    'rel_id'=>$findPage->id,
-                    'field'=>'content',
+            'field_data_0' => [
+                'attributes' => [
+                    'class' => 'container edit',
+                    'rel' => 'content',
+                    'rel_id' => $findPage->id,
+                    'field' => 'content',
                 ],
-                'html'=>$contentFieldHtml
+                'html' => $contentFieldHtml
             ]
         ];
-
         $encoded = base64_encode(json_encode($fieldsData));
 
         $response = $this->call(
@@ -92,14 +94,403 @@ HTML;
         $this->assertEquals(trim($fieldSaved[0]['content']), trim($contentFieldHtml));
         $this->assertEquals($fieldSaved[0]['rel_type'], 'content');
         $this->assertEquals($fieldSaved[0]['field'], 'content');
+        $findPage = Page::whereId($findPage->id)->first();
 
-
-        $findPage = Page::whereId($fieldSaved[0]['id'])->first();
         $this->assertTrue(str_contains($findPage->content, 'svg class="bi" width="1em" height="1em"'));
         $this->assertTrue(str_contains($findPage->content, '<h2>Featured title</h2>'));
+        $this->assertTrue(str_contains($findPage->content, '<a class="mb-2" href="https://example.com"><i class="mdi mdi-arrow-up"></i>example link</a>'));
+        $this->assertTrue(str_contains($findPage->content, '<a class="mb-3" target="_blank" href="https://example.com/2"><i class="mdi mdi-arrow-left-bold-box"></i>link 2</a>'));
+
+
+    }
+
+
+    public function testSaveContentOnPageLiveEditFromBootstrapExamples()
+    {
+        $this->cleanupAndPrepare();
+        $unique = uniqid('testSaveContentOnPage');
+        $newCleanMlPage = save_content([
+            'subtype' => 'static',
+            'content_type' => 'page',
+            'layout_file' => 'clean.php',
+            'title' => 'pagecontent-bs-examples-save' . $unique,
+            'preview_layout_file' => 'clean.php',
+            'is_active' => 1,
+        ]);
+
+
+
+        $findPage = Page::whereId($newCleanMlPage)->first();
+
+        $pageId = $findPage->id;
+        $this->assertEquals($findPage->id, $newCleanMlPage);
+
+        $pageLink = content_link($pageId);
+        $pageLink = '/' . str_replace(site_url(), '', $pageLink);
+
+        $_SERVER['PHP_SELF'] = '/index.php';
+        $_SERVER['REQ`UEST_URI'] = $pageLink;
+        $_SERVER['REDIRECT_URL'] = $pageLink;
+        $_SERVER['HTTP_REFERER'] = content_link($pageId);
+
+        $zipname = __DIR__ . '/../../Helper/tests/misc/bootstrap-5.0.2-examples.zip';
+
+
+        //
+
+        $zip = new \ZipArchive();
+
+        $htmls = [];
+        if ($zip->open($zipname)) {
+            for ($i = 0; $i < $zip->numFiles; $i++) {
+                $fn = $zip->getNameIndex($i);
+                $ext = get_file_extension($fn);
+                if ($ext == 'html') {
+                    $string = $zip->getFromName($fn);
+                    $htmls[$fn] = $string;
+                }
+            }
+        }
+        $zip->close();
+
+
+        $this->assertTrue(!empty($htmls));
+
+
+        foreach ($htmls as $k => $html) {
+
+
+            //remove empty tags
+           $html =  preg_replace('/<[^\/>]*>([\s]?)*<\/[^>]*>/', '', $html);
+
+            // remove script tags
+            $html = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', "", $html);
+
+             // remove code tags
+            $html = preg_replace('/<code\b[^>]*>(.*?)<\/code>/is', "", $html);
+
+
+            $l = $html;
+            $pq = \phpQuery::newDocument($l);
+
+            // $isolated_html = pq('main')->eq(0)->htmlOuter();
+            $contentFieldHtml = pq('main')->eq(0)->htmlOuter();
+
+
+            $fieldsData = [
+                'field_data_0' => [
+                    'attributes' => [
+                        'class' => 'container edit',
+                        'rel' => 'content',
+                        'rel_id' => $findPage->id,
+                        'field' => 'content',
+                    ],
+                    'html' => $contentFieldHtml
+                ]
+            ];
+
+
+
+
+            $encoded = base64_encode(json_encode($fieldsData));
+
+            $response = $this->call(
+                'POST',
+                route('api.content.save_edit'),
+                [
+                    'data_base64' => $encoded,
+                ],
+                [],//params
+                $_COOKIE,//cookie
+                [],//files
+                $_SERVER //server
+            );
+
+
+            $fieldSaved = $response->decodeResponseJson();
+
+            $this->assertEquals(trim($fieldSaved[0]['content']), trim($contentFieldHtml));
+            $this->assertEquals($fieldSaved[0]['rel_type'], 'content');
+            $this->assertEquals($fieldSaved[0]['field'], 'content');
+
+
+
+            $pq2 = \phpQuery::newDocument($contentFieldHtml);
+            $this->assertEquals($contentFieldHtml, $pq2->htmlOuter());
+
+
+            $findPage = Page::whereId($fieldSaved[0]['id'])->first();
+            $contentFieldHtml1 = trim($contentFieldHtml);
+            $contentFieldHtml2 = trim($findPage->content);
+
+            $this->assertEquals($contentFieldHtml1, $contentFieldHtml2);
+            $this->assertEquals($contentFieldHtml, $findPage->content);
+
+
+        }
+
+
+    }
+
+
+    public function testSaveContentOnPageLiveEditXssList()
+    {
+
+        $this->cleanupAndPrepare();
+
+        $unique = uniqid('testSaveContentOnPageLiveEditXssList');
+        $newCleanMlPage = save_content([
+            'subtype' => 'static',
+            'content_type' => 'page',
+            'layout_file' => 'clean.php',
+            'title' => 'xss-test-' . $unique,
+            'preview_layout_file' => 'clean.php',
+            'is_active' => 1,
+        ]);
+
+        $findPage = Page::whereId($newCleanMlPage)->first();
+
+        $pageId = $findPage->id;
+        $this->assertEquals($findPage->id, $newCleanMlPage);
+
+        $pageLink = content_link($pageId);
+        $pageLink = '/' . str_replace(site_url(), '', $pageLink);
+
+        $_SERVER['PHP_SELF'] = '/index.php';
+        $_SERVER['REQ`UEST_URI'] = $pageLink;
+        $_SERVER['REDIRECT_URL'] = $pageLink;
+        $_SERVER['HTTP_REFERER'] = content_link($pageId);
+
+
+
+        $zip = new \ZipArchive();
+        $zip->open(__DIR__ . '/../../Helper/tests/misc/xss-test-files.zip');
+        $xssList = $zip->getFromName('xss-payload-list.txt');
+        $zip->close();
+
+        $xssList = preg_replace('~\R~u', "\r\n", $xssList);
+        $xssList = explode(PHP_EOL, $xssList);
+
+
+        $xssListChunks = array_chunk($xssList, 100);
+
+
+        foreach ($xssListChunks as $stringChunk) {
+
+            $string = implode(PHP_EOL, $stringChunk);
+             if (empty(trim($string))) {
+                continue;
+            }
+
+            $contentFieldHtml = $string;
+
+            $fieldsData = [
+                'field_data_0' => [
+                    'attributes' => [
+                        'class' => 'container edit',
+                        'rel' => 'content',
+                        'rel_id' => $findPage->id,
+                        'field' => 'content',
+                    ],
+                    'html' => $contentFieldHtml
+                ]
+            ];
+
+            $encoded = base64_encode(json_encode($fieldsData));
+
+            $response = $this->call(
+                'POST',
+                route('api.content.save_edit'),
+                [
+                    'data_base64' => $encoded,
+                ],
+                [],//params
+                $_COOKIE,//cookie
+                [],//files
+                $_SERVER //server
+            );
+
+            $fieldSaved = $response->decodeResponseJson();
+
+            $this->assertNotEquals(trim($fieldSaved[0]['content']), trim($contentFieldHtml));
+            $this->assertEquals($fieldSaved[0]['rel_type'], 'content');
+            $this->assertEquals($fieldSaved[0]['field'], 'content');
+
+            $findPage = Page::whereId($fieldSaved[0]['id'])->first();
+            $contentFieldHtml1 = trim($contentFieldHtml);
+            $contentFieldHtml2 = trim($findPage->content);
+
+           $this->assertNotEquals($contentFieldHtml1, $contentFieldHtml2);
+
+
+            foreach ($stringChunk as $stringItem) {
+                if (trim($stringItem) == '') {
+                    continue;
+                }
+                $this->assertStringNotContainsString($stringItem, $findPage->content);
+            }
+
+
+
+        }
+    }
+
+
+
+    public function testSaveContentOnPageLiveEditFromOtherExamples()
+    {
+        $this->cleanupAndPrepare();
+
+
+        $unique = uniqid('testSaveContentOnPageLiveEditFromOtherExamples');
+        $newCleanMlPage = save_content([
+            'subtype' => 'static',
+            'content_type' => 'page',
+            'layout_file' => 'clean.php',
+            'title' => 'pagecontent-other-examples-save' . $unique,
+            'preview_layout_file' => 'clean.php',
+            'is_active' => 1,
+        ]);
+
+        $findPage = Page::whereId($newCleanMlPage)->first();
+
+        $pageId = $findPage->id;
+        $this->assertEquals($findPage->id, $newCleanMlPage);
+
+        $pageLink = content_link($pageId);
+        $pageLink = '/' . str_replace(site_url(), '', $pageLink);
+
+        $_SERVER['PHP_SELF'] = '/index.php';
+        $_SERVER['REQ`UEST_URI'] = $pageLink;
+        $_SERVER['REDIRECT_URL'] = $pageLink;
+        $_SERVER['HTTP_REFERER'] = content_link($pageId);
+
+        $zipname = __DIR__ . '/../../Helper/tests/misc/edit-fields-other-html.zip';
+
+
+        $zip = new \ZipArchive();
+
+        $htmls = [];
+        if ($zip->open($zipname)) {
+            for ($i = 0; $i < $zip->numFiles; $i++) {
+                $fn = $zip->getNameIndex($i);
+                $ext = get_file_extension($fn);
+                if ($ext == 'html') {
+                    $string = $zip->getFromName($fn);
+                    if(trim($string) == ''){
+                        continue;
+                    }
+                    $htmls[$fn] = $string;
+                }
+            }
+        }
+        $zip->close();
+
+
+        $this->assertTrue(!empty($htmls));
+
+        foreach ($htmls as $k => $html) {
+
+            $contentFieldHtml = $html;
+            $contentFieldHtml = self::fixLinksPrecentAttributes($contentFieldHtml);
+
+            $contentFieldHtmlTest1 = app()->parser->make_tags($contentFieldHtml);
+            $this->assertEquals($contentFieldHtmlTest1, $contentFieldHtml);
+
+
+            $xssClean = new XSSClean();
+            $contentFieldHtmlTest1 = $xssClean->clean($contentFieldHtml);
+            $this->assertEquals($contentFieldHtmlTest1, $contentFieldHtml);
+
+
+        }
+
+        $htmlsChunks = array_chunk($htmls, 100);
+
+
+
+      foreach ($htmlsChunks as $k => $htmlChunk) {
+
+          $html = implode('--------chunk-------', $htmlChunk);
+         $contentFieldHtml = $html;
+
+
+           // $contentFieldHtml = str_replace('{SITE_URL}', site_url(), $contentFieldHtml);
+            $fieldsData = [
+                'field_data_0' => [
+                    'attributes' => [
+                        'class' => 'container edit',
+                        'rel' => 'content',
+                        'rel_id' => $findPage->id,
+                        'field' => 'content',
+                    ],
+                    'html' => $contentFieldHtml
+                ]
+            ];
+
+            $contentFieldHtml = self::fixLinksPrecentAttributes($contentFieldHtml);
+
 
+            $encoded = base64_encode(json_encode($fieldsData));
 
+            $response = $this->call(
+                'POST',
+                route('api.content.save_edit'),
+                [
+                    'data_base64' => $encoded,
+                ],
+                [],//params
+                $_COOKIE,//cookie
+                [],//files
+                $_SERVER //server
+            );
+
+
+            $fieldSaved = $response->decodeResponseJson();
+
+
+
+            $findPage = Page::whereId($fieldSaved[0]['id'])->first();
+            $contentFieldHtml1 = trim($contentFieldHtml);
+            $contentFieldHtml2 = trim($findPage->content);
+
+            $this->assertEquals($contentFieldHtml1, $contentFieldHtml2);
+            $this->assertEquals($contentFieldHtml, $findPage->content);
+
+
+       }
+
+
+    }
 
+
+    private function cleanupAndPrepare(){
+        $user = User::where('is_admin', '=', '1')->first();
+        Auth::login($user);
+        \Config::set('microweber.disable_model_cache', 1);
+
+
+        MultilanguageHelpers::setMultilanguageEnabled(0);
+        Page::truncate();
     }
 
+    public static function fixLinksPrecentAttributes($text)
+    {
+        $text = str_ireplace('{SITE_URL}','___mw-site-url-temp-replace-on-clean___', $text);
+        $pq = \phpQuery::newDocument($text);
+
+        foreach($pq->find('a') as $stuffs)
+        {
+            $href = pq($stuffs)->attr('href');
+            if($href){
+            pq($stuffs)->attr('href', str_replace(' ', '%20', $href));
+            }
+        }
+        $text = $pq->htmlOuter();
+        $text = str_ireplace('___mw-site-url-temp-replace-on-clean___','{SITE_URL}',     $text);
+        return $text;
+
+    }
+
+
 }

programming_language: PHP
filename: DatabaseManager.php
change_type: ModificationType.MODIFY
diff: @@ -618,7 +618,6 @@ class DatabaseManager extends DbUtils
 
         $criteria_orig = $data;
         $criteria = $this->map_array_to_table($table, $data);
-
         if ($allow_html == false) {
             $criteria = $this->app->format->clean_html($criteria);
         } else {

programming_language: PHP
filename: Utils.php
change_type: ModificationType.MODIFY
diff: @@ -606,7 +606,7 @@ class Utils
             $search = array(
                 '@<script[^>]*?>.*?</script>@si', // Strip out javascript
 
-                '@<![\s\S]*?--[ \t\n\r]*>@', // Strip multi-line comments
+          //      '@<![\s\S]*?--[ \t\n\r]*>@', // Strip multi-line comments
             );
             if (is_string($input)) {
                 $output = preg_replace($search, '', $input);

programming_language: PHP
filename: Format.php
change_type: ModificationType.MODIFY
diff: @@ -630,6 +630,7 @@ class Format
 
     public function strip_unsafe($string, $img = false)
     {
+
         if (is_array($string)) {
             foreach ($string as $key => $val) {
                 $string[$key] = $this->strip_unsafe($val, $img);
@@ -641,10 +642,10 @@ class Format
             // Unsafe HTML tags that members may abuse
             $unsafe = array(
                 '/<iframe(.*?)<\/iframe>/is',
-                '/<title(.*?)<\/title>/is',
+               // '/<title(.*?)<\/title>/is',
                 //'/<pre(.*?)<\/pre>/is',
-                '/<audio(.*?)<\/audio>/is',
-                '/<video(.*?)<\/video>/is',
+              //  '/<audio(.*?)<\/audio>/is',
+             //   '/<video(.*?)<\/video>/is',
                 '/<frame(.*?)<\/frame>/is',
                 '/<frameset(.*?)<\/frameset>/is',
                 '/<object(.*?)<\/object>/is',
@@ -657,7 +658,7 @@ class Format
                 '/<style(.*?)<\/style>/is',
                 '/<body(.*?)>/is',
                 '/<\/body>/is',
-                '/<head(.*?)>/is',
+               // '/<head(.*?)>/is',
                 '/<\/head>/is',
                 '/onload="(.*?)"/is',
                 '/onunload="(.*?)"/is',

programming_language: PHP
filename: XSSClean.php
change_type: ModificationType.MODIFY
diff: @@ -34,6 +34,42 @@ class XSSClean
         if(is_array($html)){
             return $this->cleanArray($html);
         }
+
+
+        $_preserve_replaced_tags = [];
+        $html = str_ireplace('{SITE_URL}','___mw-site-url-temp-replace-on-clean___', $html);
+//        $tags = [ 'textarea', 'pre','code', 'svg', 'kbd'];
+//
+//        foreach ($tags as $tag) {
+//
+//            //  $script_pattern = "/<".$tag."[^>]*>(.*)<\/.$tag.>/Uis";
+//            $script_pattern = "/\<" . $tag . "(.*?)?\>(.|\s)*?\<\/" . $tag . "\>/i";
+//
+//            preg_match_all($script_pattern, $html, $mw_script_matches);
+//
+//            if (!empty($mw_script_matches)) {
+//                foreach ($mw_script_matches [0] as $key => $value) {
+//                    if ($value != '') {
+//                        $v1 = crc32($value);
+//                        $v1 = 'mw_xss_clean_repeserve_tags_tag_' . $tag . $v1 . '';
+//                        $html = str_replace($value, $v1, $html);
+//                        $_preserve_replaced_tags[$v1] = $value;
+//
+//                    }
+//                }
+//            }
+//
+//        }
+
+
+
+
+
+
+
+
+
+
          // from https://portswigger.net/web-security/cross-site-scripting/cheat-sheet#ontransitionend
         $cleanStrings = [
             'ontransitionstart',
@@ -154,23 +190,74 @@ class XSSClean
         $antiXss->addEvilAttributes($cleanStrings);
         $antiXss->addNeverAllowedOnEventsAfterwards($cleanStrings);
 
-        $allow_attibutes = [
+        $allowAttibutes = [
             'style',
+
+            'href',
+            'alt',
+            'target',
+            'srcset',
+            'sizes',
+            'title',
             'xlink:href',
         ];
-        $antiXss->removeEvilAttributes($allow_attibutes);
+        $antiXss->removeEvilAttributes($allowAttibutes);
 
-        $allow_tags = [
+        $allowTags = [
+            'head',
+            'header',
+            'main',
+            'aside',
             'img',
+            'form',
             'svg',
+            'title',
+            'input',
+            'button',
+            'select',
+            'option',
+            'textarea',
+            'picture',
+            'source',
+         ];
+
+        $antiXss->removeEvilHtmlTags($allowTags);
+        $allowRegex = [
+//            '<!--(.*)-->' => '<!--(.*)-->',
+//            '&lt;!--',
+//            '&lt;!--$1--&gt;'
+            '<!--(.*)-->' => '&lt;!--$1--&gt;',
+            '&lt;!--', '&lt;!--$1--&gt;'
         ];
 
-        $antiXss->removeEvilHtmlTags($allow_tags);
+
+
+        $antiXss->removeNeverAllowedRegex($allowRegex);
+
+        $allowNotClosed= [
+            'li',
+            'ul',
+            'textarea',
+        ];
+        $antiXss->removeDoNotCloseHtmlTags($allowNotClosed);
+
 
         $html = $antiXss->xss_clean($html);
+        $html_to_return = $html;
+        if ($_preserve_replaced_tags) {
+            foreach ($_preserve_replaced_tags as $key => $value) {
+
+                $html_to_return = str_replace($key, $value, $html_to_return);
+            }
+        }
+
+
+        $html_to_return = str_ireplace('___mw-site-url-temp-replace-on-clean___','{SITE_URL}', $html_to_return);
+
+
 
 
-        return $html;
+        return $html_to_return;
     }
 
 }

programming_language: PHP