Convert the xml message from the ipn payload
into an xml document

@param Message $ipnMsg ipn message

@throws OffAmazonPaymentsNotifications_InvalidMessageException

@return XmlElement xml document element
339378
private static function _getXmlFromIpnMessage(Message $ipnMsg)
    {        
        // Try and load the notification data as xml
        $notificationData = $ipnMsg->getMandatoryField("NotificationData");
        
        $dom = new DOMDocument();
        try {
            $dom->loadXML($notificationData);
        } catch (Exception $ex) {
            throw new OffAmazonPaymentsNotifications_InvalidMessageException(
                "Error with ipn message - NotificationData field does not contain xml, " .
                "contents: " . $notificationData
            );
        }
        
        return $dom->documentElement;
    }
350023
protected function sendVideoMsgToJsonString(WxSendVideoMsg $msg)
    {
        $formatStr = '{
                        "touser":"%s",
                        "msgtype":"%s",
                        "video":
                        {
                          "media_id":"%s",
                          "thumb_media_id":"%s",
                          "title":"%s",
                          "description":"%s"
                        }
                    }';
        $result = sprintf($formatStr,   $msg->getToUserName(),
                                        $msg->getMsgType(),
                                        $msg->getMediaId(),
                                        $msg->getThumbMediaId(),
                                        $msg->getTitle(),
                                        $msg->getDescription()
                        );

        return $result;
    }
465735
public function parse(Message $message)
    {
        if (!isset($message->headers['Content-Type'])) {
            throw new Exceptions\Parser('Missing Content-Type header in message.');
        }

        $mediaTypeParts = explode(';', $message->headers['Content-Type']);
        $contentTypeParts = explode('+', $mediaTypeParts[0]);
        if (count($contentTypeParts) !== 2) {
            // TODO expose default format
            $contentTypeParts[1] = 'xml';
        }

        $media = $contentTypeParts[0];

        // add version if given
        if (count($mediaTypeParts) > 1) {
            $parameters = $this->parseParameters(implode(';', array_slice($mediaTypeParts, 1)));
            if (isset($parameters['version'])) {
                $media .= '; version=' . $parameters['version'];
            }
        }

        $format = $contentTypeParts[1];

        if (!isset($this->handlers[$format])) {
            throw new Exceptions\Parser("Unknown format specification: '{$format}'.");
        }

        $rawArray = $this->handlers[$format]->convert($message->body);

        // Only 1 XML root node
        $rootNodeArray = reset($rawArray);

        // @todo: This needs to be refactored in order to make the called URL
        // available to parsers in the server in a sane way
        if (isset($message->headers['Url'])) {
            $rootNodeArray['__url'] = $message->headers['Url'];
        }
        if (isset($message->headers['__publish'])) {
            $rootNodeArray['__publish'] = $message->headers['__publish'];
        }

        return $this->parsingDispatcher->parse($rootNodeArray, $media);
    }
967788
public function loadMessageXml(string $message_xml_file): array
    {
        $messageXmlString = \file_get_contents($message_xml_file);
        $messageXml = new \SimpleXMLIterator($messageXmlString);
        unset($messageXmlString);
        $message = [
            "defaults" => $this->readMessageDefaults($messageXml),
            "segments" => $this->readXmlNodes($messageXml),
        ];
        unset($messageXml);

        return $message;
    }
516823
public static function parse(string $msg): Message
    {
        $obj = new self;
        $parts = explode("\r\n", $msg);
        $obj->body = MessageBody::parse(array_pop($parts));
        foreach ($parts as $line) {
            if ($line) {
                $pair = explode(': ', $line);
                $obj->headers[$pair[0]] = $pair[1];
            }
        }
        return $obj;
    }
172448
public function receive() : Message
    {
        $postText = $this->getInputStream();

        if ($postText === false) {
            throw new \Exception('Invalid message received to AssertionConsumerService endpoint.');
        }

        $document = DOMDocumentFactory::fromString($postText);
        $xml = $document->firstChild;
        Utils::getContainer()->debugMessage($document->documentElement, 'in');
        /** @var \DOMElement[] $results */
        $results = Utils::xpQuery($xml, '/soap-env:Envelope/soap-env:Body/*[1]');

        return Message::fromXML($results[0]);
    }
124578
public function message($message)
    {
        if (is_string($message) || is_numeric($message)) {
            $message = new Text($message);
        }

        if (!($message instanceof Message)) {
            throw new InvalidArgumentException('Invalid message.');
        }

        $this->message = $message;

        return $this;
    }
25113
protected function throwNewInvalidArgumentException ($errorMsg) {
		$msgs = [];
		if ($this->field) 
			$msgs[] = 'Field name: `'.$this->field->GetName() . '`, Field type: `'.get_class($this->field).'`';
		if ($this->form) 
			$msgs[] = 'Form id: `'.$this->form->GetId() . '`, Form type: `'.get_class($this->form).'`';
		$selfClass = version_compare(PHP_VERSION, '5.5', '>') ? self::class : __CLASS__;
		throw new \InvalidArgumentException(
			'['.$selfClass.'] ' . $errorMsg . ($msgs ? ' '.implode(', ', $msgs) : '')
		);
	}
970200
public static function fromMessage(Message $msg)
    {
        $workerHandlerId = $msg->shift();
        $requestId = $msg->shift();
        if (!$requestId) {
            $requestId = null;
        }

        return new self($workerHandlerId, $requestId);
    }
1043772
public function fromMessage($message)
    {
        static $parser;
        if (!$parser) {
            $parser = new MessageParser();
        }

        // Parse a response
        if (strtoupper(substr($message, 0, 4)) == 'HTTP') {
            $data = $parser->parseResponse($message);
            return $this->createResponse(
                $data['code'],
                $data['headers'],
                $data['body'] === '' ? null : $data['body'],
                $data
            );
        }

        // Parse a request
        if (!($data = ($parser->parseRequest($message)))) {
            throw new \InvalidArgumentException('Unable to parse request');
        }

        return $this->createRequest(
            $data['method'],
            Url::buildUrl($data['request_url']),
            [
                'headers' => $data['headers'],
                'body' => $data['body'] === '' ? null : $data['body'],
                'config' => [
                    'protocol_version' => $data['protocol_version']
                ]
            ]
        );
    }
611842
public function deserialize($data, Message $message, array $options = [])
    {
        $message = $this->messageSerializer->deserialize($data, $message, $options);

        if (isset($data['subject'])) {
            $subject = $this->om->getObject($data['subject'], Subject::class);

            if (!empty($subject)) {
                $message->setSubject($subject);
            }
        }

        if (isset($data['parent'])) {
            $parent = $this->om->getRepository($this->getClass())->findOneBy(['uuid' => $data['parent']['id']]);

            if ($parent) {
                $message->setParent($parent);
            }
        }
        $this->sipe('meta.flagged', 'setFlagged', $data, $message);
        $this->sipe('meta.moderation', 'setModerated', $data, $message);

        return $message;
    }
656052
public function toXmlElement(SimpleXMLElement $parentElement = null)
    {
        if ($parentElement !== null) {
            throw new UserMessageException(t('The sitemap XML header should be the first element.'));
        }

        return new SimpleXMLElement($this->getXmlMetaHeader() . $this->getUrlset(true));
    }
174896
public function serialize(Message $message, array $options = [])
    {
        $userMessage = $this->getUserMessage($message);

        //mainly for tests or if someting went wrong
        if (!$userMessage) {
            $userMessage = new UserMessage();
        }

        $data = [
          'id' => $message->getUuid(),
          'object' => $message->getObject(),
          'content' => $message->getContent(),
          'to' => $message->getTo(),
          'meta' => [
            'date' => DateNormalizer::normalize($message->getDate()),
            'read' => $userMessage->isRead(),
            'removed' => $userMessage->isRemoved(),
            'sent' => $userMessage->isSent(),
            'umuuid' => $userMessage->getUuid(),
          ],
        ];

        $data['from'] = $message->getSender() ?
            $this->userSerializer->serialize($message->getSender(), [Options::SERIALIZE_MINIMAL]) :
            ['username' => $message->getSenderUsername()];

        if (in_array(Options::IS_RECURSIVE, $options)) {
            $data['children'] = array_map(function (Message $child) {
                return $this->serialize($child, $options);
            }, $message->getChildren()->toArray());
        }

        return $data;
    }
569190
private function _constructSignatureFromSnsMessage(Message $snsMessage)
    {
        if (strcmp($snsMessage->getMandatoryField("Type"), "Notification") != 0) {
            throw new OffAmazonPaymentsNotifications_InvalidMessageException(
                "Error with signature verification - unable to verify " .
                $snsMessage->getMandatoryField("Type") . " message"
            );
        }
        
        // get the list of fields that we are interested in
        $fields = array(
            "Timestamp" => true,
            "Message" => true,
            "MessageId" => true,
            "Subject" => false,
            "TopicArn" => true,
            "Type" => true
        );
        
        // sort the fields into byte order based on the key name(A-Za-z)
        ksort($fields);
        
        // extract the key value pairs and sort in byte order
        $signatureFields = array();
        foreach ($fields as $fieldName => $mandatoryField) {
            if ($mandatoryField) {
                $value = $snsMessage->getMandatoryField($fieldName);
            } else {
                $value = $snsMessage->getField($fieldName);
            }
            
            if (!is_null($value)) {
                array_push($signatureFields, $fieldName);
                array_push($signatureFields, $value);
            }
        }
        
        // create the signature string - key / value in byte order
        // delimited by newline character + ending with a new line character
        return implode("\n", $signatureFields) . "\n";
    }
215542
public static function getRsaFromCert($x509) {
    $rsa = $x509->getPublicKey();
    if (!$rsa) {
      throw new InvalidMessageException("Invalid message: certificate missing or does not have public key");
    }
    $rsa->setEncryptionMode(Constants::RSA_ENC_MODE);
    $rsa->setSignatureMode(Constants::RSA_SIG_MODE);
    $rsa->setHash(Constants::RSA_HASH);
    return $rsa;
  }
635349
public function toXML(DOMElement $parent) : DOMElement
    {
        $e = $parent->ownerDocument->createElementNS(Constants::NS_SAML, 'saml:SubjectConfirmationData');
        $parent->appendChild($e);

        if ($this->NotBefore !== null) {
            $e->setAttribute('NotBefore', gmdate('Y-m-d\TH:i:s\Z', $this->NotBefore));
        }
        if ($this->NotOnOrAfter !== null) {
            $e->setAttribute('NotOnOrAfter', gmdate('Y-m-d\TH:i:s\Z', $this->NotOnOrAfter));
        }
        if ($this->Recipient !== null) {
            $e->setAttribute('Recipient', $this->Recipient);
        }
        if ($this->InResponseTo !== null) {
            $e->setAttribute('InResponseTo', $this->InResponseTo);
        }
        if ($this->Address !== null) {
            $e->setAttribute('Address', $this->Address);
        }
        /** @var \SAML2\XML\ds\KeyInfo|\SAML2\XML\Chunk $n */
        foreach ($this->getInfo() as $n) {
            $n->toXML($e);
        }

        return $e;
    }
593570
private function _verifySignatureWithVersionOneAlgorithm(Message $snsMessage)
    {      
        $result = $this->_verifySignature->verifySignatureIsCorrect(
            $this->_constructSignatureFromSnsMessage($snsMessage),
            base64_decode($snsMessage->getMandatoryField("Signature")),
            $snsMessage->getMandatoryField("SigningCertURL")
        );
        
        if (!$result) {
            throw new OffAmazonPaymentsNotifications_InvalidMessageException(
                "Unable to match signature from remote server: signature of " .
                $this->_constructSignatureFromSnsMessage($snsMessage) . 
                " , SigningCertURL of " . 
                $snsMessage->getMandatoryField("SigningCertURL") . 
                " , SignatureOf " . 
                $snsMessage->getMandatoryField("Signature")
            );
        }
    }