Comprueba y extrae errores si existen en la respuesta XML
326655
def __analizar_errores(self, ret):
        ""
        if 'arrayErrores' in ret:
            errores = ret['arrayErrores'] or []
            self.Errores = [err['error'] for err in errores]
            self.ErrCode = ' '.join(self.Errores)
            self.ErrMsg = '\n'.join(self.Errores)
1245756
public function asXml() {
		$exception = $this->_exception;
		$options   = $this->_options;
		$builder   = new Errbit_XmlBuilder();
		$self      = $this;

		return $builder->tag(
			'notice',
			array('version' => Errbit::API_VERSION),
			function($notice) use ($exception, $options, $self) {
				$notice->tag('api-key',  $options['api_key']);
				$notice->tag('notifier', function($notifier) {
					$notifier->tag('name',    Errbit::PROJECT_NAME);
					$notifier->tag('version', Errbit::VERSION);
					$notifier->tag('url',     Errbit::PROJECT_URL);
				});

				$notice->tag('error', function($error) use ($exception, $self) {
					$klass = Errbit_Notice::className($exception);
					$error->tag('class',     $self->filterTrace($klass));
					$error->tag('message',   $self->filterTrace(sprintf('%s: %s', $klass, $exception->getMessage())));
					$error->tag('backtrace', function($backtrace) use ($exception, $self) {
						$trace = $exception->getTrace();

						$file1 = $exception->getFile();
						$backtrace->tag('line', array(
							'number' => $exception->getLine(),
							'file' => !empty($file1) ? $self->filterTrace($file1) : '<unknown>',
							'method' =>  "<unknown>"
						));

						// if there is no trace we should add an empty element
						if (empty($trace)) {
							$backtrace->tag(
								'line',
								array(
									 'number' => '',
									 'file' => '',
									 'method' => ''
								)
							);
						} else {
							foreach ($trace as $frame) {
								$backtrace->tag(
									'line',
									array(
										'number' => isset($frame['line']) ? $frame['line'] : 0,
										'file'   => isset($frame['file']) ? $self->filterTrace($frame['file']) : '<unknown>',
										'method' => $self->filterTrace(Errbit_Notice::formatMethod($frame))
									)
								);
							}
						}
					});
				});

				if (!empty($options['url'])
					|| !empty($options['controller'])
					|| !empty($options['action'])
					|| !empty($options['parameters'])
					|| !empty($options['session_data'])
					|| !empty($options['cgi_data'])) {
					$notice->tag('request', function($request) use ($options) {
						$request->tag('url',       !empty($options['url']) ? $options['url'] : '');
						$request->tag('component', !empty($options['controller']) ? $options['controller'] : '');
						$request->tag('action',    !empty($options['action']) ? $options['action'] : '');
						if (!empty($options['parameters'])) {
							$request->tag('params', function($params) use ($options) {
								Errbit_Notice::xmlVarsFor($params, $options['parameters']);
							});
						}

						if (!empty($options['session_data'])) {
							$request->tag('session', function($session) use ($options) {
								Errbit_Notice::xmlVarsFor($session, $options['session_data']);
							});
						}

						if (!empty($options['cgi_data'])) {
							$request->tag('cgi-data', function($cgiData) use ($options) {
								Errbit_Notice::xmlVarsFor($cgiData, $options['cgi_data']);
							});
						}
					});
				}

				$notice->tag('server-environment', function($env) use ($options) {
					$env->tag('project-root',     $options['project_root']);
					$env->tag('environment-name', $options['environment_name']);
					$env->tag('hostname',         $options['hostname']);
				});
			}
		)->asXml();
	}
525375
public function seeResponseIsXml()
    {
        libxml_use_internal_errors(true);
        $doc = simplexml_load_string($this->connectionModule->_getResponseContent());
        $num = "";
        $title = "";
        if ($doc === false) {
            $error = libxml_get_last_error();
            $num = $error->code;
            $title = trim($error->message);
            libxml_clear_errors();
        }
        libxml_use_internal_errors(false);
        \PHPUnit\Framework\Assert::assertNotSame(
            false,
            $doc,
            "xml decoding error #$num with message \"$title\", see http://www.xmlsoft.org/html/libxml-xmlerror.html"
        );
    }
1336563
function ErrorMsg()
	{
		if (!$this->_connectionID) return "No connection established";
		$errmsg = '';

		try {
			$errc = $this->_connectionID->Errors;
			if (!$errc) return "No Errors object found";
			if ($errc->Count == 0) return '';
			$err = $errc->Item($errc->Count-1);
			$errmsg = $err->Description;
		}catch(exception $e) {
		}
		return $errmsg;
	}
132731
public function toUnsignedXML() : DOMElement
    {
        $root = parent::toUnsignedXML();

        if ($this->forceAuthn) {
            $root->setAttribute('ForceAuthn', 'true');
        }

        if (!empty($this->ProviderName)) {
            $root->setAttribute('ProviderName', $this->ProviderName);
        }

        if ($this->isPassive) {
            $root->setAttribute('IsPassive', 'true');
        }

        if ($this->assertionConsumerServiceIndex !== null) {
            $root->setAttribute('AssertionConsumerServiceIndex', strval($this->assertionConsumerServiceIndex));
        } else {
            if ($this->assertionConsumerServiceURL !== null) {
                $root->setAttribute('AssertionConsumerServiceURL', $this->assertionConsumerServiceURL);
            }
            if ($this->protocolBinding !== null) {
                $root->setAttribute('ProtocolBinding', $this->protocolBinding);
            }
        }

        if ($this->attributeConsumingServiceIndex !== null) {
            $root->setAttribute('AttributeConsumingServiceIndex', strval($this->attributeConsumingServiceIndex));
        }

        $this->addSubject($root);

        if (!empty($this->nameIdPolicy)) {
            $nameIdPolicy = $this->document->createElementNS(Constants::NS_SAMLP, 'NameIDPolicy');
            if (array_key_exists('Format', $this->nameIdPolicy)) {
                $nameIdPolicy->setAttribute('Format', $this->nameIdPolicy['Format']);
            }
            if (array_key_exists('SPNameQualifier', $this->nameIdPolicy)) {
                $nameIdPolicy->setAttribute('SPNameQualifier', $this->nameIdPolicy['SPNameQualifier']);
            }
            if (array_key_exists('AllowCreate', $this->nameIdPolicy)) {
                $nameIdPolicy->setAttribute('AllowCreate', ($this->nameIdPolicy['AllowCreate']) ? 'true' : 'false');
            }
            $root->appendChild($nameIdPolicy);
        }

        $this->addConditions($root);

        $rac = $this->requestedAuthnContext;
        if (!empty($rac) && !empty($rac['AuthnContextClassRef'])) {
            $e = $this->document->createElementNS(Constants::NS_SAMLP, 'RequestedAuthnContext');
            $root->appendChild($e);
            if (isset($rac['Comparison']) && $rac['Comparison'] !== Constants::COMPARISON_EXACT) {
                $e->setAttribute('Comparison', $rac['Comparison']);
            }
            foreach ($rac['AuthnContextClassRef'] as $accr) {
                Utils::addString($e, Constants::NS_SAML, 'AuthnContextClassRef', $accr);
            }
        }

        if ($this->ProxyCount !== null || count($this->IDPList) > 0 || count($this->RequesterID) > 0) {
            $scoping = $this->document->createElementNS(Constants::NS_SAMLP, 'Scoping');
            $root->appendChild($scoping);
            if ($this->ProxyCount !== null) {
                $scoping->setAttribute('ProxyCount', strval($this->ProxyCount));
            }
            if (count($this->IDPList) > 0) {
                $idplist = $this->document->createElementNS(Constants::NS_SAMLP, 'IDPList');
                foreach ($this->IDPList as $provider) {
                    $idpEntry = $this->document->createElementNS(Constants::NS_SAMLP, 'IDPEntry');
                    if (is_string($provider)) {
                        $idpEntry->setAttribute('ProviderID', $provider);
                    } elseif (is_array($provider)) {
                        foreach ($provider as $attribute => $value) {
                            if (in_array($attribute, [
                                'ProviderID',
                                'Loc',
                                'Name'
                            ], true)) {
                                $idpEntry->setAttribute($attribute, $value);
                            }
                        }
                    }
                    $idplist->appendChild($idpEntry);
                }
                $scoping->appendChild($idplist);
            }
            if (count($this->RequesterID) > 0) {
                Utils::addStrings($scoping, Constants::NS_SAMLP, 'RequesterID', false, $this->RequesterID);
            }
        }

        return $root;
    }
941341
protected function getValidationErrorMessage(array $xml_errors)
    {
        $ignored_errors = array(
            'extra content at the end of the document',
            'premature end of data in tag html',
            'opening and ending tag mismatch between html and body',
            'opening and ending tag mismatch between body and html'
        );

        $errors = array();
        foreach ($xml_errors as $error_object) {
            $error = $error_object->message;

            // further humanize
            $error = str_replace(
                'tag mismatch:',
                Swat::_('tag mismatch between'),
                $error
            );

            // remove some stuff that only makes sense in document context
            $error = preg_replace('/\s?line:? [0-9]+\s?/ui', ' ', $error);
            $error = preg_replace('/in entity[:,.]?/ui', '', $error);
            $error = mb_strtolower($error);

            $error = str_replace(
                'xmlparseentityref: no name',
                Swat::_('unescaped ampersand. Use &amp;amp; instead of &amp;'),
                $error
            );

            $error = str_replace(
                'starttag: invalid element name',
                Swat::_('unescaped less-than. Use &amp;lt; instead of &lt;'),
                $error
            );

            $error = str_replace(
                'specification mandate value for attribute',
                Swat::_('a value is required for the attribute'),
                $error
            );

            $error = preg_replace(
                '/^no declaration for attribute (.*?) of element (.*?)$/',
                Swat::_('the attribute \1 is not valid for the element \2'),
                $error
            );

            $error = str_replace(
                'attvalue: " or \' expected',
                Swat::_(
                    'attribute values must be contained within quotation ' .
                        'marks'
                ),
                $error
            );

            $error = trim($error);

            if (!in_array($error, $ignored_errors)) {
                $errors[] = $error;
            }
        }

        $content = Swat::_('%s must be valid XHTML markup: ');
        $content .= '<ul><li>' . implode(',</li><li>', $errors) . '.</li></ul>';
        $message = new SwatMessage($content, 'error');
        $message->content_type = 'text/xml';

        return $message;
    }
681199
public function errorsAddToXML($encoding)
    {
        $dom = new DOMDocument('1.0', 'UTF-8');
        $root = $dom->createElement("Errors");
        $dom->appendChild($root);
        $xml = simplexml_import_dom($dom);
        $xmlerr = new SimpleXMLExtended($xml, $encoding);
        foreach ($this->_arrErrorList as $arrLine) {
//            $error = $xmlerr->addCData('Error', $arrLine['message']);
            $error = $xmlerr->addChild('Error');
            $error->addAttribute('Message', $arrLine['message']);
            $error->addAttribute('Function', $arrLine['command']);
        }

        return $xmlerr->getSimpleXmlElement();
    }
1143225
protected function checkForError(\SimpleXMLElement $result)
    {
        /* -- sample general error --
        <?xml version="1.0" encoding="ISO-8859-1"?>
        <MESSAGEACK>
            <Err Code="65535" Desc="The Specified message does not conform to DTD"/>
        </MESSAGEACK>
        */
        if (0 !== $result->Err->count()) {
            $code = (int) $result->Err['Code'];
            throw new Exception\RuntimeException($this->getApiMessage($code), $code);
        }

        /* -- sample message post error --
        <?xml version="1.0" encoding="ISO-8859-1"?>
        <MESSAGEACK>
            <GUID GUID="ke3ql370590732f440014mucv1RAPIDOSPOR" SUBMITDATE="2014-03-26 21:37:05" ID="1">
                <ERROR SEQ="1" CODE="28682" />
            </GUID>
        </MESSAGEACK>
        */
        if (0 !== $result->GUID->ERROR->count()) {
            $code = (int) $result->GUID->ERROR['CODE'];
            throw new Exception\RuntimeException($this->getApiMessage($code), $code);
        }
    }
376613
def __analizar_errores(self, ret):
        ""
        self.Errores = [err['codigoDescripcion'] for err in ret.get('arrayErrores', [])]
        self.ErroresFormato = [err['codigoDescripcionString'] for err in ret.get('arrayErroresFormato', [])]
        errores = self.Errores + self.ErroresFormato
        self.ErrCode = ' '.join(["%(codigo)s" % err for err in errores])
        self.ErrMsg = '\n'.join(["%(codigo)s: %(descripcion)s" % err for err in errores])
283749
public function validate($value)
    {
        if (!$value instanceof DOMDocument) {
            $this->errors[] = TypeValidationError::xmlValidationFailed('Expected value of type DOMDocument');

            return;
        }

        $originalErrorLevel = \libxml_use_internal_errors(true);
        $value->schemaValidateSource($this->xml);
        $errors = \libxml_get_errors();
        \libxml_clear_errors();
        if ($errors) {
            foreach ($errors as $error) {
                $this->errors[] = TypeValidationError::xmlValidationFailed($error->message);
            }

            return;
        }

        \libxml_use_internal_errors($originalErrorLevel);
    }
123221
public function fail()
    {
        $args = func_get_args();
        $str = ucfirst(
            $this->prefix.
            ($this->caption ?: str_replace('_', ' ', $this->active_field)).' '.
            lcfirst(array_shift($args))
        );

        // Insert any args into placeholders
        if (count($args) > 0) {
            $n = 1;

            foreach ($args as $arg) {
                $tag = sprintf('{{arg%s}}', $n);
                $str = str_replace($tag, $arg, $str);
                ++$n;
            }
        }

        /** @type Exception_ValidityCheck $e */
        $e = $this->exception((string) ($this->custom_error ?: $str));
        throw $e->setField($this->active_field);
    }
358495
public function isValid()
    {
        $singleAssertion = $this->validateNumAssertions();
        if (!$singleAssertion) {
            throw new Exception('Multiple assertions are not supported');
        }

        $validTimestamps = $this->validateTimestamps();
        if (!$validTimestamps) {
            throw new Exception('Timing issues (please check your clock settings)');
        }

        $objXMLSecDSig = new XMLSecurityDSig();

        $objDSig = $objXMLSecDSig->locateSignature($this->_document);
        if (!$objDSig) {
            throw new Exception('Cannot locate Signature Node');
        }
        $objXMLSecDSig->canonicalizeSignedInfo();
        $objXMLSecDSig->idKeys = array('ID');

        $objKey = $objXMLSecDSig->locateKey();
        if (!$objKey) {
            throw new Exception('We have no idea about the key');
        }

        try {
            $objXMLSecDSig->validateReference();
        } catch (Exception $e) {
            throw new Exception('Reference Validation Failed');
        }

        XMLSecEnc::staticLocateKeyInfo($objKey, $objDSig);

        $objKey->loadKey($this->_settings->idpPublicCertificate, false, true);

        return ($objXMLSecDSig->verify($objKey) === 1);
    }
1193804
public function getMissingErrors()
    {
        return array_combine(
            array_keys($this->missingAttribs),
            array_map(function ($ref) {
                return $ref['error'];
            }, array_values($this->missingAttribs))
        );
    }
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;
    }
799164
function HandleError($code, $line, $col, $byte_index = 0)
    {
        $sample_size = 80;
        $sample_start = $byte_index - ($sample_size / 2);
        if ($sample_start < 0) {
          $sample_start = 0;
        }
        
        trigger_error('XML Parsing Error at '.$line.':'.$col. (($byte_index != 0)?' (byte index: '.$byte_index.')':''). '. Error '.$code.': '.xml_error_string($code). ' check sample which starts at position '.$sample_start.': html encoded: '.htmlentities(substr($this->xml, $sample_start, $sample_size)). ' (hex: '.bin2hex(substr($this->xml, $sample_start, $sample_size)).', raw: '.(substr($this->xml, $sample_start, $sample_size)).')');
    }
1148209
def ObtenerTagXml(self, *tags):
        ""
        # convierto el xml a un objeto
        try:
            if self.xml:
                xml = self.xml
                # por cada tag, lo busco segun su nombre o posición
                for tag in tags:
                    xml = xml(tag) # atajo a getitem y getattr
                # vuelvo a convertir a string el objeto xml encontrado
                return str(xml)
        except Exception, e:
            self.Excepcion = traceback.format_exception_only( sys.exc_type, sys.exc_value)[0]
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;
    }