Decode a string

@param string $string     Encoded string
@param int    $errmode    Error mode
@param bool   $isChecksum Is encoded with a checksum?

@return int

@throws \RuntimeException
555186
protected static function internalDecode($string, $errmode = self::NORMALIZE_ERRMODE_SILENT, $isChecksum = false)
    {
        if ('' === $string) {
            return '';
        }

        if (null === $string) {
            return '';
        }

        $string = static::normalize($string, $errmode);

        if ($isChecksum) {
            $valid = '/^[A-Z0-9\*\~\$=U]$/';
        } else {
            $valid = '/^[A-TV-Z0-9]+$/';
        }

        if (!preg_match($valid, $string)) {
            throw new \RuntimeException("String '$string' contains invalid characters");
        }

        $total = 0;
        foreach (str_split($string) as $symbol) {
            $total = $total * 32 + static::$flippedSymbols[$symbol];
        }

        return $total;
    }
820707
public static function decode($string, $asArray = false)
    {
        $decoded = self::safeDecode($string, $asArray);
        if (is_null($decoded) == false) {
            return $decoded;
        }
        $code = self::lastError();
        if ($code === JSON_ERROR_NONE) {
            return $decoded;
        }
        throw new JsonDecodeException(self::lastErrorMessage(), $code);
    }
754472
def checksum(string):
    
    digits = list(map(int, string))
    odd_sum = sum(digits[-1::-2])
    even_sum = sum([sum(divmod(2 * d, 10)) for d in digits[-2::-2]])
    return (odd_sum + even_sum) % 10
1278983
public function decodeReversibleString($string)
    {

        $salt = $this->getSecretAppString();

        $key = substr(base64_encode($salt), 0, 50);
        $iv = '12345678';
        $cc = base64_decode($string);

        $cipher = mcrypt_module_open(MCRYPT_BLOWFISH, '', 'cbc', '');

        mcrypt_generic_init($cipher, $key, $iv);
        $decrypted = mdecrypt_generic($cipher, $cc);
        mcrypt_generic_deinit($cipher);

        return json_decode(base64_decode($decrypted), true)['key'];
    }
1135251
public static function ord(string $char): int
    {
        $char = mb_convert_encoding($char, 'UTF-32BE', 'UTF-8');

        return (int) unpack('Ncode', $char)['code'];
    }
1034082
public static function decode($string)
    {
        if (! is_string($string)) {
            throw new JsonException('Json decode parameter must be a string');
        }

        $result = json_decode($string, true);

        if ($result === null) {
            throw new JsonException('Json decode error');
        }
        return $result;
    }
501187
protected function calculateChecksum() {
        // Calculating Checksum
        // Consider the right-most digit of the message to be in an "odd" position,
        // and assign odd/even to each character moving from right to left
        // Odd Position = 3, Even Position = 9
        // Multiply it by the number
        // Add all of that and do ?mod10
        $odd = true;
        $this->checksumValue = 0;
        $c = strlen($this->text);
        for ($i = $c; $i > 0; $i--) {
            if ($odd === true) {
                $multiplier = 3;
                $odd = false;
            } else {
                $multiplier = 9;
                $odd = true;
            }

            if (!isset($this->keys[$this->text[$i - 1]])) {
                return;
            }

            $this->checksumValue += $this->keys[$this->text[$i - 1]] * $multiplier;
        }

        $this->checksumValue = $this->checksumValue % 10;
    }
46994
function ChecksumError(cause, actual, expected) {
    this.code = 'ChecksumError';
    if (expected === undefined) {
        expected = actual;
        actual = cause;
        cause = undefined;
    }
    assert.optionalObject(cause);
    assert.string(actual);
    assert.string(expected);

    var args = [];
    if (cause) args.push(cause);
    args = args.concat('content-md5 expected to be %s, but was %s',
        expected, actual);
    WError.apply(this, args);
}
134202
public static String replaceChecksum(final String contentSpecString, final String checksum) {
        Matcher matcher = CS_CHECKSUM_PATTERN.matcher(contentSpecString);
        if (matcher.find()) {
            return matcher.replaceFirst("CHECKSUM=" + checksum + "\n");
        }

        return contentSpecString;
    }
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;
  }
1205769
private static function jsonFileDecode($string)
    {
        $json = JsonHelper::decodeIfJson($string);
        if (\is_string($json)) {
            Craft::error('Error decoding JSON file: '.$json, __METHOD__);
            $json = null;
        }

        return $json;
    }
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;
    }
278000
public static function bitmap2bytes($bitmap, $checkLen = 0)
    {
        $r = '';
        $bitmap = str_pad($bitmap, ceil(strlen($bitmap) / 8) * 8, '0', STR_PAD_LEFT);

        for ($i = 0, $n = strlen($bitmap) / 8; $i < $n; ++$i)
        {
            $r .= chr((int) bindec(static::binarySubstr($bitmap, $i * 8, 8)));
        }
        if ($checkLen && (strlen($r) != $checkLen)) {
            throw new Exception('Warning! Bitmap incorrect.');
        }

        return $r;
    }
642325
public function generateChecksum($obj = null, $secretCode = null,$isautocheckout = false)
    {
        $arr = array();
        if ($secretCode)
            array_push($arr, $secretCode);

        foreach ($obj as $val) {
            $insert = $val;

            if (is_bool($val)) {
                if ($isautocheckout) {
					$insert = ($val) ? 'True' : 'False';	// autocheckout function computes boolean checksum differently (first character uppercase)
				} else {
					$insert = ($val) ? 'true' : 'false';
				}
            }

            array_push($arr, $insert);
        }

        return sha1(implode("|", $arr));
    }
997478
private static function strord( $string )
	{ 
		for( $i=0; $i<strlen( $string ); $i++ )
		{ 
			$result[$i] = ord( $string{$i} );
		}
		return $result;
	}
712711
function decode($text)
    {
        $pad = ord(substr($text, -1));
        if ($pad < 1 || $pad > PKCS7Encoder::$blockSize) {
            $pad = 0;
        }
        return substr($text, 0, strlen($text) - $pad);
    }
583233
private function decodeInteger()
    {
        $offsetOfE = strpos($this->source, "e", $this->offset);
        if (false === $offsetOfE) {
            throw new RuntimeException("Unterminated integer entity at offset $this->offset");
        }

        $currentOffset = $this->offset;
        if ("-" == $this->getChar($currentOffset)) {
            ++$currentOffset;
        }

        if ($offsetOfE === $currentOffset) {
            throw new RuntimeException("Empty integer entity at offset $this->offset");
        }

        while ($currentOffset < $offsetOfE) {
            if (!ctype_digit($this->getChar($currentOffset))) {
                throw new RuntimeException("Non-numeric character found in integer entity at offset $this->offset");
            }
            ++$currentOffset;
        }

        $value = substr($this->source, $this->offset, $offsetOfE - $this->offset);

        // One last check to make sure zero-padded integers don't slip by, as
        // they're not allowed per bencode specification.
        $absoluteValue = (string) abs($value);
        if (1 < strlen($absoluteValue) && "0" == $value[0]) {
            throw new RuntimeException("Illegal zero-padding found in integer entity at offset $this->offset");
        }

        $this->offset = $offsetOfE + 1;

        // The +0 auto-casts the chunk to either an integer or a float(in cases
        // where an integer would overrun the max limits of integer types)
        return $value + 0;
    }