Replaces special characters for the usage inside javascript

@param string $string
@param boolean $asObject
@return string
353682
public static function prepareVariableForJavascript($string, $asObject) {
		if ($asObject) {
			$string = str_replace(array(
				'"', '/', '<', "\n", "\r"
			), array(
				'\"', '\/', '\<', '<br />', ''
			), $string);
		} else {
			$string = str_replace(array(
				'"', '/', '<', "\n", "\r"
		  ), array(
				'\"', '\/', '\<', '', ''
			), $string);
		}

		return $string;
	}
1326928
@Nonnull
    static String convertStringToPlainAscii(@Nonnull final String string) {
        return Decoder.decodeUTF16(string.toUpperCase());
    }
1104644
function escapeStringForJavascript(content) {
  return content.replace(/(['\\])/g, '\\$1')
    .replace(/[\f]/g, "\\f")
    .replace(/[\b]/g, "\\b")
    .replace(/[\n]/g, "\\n")
    .replace(/[\t]/g, "\\t")
    .replace(/[\r]/g, "\\r")
    .replace(/[\u2028]/g, "\\u2028")
    .replace(/[\u2029]/g, "\\u2029");
}
1351476
public static function clean($string, $isImage = false)
    {
        // Is the string an array?
        if (is_array($string)) {
            while (list($key) = each($string)) {
                $string[ $key ] = self::clean($string[ $key ]);
            }

            return $string;
        }

        // Remove Invisible Characters
        $string = remove_invisible_characters($string);

        /*
         * URL Decode
         *
         * Just in case stuff like this is submitted:
         *
         * <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a>
         *
         * Note: Use rawurldecode() so it does not remove plus signs
         */
        do {
            $string = rawurldecode($string);
        } while (preg_match('/%[0-9a-f]{2,}/i', $string));

        /*
         * Convert character entities to ASCII
         *
         * This permits our tests below to work reliably.
         * We only convert entities that are within tags since
         * these are the ones that will pose security problems.
         */
        $string = preg_replace_callback(
            "/[^a-z0-9>]+[a-z0-9]+=([\'\"]).*?\\1/si",
            [self::class, 'convertAttribute'],
            $string
        );

        $string = preg_replace_callback('/<\w+.*/si', [self::class, 'decodeEntity'], $string);

        // Remove Invisible Characters Again!
        $string = remove_invisible_characters($string);

        /*
         * Convert all tabs to spaces
         *
         * This prevents strings like this: ja  vascript
         * NOTE: we deal with spaces between characters later.
         * NOTE: preg_replace was found to be amazingly slow here on
         * large blocks of data, so we use str_replace.
         */
        $string = str_replace("\t", ' ', $string);

        // Capture converted string for later comparison
        $convertedString = $string;

        // Remove Strings that are never allowed
        $string = self::doNeverAllowed($string);

        /*
         * Makes PHP tags safe
         *
         * Note: XML tags are inadvertently replaced too:
         *
         * <?xml
         *
         * But it doesn't seem to pose a problem.
         */
        if ($isImage === true) {
            // Images have a tendency to have the PHP short opening and
            // closing tags every so often so we skip those and only
            // do the long opening tags.
            $string = preg_replace('/<\?(php)/i', '&lt;?\\1', $string);
        } else {
            $string = str_replace(['<?', '?' . '>'], ['&lt;?', '?&gt;'], $string);
        }

        /*
         * Compact any exploded words
         *
         * This corrects words like:  j a v a s c r i p t
         * These words are compacted back to their correct state.
         */
        $words = [
            'javascript',
            'expression',
            'vbscript',
            'jscript',
            'wscript',
            'vbs',
            'script',
            'base64',
            'applet',
            'alert',
            'document',
            'write',
            'cookie',
            'window',
            'confirm',
            'prompt',
            'eval',
        ];

        foreach ($words as $word) {
            $word = implode('\s*', str_split($word)) . '\s*';

            // We only want to do this when it is followed by a non-word character
            // That way valid stuff like "dealer to" does not become "dealerto"
            $string = preg_replace_callback(
                '#(' . substr($word, 0, -3) . ')(\W)#is',
                [self::class, 'compactExplodedWords'],
                $string
            );
        }

        /*
         * Remove disallowed Javascript in links or img tags
         * We used to do some version comparisons and use of stripos(),
         * but it is dog slow compared to these simplified non-capturing
         * preg_match(), especially if the pattern exists in the string
         *
         * Note: It was reported that not only space characters, but all in
         * the following pattern can be parsed as separators between a tag name
         * and its attributes: [\d\s"\'`;,\/\=\(\x00\x0B\x09\x0C]
         * ... however, remove_invisible_characters() above already strips the
         * hex-encoded ones, so we'll skip them below.
         */
        do {
            $original = $string;
            if (preg_match('/<a/i', $string)) {
                $string = preg_replace_callback(
                    '#<a[^a-z0-9>]+([^>]*?)(?:>|$)#si',
                    [self::class, 'jsLinkRemoval'],
                    $string
                );
            }
            if (preg_match('/<img/i', $string)) {
                $string = preg_replace_callback(
                    '#<img[^a-z0-9]+([^>]*?)(?:\s?/?>|$)#si',
                    [self::class, 'jsImgRemoval'],
                    $string
                );
            }
            if (preg_match('/script|xss/i', $string)) {
                $string = preg_replace('#</*(?:script|xss).*?>#si', '[removed]', $string);
            }
        } while ($original !== $string);
        unset($original);

        /*
         * Sanitize naughty HTML elements
         *
         * If a tag containing any of the words in the list
         * below is found, the tag gets converted to entities.
         *
         * So this: <blink>
         * Becomes: &lt;blink&gt;
         */
        $pattern = '#'
            . '<((?<slash>/*\s*)(?<tagName>[a-z0-9]+)(?=[^a-z0-9]|$)'
            // tag start and name, followed by a non-tag character
            . '[^\s\042\047a-z0-9>/=]*'
            // a valid attribute character immediately after the tag would count as a separator
            // optional attributes
            . '(?<attributes>(?:[\s\042\047/=]*'
            // non-attribute characters, excluding > (tag close) for obvious reasons
            . '[^\s\042\047>/=]+'
            // attribute characters
            // optional attribute-value
            . '(?:\s*='
            // attribute-value separator
            . '(?:[^\s\042\047=><`]+|\s*\042[^\042]*\042|\s*\047[^\047]*\047|\s*(?U:[^\s\042\047=><`]*))'
            // single, double or non-quoted value
            . ')?'
            // end optional attribute-value group
            . ')*)'
            // end optional attributes group
            . '[^>]*)(?<closeTag>\>)?#isS';
        // Note: It would be nice to optimize this for speed, BUT
        //       only matching the naughty elements here results in
        //       false positives and in turn - vulnerabilities!
        do {
            $oldString = $string;
            $string = preg_replace_callback($pattern, [self::class, 'sanitizeNaughtyHTML'], $string);
        } while ($oldString !== $string);

        unset($oldString);

        /*
         * Sanitize naughty scripting elements
         *
         * Similar to above, only instead of looking for
         * tags it looks for PHP and JavaScript commands
         * that are disallowed. Rather than removing the
         * code, it simply converts the parenthesis to entities
         * rendering the code un-executable.
         *
         * For example: eval('some code')
         * Becomes: eval&#40;'some code'&#41;
         */
        $string = preg_replace(
            '#(alert|prompt|confirm|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si',
            '\\1\\2&#40;\\3&#41;',
            $string
        );

        // Final clean up
        // This adds a bit of extra precaution in case
        // something got through the above filters
        $string = self::doNeverAllowed($string);

        /*
         * Images are Handled in a Special Way
         * - Essentially, we want to know that after all of the character
         * conversion is done whether any unwanted, likely XSS, code was found.
         * If not, we return TRUE, as the image is clean.
         * However, if the string post-conversion does not matched the
         * string post-removal of XSS, then it fails, as there was unwanted XSS
         * code found and removed/changed during processing.
         */
        if ($isImage === true) {
            return ($string === $convertedString);
        }

        return $string;
    }
343140
public static function toAscii(string $string): string
    {
        static $transliterator;

        if (!$transliterator && class_exists('Transliterator', false)) {
            $transliterator = \Transliterator::create('Any-Latin; Latin-ASCII');
        }

        $string = preg_replace('~[^\x09\x0A\x0D\x20-\x7E\xA0-\x{2FF}\x{370}-\x{10FFFF}]~u', '', $string);
        $string = strtr($string, '`\'"^~?', "\1\2\3\4\5\6");
        $string = str_replace(
            ["\u{201E}", "\u{201C}", "\u{201D}", "\u{201A}", "\u{2018}", "\u{2019}", "\u{B0}"],
            ["\3", "\3", "\3", "\2", "\2", "\2", "\4"],
            $string
        );

        if ($transliterator) {
            $string = $transliterator->transliterate($string);
        }

        if (ICONV_IMPL === 'glibc') {
            $string = str_replace(
                ["\u{BB}", "\u{AB}", "\u{2026}", "\u{2122}", "\u{A9}", "\u{AE}"],
                ['>>', '<<', '...', 'TM', '(c)', '(R)'],
                $string
            );
            $string = iconv('UTF-8', 'WINDOWS-1250//TRANSLIT//IGNORE', $string);
            $string = strtr(
                $string,
                "\xA5\xA3\xBC\x8C\xA7\x8A\xAA\x8D\x8F\x8E\xAF\xB9\xB3\xBE\x9C\x9A\xBA\x9D\x9F\x9E\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF8\xF9\xFA\xFB\xFC\xFD\xFE\x96\xA0\x8B\x97\x9B\xA6\xAD\xB7",
                'ALLSSSSTZZZallssstzzzRAAAALCCCEEEEIIDDNNOOOOxRUUUUYTsraaaalccceeeeiiddnnooooruuuuyt- <->|-.'
            );
            $string = preg_replace('~[^\x00-\x7F]++~', '', $string);
        } else {
            $string = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $string);
        }

        $string = str_replace(['`', "'", '"', '^', '~', '?'], '', $string);

        return strtr($string, "\1\2\3\4\5\6", '`\'"^~?');
    }
900466
public static function decodeHtmlEntities($string)
  {
    // Entities-replacements
    $entities = array ("'&(quot|#34);'i",
                        "'&(amp|#38);'i",
                        "'&(lt|#60);'i",
                        "'&(gt|#62);'i",
                        "'&(nbsp|#160);'i",
                        "'&(iexcl|#161);'i",
                        "'&(cent|#162);'i",
                        "'&(pound|#163);'i",
                        "'&(copy|#169);'i");
                        
    $entitie_replacements = array ("\"",
                                   "&",
                                   "<",
                                   ">",
                                   " ",
                                   chr(161),
                                   chr(162),
                                   chr(163),
                                   chr(169));
    
  
    $string = preg_replace($entities, $entitie_replacements, $string);
    
    // Numeric haracter reference replacement (non-HEX), like &#64; => "@"
    $string = preg_replace_callback("/&#([0-9]{1,4});/ i", function($m) {return chr($m[1]);}, $string);
    
    // Numeric character reference replacement (HEX), like &#x2f; => "/"
    $string = preg_replace_callback("/&#x([0-9a-z]{2,4});/ i", function($m) {return chr(hexdec($m[1]));}, $string);
    
    return $string;
  }
1125022
public static String encode(final String aString, final boolean aIgnoreSlashFlag) {
        final CharacterIterator iterator = new StringCharacterIterator(decode(aString));
        final StringBuilder builder = new StringBuilder();

        for (char c = iterator.first(); c != CharacterIterator.DONE; c = iterator.next()) {
            switch (c) {
                case '%':
                    builder.append(PERCENT);
                    break;
                case '/':
                    if (aIgnoreSlashFlag) {
                        builder.append(c);
                    } else {
                        builder.append("%2F");
                    }
                    break;
                case '?':
                    builder.append("%3F");
                    break;
                case '#':
                    builder.append("%23");
                    break;
                case '[':
                    builder.append("%5B");
                    break;
                case ']':
                    builder.append("%5D");
                    break;
                case '@':
                    builder.append("%40");
                    break;
                default:
                    builder.append(c);
                    break;
            }
        }

        // Must percent-encode any characters outside the US-ASCII set
        return URI.create(builder.toString()).toASCIIString();
    }
915228
public static String escapeXML(String s, boolean onlyASCII) {
        char cc[] = s.toCharArray();
        int len = cc.length;
        StringBuffer sb = new StringBuffer();
        for (int k = 0; k < len; ++k) {
            int c = cc[k];
            switch (c) {
                case '<':
                    sb.append("&lt;");
                    break;
                case '>':
                    sb.append("&gt;");
                    break;
                case '&':
                    sb.append("&amp;");
                    break;
                case '"':
                    sb.append("&quot;");
                    break;
                case '\'':
                    sb.append("&apos;");
                    break;
                default:
                	if ((c == 0x9) || (c == 0xA) || (c == 0xD)
                		|| ((c >= 0x20) && (c <= 0xD7FF))
                		|| ((c >= 0xE000) && (c <= 0xFFFD))
                		|| ((c >= 0x10000) && (c <= 0x10FFFF))) { 
                		if (onlyASCII && c > 127)
                			sb.append("&#").append(c).append(';');
                		else 
                			sb.append((char)c);
                	}
            }
        }
        return sb.toString();
    }
1221394
public static function convertToBinaryRepresentation(string $rawString): string
    {
        $out = '';
        $strLength = strlen($rawString);
        for ($a = 0; $a < $strLength; $a++) {
            $dec = ord($rawString[$a]); //determine symbol ASCII-code
            $bin = sprintf('%08d', base_convert($dec, 10, 2)); //convert to binary representation and add leading zeros
            $out .= $bin;
        }

        return $out;
    }
1303744
public function escape($string)
    {
        $string = mb_convert_encoding($string, 'UTF-8', 'UTF-8');
        $string = str_replace('{{', '', $string);
        $string = str_replace('}}', '', $string);

        return htmlentities($string, ENT_QUOTES, 'UTF-8');
    }
724103
static function jsonEncode($object,$option=0)
    {
        $marks = Utility::mark_js_function($object);
        $text = json_encode($object, $option);
        foreach ($marks as $i=>$js) {
            $text = str_replace("\"--js($i)\"", $js, $text);
        }
        return $text;
    }
805133
function encodeString(string) {
	//it actually accepts any kind of object as input
	if (string === null) {
		return values.NULL;
	} else if (string === "") {
		return values.EMPTY;
	} else {//0 false undefined NaN will pass from here
		return encodeURIComponent(string)
		.replace(/%20/g, "+");
	}
}
325442
function(string) {
    return string.replace(/&(?!\w+;|#\d+;|#x[\da-f]+;)/gi, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#x27;').replace(/\//g,'&#x2F;');
  }
1364142
function obj2str(obj) {
  return Object.getOwnPropertyNames(obj).map(function (key) {
    return encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]);
  }).join('&');
}
10282
private String convertToEcmaScriptString(String string) {
        int len = string.length();
        InternalStringBuilder buf = new InternalStringBuilder(len);
        for(int i = 0; i < len; i++) {
            char c = string.charAt(i);
            // skip the \\ and consume the next character either appending it or turning it back
            // into the single character that it should have been in the first place.
            
            // if slash and not at the last character...
            if(c == '\\' && i + 1 < len) {
                i++;

                // skip the slash
                c = string.charAt(i);

                if(c == 'b')
                    c = '\b';
                else if(c == 't')
                    c = '\t';
                else if(c == 'n')
                    c = '\n';
                //else if(c == 'v') c = '\v';
                else if(c == 'f')
                    c = '\f';
                else if(c == 'r') c = '\r';
                // @todo: unicode escaping?
            }

            buf.append(c);
        }

        LOGGER.trace("converted String to JavaScript compliant string: " + buf.toString());

        return buf.toString();
    }
657665
function(obj) {
                if (obj === undefined)
                    return obj + "";
                if (obj === null)
                    return obj + "";
                return Object[LEXICON.p].toString.call(obj).replace(/^\[object (.+)\]$/, '$1').toLowerCase();
            }
1059365
@Override
	public <T> T asObject(String string, Class<T> valueType) throws ConverterException {
		// at this point value type is guaranteed to be URL
		try {
			return (T) new URL(string);
		} catch (MalformedURLException e) {
			throw new ConverterException(e.getMessage());
		}
	}