Get the encoding of a given abject

@param object|string $structure

@return string
189378
public function getEncoding($structure) {
        if (property_exists($structure, 'parameters')) {
            foreach ($structure->parameters as $parameter) {
                if (strtolower($parameter->attribute) == "charset") {
                    return EncodingAliases::get($parameter->value);
                }
            }
        }elseif (is_string($structure) === true){
            return mb_detect_encoding($structure);
        }

        return 'UTF-8';
    }
1212933
public function encodeModeStructure()
    {
        try {
            $bs =  new QRbitstream();

            $bs->appendNum(4, 0x03);
            $bs->appendNum(4, ord($this->data[1]) - 1);
            $bs->appendNum(4, ord($this->data[0]) - 1);
            $bs->appendNum(8, ord($this->data[2]));

            $this->bstream = $bs;
            return 0;

        } catch (Exception $e) {
            return -1;
        }
    }
633613
def _structure_unicode(self, obj, cl):
        """"""
        if not isinstance(obj, (bytes, unicode)):
            return cl(str(obj))
        else:
            return obj
1063556
public function getAvailableLocalization(StructureBehavior $document, $locale)
    {
        $availableLocales = $this->inspector->getLocales($document);

        if (in_array($locale, $availableLocales)) {
            return $locale;
        }

        $fallbackLocale = null;

        if ($document instanceof WebspaceBehavior) {
            $fallbackLocale = $this->localizationFinder->findAvailableLocale(
                $this->inspector->getWebspace($document),
                $availableLocales,
                $locale
            );
        }

        if (!$fallbackLocale) {
            $fallbackLocale = reset($availableLocales);
        }

        if (!$fallbackLocale) {
            $fallbackLocale = $this->documentRegistry->getDefaultLocale();
        }

        return $fallbackLocale;
    }
692598
static function fr_entities_encode($s)
	{
		//$s = str_replace("&", "&amp;", $s);
		$s = str_replace("é", "&eacute;", $s);
		$s = str_replace("è", "&egrave;", $s);
		$s = str_replace("ë", "&euml;", $s);
		$s = str_replace("ê", "&ecirc;", $s);
		$s = str_replace("à", "&agrave;", $s);
		$s = str_replace("ä", "&auml;", $s);
		$s = str_replace("â", "&acirc;", $s);
		$s = str_replace("ï", "&iuml;", $s);
		$s = str_replace("î", "&icirc;", $s);
		$s = str_replace("ö", "&ouml;", $s);
		$s = str_replace("ô", "&ocirc;", $s);
		$s = str_replace("ü", "&uuml;", $s);
		$s = str_replace("û", "&ucirc;", $s);
		$s = str_replace("ù", "&ugrave;", $s);
		$s = str_replace("ç", "&ccedil;", $s);
		$s = str_replace("€", "&euro;", $s);
	
		$s = str_replace("É", "&Eacute;", $s);
		$s = str_replace("È", "&Egrave;", $s);
		$s = str_replace("Ë", "&Euml;", $s);
		$s = str_replace("Ê", "&Ecirc;", $s);
		$s = str_replace("À", "&Agrave;", $s);
		$s = str_replace("Ä", "&Auml;", $s);
		$s = str_replace("Â", "&Acirc;", $s);
		$s = str_replace("Ï", "&Iuml;", $s);
		$s = str_replace("Î", "&Icirc;", $s);
		$s = str_replace("Ö", "&Ouml;", $s);
		$s = str_replace("Ô", "&Ocirc;", $s);
		$s = str_replace("Ü", "&Uuml;", $s);
		$s = str_replace("Û", "&Ucirc;", $s);
		$s = str_replace("Ù", "&Ugrave;", $s);
		$s = str_replace("Ç", "&Ccedil;", $s);
		
		return $s;
	}
7604
public static function validate($structure)
    {
        if (12 !== strlen($structure)
        ) {
            return false;
        }

        $sequences = substr($structure, 0, 10);
        $key = substr($structure, -2);
        $control = $sequences % 97; // final control must be a 2-digits:
        $control = (1 < strlen($control)) ? $control : sprintf('0%d', $control);

        return $key === $control;
    }
93551
protected function getPrefix($object)
    {
        $id = 'user';

        if (method_exists($object, 'getOrganization')) {
            $org = $object->getOrganization();

            if ($org instanceof OrganizationInterface) {
                $id = (string) $org->getId();
            }
        }

        return $id.'__';
    }
804204
protected function getSectionStructureFromIncomingStructure($section)
    {
        $pos = strpos($section, '.');
        if ($pos === false) {
            $section = (int) $section;
            if ($section === 0) {
                return $this->structure;
            }

            return $this->structure->parts[($section - 1)];
        }
        $sections = explode('.', $section);
        $count = count($sections);
        $outObject = null;
        foreach ($sections as $section) {
            $section = (int) $section;
            if (!isset($outObject)) {
                $outObject = $this->getObjectStructureFromParts($this->structure, ($section - 1));
            } else {
                $outObject = $this->getObjectStructureFromParts($outObject, ($section - 1));
            }
        }

        return $outObject;
    }
258170
public function convertStructureToSuccessMessage(MessageStructure $structure, RawMessage $rawMessage)
    {
        $message = new SuccessMessage($structure->getElements()[0]);
        $message->setSerialization($rawMessage->getBytes());

        return $message;
    }
961701
public function convertStructureToFailureMessage(MessageStructure $structure, RawMessage $rawMessage)
    {
        $message = new FailureMessage($structure->getElements()[0]);
        $message->setSerialization($rawMessage->getBytes());

        return $message;
    }
961244
protected function _decode($source)
    {
        // entity decode
        $trans_tbl = get_html_translation_table(HTML_ENTITIES);
        foreach ($trans_tbl as $k => $v) {
            $ttr[$v] = utf8_encode($k);
        }
        $source = strtr($source, $ttr);

        // convert decimal
        //$source = preg_replace('/&#(\d+);/me', "chr(\\1)", $source); // decimal notation
        $source = preg_replace_callback(
                       '/&#(\d+);/m',
                       function ($m) {
                           return chr($m[1]);
                       },
                       $source
        );

        // convert hex
        //$source = preg_replace('/&#x([a-f0-9]+);/mei', "chr(0x\\1)", $source); // hex notation
        
        $source = preg_replace_callback(
                       '/&#x([a-f0-9]+);/mi',
                       function ($m) {
                           return chr('0x'.$m[1]);
                       },
                       $source
        );
        
        return $source;
    }
837317
public static function structToString($struct, array $options = [])
    {
        $header = StructureHelper::getValue($options, 'header');
        $asArray = StructureHelper::getValue($options, 'as_array');
        $strict = StructureHelper::getValue($options, 'strict');

        // Build the object variables string
        $vars = '';

        foreach ($struct as $k => $v) {
            if (is_scalar($v)) {
                $vars .= sprintf("    '%s' => '%s',\n", $k, addcslashes($v, '\\\''));
            } elseif (is_array($v) || is_object($v)) {
                $vars .= sprintf("    '%s' => %s,\n", $k, static::getArrayString((array) $v));
            }
        }

        if (!$asArray) {
            if ($strict) {
                $str = "<?php declare(strict_types=1);\n";
            } else {
                $str = "<?php\n";
            }

            if ($header) {
                $str .= $header . "\n";
            }

            $str .= "\nreturn [\n";
        } else {
            $str = "[\n";
        }

        $str .= $vars;
        $str .= ']';

        if (!$asArray) {
            $str .= ";\n";

            // Use the closing tag if set to true in parameters.
            if (StructureHelper::getValue($options, 'closingtag', false)) {
                $str .= "\n?>";
            }
        }

        return $str;
    }
95850
private function getExcerptStructure($locale = null)
    {
        if (null === $locale) {
            $locale = $this->languageCode;
        }

        $excerptStructure = $this->structureManager->getStructure(self::EXCERPT_EXTENSION_NAME);
        $excerptStructure->setLanguageCode($locale);

        return $excerptStructure;
    }
223455
public function decode_uhex($s)
	{
		preg_match_all('/\\\u([0-9a-f]{4})/i', $s, $matches);
		$matches = $matches[count($matches) - 1];
		$map = array();

		foreach ($matches as $match)
		{
			if (!isset($map[$match]))
			{
				$map['\u' . $match] = html_entity_decode('&#' . hexdec($match) . ';', ENT_NOQUOTES, 'UTF-8');
			}
		}

		return str_replace(array_keys($map), $map, $s);
	}
964921
private function parse_structure($structure, $recursive = false)
    {
        // real content-type of message/rfc822 part
        if ($structure->mimetype == 'message/rfc822' && $structure->real_mimetype) {
            $mimetype = $structure->real_mimetype;

            // parse headers from message/rfc822 part
            if (!isset($structure->headers['subject']) && !isset($structure->headers['from'])) {
                list($headers, ) = explode("\r\n\r\n", $this->get_part_body($structure->mime_id, false, 32768));
                $structure->headers = rcube_mime::parse_headers($headers);

                if ($this->context == $structure->mime_id) {
                    $this->headers = rcube_message_header::from_array($structure->headers);
                }
            }
        }
        else {
            $mimetype = $structure->mimetype;
        }

        // show message headers
        if ($recursive && is_array($structure->headers) &&
            (isset($structure->headers['subject']) || $structure->headers['from'] || $structure->headers['to'])
        ) {
            $c = new stdClass;
            $c->type = 'headers';
            $c->headers = $structure->headers;
            $this->add_part($c);
        }

        // Allow plugins to handle message parts
        $plugin = $this->app->plugins->exec_hook('message_part_structure',
            array('object' => $this, 'structure' => $structure,
                'mimetype' => $mimetype, 'recursive' => $recursive));

        if ($plugin['abort']) {
            return;
        }

        $structure = $plugin['structure'];
        $mimetype  = $plugin['mimetype'];
        $recursive = $plugin['recursive'];

        list($message_ctype_primary, $message_ctype_secondary) = explode('/', $mimetype);

        // print body if message doesn't have multiple parts
        if ($message_ctype_primary == 'text' && !$recursive) {
            // parts with unsupported type add to attachments list
            if (!in_array($message_ctype_secondary, array('plain', 'html', 'enriched'))) {
                $this->add_part($structure, 'attachment');
                return;
            }

            $structure->type = 'content';
            $this->add_part($structure);

            // Parse simple (plain text) message body
            if ($message_ctype_secondary == 'plain') {
                foreach ((array)$this->uu_decode($structure) as $uupart) {
                    $this->mime_parts[$uupart->mime_id] = $uupart;
                    $this->add_part($uupart, 'attachment');
                }
            }
        }
        // the same for pgp signed messages
        else if ($mimetype == 'application/pgp' && !$recursive) {
            $structure->type = 'content';
            $this->add_part($structure);
        }
        // message contains (more than one!) alternative parts
        else if ($mimetype == 'multipart/alternative'
            && is_array($structure->parts) && count($structure->parts) > 1
        ) {
            // get html/plaintext parts, other add to attachments list
            foreach ($structure->parts as $p => $sub_part) {
                $sub_mimetype = $sub_part->mimetype;
                $is_multipart = preg_match('/^multipart\/(related|relative|mixed|alternative)/', $sub_mimetype);

                // skip empty text parts
                if (!$sub_part->size && !$is_multipart) {
                    continue;
                }

                // We've encountered (malformed) messages with more than
                // one text/plain or text/html part here. There's no way to choose
                // which one is better, so we'll display first of them and add
                // others as attachments (#1489358)

                // check if sub part is
                if ($is_multipart)
                    $related_part = $p;
                else if ($sub_mimetype == 'text/plain' && !$plain_part)
                    $plain_part = $p;
                else if ($sub_mimetype == 'text/html' && !$html_part) {
                    $html_part = $p;
                    $this->got_html_part = true;
                }
                else if ($sub_mimetype == 'text/enriched' && !$enriched_part)
                    $enriched_part = $p;
                else {
                    // add unsupported/unrecognized parts to attachments list
                    $this->add_part($sub_part, 'attachment');
                }
            }

            // parse related part (alternative part could be in here)
            if ($related_part !== null && !$this->parse_alternative) {
                $this->parse_alternative = true;
                $this->parse_structure($structure->parts[$related_part], true);
                $this->parse_alternative = false;

                // if plain part was found, we should unset it if html is preferred
                if ($this->opt['prefer_html'] && count($this->parts)) {
                    $plain_part = null;
                }
            }

            // choose html/plain part to print
            if ($html_part !== null && $this->opt['prefer_html']) {
                $print_part = $structure->parts[$html_part];
            }
            else if ($enriched_part !== null) {
                $print_part = $structure->parts[$enriched_part];
            }
            else if ($plain_part !== null) {
                $print_part = $structure->parts[$plain_part];
            }

            // add the right message body
            if (is_object($print_part)) {
                $print_part->type = 'content';

                // Allow plugins to handle also this part
                $plugin = $this->app->plugins->exec_hook('message_part_structure',
                    array('object' => $this, 'structure' => $print_part,
                        'mimetype' => $print_part->mimetype, 'recursive' => true));

                if (!$plugin['abort']) {
                    $this->add_part($print_part);
                }
            }
            // show plaintext warning
            else if ($html_part !== null && empty($this->parts)) {
                $c = new stdClass;
                $c->type            = 'content';
                $c->ctype_primary   = 'text';
                $c->ctype_secondary = 'plain';
                $c->mimetype        = 'text/plain';
                $c->realtype        = 'text/html';

                $this->add_part($c);
            }
        }
        // this is an ecrypted message -> create a plaintext body with the according message
        else if ($mimetype == 'multipart/encrypted') {
            $p = new stdClass;
            $p->type            = 'content';
            $p->ctype_primary   = 'text';
            $p->ctype_secondary = 'plain';
            $p->mimetype        = 'text/plain';
            $p->realtype        = 'multipart/encrypted';
            $p->mime_id         = $structure->mime_id;

            $this->add_part($p);

            // add encrypted payload part as attachment
            if (is_array($structure->parts)) {
                for ($i=0; $i < count($structure->parts); $i++) {
                    $subpart = $structure->parts[$i];
                    if ($subpart->mimetype == 'application/octet-stream' || !empty($subpart->filename)) {
                        $this->add_part($subpart, 'attachment');
                    }
                }
            }
        }
        // this is an S/MIME ecrypted message -> create a plaintext body with the according message
        else if ($mimetype == 'application/pkcs7-mime') {
            $p = new stdClass;
            $p->type            = 'content';
            $p->ctype_primary   = 'text';
            $p->ctype_secondary = 'plain';
            $p->mimetype        = 'text/plain';
            $p->realtype        = 'application/pkcs7-mime';
            $p->mime_id         = $structure->mime_id;

            $this->add_part($p);

            if (!empty($structure->filename)) {
                $this->add_part($structure, 'attachment');
            }
        }
        // message contains multiple parts
        else if (is_array($structure->parts) && !empty($structure->parts)) {
            // iterate over parts
            for ($i=0; $i < count($structure->parts); $i++) {
                $mail_part      = &$structure->parts[$i];
                $primary_type   = $mail_part->ctype_primary;
                $secondary_type = $mail_part->ctype_secondary;
                $part_mimetype  = $mail_part->mimetype;

                // multipart/alternative or message/rfc822
                if ($primary_type == 'multipart' || $part_mimetype == 'message/rfc822') {
                    // list message/rfc822 as attachment as well
                    if ($part_mimetype == 'message/rfc822') {
                        $this->add_part($mail_part, 'attachment');
                    }

                    $this->parse_structure($mail_part, true);
                }
                // part text/[plain|html] or delivery status
                else if ((($part_mimetype == 'text/plain' || $part_mimetype == 'text/html') && $mail_part->disposition != 'attachment') ||
                    in_array($part_mimetype, array('message/delivery-status', 'text/rfc822-headers', 'message/disposition-notification'))
                ) {
                    // Allow plugins to handle also this part
                    $plugin = $this->app->plugins->exec_hook('message_part_structure',
                        array('object' => $this, 'structure' => $mail_part,
                            'mimetype' => $part_mimetype, 'recursive' => true));

                    if ($plugin['abort']) {
                        continue;
                    }

                    if ($part_mimetype == 'text/html' && $mail_part->size) {
                        $this->got_html_part = true;
                    }

                    $mail_part = $plugin['structure'];
                    list($primary_type, $secondary_type) = explode('/', $plugin['mimetype']);

                    // add text part if it matches the prefs
                    if (!$this->parse_alternative ||
                        ($secondary_type == 'html' && $this->opt['prefer_html']) ||
                        ($secondary_type == 'plain' && !$this->opt['prefer_html'])
                    ) {
                        $mail_part->type = 'content';
                        $this->add_part($mail_part);
                    }

                    // list as attachment as well
                    if (!empty($mail_part->filename)) {
                        $this->add_part($mail_part, 'attachment');
                    }
                }
                // ignore "virtual" protocol parts
                else if ($primary_type == 'protocol') {
                    continue;
                }
                // part is Microsoft Outlook TNEF (winmail.dat)
                else if ($part_mimetype == 'application/ms-tnef') {
                    $tnef_parts = (array) $this->tnef_decode($mail_part);
                    foreach ($tnef_parts as $tpart) {
                        $this->mime_parts[$tpart->mime_id] = $tpart;
                        $this->add_part($tpart, 'attachment');
                    }

                    // add winmail.dat to the list if it's content is unknown
                    if (empty($tnef_parts) && !empty($mail_part->filename)) {
                        $this->mime_parts[$mail_part->mime_id] = $mail_part;
                        $this->add_part($mail_part, 'attachment');
                    }
                }
                // part is a file/attachment
                else if (preg_match('/^(inline|attach)/', $mail_part->disposition) ||
                    $mail_part->headers['content-id'] ||
                    ($mail_part->filename &&
                        (empty($mail_part->disposition) || preg_match('/^[a-z0-9!#$&.+^_-]+$/i', $mail_part->disposition)))
                ) {
                    // skip apple resource forks
                    if ($message_ctype_secondary == 'appledouble' && $secondary_type == 'applefile')
                        continue;

                    // part belongs to a related message and is linked
                    if (preg_match('/^multipart\/(related|relative)/', $mimetype)
                        && ($mail_part->headers['content-id'] || $mail_part->headers['content-location'])
                    ) {
                        if ($mail_part->headers['content-id'])
                            $mail_part->content_id = preg_replace(array('/^</', '/>$/'), '', $mail_part->headers['content-id']);
                        if ($mail_part->headers['content-location'])
                            $mail_part->content_location = $mail_part->headers['content-base'] . $mail_part->headers['content-location'];

                        $this->add_part($mail_part, 'inline');
                    }
                    // regular attachment with valid content type
                    // (content-type name regexp according to RFC4288.4.2)
                    else if (preg_match('/^[a-z0-9!#$&.+^_-]+\/[a-z0-9!#$&.+^_-]+$/i', $part_mimetype)) {
                        $this->add_part($mail_part, 'attachment');
                    }
                    // attachment with invalid content type
                    // replace malformed content type with application/octet-stream (#1487767)
                    else if ($mail_part->filename) {
                        $mail_part->ctype_primary   = 'application';
                        $mail_part->ctype_secondary = 'octet-stream';
                        $mail_part->mimetype        = 'application/octet-stream';

                        $this->add_part($mail_part, 'attachment');
                    }
                }
                // calendar part not marked as attachment (#1490325)
                else if ($part_mimetype == 'text/calendar') {
                    if (!$mail_part->filename) {
                        $mail_part->filename = 'calendar.ics';
                    }

                    $this->add_part($mail_part, 'attachment');
                }
            }

            // if this was a related part try to resolve references
            if (preg_match('/^multipart\/(related|relative)/', $mimetype) && count($this->inline_parts)) {
                $a_replaces = array();
                $img_regexp = '/^image\/(gif|jpe?g|png|tiff|bmp|svg)/';

                foreach ($this->inline_parts as $inline_object) {
                    $part_url = $this->get_part_url($inline_object->mime_id, $inline_object->ctype_primary);
                    if (isset($inline_object->content_id))
                        $a_replaces['cid:'.$inline_object->content_id] = $part_url;
                    if ($inline_object->content_location) {
                        $a_replaces[$inline_object->content_location] = $part_url;
                    }

                    if (!empty($inline_object->filename)) {
                        // MS Outlook sends sometimes non-related attachments as related
                        // In this case multipart/related message has only one text part
                        // We'll add all such attachments to the attachments list
                        if (!isset($this->got_html_part)) {
                            $this->add_part($inline_object, 'attachment');
                        }
                        // MS Outlook sometimes also adds non-image attachments as related
                        // We'll add all such attachments to the attachments list
                        // Warning: some browsers support pdf in <img/>
                        else if (!preg_match($img_regexp, $inline_object->mimetype)) {
                            $this->add_part($inline_object, 'attachment');
                        }
                        // @TODO: we should fetch HTML body and find attachment's content-id
                        // to handle also image attachments without reference in the body
                        // @TODO: should we list all image attachments in text mode?
                    }
                }

                // add replace array to each content part
                // (will be applied later when part body is available)
                foreach ($this->parts as $i => $part) {
                    if ($part->type == 'content')
                        $this->parts[$i]->replaces = $a_replaces;
                }
            }
        }
        // message is a single part non-text
        else if ($structure->filename || preg_match('/^application\//i', $mimetype)) {
            $this->add_part($structure, 'attachment');
        }
    }
1330644
public static function getEncoding(ContainerInterface $container = null): string
    {
        $i18n = static::get('i18n', $container, false);

        return $i18n ? $i18n->getEncoding() : mb_internal_encoding();
    }
1173116
private static function printStructureLine($key, $value, Structure $structure, $maxKeyLength, $maxValueLength)
    {
        $result    = '';
        $insertTab = ($structure->getTab()) ? true : false;
        $border    = $structure->getBorder();

        if ($border) {
            $keyLength        = Util::getVisibleStringLength($key);
            $missingKeyLength = $maxKeyLength - $keyLength;
            $fillingKeySpace  = Util::buildPatternLine(' ', $missingKeyLength);

            $valueLength        = Util::getVisibleStringLength($value);
            $missingValueLength = $maxValueLength - $valueLength;
            $fillingValueSpace  = Util::buildPatternLine(' ', $missingValueLength);

            $result .= ($insertTab ? $structure->getTab() : '');
            $result .= $border->getColumnCharacter() . ' ' . $key . $fillingKeySpace . ' ';
            $result .= $structure->getKeyToValueCharacter() . ' ' . $value . $fillingValueSpace . ' ';
            $result .= $border->getColumnCharacter() . PHP_EOL;
        } else {
            $keyLength        = Util::getVisibleStringLength($key);
            $missingKeyLength = $maxKeyLength - $keyLength;
            $fillingKeySpace  = Util::buildPatternLine(' ', $missingKeyLength);

            $result .= ($insertTab ? $structure->getTab() : '');
            $result .= $key . $fillingKeySpace . ' ';
            $result .= $structure->getKeyToValueCharacter() . ' ' . $value;
            $result .= PHP_EOL;
        }

        return $result;
    }