Validate the receipt contained in the given XML element using the
certificate provided.

@param DOMDocument $dom
@param resource $certificate

@return bool
@throws RunTimeException
332883
protected function validateXml(DOMDocument $dom, $certificate)
    {
        $secDsig = new XMLSecurityDSig;

        // Locate the signature in the receipt XML.
        $dsig = $secDsig->locateSignature($dom);
        if ($dsig === null) {
            throw new RunTimeException('Cannot locate receipt signature');
        }

        $secDsig->canonicalizeSignedInfo();
        $secDsig->idKeys = ['wsu:Id'];
        $secDsig->idNS = [
            'wsu' => 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd',
        ];

        if (!$secDsig->validateReference()) {
            throw new RunTimeException('Reference validation failed');
        }

        $key = $secDsig->locateKey();
        if ($key === null) {
            throw new RunTimeException('Could not locate key in receipt');
        }

        $keyInfo = XMLSecEnc::staticLocateKeyInfo($key, $dsig);
        if (!$keyInfo->key) {
            $key->loadKey($certificate);
        }

        return $secDsig->verify($key) == 1;
    }
1010763
protected function isXsl(DOMNode $node, $localName = null)
	{
		return ($node->namespaceURI === self::XMLNS_XSL && (!isset($localName) || $localName === $node->localName));
	}
654951
public function process(\DOMDocument $xml)
    {
        $xpath = new \DOMXPath($xml);
        $nodes = $xpath->query(
            '/project/file/class/docblock/tag[@name="method"]'
        );

        /** @var \DOMElement $node */
        foreach ($nodes as $node) {
            $class = $node->parentNode->parentNode;

            $method = new \DOMElement('method');
            $class->appendChild($method);

            // set basic information
            $method->setAttribute('final', 'false');
            $method->setAttribute('static', 'false');
            $method->setAttribute('visibility', 'public');
            $method->setAttribute('line', $node->getAttribute('line'));
            $method->appendChild(
                new \DOMElement('name', $node->getAttribute('method_name'))
            );

            // fill docblock
            $docblock = new \DOMElement('docblock');
            $method->appendChild($docblock);
            $docblock->appendChild(
                new \DOMElement('description', $node->getAttribute('description'))
            );
            $docblock->appendChild(new \DOMElement('long-description'));

            // for each argument; create an @param tag and an argument element
            /** @var \DOMElement $argument */
            foreach ($node->getElementsByTagName('argument') as $argument) {
                $param_tag = new \DOMElement('tag');
                $docblock->appendChild($param_tag);
                $param_tag->setAttribute('name', 'param');
                $param_tag->setAttribute(
                    'type',
                    $argument->getElementsByTagName('type')->item(0)->nodeValue
                );
                $param_tag->setAttribute(
                    'variable',
                    $argument->getElementsByTagName('name')->item(0)->nodeValue
                );
                $param_tag->setAttribute('line', $node->getAttribute('line'));

                $types = explode(
                    '|',
                    $argument->getElementsByTagName('type')->item(0)->nodeValue
                );

                foreach ($types as $type) {
                    $type_element = new \DOMElement('type', $type);
                    $param_tag->appendChild($type_element);
                }

                $argument_element = $argument->cloneNode(true);
                $method->appendChild($argument_element);
            }

            // add a tag 'magic'
            $magic_tag = new \DOMElement('tag');
            $docblock->appendChild($magic_tag);
            $magic_tag->setAttribute('name', 'magic');
            $magic_tag->setAttribute('line', $node->getAttribute('line'));

            // add a @return tag
            $return_tag = new \DOMElement('tag');
            $docblock->appendChild($return_tag);
            $return_tag->setAttribute('name', 'return');
            $return_tag->setAttribute('line', $node->getAttribute('line'));
            $return_tag->setAttribute('type', $node->getAttribute('type'));

            // add type sub elements to the param
            foreach (explode('|', $node->getAttribute('type')) as $type) {
                $type_element = new \DOMElement('type', $type);
                $return_tag->appendChild($type_element);
            }

            // remove the tag, it is unneeded
            $node->parentNode->removeChild($node);
            $docblock->appendChild($node);
        }

        return $xml;
    }
883115
private function loadXmlInDom(\DOMDocument $dom, $xml, $method)
    {
        $usedInternalErrors       = libxml_use_internal_errors(true);
        $externalEntitiesDisabled = libxml_disable_entity_loader(false);

        libxml_clear_errors();

        if (!$this->loadDomDocument($dom, $xml, $method)) {
            libxml_disable_entity_loader($externalEntitiesDisabled);

            throw new InvalidArgumentException($this->formatLibXmlErrors($usedInternalErrors));
        }

        // restore previous libxml setting:
        libxml_use_internal_errors($usedInternalErrors);
        libxml_disable_entity_loader($externalEntitiesDisabled);

        return $dom;
    }
263415
public function toXML( DOMDocument $dom )
    {
        if ( !$this->XMLStorable )
        {
            return false;
        }

        $itemNode = $dom->createElement( 'item' );

        foreach ( $this->attributes as $attrName => $attrValue )
        {
            switch ( $attrName )
            {
                case 'id':
                    $itemNode->setAttribute( 'id', $attrValue );
                    break;

                case 'action':
                    $itemNode->setAttribute( 'action', $attrValue );
                    break;

                default:
                    $node = $dom->createElement( $attrName );
                    $nodeValue = $dom->createTextNode( $attrValue );
                    $node->appendChild( $nodeValue );
                    $itemNode->appendChild( $node );
                    break;
            }
        }

        return $itemNode;
    }
91151
private function getValidationResult(FormRuntime $formRuntime, RootRenderableInterface $element): Result
    {
        /** @var Result $validationResults */
        $validationResults = $formRuntime->getRequest()->getInternalArgument('__submittedArgumentValidationResults');
        if ($validationResults === null) {
            return new Result();
        }
        return $validationResults->forProperty($element->getIdentifier());
    }
880132
public function toXML(DOMElement $parent = null) : DOMElement
    {
        if (($this->Saml2IssuerShowAll && ($this->Format === Constants::NAMEID_ENTITY))
            || ($this->Format !== Constants::NAMEID_ENTITY)
        ) {
            return parent::toXML($parent);
        }

        /*
         * if $this->Saml2IssuerShowAll is set false
         * From saml-core-2.0-os 8.3.6, when the entity Format is used: "The NameQualifier, SPNameQualifier, and
         * SPProvidedID attributes MUST be omitted."
         * if $this->isSaml2IssuerShowAll() is set true when the entity Format is used: "The NameQualifier,
         * SPNameQualifier, and SPProvidedID attributes are not omitted."
         */

        if ($parent === null) {
            $parent = DOMDocumentFactory::create();
            $doc = $parent;
        } else {
            $doc = $parent->ownerDocument;
        }
        $element = $doc->createElementNS(Constants::NS_SAML, 'saml:Issuer');
        $parent->appendChild($element);

        if (empty($this->value)) {
            throw new \Exception("Cannot convert Issuer to XML with no value.");
        }
        $value = $element->ownerDocument->createTextNode($this->value);
        $element->appendChild($value);

        return $element;
    }
237310
public function parseDom(\DOMDocument $dom)
    {
        $this->logger->info('Running parser: '.(new \ReflectionClass(__CLASS__))->getShortName());
        $items = [];

        // Find and process all JSON-LD documents
        $xpath      = new \DOMXPath($dom);
        $jsonLDDocs = $xpath->query('//*[local-name(.) = "script"][@type = "application/ld+json"]');
        $this->logger->debug('Processing '.$jsonLDDocs->length.' JSON-LD documents');

        // Run through all JSON-LD documents
        foreach ($jsonLDDocs as $jsonLDDoc) {
            $jsonLDDocSource = preg_replace(self::JSON_COMMENT_PATTERN, '', $jsonLDDoc->textContent);
            $i               = $this->parseDocument($jsonLDDocSource);
            $items           = array_merge($items, $i);
        }

        return new ParsingResult(self::FORMAT, $items);
    }
1157098
public function canValidate(
        SignedElement $signedElement,
        CertificateProvider $configuration
    ) : bool {
        $this->configuredKeys = $this->keyLoader->extractPublicKeys($configuration);

        return !!count($this->configuredKeys);
    }
564317
private function processDOM(\DOMNode $node, \DOMDocument $dom)
    {
        if ($node->hasChildNodes()) {
            $nodes = [];
            foreach ($node->childNodes as $childNode) {
                if ($childNode instanceof \DOMElement && $childNode->tagName) {
                    if (in_array($childNode->tagName, $this->protectedTags)) {
                        continue;
                    }
                }

                $nodes[] = $childNode;
            }

            $depth = $this->stateBag->getCurrentDepth();

            foreach ($nodes as $childNode) {
                if ($childNode instanceof \DOMText && !$childNode->isWhitespaceInElementContent()) {
                    $this->stateBag->setCurrentDepth($depth);
                    $this->doFix($childNode, $node, $dom);
                } else {
                    $this->stateBag->setCurrentDepth($this->stateBag->getCurrentDepth() + 1);
                    $this->processDOM($childNode, $dom);
                }
            }
        }
    }
893679
protected function collectMetadata(\DOMDocument $dom, $source)
    {
        $metadata = array();

        $metadata['xmldeclaration'] = strpos(rtrim($source), '<?xml ') === 0;
        $metadata['doctype'] = !!$dom->doctype;

        return $metadata;
    }
1216689
public static function validateSchema(\DOMDocument $dom): array
    {
        $xliffVersion = static::getVersionNumber($dom);
        $internalErrors = libxml_use_internal_errors(true);
        $disableEntities = libxml_disable_entity_loader(false);

        $isValid = @$dom->schemaValidateSource(self::getSchema($xliffVersion));
        if (!$isValid) {
            libxml_disable_entity_loader($disableEntities);

            return self::getXmlErrors($internalErrors);
        }

        libxml_disable_entity_loader($disableEntities);

        $dom->normalizeDocument();

        libxml_clear_errors();
        libxml_use_internal_errors($internalErrors);

        return [];
    }
971997
private function loadDomDocument(\DOMDocument $dom, $xml, $method)
    {
        return call_user_func_array(
            [$dom, $method],
            // set LIBXML_NONET to prevent local and remote file inclusion attacks.
            [$xml, LIBXML_NONET | LIBXML_DTDATTR | defined('LIBXML_COMPACT') ? LIBXML_COMPACT : 0]
        );
    }
774305
protected function checkVariable(DOMNode $node, $tag, $qname)
	{
		// Test whether this variable comes from a previous xsl:param or xsl:variable element
		$this->checkVariableDeclaration($node, $tag, 'xsl:param[@name="' . $qname . '"]');
		$this->checkVariableDeclaration($node, $tag, 'xsl:variable[@name="' . $qname . '"]');
	}
1305295
protected function _decryptAssertion($dom)
    {
        $pem = $this->_settings->getSPkey();

        if (empty($pem)) {
            throw new OneLogin_Saml2_Error(
                "No private key available, check settings",
                OneLogin_Saml2_Error::PRIVATE_KEY_NOT_FOUND
            );
        }

        $objenc = new XMLSecEnc();
        $encData = $objenc->locateEncryptedData($dom);
        if (!$encData) {
            throw new OneLogin_Saml2_ValidationError(
                "Cannot locate encrypted assertion",
                OneLogin_Saml2_ValidationError::MISSING_ENCRYPTED_ELEMENT
            );
        }

        $objenc->setNode($encData);
        $objenc->type = $encData->getAttribute("Type");
        if (!$objKey = $objenc->locateKey()) {
            throw new OneLogin_Saml2_ValidationError(
                "Unknown algorithm",
                OneLogin_Saml2_ValidationError::KEY_ALGORITHM_ERROR
            );
        }

        $key = null;
        if ($objKeyInfo = $objenc->locateKeyInfo($objKey)) {
            if ($objKeyInfo->isEncrypted) {
                $objencKey = $objKeyInfo->encryptedCtx;
                $objKeyInfo->loadKey($pem, false, false);
                $key = $objencKey->decryptKey($objKeyInfo);
            } else {
                // symmetric encryption key support
                $objKeyInfo->loadKey($pem, false, false);
            }
        }
                
        if (empty($objKey->key)) {
            $objKey->loadKey($key);
        }

        $decrypted = $objenc->decryptNode($objKey, true);

        if ($decrypted instanceof DOMDocument) {
            return $decrypted;
        } else {
            $encryptedAssertion = $decrypted->parentNode;
            $container = $encryptedAssertion->parentNode;

            # Fix possible issue with saml namespace
            if (!$decrypted->hasAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:saml') &&
              !$decrypted->hasAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:saml2') &&
              !$decrypted->hasAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns') &&
              !$container->hasAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:saml') &&
              !$container->hasAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:saml2')
              ) {
                if (strpos($encryptedAssertion->tagName, 'saml2:') !== false) {
                    $ns = 'xmlns:saml2';
                } else if (strpos($encryptedAssertion->tagName, 'saml:') !== false) {
                    $ns = 'xmlns:saml';
                } else {
                    $ns = 'xmlns';
                }

                $decrypted->setAttributeNS('http://www.w3.org/2000/xmlns/', $ns, OneLogin_Saml2_Constants::NS_SAML);
            }

            $container->replaceChild($decrypted, $encryptedAssertion);

            return $decrypted->ownerDocument;
        }
    }
527800
public static function save(DOMDocument $dom)
	{
		$xml = self::innerXML($dom->documentElement);
		if (strpos($xml, 'xmlns:xsl') !== false)
		{
			$xml = preg_replace('((<[^>]+?) xmlns:xsl="' . self::XMLNS_XSL . '")', '$1', $xml);
		}

		return $xml;
	}
832608
private function getSchemaValidationFile(\DOMDocument $document)
    {
        $firstChild = $this->getFirstChild($document);
        // @codeCoverageIgnoreStart
        if (false === $firstChild) {
            return false;
        }
        // @codeCoverageIgnoreEnd

        $attribute = $firstChild->getAttribute('xsi:noNamespaceSchemaLocation');

        if (empty($attribute)) {
            return false;
        }

        return $attribute;
    }