Get message part body.

@param rcube_message      Message object
@param rcube_message_part Message part
332893
private function get_part_body($msg, $part)
    {
        // @TODO: Handle big bodies using file handles

        // This is a special case when we want to get the whole body
        // using direct IMAP access, in other cases we prefer
        // rcube_message::get_part_body() as the body may be already in memory
        if (!$part->mime_id) {
            // fake the size which may be empty for multipart/* parts
            // otherwise get_message_part() below will fail
            if (!$part->size) {
                $reset = true;
                $part->size = 1;
            }

            $storage = $this->rc->get_storage();
            $body    = $storage->get_message_part($msg->uid, $part->mime_id, $part,
                null, null, true, 0, false);

            if ($reset) {
                $part->size = 0;
            }
        }
        else {
            $body = $msg->get_part_body($part->mime_id, false);

            // Convert charset to get rid of possible non-ascii characters (#5962)
            if ($part->charset && stripos($part->charset, 'ASCII') === false) {
                $body = rcube_charset::convert($body, $part->charset, 'US-ASCII');
            }
        }

        return $body;
    }
1104210
private static function bodyToText(\Google_Service_Gmail_MessagePartBody $body = null): string
    {
        $sanitizedData = strtr($body->getData(), '-_', '+/');

        // On fail base64_decode returns false.
        // We can't know with certainty that getData() is ok.
        // So fail gracefully.
        return base64_decode($sanitizedData) ?? '';
    }
1297938
def part(self, channels, message=""):
        """"""
        self.send_items('PART', ','.join(always_iterable(channels)), message)
944323
private int findOtherSubMessage(int partIndex) {
        int count=msgPattern.countParts();
        MessagePattern.Part part=msgPattern.getPart(partIndex);
        if(part.getType().hasNumericValue()) {
            ++partIndex;
        }
        // Iterate over (ARG_SELECTOR [ARG_INT|ARG_DOUBLE] message) tuples
        // until ARG_LIMIT or end of plural-only pattern.
        do {
            part=msgPattern.getPart(partIndex++);
            MessagePattern.Part.Type type=part.getType();
            if(type==MessagePattern.Part.Type.ARG_LIMIT) {
                break;
            }
            assert type==MessagePattern.Part.Type.ARG_SELECTOR;
            // part is an ARG_SELECTOR followed by an optional explicit value, and then a message
            if(msgPattern.partSubstringMatches(part, "other")) {
                return partIndex;
            }
            if(msgPattern.getPartType(partIndex).hasNumericValue()) {
                ++partIndex;  // skip the numeric-value part of "=1" etc.
            }
            partIndex=msgPattern.getLimitPartIndex(partIndex);
        } while(++partIndex<count);
        return 0;
    }
789149
function getText(msg) {
    return msg.parts.filter(function (part) {
      return part.mime_type === 'text/plain';
    }).map(function (part) {
      return part.body;
    }).join('; ');
  }
1010737
def body(self):
        
        if self._message_body:  # If already set, return it
            return self._message_body
        self._message_body = self._maybe_decompress_body()
        self._message_body = self._maybe_deserialize_body()
        return self._message_body
718407
private Message doMessageToTypeJoin(Message msg) throws SAXException {
        for (int i = 0; i < msg.messageParts.length; i++) {
            Type schemaType = null;
            String nsprefix = null;
            String partTypeLocalName = null;
            StringTokenizer st =
                    new StringTokenizer(msg.messageParts[i].partTypeName, ":");
            if (st.hasMoreTokens()) {
                nsprefix = st.nextToken();
                partTypeLocalName = st.nextToken();
            } else {
                partTypeLocalName = msg.messageParts[i].partTypeName;
            }
            // FIXIT!! Test whether null nsprefix makes this bag.
            if (nsprefix
                    .equalsIgnoreCase((String) nsPrefixMap.get(XML_XSD.uri))) {
                msg.messageParts[i].partBaseTypeNamespaceURI = XML_XSD.uri;
                msg.messageParts[i].partBaseTypeLocalName = partTypeLocalName;
            }
            // If the part is not an XSD base type, then we assume it is a type defined
            // in the schema definition section of THIS WSDL document (i.e., either
            // a simpleType or a complexType).  NOTE that complexType not currently supported
            // by Fedora.  Also, note that if the part type is not found it the type table
            // (wsdlTypeTbl was created from parsing the schema types section of the WSDL),
            // then an exception will be thrown.  This means that Fedora only supports WSDL
            // whose message parts are either XSD base types or simpleTypes defined in the WSDL document.
            else if ((schemaType = (Type) wsdlTypeTbl.get(partTypeLocalName)) != null) {
                if (schemaType
                        .getClass()
                        .getName()
                        .equalsIgnoreCase("org.fcrepo.server.storage.service.SimpleType")) {
                    msg.messageParts[i].partBaseTypeNamespaceURI =
                            schemaType.baseTypeNamespaceURI;
                    msg.messageParts[i].partBaseTypeLocalName =
                            schemaType.baseTypeLocalName;
                    msg.messageParts[i].enumerationOfValues =
                            ((SimpleType) schemaType).enumerationOfValues;
                    // FIXIT!! Do we want to put more information in the Part object??
                }
            } else {
                throw new SAXException("WSDLParser: message part type must be XSD type or defined in WSDL as simpleType"
                        + msg.messageParts[i].partTypeName);
            }
        }
        return msg;
    }
142286
def get_body(self, msg):
        

        body = ""
        charset = ""

        if msg.is_multipart():
            for part in msg.walk():
                ctype = part.get_content_type()
                cdispo = str(part.get('Content-Disposition'))

                # skip any text/plain (txt) attachments
                if ctype == 'text/plain' and 'attachment' not in cdispo:
                    body = part.get_payload(decode=True)  # decode
                    charset = part.get_content_charset()
                    break

        # not multipart - i.e. plain text, no attachments, keeping fingers crossed
        else:
            body = msg.get_payload(decode=True)
            charset = msg.get_content_charset()

        return body.decode(charset)
503489
public String getContentString(Message message)
    {
        try {
            String strContentType = message.getContentType();
            Object content = message.getContent();
            if (content instanceof MimeMultipart)
            {
                for (int index = 0; ; index++)
                {
                    BodyPart bodyPart = ((javax.mail.internet.MimeMultipart)content).getBodyPart(index);
                    Object contents = bodyPart.getContent();
                    if (contents != null)
                        return contents.toString();
                }
            }
            return message.getContent().toString();     // pend(don) FIX THIS!
        } catch (IOException ex)    {
            ex.printStackTrace();
        } catch (MessagingException ex)    {
            ex.printStackTrace();
        }
        return null;
    }
308808
protected function getPartBodyFromText(&$part)
    {
        $start = $part['starting-pos-body'];
        $end = $part['ending-pos-body'];

        return substr($this->data, $start, $end - $start);
    }
1048968
private SoyMsgPart compactPart(SoyMsgPart part) {
    if (part instanceof SoyMsgPluralPart) {
      part = compactPlural((SoyMsgPluralPart) part);
    } else if (part instanceof SoyMsgSelectPart) {
      part = compactSelect((SoyMsgSelectPart) part);
    } else if (part instanceof SoyMsgPlaceholderPart) {
      part = compactPlaceholder((SoyMsgPlaceholderPart) part);
    }
    // Now intern the message part.
    return intern(part);
  }
133904
function uu_decode(&$part)
    {
        // @TODO: messages may be huge, handle body via file
        $part->body = $this->get_part_body($part->mime_id);
        $parts      = array();
        $pid        = 0;

        // FIXME: line length is max.65?
        $uu_regexp_begin = '/begin [0-7]{3,4} ([^\r\n]+)\r?\n/s';
        $uu_regexp_end   = '/`\r?\nend((\r?\n)|($))/s';

        while (preg_match($uu_regexp_begin, $part->body, $matches, PREG_OFFSET_CAPTURE)) {
            $startpos = $matches[0][1];

            if (!preg_match($uu_regexp_end, $part->body, $m, PREG_OFFSET_CAPTURE, $startpos)) {
                break;
            }

            $endpos    = $m[0][1];
            $begin_len = strlen($matches[0][0]);
            $end_len   = strlen($m[0][0]);

            // extract attachment body
            $filebody = substr($part->body, $startpos + $begin_len, $endpos - $startpos - $begin_len - 1);
            $filebody = str_replace("\r\n", "\n", $filebody);

            // remove attachment body from the message body
            $part->body = substr_replace($part->body, '', $startpos, $endpos + $end_len - $startpos);
            // mark body as modified so it will not be cached by rcube_imap_cache
            $part->body_modified = true;

            // add attachments to the structure
            $uupart = new rcube_message_part;
            $uupart->filename = trim($matches[1][0]);
            $uupart->encoding = 'stream';
            $uupart->body     = convert_uudecode($filebody);
            $uupart->size     = strlen($uupart->body);
            $uupart->mime_id  = 'uu.' . $part->mime_id . '.' . $pid;

            $ctype = rcube_mime::file_content_type($uupart->body, $uupart->filename, 'application/octet-stream', true);
            $uupart->mimetype = $ctype;
            list($uupart->ctype_primary, $uupart->ctype_secondary) = explode('/', $ctype);

            $parts[] = $uupart;
            $pid++;
        }

        return $parts;
    }
1324184
public String getSubstring(Part part) {
        int index=part.index;
        return msg.substring(index, index+part.length);
    }
555577
protected function structure_part($part, $count = 0, $parent = '', $mime_headers = null)
    {
        $struct = new rcube_message_part;
        $struct->mime_id = empty($parent) ? (string)$count : "$parent.$count";

        // multipart
        if (is_array($part[0])) {
            $struct->ctype_primary = 'multipart';

        /* RFC3501: BODYSTRUCTURE fields of multipart part
            part1 array
            part2 array
            part3 array
            ....
            1. subtype
            2. parameters (optional)
            3. description (optional)
            4. language (optional)
            5. location (optional)
        */

            // find first non-array entry
            for ($i=1; $i<count($part); $i++) {
                if (!is_array($part[$i])) {
                    $struct->ctype_secondary = strtolower($part[$i]);

                    // read content type parameters
                    if (is_array($part[$i+1])) {
                        $struct->ctype_parameters = array();
                        for ($j=0; $j<count($part[$i+1]); $j+=2) {
                            $param = strtolower($part[$i+1][$j]);
                            $struct->ctype_parameters[$param] = $part[$i+1][$j+1];
                        }
                    }

                    break;
                }
            }

            $struct->mimetype = 'multipart/'.$struct->ctype_secondary;

            // build parts list for headers pre-fetching
            for ($i=0; $i<count($part); $i++) {
                if (!is_array($part[$i])) {
                    break;
                }
                // fetch message headers if message/rfc822
                // or named part (could contain Content-Location header)
                if (!is_array($part[$i][0])) {
                    $tmp_part_id = $struct->mime_id ? $struct->mime_id.'.'.($i+1) : $i+1;
                    if (strtolower($part[$i][0]) == 'message' && strtolower($part[$i][1]) == 'rfc822') {
                        $mime_part_headers[] = $tmp_part_id;
                    }
                    else if (in_array('name', (array)$part[$i][2]) && empty($part[$i][3])) {
                        $mime_part_headers[] = $tmp_part_id;
                    }
                }
            }

            // pre-fetch headers of all parts (in one command for better performance)
            // @TODO: we could do this before _structure_part() call, to fetch
            // headers for parts on all levels
            if ($mime_part_headers) {
                $mime_part_headers = $this->conn->fetchMIMEHeaders($this->folder,
                    $this->msg_uid, $mime_part_headers);
            }

            $struct->parts = array();
            for ($i=0, $count=0; $i<count($part); $i++) {
                if (!is_array($part[$i])) {
                    break;
                }
                $tmp_part_id = $struct->mime_id ? $struct->mime_id.'.'.($i+1) : $i+1;
                $struct->parts[] = $this->structure_part($part[$i], ++$count, $struct->mime_id,
                    $mime_part_headers[$tmp_part_id]);
            }

            return $struct;
        }

        /* RFC3501: BODYSTRUCTURE fields of non-multipart part
            0. type
            1. subtype
            2. parameters
            3. id
            4. description
            5. encoding
            6. size
          -- text
            7. lines
          -- message/rfc822
            7. envelope structure
            8. body structure
            9. lines
          --
            x. md5 (optional)
            x. disposition (optional)
            x. language (optional)
            x. location (optional)
        */

        // regular part
        $struct->ctype_primary = strtolower($part[0]);
        $struct->ctype_secondary = strtolower($part[1]);
        $struct->mimetype = $struct->ctype_primary.'/'.$struct->ctype_secondary;

        // read content type parameters
        if (is_array($part[2])) {
            $struct->ctype_parameters = array();
            for ($i=0; $i<count($part[2]); $i+=2) {
                $struct->ctype_parameters[strtolower($part[2][$i])] = $part[2][$i+1];
            }

            if (isset($struct->ctype_parameters['charset'])) {
                $struct->charset = $struct->ctype_parameters['charset'];
            }
        }

        // #1487700: workaround for lack of charset in malformed structure
        if (empty($struct->charset) && !empty($mime_headers) && $mime_headers->charset) {
            $struct->charset = $mime_headers->charset;
        }

        // read content encoding
        if (!empty($part[5])) {
            $struct->encoding = strtolower($part[5]);
            $struct->headers['content-transfer-encoding'] = $struct->encoding;
        }

        // get part size
        if (!empty($part[6])) {
            $struct->size = intval($part[6]);
        }

        // read part disposition
        $di = 8;
        if ($struct->ctype_primary == 'text') {
            $di += 1;
        }
        else if ($struct->mimetype == 'message/rfc822') {
            $di += 3;
        }

        if (is_array($part[$di]) && count($part[$di]) == 2) {
            $struct->disposition = strtolower($part[$di][0]);
            if ($struct->disposition && $struct->disposition !== 'inline' && $struct->disposition !== 'attachment') {
                // RFC2183, Section 2.8 - unrecognized type should be treated as "attachment"
                $struct->disposition = 'attachment';
            }
            if (is_array($part[$di][1])) {
                for ($n=0; $n<count($part[$di][1]); $n+=2) {
                    $struct->d_parameters[strtolower($part[$di][1][$n])] = $part[$di][1][$n+1];
                }
            }
        }

        // get message/rfc822's child-parts
        if (is_array($part[8]) && $di != 8) {
            $struct->parts = array();
            for ($i=0, $count=0; $i<count($part[8]); $i++) {
                if (!is_array($part[8][$i])) {
                    break;
                }
                $struct->parts[] = $this->structure_part($part[8][$i], ++$count, $struct->mime_id);
            }
        }

        // get part ID
        if (!empty($part[3])) {
            $struct->content_id = $part[3];
            $struct->headers['content-id'] = $part[3];

            if (empty($struct->disposition)) {
                $struct->disposition = 'inline';
            }
        }

        // fetch message headers if message/rfc822 or named part (could contain Content-Location header)
        if ($struct->ctype_primary == 'message' || ($struct->ctype_parameters['name'] && !$struct->content_id)) {
            if (empty($mime_headers)) {
                $mime_headers = $this->conn->fetchPartHeader(
                    $this->folder, $this->msg_uid, true, $struct->mime_id);
            }

            if (is_string($mime_headers)) {
                $struct->headers = rcube_mime::parse_headers($mime_headers) + $struct->headers;
            }
            else if (is_object($mime_headers)) {
                $struct->headers = get_object_vars($mime_headers) + $struct->headers;
            }

            // get real content-type of message/rfc822
            if ($struct->mimetype == 'message/rfc822') {
                // single-part
                if (!is_array($part[8][0])) {
                    $struct->real_mimetype = strtolower($part[8][0] . '/' . $part[8][1]);
                }
                // multi-part
                else {
                    for ($n=0; $n<count($part[8]); $n++) {
                        if (!is_array($part[8][$n])) {
                            break;
                        }
                    }
                    $struct->real_mimetype = 'multipart/' . strtolower($part[8][$n]);
                }
            }

            if ($struct->ctype_primary == 'message' && empty($struct->parts)) {
                if (is_array($part[8]) && $di != 8) {
                    $struct->parts[] = $this->structure_part($part[8], ++$count, $struct->mime_id);
                }
            }
        }

        // normalize filename property
        $this->set_part_filename($struct, $mime_headers);

        return $struct;
    }
659870
public SOAPMessage setSOAPBody(SOAPMessage msg, BaseMessage message)
    {
        try {
            if (msg == null)
                msg = fac.createMessage();
            // Message creation takes care of creating the SOAPPart - a
            // required part of the message as per the SOAP 1.1
            // specification.
            SOAPPart soappart = msg.getSOAPPart();

            // Retrieve the envelope from the soap part to start building
            // the soap message.
            SOAPEnvelope envelope = soappart.getEnvelope();
            
            // Create a soap header from the envelope.
            //?SOAPHeader header = envelope.getHeader();
            
            // Create a soap body from the envelope.
            SOAPBody body = envelope.getBody();

            DOMResult result = new DOMResult(body);
            if (((BaseXmlTrxMessageOut)message.getExternalMessage()).copyMessageToResult(result))
            {   // Success
            	// Note: For Jabx, I would have to fix the namespace of the message (so don't use JAXB)
                msg.saveChanges();
                return msg;
            }
        } catch(Throwable e) {
            e.printStackTrace();
            Utility.getLogger().warning("Error in constructing or sending message "
            +e.getMessage());
        }
        return null;
    }
23617
def add_part(part)
      if !body.multipart? && !Utilities.blank?(self.body.decoded)
        @text_part = Mail::Part.new('Content-Type: text/plain;')
        @text_part.body = body.decoded
        self.body << @text_part
        add_multipart_alternate_header
      end
      add_boundary
      self.body << part
    end
537623
def message_to_objects(
        message: Dict, sender: str, sender_key_fetcher: Callable[[str], str] = None, user: UserType = None,
) -> List:
    
    # We only really expect one element here for ActivityPub.
    return element_to_objects(message)