verifySignature
Verifica a validade da assinatura digital contida no xml.
@param string $docxml conteudo do xml a ser verificado ou o path completo
@param string $tagid tag que foi assinada no documento xml
@return bool
@throws Exception
@throws Exception
509630
public function verifySignature($docxml = '', $tagid = '')
    {
        if ($docxml == '') {
            $msg = 'Não foi passado um xml para a verificação.';
            throw new Exception($msg);
        }
        if ($tagid == '') {
            $msg = 'Não foi indicada a TAG a ser verificada.';
            throw new Exception($msg);
        }
        $xml = $docxml;
        if (is_file($docxml)) {
            $xml = file_get_contents($docxml);
        }
        $dom = new Dom();
        $dom->loadXMLString($xml);
        $flag = $this->zDigCheck($dom, $tagid);
        $flag = $this->zSignCheck($dom);

        return $flag;
    }
1310698
public static Specification<JpaTarget> hasTag(final Long tagId) {

        return (targetRoot, query, cb) -> {
            final SetJoin<JpaTarget, JpaTargetTag> tags = targetRoot.join(JpaTarget_.tags, JoinType.LEFT);
            return cb.equal(tags.get(JpaTargetTag_.id), tagId);
        };
    }
1212178
private function readDocument(\DOMDocument $document, $workflowId = null)
    {
        $errorToExceptionContext = new ErrorToExceptionContext(E_WARNING, function () use ($document) {
            $document->schemaValidate(dirname(__DIR__).'/Resources/config/workflower/schema/BPMN20.xsd');
        });
        $errorToExceptionContext->invoke();

        $workflowBuilder = new WorkflowBuilder($workflowId);

        foreach ($document->getElementsByTagNameNs('http://www.omg.org/spec/BPMN/20100524/MODEL', 'process') as $element) {
            /* @var $element \DOMElement */
            if ($element->hasAttribute('id')) {
                $workflowBuilder->setWorkflowId($element->getAttribute('id'));
            }

            if ($element->hasAttribute('name')) {
                $workflowBuilder->setWorkflowName($element->getAttribute('name'));
            }
        }

        $flowObjectRoles = array();
        foreach ($document->getElementsByTagNameNs('http://www.omg.org/spec/BPMN/20100524/MODEL', 'lane') as $element) {
            if (!$element->hasAttribute('id')) {
                throw $this->createIdAttributeNotFoundException($element, $workflowId);
            }

            $workflowBuilder->addRole(
                $element->getAttribute('id'),
                $element->hasAttribute('name') ? $element->getAttribute('name') : null
            );

            foreach ($element->getElementsByTagNameNs('http://www.omg.org/spec/BPMN/20100524/MODEL', 'flowNodeRef') as $childElement) {
                $flowObjectRoles[$childElement->nodeValue] = $element->getAttribute('id');
            }
        }

        if (count($flowObjectRoles) == 0) {
            $workflowBuilder->addRole(Workflow::DEFAULT_ROLE_ID);
        }

        $messages = array();
        foreach ($document->getElementsByTagNameNs('http://www.omg.org/spec/BPMN/20100524/MODEL', 'message') as $element) {
            if (!$element->hasAttribute('id')) {
                throw $this->createIdAttributeNotFoundException($element, $workflowId);
            }

            $messages[$element->getAttribute('id')] = $element->getAttribute('name');
        }

        $operations = array();
        foreach ($document->getElementsByTagNameNs('http://www.omg.org/spec/BPMN/20100524/MODEL', 'operation') as $element) {
            if (!$element->hasAttribute('id')) {
                throw $this->createIdAttributeNotFoundException($element, $workflowId);
            }

            $operations[$element->getAttribute('id')] = $element->getAttribute('name');
        }

        foreach ($document->getElementsByTagNameNs('http://www.omg.org/spec/BPMN/20100524/MODEL', 'startEvent') as $element) {
            if (!$element->hasAttribute('id')) {
                throw $this->createIdAttributeNotFoundException($element, $workflowId);
            }

            $workflowBuilder->addStartEvent(
                $element->getAttribute('id'),
                $this->provideRoleIdForFlowObject($flowObjectRoles, $element->getAttribute('id')),
                $element->hasAttribute('name') ? $element->getAttribute('name') : null,
                $element->hasAttribute('default') ? $element->getAttribute('default') : null
            );
        }

        foreach ($document->getElementsByTagNameNs('http://www.omg.org/spec/BPMN/20100524/MODEL', 'task') as $element) {
            if (!$element->hasAttribute('id')) {
                throw $this->createIdAttributeNotFoundException($element, $workflowId);
            }

            $workflowBuilder->addTask(
                $element->getAttribute('id'),
                $this->provideRoleIdForFlowObject($flowObjectRoles, $element->getAttribute('id')),
                $element->hasAttribute('name') ? $element->getAttribute('name') : null,
                $element->hasAttribute('default') ? $element->getAttribute('default') : null
            );
        }

        foreach ($document->getElementsByTagNameNs('http://www.omg.org/spec/BPMN/20100524/MODEL', 'serviceTask') as $element) {
            if (!$element->hasAttribute('id')) {
                throw $this->createIdAttributeNotFoundException($element, $workflowId);
            }

            $workflowBuilder->addServiceTask(
                $element->getAttribute('id'),
                $this->provideRoleIdForFlowObject($flowObjectRoles, $element->getAttribute('id')),
                $element->hasAttribute('operationRef') ? $operations[$element->getAttribute('operationRef')] : null,
                $element->hasAttribute('name') ? $element->getAttribute('name') : null,
                $element->hasAttribute('default') ? $element->getAttribute('default') : null
            );
        }

        foreach ($document->getElementsByTagNameNs('http://www.omg.org/spec/BPMN/20100524/MODEL', 'sendTask') as $element) {
            if (!$element->hasAttribute('id')) {
                throw $this->createIdAttributeNotFoundException($element, $workflowId);
            }

            $workflowBuilder->addSendTask(
                $element->getAttribute('id'),
                $this->provideRoleIdForFlowObject($flowObjectRoles, $element->getAttribute('id')),
                $element->hasAttribute('messageRef') ? $messages[$element->getAttribute('messageRef')] : null,
                $element->hasAttribute('operationRef') ? $operations[$element->getAttribute('operationRef')] : null,
                $element->hasAttribute('name') ? $element->getAttribute('name') : null,
                $element->hasAttribute('default') ? $element->getAttribute('default') : null
            );
        }

        foreach ($document->getElementsByTagNameNs('http://www.omg.org/spec/BPMN/20100524/MODEL', 'exclusiveGateway') as $element) {
            if (!$element->hasAttribute('id')) {
                throw $this->createIdAttributeNotFoundException($element, $workflowId);
            }

            $workflowBuilder->addExclusiveGateway(
                $element->getAttribute('id'),
                $this->provideRoleIdForFlowObject($flowObjectRoles, $element->getAttribute('id')),
                $element->hasAttribute('name') ? $element->getAttribute('name') : null,
                $element->hasAttribute('default') ? $element->getAttribute('default') : null
            );
        }

        foreach ($document->getElementsByTagNameNs('http://www.omg.org/spec/BPMN/20100524/MODEL', 'endEvent') as $element) {
            if (!$element->hasAttribute('id')) {
                throw $this->createIdAttributeNotFoundException($element, $workflowId);
            }

            $workflowBuilder->addEndEvent($element->getAttribute('id'), $this->provideRoleIdForFlowObject($flowObjectRoles, $element->getAttribute('id')), $element->hasAttribute('name') ? $element->getAttribute('name') : null);
        }

        foreach ($document->getElementsByTagNameNs('http://www.omg.org/spec/BPMN/20100524/MODEL', 'sequenceFlow') as $element) {
            if (!$element->hasAttribute('id')) {
                throw $this->createIdAttributeNotFoundException($element, $workflowId);
            }

            $condition = null;
            foreach ($element->getElementsByTagNameNs('http://www.omg.org/spec/BPMN/20100524/MODEL', 'conditionExpression') as $childElement) {
                $condition = $childElement->nodeValue;
                break;
            }

            $workflowBuilder->addSequenceFlow(
                $element->getAttribute('sourceRef'),
                $element->getAttribute('targetRef'),
                $element->getAttribute('id'),
                $element->hasAttribute('name') ? $element->getAttribute('name') : null,
                $condition === null ? null : $condition
            );
        }

        return $workflowBuilder->build();
    }
559080
public static function isValidXml($xml, $doc = null)
    {
        if ($doc == null) {
            $doc = new DOMDocument("1.0", "ISO-8859-1");
        }

        // tries to load the document and gets the errors
        $useInternalErrors = libxml_use_internal_errors(true);
        $doc->loadXML($xml);
        $errors = libxml_get_errors();
        libxml_use_internal_errors($useInternalErrors);

        return count($errors) == 0;
    }
705556
public static function validar($xml, $schemaFile)
    {
        //Para poder pegar os erros caso houver
        libxml_use_internal_errors(true);
        libxml_clear_errors();

        if (is_file($xml)) {
            $xml = file_get_contents($xml);
        }

        $dom = new DOMDocument('1.0', 'utf-8');

        $dom->loadXML($xml, LIBXML_NOBLANKS | LIBXML_NOEMPTYTAG);

        if (! $dom->schemaValidate($schemaFile)) {
            $errors = libxml_get_errors();
            $returnErrors = [];
            foreach ($errors as $error) {
                $returnErrors[] = $error->message . 'at line ' . $error->line;
            }

            $msg = "Erro ao validar XML:\r\n" . implode("\r\n", $returnErrors);

            throw new \Exception($msg);
        }

        return true;
    }
1121955
public static function scan($xml, DOMDocument $dom = null)
    {
        // If running with PHP-FPM we perform an heuristic scan
        // We cannot use libxml_disable_entity_loader because of this bug
        // @see https://bugs.php.net/bug.php?id=64938
        if (self::isPhpFpm()) {
            self::heuristicScan($xml);
        }

        if (null === $dom) {
            $simpleXml = true;
            $dom = new DOMDocument();
        }

        if (!self::isPhpFpm()) {
            $loadEntities = libxml_disable_entity_loader(true);
            $useInternalXmlErrors = libxml_use_internal_errors(true);
        }

        // Load XML with network access disabled (LIBXML_NONET)
        // error disabled with @ for PHP-FPM scenario
        set_error_handler(array('fproject\common\utils\XmlSecurity', 'loadXmlErrorHandler'), E_WARNING);

        $result = $dom->loadXML($xml, LIBXML_NONET);
        restore_error_handler();

        if (!$result) {
            // Entity load to previous setting
            if (!self::isPhpFpm()) {
                libxml_disable_entity_loader($loadEntities);
                libxml_use_internal_errors($useInternalXmlErrors);
            }
            return false;
        }

        // Scan for potential XEE attacks using ENTITY, if not PHP-FPM
        if (!self::isPhpFpm()) {
            foreach ($dom->childNodes as $child) {
                if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) {
                    if ($child->entities->length > 0) {
                        throw new Exception(self::ENTITY_DETECT);
                    }
                }
            }
        }

        // Entity load to previous setting
        if (!self::isPhpFpm()) {
            libxml_disable_entity_loader($loadEntities);
            libxml_use_internal_errors($useInternalXmlErrors);
        }

        if (isset($simpleXml)) {
            $result = simplexml_import_dom($dom);
            if (!$result instanceof SimpleXMLElement) {
                return false;
            }
            return $result;
        }
        return $dom;
    }
11002
public function process(\DOMDocument $xml)
    {
        $licenseMap = array(
            '#^\s*(GPL|GNU General Public License)((\s?v?|version)?2)\s*$#i'
                => 'http://opensource.org/licenses/GPL-2.0',
            '#^\s*(GPL|GNU General Public License)((\s?v?|version)?3?)\s*$#i'
                => 'http://opensource.org/licenses/GPL-3.0',
            '#^\s*(LGPL|GNU (Lesser|Library) (General Public License|GPL))'
                .'((\s?v?|version)?2(\.1)?)\s*$#i'
                => 'http://opensource.org/licenses/LGPL-2.1',
            '#^\s*(LGPL|GNU (Lesser|Library) (General Public License|GPL))'
                .'((\s?v?|version)?3?)\s*$#i'
                => 'http://opensource.org/licenses/LGPL-3.0',
            '#^\s*((new |revised |modified |three-clause |3-clause )BSD'
                .'( License)?)\s*$#i'
                => 'http://opensource.org/licenses/BSD-3-Clause',
            '#^\s*((simplified |two-clause |2-clause |Free)BSD)( License)?\s*$#i'
                => 'http://opensource.org/licenses/BSD-2-Clause',
            '#^\s*MIT( License)?\s*$#i' => 'http://opensource.org/licenses/MIT',
        );

        $xpath = new \DOMXPath($xml);
        $nodes = $xpath->query('//tag[@name="license"]/@description');

        /** @var \DOMElement $node */
        foreach ($nodes as $node) {

            $license = $node->nodeValue;

            // FIXME: migrate to '#^' . PHPDOC::LINK_REGEX . '(\s+(?P<text>.+))
            // ?$#u' once that const exists
            if (preg_match(
                '#^(?i)\b(?P<url>(?:https?://|www\d{0,3}\.|[a-z0-9.\-]+\.'
                .'[a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+'
                .'(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|'
                .'[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))(\s+(?P<text>.+))?$#u',
                $license,
                $matches
            )) {
                if (!isset($matches['text']) || !$matches['text']) {
                    // set text to URL if not present
                    $matches['text'] = $matches['url'];
                }
                $node->parentNode->setAttribute('link', $matches['url']);
                $node->nodeValue = $matches['text'];

                // bail out early
                continue;
            }

            // check map if any license matches
            foreach ($licenseMap as $regex => $url) {
                if (preg_match($regex, $license, $matches)) {
                    $node->parentNode->setAttribute('link', $url);

                    // we're done here
                    break;
                }
            }
        }

        return $xml;
    }
773155
protected function checkToken($xml){
        if ($xml && $xml->NextToken && (string)$xml->HasNext != 'false' && (string)$xml->MoreResultsAvailable != 'false'){
            $this->tokenFlag = true;
            $this->options['NextToken'] = (string)$xml->NextToken;
        } else {
            unset($this->options['NextToken']);
            $this->tokenFlag = false;
        }
    }
9037
protected function processTag(DOMDocument $xmlDoc, $tagName)
    {
        /** @var $embed \DOMElement */
        foreach ($xmlDoc->getElementsByTagName($tagName) as $embed) {
            if (!$view = $embed->getAttribute('view')) {
                $view = $tagName;
            }

            $embedContent = null;
            $parameters = $this->getParameters($embed);

            if ($contentId = $embed->getAttribute('object_id')) {
                try {
                    /** @var \eZ\Publish\API\Repository\Values\Content\Content $content */
                    $content = $this->repository->sudo(
                        static function (Repository $repository) use ($contentId) {
                            return $repository->getContentService()->loadContent($contentId);
                        }
                    );

                    if (
                        !$this->repository->canUser('content', 'read', $content)
                        && !$this->repository->canUser('content', 'view_embed', $content)
                    ) {
                        throw new UnauthorizedException('content', 'read', ['contentId' => $contentId]);
                    }

                    // Check published status of the Content
                    if (
                        $content->getVersionInfo()->status !== APIVersionInfo::STATUS_PUBLISHED
                        && !$this->repository->canUser('content', 'versionread', $content)
                    ) {
                        throw new UnauthorizedException('content', 'versionread', ['contentId' => $contentId]);
                    }

                    $embedContent = $this->fragmentHandler->render(
                        new ControllerReference(
                            'ez_content:embedAction',
                            [
                                'contentId' => $contentId,
                                'viewType' => $view,
                                'layout' => false,
                                'params' => $parameters,
                            ]
                        )
                    );
                } catch (APINotFoundException $e) {
                    if ($this->logger) {
                        $this->logger->error(
                            'While generating embed for xmltext, could not locate ' .
                            'Content object with ID ' . $contentId
                        );
                    }
                }
            } elseif ($locationId = $embed->getAttribute('node_id')) {
                try {
                    /** @var \eZ\Publish\API\Repository\Values\Content\Location $location */
                    $location = $this->repository->sudo(
                        static function (Repository $repository) use ($locationId) {
                            return $repository->getLocationService()->loadLocation($locationId);
                        }
                    );

                    if (
                        !$this->repository->canUser('content', 'read', $location->getContentInfo(), $location)
                        && !$this->repository->canUser('content', 'view_embed', $location->getContentInfo(), $location)
                    ) {
                        throw new UnauthorizedException('content', 'read', ['locationId' => $location->id]);
                    }

                    $embedContent = $this->fragmentHandler->render(
                        new ControllerReference(
                            'ez_content:embedAction',
                            [
                                'contentId' => $location->getContentInfo()->id,
                                'locationId' => $location->id,
                                'viewType' => $view,
                                'layout' => false,
                                'params' => $parameters,
                            ]
                        )
                    );
                } catch (APINotFoundException $e) {
                    if ($this->logger) {
                        $this->logger->error(
                            'While generating embed for xmltext, could not locate ' .
                            'Location with ID ' . $locationId
                        );
                    }
                }
            }

            if ($embedContent === null) {
                // Remove empty embed
                $embed->parentNode->removeChild($embed);
            } else {
                while ($embed->hasChildNodes()) {
                    $embed->removeChild($embed->firstChild);
                }
                $embed->appendChild($xmlDoc->createCDATASection($embedContent));
            }
        }
    }
713520
public function match($regexp, $tagName)
	{
		$tagName        = TagName::normalize($tagName);
		$passthroughIdx = 0;
		$this->parseRegexp($regexp);
		foreach ($this->captures as $i => $capture)
		{
			if (!$this->isCatchAll($capture['expr']))
			{
				continue;
			}
			$passthroughIdx = $i;
		}

		$this->collection[] = [$tagName, $regexp, $passthroughIdx];
	}
898312
public function deleteTag($tagid){
	    if (!$this->access_token && !$this->checkAuth()) return false;
	    $result = $this->http_get(self::API_URL_PREFIX.self::TAG_DELETE_URL.'access_token='.$this->access_token.'&tagid='.$tagid);
	    if ($result)
	    {
	        $json = json_decode($result,true);
	        if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
	            $this->errCode = $json['errcode'];
	            $this->errMsg = $json['errmsg'];
	            return false;
	        }
	        return $json;
	    }
	    return false;
	}
909826
protected function validateTagToken(TagToken $token) : bool
    {
        $tagName = $token->getTagName();
        $tagDef = $this->tagDefs->get($tagName);
        if (!isset($tagDef)) {
            return false;
        }

        return $tagDef->validate($token);
    }
509537
public static function isFidaVista($statement) {

        $result = false;
        $domDocument = new \DOMDocument();
        libxml_use_internal_errors(true);
        
        try {
            //$domDocument->loadXML($statement);
            if ($domDocument->loadXML($statement) == true) {
                $node = $domDocument->childNodes->item(0);
                
                if ($node->nodeName === 'FIDAVISTA') {
                    $result = true;
                }
            }
        } catch (Exception $exc) {
            $result = false;
        } finally {
            unset($domDocument);
        }
        
        return $result;
    }
1069513
public function hasTagById( $id )
	{
		$xpath	= new DomXPath( $this->document );
		$query	= "//*[@id = '$id']";
		$nodes	= $xpath->query( $query );
		return (bool) $nodes->length;
	}
624227
public function assinarXML($xml, $tag, $ignoreValidCert = false)
    {
        $xmlDoc = new Dom();

        //Limpando o XML
        //$order = ["\r\n", "\n", "\r", "\t"];
        $order = ["\t"];
        $xml = str_replace($order, '', $xml);

        $xmlDoc->loadXMLString($xml);
        $node = $xmlDoc->getElementsByTagName($tag)->item(0);

        // Raiz
        $root = $xmlDoc->getElementsByTagName($tag)->item(0)->parentNode;

        $pkcs = new Pkcs12('', $this->getChavePub(), $this->getChavePri(), $this->getCertificado(), $ignoreValidCert);

        // Assinando
        $objSSLPriKey = openssl_get_privatekey($this->chavePri);
        $sxml = $pkcs->zSignXML($xmlDoc, $root, $node, $objSSLPriKey);

        return $sxml;
    }
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;
    }
185996
public static function stringToDOMDocument($xml, $filename = '')
    {
        $preUseInternalErrors = libxml_use_internal_errors(true);
        try {
            libxml_clear_errors();
            $doc = new DOMDocument();
            if (@$doc->loadXML($xml) === false) {
                throw new Exception(empty($filename) ? 'Failed to parse xml' : ('Failed to load file '.$filename));
            }
        } catch (Exception $x) {
            libxml_use_internal_errors($preUseInternalErrors);
            libxml_clear_errors();
            throw $x;
        }
        libxml_use_internal_errors($preUseInternalErrors);

        return $doc;
    }