Example #1
0
 public function isValid($XSDString)
 {
     $ok = false;
     try {
         $this->xml->schemaValidateSource($XSDString);
         $ok = true;
     } catch (\ErrorException $e) {
         $this->errorMessage = $e->getMessage();
     }
     return $ok;
 }
Example #2
0
 public function validateCybertipSchema(EntityEnclosingRequest $req)
 {
     $xsd = $this->getConfig()->get('xsd');
     $error = null;
     $prev = libxml_use_internal_errors(true);
     try {
         $body = (string) $req->getBody();
         $dom = new \DOMDocument();
         $dom->loadXML($body);
         $ret = $dom->schemaValidateSource($xsd);
         if (!$ret) {
             $error = self::libxmlErrorExceptionFactory();
         }
     } catch (\Exception $e) {
         $error = $e;
     }
     libxml_use_internal_errors($prev);
     if ($error instanceof \Exception) {
         throw $error;
     } else {
         if ($error) {
             throw new XsdValidateException($error);
         }
     }
 }
Example #3
0
 public function schemaValidate($filename)
 {
     if (!file_exists($filename) || !filesize($filename)) {
         throw new Exception('Empty file supplied as input');
     }
     return parent::schemaValidateSource(file_get_contents($filename));
 }
Example #4
0
    /**
     * Validates and parses the given file into a SimpleXMLElement
     *
     * @param  string $file
     * @return SimpleXMLElement
     */
    private function parseFile($file)
    {
        $dom = new \DOMDocument();
        $current = libxml_use_internal_errors(true);
        if (!@$dom->load($file, LIBXML_COMPACT)) {
            throw new \RuntimeException(implode("\n", $this->getXmlErrors()));
        }

        $location = str_replace('\\', '/', __DIR__).'/schema/dic/xliff-core/xml.xsd';
        $parts = explode('/', $location);
        if (preg_match('#^phar://#i', $location)) {
            $tmpfile = tempnam(sys_get_temp_dir(), 'sf2');
            if ($tmpfile) {
                file_put_contents($tmpfile, file_get_contents($location));
                $tmpfiles[] = $tmpfile;
                $parts = explode('/', str_replace('\\', '/', $tmpfile));
            }
        }
        $drive = '\\' === DIRECTORY_SEPARATOR ? array_shift($parts).'/' : '';
        $location = 'file:///'.$drive.implode('/', array_map('rawurlencode', $parts));

        $source = file_get_contents(__DIR__.'/schema/dic/xliff-core/xliff-core-1.2-strict.xsd');
        $source = str_replace('http://www.w3.org/2001/xml.xsd', $location, $source);

        if (!@$dom->schemaValidateSource($source)) {
            throw new \RuntimeException(implode("\n", $this->getXmlErrors()));
        }
        $dom->validateOnParse = true;
        $dom->normalizeDocument();
        libxml_use_internal_errors($current);

        return simplexml_import_dom($dom);
    }
 /**
  * {@inheritdoc}
  */
 protected function stringMatches($other)
 {
     $internalErrors = libxml_use_internal_errors(true);
     $disableEntities = libxml_disable_entity_loader(true);
     libxml_clear_errors();
     $dom = new \DOMDocument();
     $dom->preserveWhiteSpace = false;
     $dom->validateOnParse = true;
     if (!@$dom->loadXML($other, LIBXML_NONET | (defined('LIBXML_COMPACT') ? LIBXML_COMPACT : 0))) {
         libxml_disable_entity_loader($disableEntities);
         $this->setXMLConstraintErrors();
         libxml_clear_errors();
         libxml_use_internal_errors($internalErrors);
         return false;
     }
     $dom->normalizeDocument();
     libxml_disable_entity_loader($disableEntities);
     libxml_clear_errors();
     if (false === ($result = @$dom->schemaValidateSource($this->XSD))) {
         $this->setXMLConstraintErrors();
     }
     libxml_clear_errors();
     libxml_use_internal_errors($internalErrors);
     return $result;
 }
 public function testExportSites()
 {
     $foo = Site::newForType(Site::TYPE_UNKNOWN);
     $foo->setGlobalId('Foo');
     $acme = Site::newForType(Site::TYPE_UNKNOWN);
     $acme->setGlobalId('acme.com');
     $acme->setGroup('Test');
     $acme->addLocalId(Site::ID_INTERWIKI, 'acme');
     $acme->setPath(Site::PATH_LINK, 'http://acme.com/');
     $tmp = tmpfile();
     $exporter = new SiteExporter($tmp);
     $exporter->exportSites(array($foo, $acme));
     fseek($tmp, 0);
     $xml = fread($tmp, 16 * 1024);
     $this->assertContains('<sites ', $xml);
     $this->assertContains('<site>', $xml);
     $this->assertContains('<globalid>Foo</globalid>', $xml);
     $this->assertContains('</site>', $xml);
     $this->assertContains('<globalid>acme.com</globalid>', $xml);
     $this->assertContains('<group>Test</group>', $xml);
     $this->assertContains('<localid type="interwiki">acme</localid>', $xml);
     $this->assertContains('<path type="link">http://acme.com/</path>', $xml);
     $this->assertContains('</sites>', $xml);
     // NOTE: HHVM (at least on wmf Jenkins) doesn't like file URLs.
     $xsdFile = __DIR__ . '/../../../../docs/sitelist-1.0.xsd';
     $xsdData = file_get_contents($xsdFile);
     $document = new DOMDocument();
     $document->loadXML($xml, LIBXML_NONET);
     $document->schemaValidateSource($xsdData);
 }
 /**
  * Checks whether XML is valid to XMLSchema.
  * @param DOMDocument $xmlDom source XML
  * @param string $schemaString source XMLSchema
  */
 protected function checkValidityToXmlSchema(DOMDocument $xmlDom, $schemaString)
 {
     $this->useLibxmlErrors();
     // var_dump($schemaString);
     try {
         $xmlDom->schemaValidateSource($schemaString);
     } catch (Exception $ex) {
         if ($this->reachGoalOnNoLibxmlErrors(self::goalValidToSchema, null)) {
             $this->addError("An error occurred while validating the document. This should not have happened. " . $ex->getMessage());
         }
         return;
     }
     $this->reachGoalOnNoLibxmlErrors(self::goalValidToSchema, null);
 }
 /**
  * Validate an XML string against the schema
  *
  * @param $string
  *
  * @throws \Exception
  *
  * @return boolean
  */
 public function validate($string)
 {
     $dom = new \DOMDocument();
     $originalErrorLevel = libxml_use_internal_errors(true);
     $dom->loadXML($string);
     $errors = libxml_get_errors();
     libxml_clear_errors();
     if ($errors) {
         throw new InvalidXmlException($errors);
     }
     // ---
     $dom->schemaValidateSource($this->xml);
     $errors = libxml_get_errors();
     libxml_clear_errors();
     if ($errors) {
         throw new InvalidSchemaException($errors);
     }
     libxml_use_internal_errors($originalErrorLevel);
     return true;
 }
Example #9
0
 /**
  * На вход подается содержимое XML и XSD-схемы.
  * Далее входной XML валидируется по заданной XSD-схеме
  *
  * @param $xml
  * @param $xsd
  * @return array
  */
 public function validateXmlByXsd($xml, $xsd)
 {
     $isValid = false;
     $err = [];
     libxml_use_internal_errors(true);
     $validator = new \DOMDocument('1.0', 'UTF-8');
     $validator->loadXML($xml);
     if (!$validator->schemaValidateSource($xsd)) {
         $errors = libxml_get_errors();
         $i = 1;
         foreach ($errors as $error) {
             $err[] = $error->message;
             $i++;
         }
         libxml_clear_errors();
     } else {
         $isValid = true;
     }
     libxml_use_internal_errors(false);
     return ['validation' => $isValid, 'errors' => $err];
 }
 /**
  * Validates xml against a given schema
  *
  * @param string $xml
  * @return void
  * @throws EngineBlock_Exception in case validating itself fails or if xml does not validate
  */
 public function validate($xml)
 {
     if (!ini_get('allow_url_fopen')) {
         throw new EngineBlock_Exception('Failed validating XML, url_fopen is not allowed');
     }
     // Load schema
     $schemaXml = @file_get_contents($this->_schemaLocation);
     if ($schemaXml === false) {
         throw new EngineBlock_Exception('Failed validating XML, schema url could not be opened: "' . $this->_schemaLocation . '"');
     }
     $schemaXml = $this->_absolutizeSchemaLocations($schemaXml, $this->_schemaLocation);
     $dom = new DOMDocument();
     $dom->loadXML($xml);
     if (!@$dom->schemaValidateSource($schemaXml)) {
         $errorInfo = error_get_last();
         $errorMessage = $errorInfo['message'];
         // @todo improve parsing message by creating custom exceptions for which know that structure of messages
         $parsedErrorMessage = preg_replace('/\\{[^}]*\\}/', '', $errorMessage);
         echo '<pre>' . htmlentities(EngineBlock_Corto_XmlToArray::formatXml($xml)) . '</pre>';
         throw new EngineBlock_Exception("Metadata XML doesn't validate against schema at '{$schemaXml}', gives error:: '{$parsedErrorMessage}'");
     }
 }
Example #11
0
 /**
  * Validates and parses the given file into a SimpleXMLElement
  *
  * @param string $file
  *
  * @return \SimpleXMLElement
  */
 private function parseFile($file)
 {
     $internalErrors = libxml_use_internal_errors(true);
     $disableEntities = libxml_disable_entity_loader(true);
     libxml_clear_errors();
     $dom = new \DOMDocument();
     $dom->validateOnParse = true;
     if (!@$dom->loadXML(file_get_contents($file), LIBXML_NONET | (defined('LIBXML_COMPACT') ? LIBXML_COMPACT : 0))) {
         libxml_disable_entity_loader($disableEntities);
         throw new \RuntimeException(implode("\n", $this->getXmlErrors($internalErrors)));
     }
     libxml_disable_entity_loader($disableEntities);
     foreach ($dom->childNodes as $child) {
         if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) {
             libxml_use_internal_errors($internalErrors);
             throw new \RuntimeException('Document types are not allowed.');
         }
     }
     $location = str_replace('\\', '/', __DIR__) . '/schema/dic/xliff-core/xml.xsd';
     $parts = explode('/', $location);
     if (0 === stripos($location, 'phar://')) {
         $tmpfile = tempnam(sys_get_temp_dir(), 'sf2');
         if ($tmpfile) {
             copy($location, $tmpfile);
             $parts = explode('/', str_replace('\\', '/', $tmpfile));
         }
     }
     $drive = '\\' === DIRECTORY_SEPARATOR ? array_shift($parts) . '/' : '';
     $location = 'file:///' . $drive . implode('/', array_map('rawurlencode', $parts));
     $source = file_get_contents(__DIR__ . '/schema/dic/xliff-core/xliff-core-1.2-strict.xsd');
     $source = str_replace('http://www.w3.org/2001/xml.xsd', $location, $source);
     if (!@$dom->schemaValidateSource($source)) {
         throw new \RuntimeException(implode("\n", $this->getXmlErrors($internalErrors)));
     }
     $dom->normalizeDocument();
     libxml_use_internal_errors($internalErrors);
     return simplexml_import_dom($dom);
 }
Example #12
0
function ext_module_manifest_parse($xml)
{
    $dom = new DOMDocument();
    $dom->loadXML($xml);
    if ($dom->schemaValidateSource(ext_module_manifest_validate())) {
        $root = $dom->getElementsByTagName('manifest')->item(0);
        $vcode = explode(',', $root->getAttribute('versionCode'));
        $manifest['versions'] = array();
        if (is_array($vcode)) {
            foreach ($vcode as $v) {
                $v = trim($v);
                if (!empty($v)) {
                    $manifest['versions'][] = $v;
                }
            }
            $manifest['versions'][] = '0.52';
            $manifest['versions'][] = '0.6';
            $manifest['versions'] = array_unique($manifest['versions']);
        }
        $manifest['install'] = $root->getElementsByTagName('install')->item(0)->textContent;
        $manifest['uninstall'] = $root->getElementsByTagName('uninstall')->item(0)->textContent;
        $manifest['upgrade'] = $root->getElementsByTagName('upgrade')->item(0)->textContent;
        $application = $root->getElementsByTagName('application')->item(0);
        $manifest['application'] = array('name' => trim($application->getElementsByTagName('name')->item(0)->textContent), 'identifie' => trim($application->getElementsByTagName('identifie')->item(0)->textContent), 'version' => trim($application->getElementsByTagName('version')->item(0)->textContent), 'type' => trim($application->getElementsByTagName('type')->item(0)->textContent), 'ability' => trim($application->getElementsByTagName('ability')->item(0)->textContent), 'description' => trim($application->getElementsByTagName('description')->item(0)->textContent), 'author' => trim($application->getElementsByTagName('author')->item(0)->textContent), 'url' => trim($application->getElementsByTagName('url')->item(0)->textContent), 'setting' => trim($application->getAttribute('setting')) == 'true');
        $platform = $root->getElementsByTagName('platform')->item(0);
        if (!empty($platform)) {
            $manifest['platform'] = array('subscribes' => array(), 'handles' => array(), 'isrulefields' => false);
            $subscribes = $platform->getElementsByTagName('subscribes')->item(0);
            if (!empty($subscribes)) {
                $messages = $subscribes->getElementsByTagName('message');
                for ($i = 0; $i < $messages->length; $i++) {
                    $t = $messages->item($i)->getAttribute('type');
                    if (!empty($t)) {
                        $manifest['platform']['subscribes'][] = $t;
                    }
                }
            }
            $handles = $platform->getElementsByTagName('handles')->item(0);
            if (!empty($handles)) {
                $messages = $handles->getElementsByTagName('message');
                for ($i = 0; $i < $messages->length; $i++) {
                    $t = $messages->item($i)->getAttribute('type');
                    if (!empty($t)) {
                        $manifest['platform']['handles'][] = $t;
                    }
                }
            }
            $rule = $platform->getElementsByTagName('rule')->item(0);
            if (!empty($rule) && $rule->getAttribute('embed') == 'true') {
                $manifest['platform']['isrulefields'] = true;
            }
        }
        $bindings = $root->getElementsByTagName('bindings')->item(0);
        if (!empty($bindings)) {
            global $points;
            if (!empty($points)) {
                $ps = array_keys($points);
                $manifest['bindings'] = array();
                foreach ($ps as $p) {
                    $define = $bindings->getElementsByTagName($p)->item(0);
                    $manifest['bindings'][$p] = _ext_module_manifest_entries($define);
                }
            }
        }
    } else {
        $err = error_get_last();
        if ($err['type'] == 2) {
            return $err['message'];
        }
    }
    return $manifest;
}
function validaXML($cadena_xml = "", $validaSAT = true)
{
    $r = array('success' => true, 'numCtaPago' => "", 'error' => '', 'xml' => '');
    if (trim($cadena_xml) == "") {
        $r['success'] = false;
        $r['error'] = 'XML vacio';
    }
    $xml = new DOMDocument();
    //    $ctx = stream_context_create([
    //        'ssl' => [
    //            'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT,
    //        ],
    //    ]);
    $archivo_esquema = 'res/xml/cfdv32.xsd';
    $esquema = file_get_contents($archivo_esquema, false);
    // Validamos solamente la estructura del XML para ver si cumple con la estructura del SAT
    if ($cadena_xml !== false) {
        $datos = array("rfc_emisor" => "", "rfc_receptor" => "", "total" => "", "uuid" => "");
        $xml->loadXML($cadena_xml);
        // establecer el gestor de errores definido por el usuario
        $gestor_errores_antiguo = set_error_handler("miGestorDeErrores");
        $error = $xml->schemaValidateSource($esquema);
        //$error = true;
        // Reestablecemos el gestor de errores definido por el sistema
        restore_error_handler();
        if ($error == false || is_string($error) || is_array($error) && $error['success'] == false) {
            $r['success'] = false;
            $msg = is_array($error) || is_string($error) ? "" . $error['errstr'] : "El archivo XML no cumple con la estructura del CFDI del SAT.";
            $r['error'] = "XML con formato incorrecto.<br><br>" . $msg;
        } else {
            $array = XML2Array::createArray($cadena_xml);
            $r['xml'] = $array;
            $error = array();
            if (isset($array) && $array != false && count($array) > 0) {
                if (!valid_rfc($array['cfdi:Comprobante']['cfdi:Emisor']['@attributes']['rfc'])) {
                    $error[] = "RFC del emisor invalido";
                    $r['success'] = false;
                } else {
                    $r['rfc_emisor'] = $datos['rfc_emisor'] = $array['cfdi:Comprobante']['cfdi:Emisor']['@attributes']['rfc'];
                }
                if (!valid_rfc($array['cfdi:Comprobante']['cfdi:Receptor']['@attributes']['rfc'])) {
                    $error[] = "RFC del receptor inválido";
                    $r['success'] = false;
                } else {
                    $r['rfc_receptor'] = $datos['rfc_receptor'] = $array['cfdi:Comprobante']['cfdi:Receptor']['@attributes']['rfc'];
                }
                if (isset($array['cfdi:Comprobante']['@attributes']['NumCtaPago']) && $array['cfdi:Comprobante']['@attributes']['NumCtaPago']) {
                    $r['numCtaPago'] = $array['cfdi:Comprobante']['@attributes']['NumCtaPago'];
                }
                if (isset($array['cfdi:Comprobante']['@attributes']['total']) && $array['cfdi:Comprobante']['@attributes']['total']) {
                    $datos['total'] = $array['cfdi:Comprobante']['@attributes']['total'];
                } else {
                    //$datos['total'] = 0;
                    $error[] = "La factura no tiene importe de TOTAL";
                    $r['success'] = false;
                }
                $datos['uuid'] = $array['cfdi:Comprobante']['cfdi:Complemento']['tfd:TimbreFiscalDigital']['@attributes']['UUID'];
                if (isset($array['cfdi:Comprobante']['cfdi:Complemento']['tfd:TimbreFiscalDigital']['@attributes']['UUID']) && $array['cfdi:Comprobante']['cfdi:Complemento']['tfd:TimbreFiscalDigital']['@attributes']['UUID']) {
                    $datos['uuid'] = $array['cfdi:Comprobante']['cfdi:Complemento']['tfd:TimbreFiscalDigital']['@attributes']['UUID'];
                } else {
                    $error[] = "La factura no tiene UUID";
                    $r['success'] = false;
                }
                if ($r['success'] && $validaSAT === true) {
                    //$t = json_encode(array('success' => true, 'mensaje' => 'Validando con el SAT'));
                    $sat = validarXMLenSAT($datos);
                    if (substr($sat['CodigoEstatus'], 0, 1) == "N") {
                        $error[] = "El SAT reporta: " . $sat['CodigoEstatus'] . "<br>Estado: " . $sat['Estado'];
                        $r['success'] = false;
                    }
                }
                $r['error'] = "";
                if (count($error) > 0) {
                    $r['error'] = implode("<br><br><br>", $error);
                }
            }
        }
    }
    return $r;
}
Example #14
0
/**
 * Import a .mpr (moodle profile runs) file into moodle.
 *
 * See {@link profiling_export_runs()} for more details about the
 * implementation of .mpr files.
 *
 * @param string $file filesystem fullpath to target .mpr file.
 * @param string $commentprefix prefix to add to the comments of all the imported runs.
 * @return boolean the mpr file has been successfully imported (true) or no (false).
 */
function profiling_import_runs($file, $commentprefix = '')
{
    global $DB;
    // Any problem with the file or its directory, abort.
    if (!file_exists($file) or !is_readable($file) or !is_writable(dirname($file))) {
        return false;
    }
    // Unzip the file into temp directory.
    $tmpdir = dirname($file) . '/' . time() . '_' . random_string(4);
    $fp = get_file_packer('application/vnd.moodle.profiling');
    $status = $fp->extract_to_pathname($file, $tmpdir);
    // Look for master file and verify its format.
    if ($status) {
        $mfile = $tmpdir . '/moodle_profiling_runs.xml';
        if (!file_exists($mfile) or !is_readable($mfile)) {
            $status = false;
        } else {
            $mdom = new DOMDocument();
            if (!$mdom->load($mfile)) {
                $status = false;
            } else {
                $status = @$mdom->schemaValidateSource(profiling_get_import_main_schema());
            }
        }
    }
    // Verify all detail files exist and verify their format.
    if ($status) {
        $runs = $mdom->getElementsByTagName('run');
        foreach ($runs as $run) {
            $rfile = $tmpdir . '/' . clean_param($run->getAttribute('ref'), PARAM_FILE);
            if (!file_exists($rfile) or !is_readable($rfile)) {
                $status = false;
            } else {
                $rdom = new DOMDocument();
                if (!$rdom->load($rfile)) {
                    $status = false;
                } else {
                    $status = @$rdom->schemaValidateSource(profiling_get_import_run_schema());
                }
            }
        }
    }
    // Everything looks ok, let's import all the runs.
    if ($status) {
        reset($runs);
        foreach ($runs as $run) {
            $rfile = $tmpdir . '/' . $run->getAttribute('ref');
            $rdom = new DOMDocument();
            $rdom->load($rfile);
            $runarr = array();
            $runarr['runid'] = clean_param($rdom->getElementsByTagName('runid')->item(0)->nodeValue, PARAM_ALPHANUMEXT);
            $runarr['url'] = clean_param($rdom->getElementsByTagName('url')->item(0)->nodeValue, PARAM_CLEAN);
            $runarr['runreference'] = clean_param($rdom->getElementsByTagName('runreference')->item(0)->nodeValue, PARAM_INT);
            $runarr['runcomment'] = $commentprefix . clean_param($rdom->getElementsByTagName('runcomment')->item(0)->nodeValue, PARAM_CLEAN);
            $runarr['timecreated'] = time();
            // Now.
            $runarr['totalexecutiontime'] = clean_param($rdom->getElementsByTagName('totalexecutiontime')->item(0)->nodeValue, PARAM_INT);
            $runarr['totalcputime'] = clean_param($rdom->getElementsByTagName('totalcputime')->item(0)->nodeValue, PARAM_INT);
            $runarr['totalcalls'] = clean_param($rdom->getElementsByTagName('totalcalls')->item(0)->nodeValue, PARAM_INT);
            $runarr['totalmemory'] = clean_param($rdom->getElementsByTagName('totalmemory')->item(0)->nodeValue, PARAM_INT);
            $runarr['data'] = clean_param($rdom->getElementsByTagName('data')->item(0)->nodeValue, PARAM_CLEAN);
            // If the runid does not exist, insert it.
            if (!$DB->record_exists('profiling', array('runid' => $runarr['runid']))) {
                $DB->insert_record('profiling', $runarr);
            } else {
                return false;
            }
        }
    }
    // Clean the temp directory used for import.
    remove_dir($tmpdir);
    return $status;
}
<?php

$doc = new DOMDocument();
$doc->load(dirname(__FILE__) . "/book-attr.xml");
$xsd = file_get_contents(dirname(__FILE__) . "/book.xsd");
$doc->schemaValidateSource($xsd);
foreach ($doc->getElementsByTagName('book') as $book) {
    var_dump($book->getAttribute('is-hardback'));
}
 /**
  * Validate a document based on a schema.
  *
  * @param      string A string containing the schema.
  *
  * @return     bool True if the validation is successful; false otherwise.
  *
  * @author     Noah Fontes <*****@*****.**>
  * @since      1.0.0
  */
 public function schemaValidateSource($source)
 {
     $luie = libxml_use_internal_errors(true);
     libxml_clear_errors();
     // gotta do the @ to suppress PHP warnings when the schema cannot be loaded or is invalid
     if (!($result = @parent::schemaValidateSource($source))) {
         $errors = array();
         foreach (libxml_get_errors() as $error) {
             $errors[] = sprintf('[%s #%d] Line %d: %s', $error->level == LIBXML_ERR_WARNING ? 'Warning' : ($error->level == LIBXML_ERR_ERROR ? 'Error' : 'Fatal'), $error->code, $error->line, $error->message);
         }
         libxml_clear_errors();
         libxml_use_internal_errors($luie);
         throw new DOMException(sprintf('XML Schema validation failed due to the following error%s: ' . "\n\n%s", count($errors) > 1 ? 's' : '', implode("\n", $errors)));
     }
     libxml_use_internal_errors($luie);
     return $result;
 }
Example #17
0
    /**
     * Check whether the generated xsd is valid and we can use it agains some
     * custom xml
     */
    public function testXsd()
    {
        $generator = new Xsd('http://ns.foo.com');
        $result = $generator->generate($this->getSchema());
        $xml = <<<XML
<news xmlns="http://ns.foo.com">
\t<tags>foo</tags>
\t<tags>bar</tags>
\t<receiver>
\t\t<title>bar</title>
\t</receiver>
\t<resources>
\t\t<web>
\t\t\t<name>foo</name>
\t\t\t<url>http://google.com</url>
\t\t</web>
\t</resources>
\t<resources>
\t\t<location>
\t\t\t<lat>13</lat>
\t\t\t<long>-37</long>
\t\t</location>
\t</resources>
\t<read>1</read>
\t<source>
\t\t<web>
\t\t\t<name>foo</name>
\t\t\t<url>http://google.com</url>
\t\t</web>
\t</source>
\t<author>
\t\t<title>test</title>
\t\t<categories>foo</categories>
\t\t<categories>bar</categories>
\t\t<locations>
\t\t\t<lat>13</lat>
\t\t\t<long>-37</long>
\t\t</locations>
\t</author>
\t<sendDate>2014-07-22</sendDate>
\t<readDate>2014-07-22T22:47:00</readDate>
\t<expires>P1M</expires>
\t<price>13.37</price>
\t<rating>4</rating>
\t<content>foobar</content>
\t<coffeeTime>16:00:00</coffeeTime>
</news>
XML;
        $dom = new \DOMDocument();
        $dom->loadXML($xml);
        $this->assertTrue($dom->schemaValidateSource($result));
    }
Example #18
0
 /**
  * @param string $value
  * @param string $schema
  *
  * @throws \RREST\Exception\InvalidXMLException
  * @throws \RREST\Exception\InvalidResponsePayloadBodyException
  */
 public function assertResponseXML($value, $schema)
 {
     $thowInvalidXMLException = function ($exceptionClassName) {
         $invalidBodyError = [];
         $libXMLErrors = libxml_get_errors();
         libxml_clear_errors();
         if (empty($libXMLErrors) === false) {
             foreach ($libXMLErrors as $libXMLError) {
                 $message = $libXMLError->message . ' (line: ' . $libXMLError->line . ')';
                 $invalidBodyError[] = new Error($message, 'invalid-response-xml');
             }
             if (empty($invalidBodyError) == false) {
                 throw new $exceptionClassName($invalidBodyError);
             }
         }
     };
     //validate XML
     $originalErrorLevel = libxml_use_internal_errors(true);
     $valueDOM = new \DOMDocument();
     $valueDOM->loadXML($value);
     $thowInvalidXMLException('RREST\\Exception\\InvalidXMLException');
     //validate XMLSchema
     $valueDOM->schemaValidateSource($schema);
     $thowInvalidXMLException('RREST\\Exception\\InvalidResponsePayloadBodyException');
     libxml_use_internal_errors($originalErrorLevel);
 }
Example #19
0
 /**
  * Validate dom document
  *
  * @param \DOMDocument $dom
  * @param string $schema Absolute schema file path or URN
  * @param string $errorFormat
  * @return array of errors
  * @throws \Exception
  */
 public static function validateDomDocument(\DOMDocument $dom, $schema, $errorFormat = self::ERROR_FORMAT_DEFAULT)
 {
     if (!self::$urnResolver) {
         self::$urnResolver = new UrnResolver();
     }
     $schema = self::$urnResolver->getRealPath($schema);
     libxml_use_internal_errors(true);
     try {
         if (file_exists($schema)) {
             $result = $dom->schemaValidate($schema);
         } else {
             $result = $dom->schemaValidateSource($schema);
         }
         $errors = [];
         if (!$result) {
             $validationErrors = libxml_get_errors();
             if (count($validationErrors)) {
                 foreach ($validationErrors as $error) {
                     $errors[] = self::_renderErrorMessage($error, $errorFormat);
                 }
             } else {
                 $errors[] = 'Unknown validation error';
             }
         }
     } catch (\Exception $exception) {
         libxml_use_internal_errors(false);
         throw $exception;
     }
     libxml_use_internal_errors(false);
     return $errors;
 }
function setting_module_manifest_compat($modulename)
{
    $manifest = array();
    $filename = IA_ROOT . '/source/modules/' . $modulename . '/manifest.xml';
    if (!file_exists($filename)) {
        return array();
    }
    $xml = str_replace(array('&'), array('&amp;'), file_get_contents($filename));
    $xml = @simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
    if (empty($xml)) {
        return array();
    }
    $dom = new DOMDocument();
    @$dom->load($filename);
    if (@$dom->schemaValidateSource(setting_module_manifest_validate_050())) {
        $attributes = $xml->attributes();
        $manifest['versions'] = explode(',', strval($attributes['versionCode']));
        if (is_array($manifest['versions'])) {
            foreach ($manifest['versions'] as &$v) {
                $v = trim($v);
                if (empty($v)) {
                    unset($v);
                }
            }
        }
        $manifest['version'] = '0.5';
        $manifest['install'] = strval($xml->install);
        $manifest['uninstall'] = strval($xml->uninstall);
        $manifest['upgrade'] = strval($xml->upgrade);
        $attributes = $xml->application->attributes();
        $manifest['application'] = array('name' => trim(strval($xml->application->name)), 'identifie' => trim(strval($xml->application->identifie)), 'version' => trim(strval($xml->application->version)), 'ability' => trim(strval($xml->application->ability)), 'description' => trim(strval($xml->application->description)), 'author' => trim(strval($xml->application->author)), 'url' => trim(strval($xml->application->url)), 'setting' => trim(strval($attributes['setting'])) == 'true');
        $rAttrs = array();
        if ($xml->platform && $xml->platform->rule) {
            $rAttrs = $xml->platform->rule->attributes();
        }
        $mAttrs = array();
        if ($xml->platform && $xml->platform->menus) {
            $mAttrs = $xml->platform->menus->attributes();
        }
        $manifest['platform'] = array('subscribes' => array(), 'handles' => array(), 'isrulefields' => trim(strval($rAttrs['embed'])) == 'true', 'options' => array(), 'ismenus' => trim(strval($mAttrs['embed'])) == 'true', 'menus' => array());
        if ($xml->platform->subscribes->message) {
            foreach ($xml->platform->subscribes->message as $msg) {
                $attrs = $msg->attributes();
                $manifest['platform']['subscribes'][] = trim(strval($attrs['type']));
            }
        }
        if ($xml->platform->handles->message) {
            foreach ($xml->platform->handles->message as $msg) {
                $attrs = $msg->attributes();
                $manifest['platform']['handles'][] = trim(strval($attrs['type']));
            }
        }
        if ($manifest['platform']['isrulefields'] && $xml->platform->rule->option) {
            foreach ($xml->platform->rule->option as $msg) {
                $attrs = $msg->attributes();
                $manifest['platform']['options'][] = array('title' => trim(strval($attrs['title'])), 'do' => trim(strval($attrs['do'])), 'state' => trim(strval($attrs['state'])));
            }
        }
        if ($manifest['platform']['ismenus'] && $xml->platform->menus->menu) {
            foreach ($xml->platform->menus->menu as $msg) {
                $attrs = $msg->attributes();
                $manifest['platform']['menus'][] = array('title' => trim(strval($attrs['title'])), 'do' => trim(strval($attrs['do'])));
            }
        }
        $hAttrs = array();
        if ($xml->site && $xml->site->home) {
            $hAttrs = $xml->site->home->attributes();
        }
        $pAttrs = array();
        if ($xml->site && $xml->site->profile) {
            $pAttrs = $xml->site->profile->attributes();
        }
        $mAttrs = array();
        if ($xml->site && $xml->site->menus) {
            $mAttrs = $xml->site->menus->attributes();
        }
        $manifest['site'] = array('home' => trim(strval($hAttrs['embed'])) == 'true', 'profile' => trim(strval($pAttrs['embed'])) == 'true', 'ismenus' => trim(strval($mAttrs['embed'])) == 'true', 'menus' => array());
        if ($manifest['site']['ismenus'] && $xml->site->menus->menu) {
            foreach ($xml->site->menus->menu as $msg) {
                $attrs = $msg->attributes();
                $manifest['site']['menus'][] = array('title' => trim(strval($attrs['title'])), 'do' => trim(strval($attrs['do'])));
            }
        }
    } else {
        $attributes = $xml->attributes();
        $manifest['version'] = strval($attributes['versionCode']);
        $manifest['install'] = strval($xml->install);
        $manifest['uninstall'] = strval($xml->uninstall);
        $manifest['upgrade'] = strval($xml->upgrade);
        $attributes = $xml->application->attributes();
        $manifest['application'] = array('name' => strval($xml->application->name), 'identifie' => strval($xml->application->identifie), 'version' => strval($xml->application->version), 'ability' => strval($xml->application->ability), 'description' => strval($xml->application->description), 'author' => strval($xml->application->author), 'setting' => strval($attributes['setting']) == 'true');
        $hooks = @(array) $xml->hooks->children();
        if (!empty($hooks['hook'])) {
            foreach ((array) $hooks['hook'] as $hook) {
                $manifest['hooks'][strval($hook['name'])] = strval($hook['name']);
            }
        }
        $menus = @(array) $xml->menus->children();
        if (!empty($menus['menu'])) {
            foreach ((array) $menus['menu'] as $menu) {
                $manifest['menus'][] = array(strval($menu['name']), strval($menu['value']));
            }
        }
    }
    $ret = array();
    $ret['meta'] = $manifest;
    $ret['meta']['compact'] = $manifest['version'];
    global $points;
    if ($ret['meta']['compact'] == '0.41' || $ret['meta']['compact'] == '0.4') {
        //Compact 0.41
        $ret['convert'] = setting_module_convert($manifest);
        $ret['convert']['compact'] = $manifest['version'];
        $ret['convert']['type'] = 'other';
        foreach ($points as $p => $row) {
            $ret['convert'][$p] = array();
        }
        $handles = iunserializer($ret['convert']['handles']);
        if ($ret['meta']['hooks'] && $ret['meta']['hooks']['rule']) {
            $handles[] = 'text';
            $ret['convert']['isrulefields'] = true;
        }
        $ret['convert']['handles'] = iserializer($handles);
        if (is_array($ret['meta']['menus'])) {
            foreach ($ret['meta']['menus'] as $row) {
                $opt = array();
                $opt['title'] = $row[0];
                $urls = parse_url($row[1]);
                parse_str($urls['query'], $vars);
                $opt['do'] = $vars['do'];
                $opt['state'] = $vars['state'];
                if (!empty($opt['title']) && !empty($opt['do'])) {
                    $ret['convert']['rule'][] = $opt;
                }
            }
        }
        $m = $ret['convert'];
        $m['install'] = $manifest['install'];
        $m['uninstall'] = $manifest['uninstall'];
        $m['upgrade'] = $manifest['upgrade'];
        $m['handles'] = iunserializer($m['handles']);
        $versions = IMS_VERSION;
        $setting = $m['settings'] ? 'true' : 'false';
        $handles = '';
        foreach ($m['handles'] as $h) {
            $handles .= "\r\n\t\t\t<message type=\"{$h}\" />";
        }
        $rule = $m['isrulefields'] ? 'true' : 'false';
        $bindings = '';
        foreach ($points as $p => $row) {
            if (is_array($m[$p]) && !empty($m[$p])) {
                $piece = "\r\n\t\t<{$p}{$calls[$p]}>";
                foreach ($m[$p] as $entry) {
                    if (!empty($entry['title']) && !empty($entry['do'])) {
                        $direct = $entry['direct'] ? 'true' : 'false';
                        $piece .= "\r\n\t\t\t<entry title=\"{$entry['title']}\" do=\"{$entry['do']}\" state=\"{$entry['state']}\" direct=\"{$direct}\" />";
                    }
                }
                $piece .= "\r\n\t\t</{$p}>";
                $bindings .= $piece;
            }
        }
        $tpl = <<<TPL
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns="http://www.we7.cc" versionCode="{$versions}">
\t<application setting="{$setting}">
\t\t<name><![CDATA[{$m['title']}]]></name>
\t\t<identifie><![CDATA[{$m['name']}]]></identifie>
\t\t<version><![CDATA[{$m['version']}]]></version>
\t\t<type><![CDATA[{$manifest['application']['type']}]]></type>
\t\t<ability><![CDATA[{$m['ability']}]]></ability>
\t\t<description><![CDATA[{$m['description']}]]></description>
\t\t<author><![CDATA[{$m['author']}]]></author>
\t\t<url><![CDATA[{$m['url']}]]></url>
\t</application>
\t<platform>
\t\t<handles>{$handles}
\t\t</handles>
\t\t<rule embed="{$rule}" />
\t</platform>
\t<bindings>{$bindings}
\t</bindings>
\t<install><![CDATA[{$m['install']}]]></install>
\t<uninstall><![CDATA[{$m['uninstall']}]]></uninstall>
\t<upgrade><![CDATA[{$m['upgrade']}]]></upgrade>
</manifest>
TPL;
        $ret['manifest'] = ltrim($tpl);
        return $ret;
    }
    if ($ret['meta']['compact'] == '0.5') {
        // Compact 0.5
        $ret['convert'] = setting_module_convert($manifest);
        $ret['convert']['compact'] = $manifest['version'];
        $ret['convert']['type'] = 'other';
        foreach ($points as $p => $row) {
            $ret['convert'][$p] = array();
        }
        if (is_array($manifest['platform']['options'])) {
            foreach ($manifest['platform']['options'] as $opt) {
                $entry = array();
                $entry['title'] = $opt['title'];
                $entry['do'] = $opt['do'];
                $entry['state'] = $opt['state'];
                if (!empty($entry['title']) && !empty($entry['do'])) {
                    $ret['convert']['rule'][] = $entry;
                }
            }
        }
        if (is_array($manifest['platform']['menus'])) {
            foreach ($manifest['platform']['menus'] as $opt) {
                $entry = array();
                $entry['title'] = $opt['title'];
                $entry['do'] = $opt['do'];
                $entry['state'] = $opt['state'];
                if (!empty($entry['title']) && !empty($entry['do'])) {
                    $ret['convert']['menu'][] = $entry;
                }
            }
        }
        if (is_array($manifest['site']['menus'])) {
            foreach ($manifest['site']['menus'] as $opt) {
                $entry = array();
                $entry['title'] = $opt['title'];
                $entry['do'] = $opt['do'];
                $entry['state'] = $opt['state'];
                if (!empty($entry['title']) && !empty($entry['do'])) {
                    $ret['convert']['menu'][] = $entry;
                }
            }
        }
        $calls = array();
        if (!empty($manifest['site']['home'])) {
            $calls['home'] = ' call="getHomeTiles"';
            $ret['convert']['home'][] = array('call' => 'getHomeTiles');
        }
        if (!empty($manifest['site']['profile'])) {
            $calls['profile'] = ' call="getProfileTiles"';
            $ret['convert']['profile'][] = array('call' => 'getProfileTiles');
        }
        $m = $ret['convert'];
        $versions = IMS_VERSION;
        $setting = $m['settings'] ? 'true' : 'false';
        $subscribes = '';
        foreach ($manifest['platform']['subscribes'] as $s) {
            $subscribes .= "\r\n\t\t\t<message type=\"{$s}\" />";
        }
        $handles = '';
        foreach ($manifest['platform']['handles'] as $h) {
            $handles .= "\r\n\t\t\t<message type=\"{$h}\" />";
        }
        $rule = $m['isrulefields'] ? 'true' : 'false';
        $bindings = '';
        foreach ($points as $p => $row) {
            if (is_array($m[$p]) && !empty($m[$p])) {
                $piece = "\r\n\t\t<{$p}{$calls[$p]}>";
                foreach ($m[$p] as $entry) {
                    if (!empty($entry['title']) && !empty($entry['do'])) {
                        $direct = $entry['direct'] ? 'true' : 'false';
                        $piece .= "\r\n\t\t\t<entry title=\"{$entry['title']}\" do=\"{$entry['do']}\" state=\"{$entry['state']}\" direct=\"{$direct}\" />";
                    }
                }
                $piece .= "\r\n\t\t</{$p}>";
                $bindings .= $piece;
            }
        }
        $tpl = <<<TPL
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns="http://www.we7.cc" versionCode="{$versions}">
\t<application setting="{$setting}">
\t\t<name><![CDATA[{$m['title']}]]></name>
\t\t<identifie><![CDATA[{$m['name']}]]></identifie>
\t\t<version><![CDATA[{$m['version']}]]></version>
\t\t<type><![CDATA[{$manifest['application']['type']}]]></type>
\t\t<ability><![CDATA[{$m['ability']}]]></ability>
\t\t<description><![CDATA[{$m['description']}]]></description>
\t\t<author><![CDATA[{$m['author']}]]></author>
\t\t<url><![CDATA[{$m['url']}]]></url>
\t</application>
\t<platform>
\t\t<subscribes>{$subscribes}
\t\t</subscribes>
\t\t<handles>{$handles}
\t\t</handles>
\t\t<rule embed="{$rule}" />
\t</platform>
\t<bindings>{$bindings}
\t</bindings>
\t<install><![CDATA[{$m['install']}]]></install>
\t<uninstall><![CDATA[{$m['uninstall']}]]></uninstall>
\t<upgrade><![CDATA[{$m['upgrade']}]]></upgrade>
</manifest>
TPL;
        $ret['manifest'] = ltrim($tpl);
        return $ret;
    }
    return array();
}
Example #21
0
 /**
  * Validates the current document according to the given schema file content.
  *
  * @param string $source content of a schema file
  *
  * @return bool true on success
  *
  * @throws \DomException in case of validation errors or empty schema
  */
 public function schemaValidateSource($source)
 {
     if (empty($source)) {
         throw new \DOMException('Schema is empty.');
     }
     $user_error_handling = $this->enableErrorHandling();
     $success = parent::schemaValidateSource($source);
     $this->handleErrors('Validating the document failed. Details are:' . PHP_EOL . PHP_EOL, PHP_EOL . 'Please fix the mentioned errors or use another schema.', $user_error_handling);
     return $success;
 }
Example #22
0
 /**
  * Validates the Responses-Only XML against the Completed Responses XML Schema
  */
 public function validateCompletedResponseXML()
 {
     $xml = new DOMDocument();
     $xml->loadXML($this->toXML());
     if (!$xml->schemaValidateSource($this->parent->fetchCompletedResponseSchema())) {
         $errors = libxml_get_errors();
         if (count($errors)) {
             throw new Exception('XML error on line ' . $errors[0]->line . ': ' . $errors[0]->message);
         }
     }
 }
    /**
     * @param  \DOMDocument              $dom
     * @throws \InvalidArgumentException When xml doesn't validate its xsd schema
     */
    protected function validate(\DOMDocument $dom)
    {
        $restRoutinglocation = realpath(__DIR__ . '/../../Resources/config/schema/routing/rest_routing-1.0.xsd');
        $routinglocation = realpath(__DIR__ . '/../../Resources/config/schema/routing/routing-1.0.xsd');
        $source = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<xsd:schema xmlns="http://symfony.com/schema"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://symfony.com/schema"
    elementFormDefault="qualified">

    <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
    <xsd:import namespace="http://friendsofsymfony.github.com/schema/rest" schemaLocation="{$restRoutinglocation}" />
    <xsd:import namespace="http://symfony.com/schema/routing" schemaLocation="{$routinglocation}" />
</xsd:schema>
EOF;
        $current = libxml_use_internal_errors(true);
        libxml_clear_errors();
        if (!$dom->schemaValidateSource($source)) {
            throw new \InvalidArgumentException(implode("\n", $this->getXmlErrors_($current)));
        }
        libxml_use_internal_errors($current);
    }
Example #24
0
 /**
  * Validates and parses the given file into a DOMDocument.
  *
  * @param string       $file
  * @param \DOMDocument $dom
  * @param string       $schema source of the schema
  *
  * @throws InvalidResourceException
  */
 private function validateSchema($file, \DOMDocument $dom, $schema)
 {
     $internalErrors = libxml_use_internal_errors(true);
     $disableEntities = libxml_disable_entity_loader(false);
     if (!@$dom->schemaValidateSource($schema)) {
         libxml_disable_entity_loader($disableEntities);
         throw new InvalidResourceException(sprintf('Invalid resource provided: "%s"; Errors: %s', $file, implode("\n", $this->getXmlErrors($internalErrors))));
     }
     libxml_disable_entity_loader($disableEntities);
     $dom->normalizeDocument();
     libxml_clear_errors();
     libxml_use_internal_errors($internalErrors);
 }
Example #25
0
 /**
  * query
  * 
  * @param string $xml
  * @param string $schema
  * @return array 
  */
 public function query($xml, $schema, $productId, $compatible = false)
 {
     $code = API::ERROR_NONE;
     $info = '';
     if (empty($xml)) {
         $code = API::ERROR_QUERY_EMPTY;
         $info = Yii::t('API', 'query empty error info');
     } else {
         Yii::app()->request->stripSlashes($xml);
         $xml = preg_replace("/>\\s+</", "><", $xml);
         libxml_use_internal_errors(true);
         $dom = new DOMDocument();
         $dom->loadXML($xml);
         if ($dom->schemaValidateSource($schema)) {
             $query = $dom->getElementsByTagName('query');
             $query = $query->item(0);
             $infoType = strtolower($query->getAttribute('table'));
             $showFieldArr = $query->getAttribute('select') ? explode(',', $query->getAttribute('select')) : null;
             $order = $query->getAttribute('order') ? $query->getAttribute('order') : null;
             $isAsc = $query->getAttribute('asc') ? $query->getAttribute('asc') : false;
             $orderArr = $order ? array($order => $isAsc) : null;
             $currentPage = $query->getAttribute('page') ? $query->getAttribute('page') : 1;
             $pageSize = $query->getAttribute('size') ? $query->getAttribute('size') : 100;
             $arr = array();
             $searchRowArr = $this->getSearchRowArr($query->firstChild, $arr, $infoType, $compatible);
             $result = ExportService::getExportData($infoType, $searchRowArr, $productId, $showFieldArr, $orderArr, null, $pageSize, $currentPage);
             $detail = $result['detail'];
             if (CommonService::$ApiResult['FAIL'] == $result['status']) {
                 $code = API::ERROR_QUERY;
                 $info = $detail;
             } else {
                 $list = array();
                 if ('count(*)' == $showFieldArr[0]) {
                     $list = $detail;
                 } else {
                     foreach ($detail as $val) {
                         $id = $val['id'];
                         if ($compatible) {
                             foreach ($val as $key => $field) {
                                 unset($val[$key]);
                                 $key = $this->fieldNew2Old($key, $infoType);
                                 $val[$key] = $field;
                             }
                         }
                         $list[$id] = $val;
                     }
                 }
                 $info['QueryList'] = $list;
                 $info['size'] = $pageSize;
                 $info['page'] = $currentPage;
             }
         } else {
             $code = API::ERROR_QUERY_EMPTY;
             $info = Yii::t('API', 'query xml invalid info');
         }
     }
     return array($code, $info);
 }
<?php

$doc = new DOMDocument();
$doc->load(dirname(__FILE__) . "/book.xml");
$xsd = file_get_contents(dirname(__FILE__) . "/book.xsd");
$result = $doc->schemaValidateSource($xsd);
var_dump($result);
Example #27
0
    /**
     * Validates a documents XML schema.
     *
     * @param \DOMDocument $dom
     *
     * @return Boolean
     *
     * @throws RuntimeException When extension references a non-existent XSD file
     */
    public function validateSchema(\DOMDocument $dom)
    {
        $schemaLocations = array('http://thelia.net/schema/dic/config' => str_replace('\\', '/', __DIR__ . '/schema/dic/config/thelia-1.0.xsd'));
        $tmpfiles = array();
        $imports = '';
        foreach ($schemaLocations as $namespace => $location) {
            $parts = explode('/', $location);
            if (0 === stripos($location, 'phar://')) {
                $tmpfile = tempnam(sys_get_temp_dir(), 'sf2');
                if ($tmpfile) {
                    copy($location, $tmpfile);
                    $tmpfiles[] = $tmpfile;
                    $parts = explode('/', str_replace('\\', '/', $tmpfile));
                }
            }
            $drive = '\\' === DIRECTORY_SEPARATOR ? array_shift($parts) . '/' : '';
            $location = 'file:///' . $drive . implode('/', array_map('rawurlencode', $parts));
            $imports .= sprintf('  <xsd:import namespace="%s" schemaLocation="%s" />' . "\n", $namespace, $location);
        }
        $source = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<xsd:schema xmlns="http://symfony.com/schema"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://symfony.com/schema"
    elementFormDefault="qualified">

    <xsd:import namespace="http://www.w3.org/XML/1998/namespace"/>
{$imports}
</xsd:schema>
EOF;
        $valid = @$dom->schemaValidateSource($source);
        foreach ($tmpfiles as $tmpfile) {
            @unlink($tmpfile);
        }
        return $valid;
    }
 /**
  * Load Xliff File, validate it
  * and create DOMDocument object from it
  *
  * @param string $file full path to XLIFF xml file
  *
  * @throws \Lampcms\DevException
  * @throws \Exception
  */
 protected function parseFile($file)
 {
     d('parsing $file: ' . $file);
     $oDom = new \DOMDocument();
     $current = \libxml_use_internal_errors(true);
     if (!@$oDom->load($file, LIBXML_COMPACT)) {
         $err = \implode("\n", $this->getXmlErrors());
         throw new \Lampcms\DevException($err);
     }
     $location = \str_replace('\\', '/', LAMPCMS_CONFIG_DIR . DIRECTORY_SEPARATOR) . 'xml.xsd';
     $parts = \explode('/', $location);
     $drive = '\\' === DIRECTORY_SEPARATOR ? \array_shift($parts) . '/' : '';
     $location = 'file:///' . $drive . implode('/', \array_map('rawurlencode', $parts));
     d('$location: ' . $location);
     $source = \file_get_contents(LAMPCMS_CONFIG_DIR . DIRECTORY_SEPARATOR . 'xliff-core-1.2-strict.xsd');
     $source = \str_replace('http://www.w3.org/2001/xml.xsd', $location, $source);
     if (!@$oDom->schemaValidateSource($source)) {
         d('schemaValidateSource() failed');
         throw new \Lampcms\DevException(implode("\n", $this->getXmlErrors()));
     }
     $oDom->validateOnParse = true;
     $oDom->normalizeDocument();
     d('cp');
     \libxml_use_internal_errors($current);
     $this->xml2array($oDom);
 }
    /**
     * Validates a documents XML schema.
     *
     * @param \DOMDocument $dom
     *
     * @return bool
     *
     * @throws RuntimeException When extension references a non-existent XSD file
     */
    public function validateSchema(\DOMDocument $dom)
    {
        $schemaLocations = array('http://symfony.com/schema/dic/services' => str_replace('\\', '/', __DIR__ . '/schema/dic/services/services-1.0.xsd'));
        if ($element = $dom->documentElement->getAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'schemaLocation')) {
            $items = preg_split('/\\s+/', $element);
            for ($i = 0, $nb = count($items); $i < $nb; $i += 2) {
                if (!$this->container->hasExtension($items[$i])) {
                    continue;
                }
                if (($extension = $this->container->getExtension($items[$i])) && false !== $extension->getXsdValidationBasePath()) {
                    $path = str_replace($extension->getNamespace(), str_replace('\\', '/', $extension->getXsdValidationBasePath()) . '/', $items[$i + 1]);
                    if (!is_file($path)) {
                        throw new RuntimeException(sprintf('Extension "%s" references a non-existent XSD file "%s"', get_class($extension), $path));
                    }
                    $schemaLocations[$items[$i]] = $path;
                }
            }
        }
        $tmpfiles = array();
        $imports = '';
        foreach ($schemaLocations as $namespace => $location) {
            $parts = explode('/', $location);
            if (0 === stripos($location, 'phar://')) {
                $tmpfile = tempnam(sys_get_temp_dir(), 'sf2');
                if ($tmpfile) {
                    copy($location, $tmpfile);
                    $tmpfiles[] = $tmpfile;
                    $parts = explode('/', str_replace('\\', '/', $tmpfile));
                }
            }
            $drive = '\\' === DIRECTORY_SEPARATOR ? array_shift($parts) . '/' : '';
            $location = 'file:///' . $drive . implode('/', array_map('rawurlencode', $parts));
            $imports .= sprintf('  <xsd:import namespace="%s" schemaLocation="%s" />' . "\n", $namespace, $location);
        }
        $source = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<xsd:schema xmlns="http://symfony.com/schema"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://symfony.com/schema"
    elementFormDefault="qualified">

    <xsd:import namespace="http://www.w3.org/XML/1998/namespace"/>
{$imports}
</xsd:schema>
EOF;
        $valid = @$dom->schemaValidateSource($source);
        foreach ($tmpfiles as $tmpfile) {
            @unlink($tmpfile);
        }
        return $valid;
    }
Example #30
0
 public function validateDocument(\DOMDocument $xml, $schema)
 {
     libxml_clear_errors();
     $errorHandling = libxml_use_internal_errors(false);
     $entities = libxml_disable_entity_loader(true);
     try {
         if (false !== stripos($schema, '<?xml')) {
             $xml->schemaValidateSource($schema);
         } else {
             $xml->schemaValidate($schema);
         }
         $errors = libxml_get_errors();
     } catch (\Exception $e) {
         $ex = new XmlValidationException('XML schema validation failed', 0, $e);
         $ex->addError(new XmlError(0, $e->getMessage()));
         throw $ex;
     } finally {
         libxml_use_internal_errors($errorHandling);
         libxml_disable_entity_loader($entities);
     }
     if (!empty($errors)) {
         $e = new XmlValidationException('XML document did not pass XML schema validation');
         foreach ($errors as $tmp) {
             $e->addError(new XmlError($tmp->level, $tmp->message));
         }
         throw $e;
     }
 }