Strips extra whitespace, images, scripts and stylesheets from output

@param string $str String to sanitize
@return string sanitized string
439666
protected function strip_all($str) {
		$str = $this->strip_whitespace($str);
		$str = $this->strip_images($str);
		$str = $this->strip_scripts($str);
		return $str;
	}
1182403
public static function strrev($str)
    {
        $result = '';
        $strLen = static::length($str);

        if (!$strLen) {
            return $result;
        }

        for ($i = $strLen - 1; $i >= 0; $i--) {
            $result .= static::substr($str, $i, 1);
        }

        return $result;
    }
649525
public static function removeUnsafeChars($str) {
		static $blacklist = '/[!\"?():\']/';
		static $whitelist = '/[^a-zA-Z0-9-_.]/';
		$validStr = preg_replace(array($blacklist, $whitelist), array('', '-'), $str);
		return $validStr;
	}
1187029
public static function restoreLineBreaks($str)
    {
        if (isset($str) and strlen($str) !== 0) {
            $result = str_replace(PHP_EOL, "\n\r<br />\n\r", $str);

            return $result;
        } else {
            return false;
        }
    }
1218463
public function unescapeMd($str)
    {
        if (strpos ($str,'\\') === false) return $str;
        return preg_replace(self::UNESCAPE_MD_RE, '$1', $str);
    }
473081
private static function cutString(string $str): string
    {
        static $mb;
        if ($mb === null) {
            $mb = function_exists('mb_strlen');
        }
        if ($mb) {
            $len = mb_strlen($str, 'UTF-8');
        } else {
            $len = strlen($str);
        }
        if ($len > self::MAX_LEN) {
            if ($mb) {
                return mb_substr($str, 0, self::MAX_LEN, 'UTF-8').'...';
            } else {
                return substr($str, 0, self::MAX_LEN).'...';
            }
        }
        return $str;
    }
662632
private function toNamespace($str) {
        $stringParts = preg_split('/_+/', $str);

        foreach($stringParts as $key => $stringPart){
            $stringParts[$key] = ucfirst(strtolower($stringPart));
        }
        return implode('\\', $stringParts) . '\\';
    }
263551
private function _filter_attributes(string $str): string
    {
        if ($str === '') {
            return '';
        }

        $out = '';
        if (\preg_match_all('#\s*[\\p{L}0-9_\-\[\]]+\s*=\s*("|\042|\'|\047)(?:[^\\1]*?)\\1#ui', $str, $matches)) {
            foreach ($matches[0] as $match) {
                $out .= $match;
            }
        }

        return $out;
    }
146693
function($str)
    {
        if (!this.hasFormatOptions)
        {
            this.addToLog($str);
            return false;
        }

        // strip colors from the string. this is ok with multilines
        if (this.options.stripColor)
        {
            $str = Utils.stripColor($str);
        }

        var $result = [];
        if (this.options.splitOnLinebreak)
        {
            var $split = Utils.splitOnLinebreak($str,
                                                this.options.trimLinebreak);

            for (var $i = 0, $iL = $split.length; $i < $iL; $i++)
            {
                $str = $split[$i];
                if (this.options.trimTimestamp)
                {
                    $str = Utils.trimTimestamp($str, !this.options.stripColor);
                }

                this.addToLog($str);
                $result.push($str);
            }
        }
        else
        {
            if (this.options.trimTimestamp)
            {
                $str = Utils.trimTimestamp($str, !this.options.stripColor);
            }

            if (this.options.trimLinebreak)
            {
                $str = Utils.trimLinebreak($str);
            }

            this.addToLog($str);
            $result.push($str);
        }

        return $result;
    }
469846
protected function clean($str)
    {
        if ($this->options->get('cleanupInput') != true) {
            // skip entire cleanup step
            return $str;
        }

        // remove white space before closing tags
        $str = mb_eregi_replace("'\s+>", "'>", $str);
        $str = mb_eregi_replace('"\s+>', '">', $str);

        // clean out the \n\r
        $replace = ' ';
        if ($this->options->get('preserveLineBreaks')) {
            $replace = '&#10;';
        }
        $str = str_replace(["\r\n", "\r", "\n"], $replace, $str);

        // strip the doctype
        $str = mb_eregi_replace("<!doctype(.*?)>", '', $str);

        // strip out comments
        $str = mb_eregi_replace("<!--(.*?)-->", '', $str);

        // strip out cdata
        $str = mb_eregi_replace("<!\[CDATA\[(.*?)\]\]>", '', $str);

        // strip out <script> tags
        if ($this->options->get('removeScripts') == true) {
            $str = mb_eregi_replace("<\s*script[^>]*[^/]>(.*?)<\s*/\s*script\s*>", '', $str);
            $str = mb_eregi_replace("<\s*script\s*>(.*?)<\s*/\s*script\s*>", '', $str);
        }

        // strip out <style> tags
        if ($this->options->get('removeStyles') == true) {
            $str = mb_eregi_replace("<\s*style[^>]*[^/]>(.*?)<\s*/\s*style\s*>", '', $str);
            $str = mb_eregi_replace("<\s*style\s*>(.*?)<\s*/\s*style\s*>", '', $str);
        }

        // strip out server side scripts
        $str = mb_eregi_replace("(<\?)(.*?)(\?>)", '', $str);

        // strip smarty scripts
        $str = mb_eregi_replace("(\{\w)(.*?)(\})", '', $str);

        return $str;
    }
310651
protected function sanitizeValue($str)
    {
        if (is_array($str)) {
            foreach ($str as &$value) {
                $value = $this->sanitizeValue($value);
            }
            unset($value);

            return $str;
        }

        $str = filter_var((string) $str, FILTER_UNSAFE_RAW, array('flags' => FILTER_FLAG_STRIP_LOW));
        $str = trim($str);

        return $str;
    }
1008817
public static String trimAllWhitespace(String str) {
        if (!hasLength(str)) {
            return str;
        }
        StringBuilder sb = new StringBuilder(str);
        int index = 0;
        while (sb.length() > index) {
            if (Character.isWhitespace(sb.charAt(index))) {
                sb.deleteCharAt(index);
            }
            else {
                index++;
            }
        }
        return sb.toString();
    }
137769
private function _parse_css($str)
    {

        $str = trim($str);

        // Destroy comments and remove HTML comments
        $css = preg_replace(array(
            "'/\*.*?\*/'si",
            "/^<!--/",
            "/-->$/"
        ), "", $str);

        // FIXME: handle '{' within strings, e.g. [attr="string {}"]

        // Something more legible:
        $re =
            "/\s*                                   # Skip leading whitespace                             \n" .
            "( @([^\s{]+)\s*([^{;]*) (?:;|({)) )?   # Match @rules followed by ';' or '{'                 \n" .
            "(?(1)                                  # Only parse sub-sections if we're in an @rule...     \n" .
            "  (?(4)                                # ...and if there was a leading '{'                   \n" .
            "    \s*( (?:(?>[^{}]+) ({)?            # Parse rulesets and individual @page rules           \n" .
            "            (?(6) (?>[^}]*) }) \s*)+?                                                        \n" .
            "       )                                                                                     \n" .
            "   })                                  # Balancing '}'                                       \n" .
            "|                                      # Branch to match regular rules (not preceded by '@') \n" .
            "([^{]*{[^}]*}))                        # Parse normal rulesets                               \n" .
            "/xs";

        if (preg_match_all($re, $css, $matches, PREG_SET_ORDER) === false) {
            // An error occurred
            throw new Exception("Error parsing css file: preg_match_all() failed.");
        }

        // After matching, the array indicies are set as follows:
        //
        // [0] => complete text of match
        // [1] => contains '@import ...;' or '@media {' if applicable
        // [2] => text following @ for cases where [1] is set
        // [3] => media types or full text following '@import ...;'
        // [4] => '{', if present
        // [5] => rulesets within media rules
        // [6] => '{', within media rules
        // [7] => individual rules, outside of media rules
        //

        $media_query_regex = "/(?:((only|not)?\s*(" . implode("|", self::$VALID_MEDIA_TYPES) . "))|(\s*\(\s*((?:(min|max)-)?([\w\-]+))\s*(?:\:\s*(.*?)\s*)?\)))/isx";

        //Helpers::pre_r($matches);
        foreach ($matches as $match) {
            $match[2] = trim($match[2]);

            if ($match[2] !== "") {
                // Handle @rules
                switch ($match[2]) {

                    case "import":
                        $this->_parse_import($match[3]);
                        break;

                    case "media":
                        $acceptedmedia = self::$ACCEPTED_GENERIC_MEDIA_TYPES;
                        $acceptedmedia[] = $this->_dompdf->getOptions()->getDefaultMediaType();

                        $media_queries = preg_split("/\s*,\s*/", mb_strtolower(trim($match[3])));
                        foreach ($media_queries as $media_query) {
                            if (in_array($media_query, $acceptedmedia)) {
                                //if we have a media type match go ahead and parse the stylesheet
                                $this->_parse_sections($match[5]);
                                break;
                            } elseif (!in_array($media_query, self::$VALID_MEDIA_TYPES)) {
                                // otherwise conditionally parse the stylesheet assuming there are parseable media queries
                                if (preg_match_all($media_query_regex, $media_query, $media_query_matches, PREG_SET_ORDER) !== false) {
                                    $mq = array();
                                    foreach ($media_query_matches as $media_query_match) {
                                        if (empty($media_query_match[1]) === false) {
                                            $media_query_feature = strtolower($media_query_match[3]);
                                            $media_query_value = strtolower($media_query_match[2]);
                                            $mq[] = array($media_query_feature, $media_query_value);
                                        } else if (empty($media_query_match[4]) === false) {
                                            $media_query_feature = strtolower($media_query_match[5]);
                                            $media_query_value = (array_key_exists(8, $media_query_match) ? strtolower($media_query_match[8]) : null);
                                            $mq[] = array($media_query_feature, $media_query_value);
                                        }
                                    }
                                    $this->_parse_sections($match[5], $mq);
                                    break;
                                }
                            }
                        }
                        break;

                    case "page":
                        //This handles @page to be applied to page oriented media
                        //Note: This has a reduced syntax:
                        //@page { margin:1cm; color:blue; }
                        //Not a sequence of styles like a full.css, but only the properties
                        //of a single style, which is applied to the very first "root" frame before
                        //processing other styles of the frame.
                        //Working properties:
                        // margin (for margin around edge of paper)
                        // font-family (default font of pages)
                        // color (default text color of pages)
                        //Non working properties:
                        // border
                        // padding
                        // background-color
                        //Todo:Reason is unknown
                        //Other properties (like further font or border attributes) not tested.
                        //If a border or background color around each paper sheet is desired,
                        //assign it to the <body> tag, possibly only for the css of the correct media type.

                        // If the page has a name, skip the style.
                        $page_selector = trim($match[3]);

                        $key = null;
                        switch ($page_selector) {
                            case "":
                                $key = "base";
                                break;

                            case ":left":
                            case ":right":
                            case ":odd":
                            case ":even":
                            /** @noinspection PhpMissingBreakStatementInspection */
                            case ":first":
                                $key = $page_selector;

                            default:
                                continue;
                        }

                        // Store the style for later...
                        if (empty($this->_page_styles[$key])) {
                            $this->_page_styles[$key] = $this->_parse_properties($match[5]);
                        } else {
                            $this->_page_styles[$key]->merge($this->_parse_properties($match[5]));
                        }
                        break;

                    case "font-face":
                        $this->_parse_font_face($match[5]);
                        break;

                    default:
                        // ignore everything else
                        break;
                }

                continue;
            }

            if ($match[7] !== "") {
                $this->_parse_sections($match[7]);
            }

        }
    }
858989
protected function convertToFullwidth(string $str): string
    {
        return preg_replace_callback('/[!-~]/u', function (array $matches): string {
            return \IntlChar::chr(\IntlChar::ord($matches[0]) - (\IntlChar::ord('!') - \IntlChar::ord('！')));
        }, $str);
    }
535643
private function _clean_input_data($str) {
		if (is_array($str)) {
			$new_array = array();
			foreach ($str as $key => $val) {
				$new_array[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
			}
			return $new_array;
		}
		
		/*
		 * We strip slashes if magic quotes is on to keep things consistent
		 * NOTE: In PHP 5.4 get_magic_quotes_gpc() will always return 0 and it
		 * will probably not exist in future versions at all.
		 */
		if (get_magic_quotes_gpc()) {
			$str = stripslashes($str);
		}
		
		// Remove control characters
		$str = Security::remove_invisible_characters($str);
		
		// Should we filter the input data?
		if ($this->_enable_xss === TRUE) {
			$str = Security::xss_clean($str);
		}
		
		// Standardize newlines if needed
		if ($this->_standardize_newlines == TRUE) {
			if (strpos($str, "\r") !== FALSE) {
				$str = str_replace(array("\r\n", "\r", "\r\n\n"), PHP_EOL, $str);
			}
		}
		
		return $str;
	}
816933
public static function cleanFileName($str)
    {
        preg_match('~\.\w{1,4}$~', $str, $ext);

        $str = preg_replace('~\.\w{1,4}$~', '', $str);

        return str_replace(Array(' ', '.', '-'), "_", $str).$ext[0];
    }
441326
public static function removeEmoji(string $str): string
    {
        $patterns = [
            '/[\x{1F600}-\x{1F64F}]/u', // Emoticons
            '/[\x{1F300}-\x{1F5FF}]/u', // Miscellaneous symbols and pictographs
            '/[\x{1F680}-\x{1F6FF}]/u', // Transport and map symbols
            '/[\x{2600}-\x{26FF}]/u',   // Miscellaneous symbols
            '/[\x{2700}-\x{27BF}]/u',   // Dingbats
        ];

        foreach ($patterns as $pattern) {
            $str = preg_replace(
                $pattern,
                ' ',
                $str
            );
        }

        return static::removeMultipleSpaces($str);
    }