/** * Validates the XML of this template. * @returns boolean true on sucess */ public function validate() { if ($this->working_dir !== null) { $dir = getcwd(); chdir($this->working_dir); } libxml_use_internal_errors(true); if (!$this->doc->validate()) { $this->raiseError($this->xmlError(libxml_get_errors(), "Invalid XML Configuration")); if ($this->working_dir !== null) { chdir($dir); } return false; } libxml_clear_errors(); if (count($errors) > 0) { $this->raiseError("Invalid XML Configuaration"); if ($this->working_dir !== null) { chdir($dir); } return false; } if ($this->working_dir !== null) { chdir($dir); } libxml_use_internal_errors(false); return true; }
/** * @throws SMSConfigurationException * @version : v0.1 */ public function setup() { $fileNamespace = $this->getXMLFileNamespace(); $vendor = RootClassLoader::getVendor($fileNamespace); $libPath = RootClassLoader::getLoaderByVendor($vendor)->getRootPath(); $basePath = str_replace('\\', '/', RootClassLoader::getNamespaceWithoutVendor($fileNamespace)); $filename = $this->getXMLFilename(); $fullPath = $libPath . (empty($basePath) ? '' : '/' . $basePath) . '/' . $filename; if (!file_exists($fullPath)) { throw new SMSConfigurationException('[SMSXMLMapper::setup()] XML file "' . $filename . '" in namespace "' . $fileNamespace . '" could not be found. (Full path: "' . $fullPath . '").', E_USER_ERROR); } $this->XML_DOMDocument = new \DOMDocument(); $this->XML_DOMDocument->load($fullPath); // we need to validate the document, to let the DTD be parsed and the id attribute be recognized as id by DOMDocument::getElementById(). // do not care about failures this time $this->XML_DOMDocument->validate(); }
public function testSpecialCharsFillinValidXhtml() { $this->form->bind(array('username' => '&<>&', 'password' => '&%$""<>')); $xhtml = $this->xhtmlDecl . $this->form->__toString(); $doc = new DOMDocument(); $doc->loadXML($xhtml); $this->assertTrue($doc->validate(), 'The rendered form is valid xhtml'); }
/** * Validated the current document against the defined DTD * * @return bool */ public function xmlValidateDTD() { if ($this->objDocument != null) { if ($this->objDocument->validate() !== false) { return true; } } return false; }
/** * Validate an XML document which is bound to a DTD. * * @param (string) $filename - The name of the XML document * @return (string) - Results of the validation */ function validate_xml($filename) { $doc = new DOMDocument(); $doc->validateOnParse = true; libxml_use_internal_errors(true); $doc->load($filename); if ($doc->validate()) { return 'The XML document "' . $filename . '" has validated successfully.'; } else { $result = "<b>Oh nooooo...</b><br/>"; foreach (libxml_get_errors() as $error) { $result .= $error->message . '<br/>'; } libxml_clear_errors(); return $result; } }
private function validate() { libxml_use_internal_errors(true); shopYandexmarketPlugin::path('shops.dtd'); $this->loadDom($this->data['path']['offers']); $valid = @$this->dom->validate(); $strict = waSystemConfig::isDebug(); if ((!$valid || $strict) && ($r = libxml_get_errors())) { $this->data['error'] = array(); $error = array(); if ($valid) { $this->data['error'][] = array('level' => 'info', 'message' => 'YML-файл валиден'); } else { $this->data['error'][] = array('level' => 'error', 'message' => 'YML-файл содержит ошибки'); } foreach ($r as $er) { /** * @var libXMLError $er */ $level_name = ''; switch ($er->level) { case LIBXML_ERR_WARNING: $level_name = 'LIBXML_ERR_WARNING'; break; case LIBXML_ERR_ERROR: $level_name = 'LIBXML_ERR_ERROR'; break; case LIBXML_ERR_FATAL: $level_name = 'LIBXML_ERR_FATAL'; break; } if ($er->code != 505) { $this->data['error'][] = array('level' => $valid ? 'warning' : 'error', 'message' => "{$level_name} #{$er->code} [{$er->line}:{$er->column}]: {$er->message}"); } $error[] = "Error #{$er->code}[{$er->level}] at [{$er->line}:{$er->column}]: {$er->message}"; } if ($valid && count($this->data['error']) == 1) { $this->data['error'] = array(); } $this->error(implode("\n\t", $error)); } }
function getContent() { $this->mContent = null; $source = $this->mSource; $source = str_replace('class="padded"', 'id="confluence_content"', $source); // add DTD $dtd = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">'; $source = $dtd . $source; $dom = new DOMDocument(); echo "Loading document... "; $status = $dom->loadHTML($source); $this->msgStatus($status); $this->msg("Validating document... "); $dom->validate(); $this->msgStatus(true); // we don't really care if it validates or not ;) $this->msg("Looking for node... "); $node = $dom->getElementById('confluence_content'); $this->msgStatus((bool) $node); $this->mContent = $dom->saveXML($node); return (bool) $this->mContent; }
public static function getInstance($path) { global $plugin; $plugin = $path; if (!self::$obj instanceof self) { self::$obj = new self(); $dom = new DOMDocument(); $dom->load(dirname(__FILE__) . "/{$path}/actions.xml"); if (@$dom->validate()) { $packages = $dom->getElementsByTagName("package"); foreach ($packages as $package) { $actions = $package->getElementsByTagName('action'); $action_tem = array(); foreach ($actions as $action) { $action_tem['file'] = $action->getAttributeNode('file')->value; unset($action_tem['class']); if ($action->hasAttribute('class')) { $action_tem['class'] = $action->getAttributeNode('class')->value; } $action_tem['method'] = $action->getAttributeNode('method')->value; $returns = $action->getElementsByTagName('return'); $return_tem = array(); foreach ($returns as $return) { $return_tem[$return->getAttributeNode('name')->value] = $return->nodeValue; } $action_tem['returns'] = $return_tem; self::$action_info[$package->getAttributeNode('name')->value . '_' . $action->getAttributeNode('name')->value] = $action_tem; } // var_dump( self::$action_info); } } else { echo "此XML文件不符合规范!"; exit; } } return self::$obj; }
/** * @copydoc TypeDescription::checkType() */ function checkType(&$object) { // We only accept DOMDocument objects and source strings. if (!is_a($object, 'DOMDocument') && !is_string($object)) { return false; } // No validation... if ($this->_validationStrategy == XML_TYPE_DESCRIPTION_VALIDATE_NONE) { return true; } // Validation - requires DOMDocument if (is_string($object)) { $xmlDom = new DOMDocument(); $xmlDom->loadXML($object); } else { $xmlDom =& $object; } switch ($this->_validationStrategy) { // We have to suppress validation errors, otherwise the script // will stop when validation errors occur. case XML_TYPE_DESCRIPTION_VALIDATE_DTD: if (!$xmlDom->validate()) { return false; } break; case XML_TYPE_DESCRIPTION_VALIDATE_SCHEMA: if (!$xmlDom->schemaValidate($this->_validationSource)) { return false; } break; case XML_TYPE_DESCRIPTION_VALIDATE_RELAX_NG: if (!$xmlDom->relaxNGValidate($this->_validationSource)) { return false; } break; default: assert(false); } return true; }
<?php DOMDocument::validate();
function jdVideoPlayerFunction($atts, $content = null) { try { if (preg_match("/youtube/", $content)) { preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&\n]+|(?<=v=)[^&\n]+#", $content, $results); $videoid = $results[0]; $someurl = "http://gdata.youtube.com/feeds/api/videos/" . $videoid; $somedoc = new DOMDocument(); @$somedoc->load($someurl); if (@$somedoc->validate()) { @($ourtitle = $somedoc->getElementsByTagName("title")->item(0)->nodeValue); } else { $ourtitle = "Title"; } $service = "youtube"; $videolink = "http://www.youtube.com/watch?v=" . $videoid; $videoimagelink = "http://img.youtube.com/vi/" . $videoid . "/0.jpg"; } elseif (preg_match("/vimeo/", $content)) { preg_match("/(?<=vimeo\\.com\\/)\\d+/", $content, $results); $videoid = $results[0]; $url = 'http://vimeo.com/api/v2/video/' . $videoid . '.php'; $array = unserialize(file_get_contents($url)); $anotherarray = $array[0]; $thumbnail = $anotherarray["thumbnail_large"]; $height = $anotherarray["height"]; $width = $anotherarray["width"]; $service = "vimeo"; $ourtitle = $anotherarray["title"]; $videolink = 'http://vimeo.com/moogaloop.swf?clip_id=' . $videoid; $videoimagelink = $thumbnail; } $linkimage = videoThumb($videoimagelink, 'made_thumbstored' . $videoid); return '<div class="jddivclass"> <a data-fb-options="width:1280 height:745 autoFitMedia:true enableDragResize:true outerBorder:0 innerBorder:0 padding:0 panelPadding:0 roundCorners:none showClose:false imageClickCloses:true" class="floatbox" href="' . $videolink . '"> <div style="position:absolute;right:4px;bottom:4px;"> <img style="border:0 !important;" src="http://redesigndavid.com/wp-content/themes/redesigndavid-wp/socialicons/24/' . $service . '.png"/></div> <img class="imageclass" width="620px" src="' . $linkimage . '" > </a> </div>'; } catch (Exception $e) { echo "helloworld"; } }
$new_service->appendChild($memory); $cpu = $dom->createElement("cpu", $record->cpu); $new_service->appendChild($cpu); $pid = $dom->createElement("pid", $record->pid); $new_service->appendChild($pid); $uptime = $dom->createElement("uptime", $record->uptime); $new_service->appendChild($uptime); $children = $dom->createElement("children", $record->children); $new_service->appendChild($children); } $status = $dom->createElement("status", $record->status); $new_service->appendChild($status); $alert = $dom->createElement("alert", $record->alert); $new_service->appendChild($alert); $monitor = $dom->createElement("monitor", $record->monitor); $new_service->appendChild($monitor); $service->appendChild($new_service); } $dom->validate(); if (!($handle = fopen($file, 'w'))) { exit("Cannot open {$filename}"); } $dom->preserveWhiteSpace = false; $dom->formatOutput = false; if (fwrite($handle, $dom->saveXML()) === FALSE) { fclose($handle); exit("Cannot write to {$filename}"); } fclose($handle); } }
} } } } } } } if (isset($_POST["law_import"]) && isset($_FILES["law_import_file"])) { $file = $_FILES["law_import_file"]; if (!is_uploaded_file($file['tmp_name'])) { die(T_('Please enter a valid path for the file to upload')); } $doc = new DOMDocument(); $doc->load($file['tmp_name']); $doc->xinclude(); $doc->validate() or die('Malformed XML file'); if ($doc->doctype->publicId != 'DemoWave//law//0.1.0') { die('Not a DemoWave Law file'); } function domNodeIsEmpty($node) { return $node->nodeType == XML_TEXT_NODE && trim($node->data) == ''; } function insertNode($path, $node) { $children = $node->childNodes; $virtual = true; $title = ''; $text = ''; $pos = 0; while ($pos < $children->length && domNodeIsEmpty($children->item($pos))) {
protected function validateXmlConfig($configFiles) { foreach ($configFiles as $configFile) { if (file_exists($configFile)) { $xmlDom = new DOMDocument(); $xmlDom->load($configFile); self::assertTrue($xmlDom->validate()); unset($xmlDom); } } }
<?php $dom = new DOMDocument('1.0'); $dom->validate(true);
/** * @param DOMDocument $dom * @param bool $strict * @return array */ private function validate($dom, $strict = false) { libxml_use_internal_errors(true); $valid = @$dom->validate(); $report = array(); if ((!$valid || $strict) && ($r = libxml_get_errors())) { $report = array(); if ($valid) { $report[] = array('level' => 'info', 'message' => 'theme XML is valid'); } else { $report[] = array('level' => 'error', 'message' => 'theme XML contains errors'); } foreach ($r as $er) { /** * @var libXMLError $er */ $level_name = ''; switch ($er->level) { case LIBXML_ERR_WARNING: $level_name = 'LIBXML_ERR_WARNING'; break; case LIBXML_ERR_ERROR: $level_name = 'LIBXML_ERR_ERROR'; break; case LIBXML_ERR_FATAL: $level_name = 'LIBXML_ERR_FATAL'; break; } if ($er->code != 505) { $report[] = array('level' => $valid ? 'warning' : 'error', 'message' => "{$level_name} #{$er->code} [{$er->line}:{$er->column}]: {$er->message}"); } } if ($valid && count($report) == 1) { $report = array(); } } if (!empty($this->info['files'])) { $files = array(); foreach ($this->info['files'] as $path => $file) { if (empty($file['parent'])) { if (!file_exists($this->path . '/' . $path)) { $files[] = $path; } } } if (!empty($files)) { $report[] = array('level' => 'warning', 'message' => sprintf(_w('Missed theme file(s): %s'), implode(', ', $files))); } } return $report; }
} //语言包引入 $t_langpackage = new toollp(); $er_langpackage = new errorlp(); $tool_id = get_argg('id'); if ($tool_id == '') { echo '<script type="text/javascript">alert("' . $t_langpackage->t_id_wrong . '");window.history.go(-1);</script>'; exit; } $serv_url = act_substitue("tools", "&folder=" . $tool_id); //远程工具箱代理地址 $client_tool_root = 'toolsBox'; //本地工具箱路径 $xmlDom = new DOMDocument(); $xmlDom->load($client_tool_root . '/tool.xml'); if (!$xmlDom->validate()) { //检测本地工具箱规范 echo '<script type="text/javascript">alert("' . $t_langpackage->t_not_stand . '");window.history.go(-1);</script>'; exit; } $tool_client = file_get_contents($client_tool_root . "/tool.xml"); //取得本地的工具箱列表 if (!$tool_client) { echo '<script type="text/javascript">alert("' . $t_langpackage->t_not_find . '");window.history.go(-1);</script>'; exit; } $tool_list = file_get_contents($serv_url); //取得代理返回的数据 if ($tool_list == '') { echo '<script type="text/javascript">alert("' . $t_langpackage->t_false_connect . '");window.history.go(-1);</script>'; exit;
<?php $xml = <<<XML <!DOCTYPE foo PUBLIC "-//FOO/BAR" "http://example.com/foobar"> <foo>bar</foo> XML; $dtd = <<<DTD <!ELEMENT foo (#PCDATA)> DTD; libxml_set_external_entity_loader(function ($public, $system, $context) use($dtd) { var_dump($public); var_dump($system); var_dump($context); $f = fopen("php://temp", "r+"); fwrite($f, $dtd); rewind($f); return $f; }); $dd = new DOMDocument(); $r = $dd->loadXML($xml); var_dump($dd->validate()); echo "Done.\n";
/** * Will write the XML history file for a specific service. Inputs simplexml object and service type */ public static function writeServiceHistoric($server_id, $xml, $type, $chunk_size = 0, $number_of_chunks = 0) { if ($type == "3" || $type == "5" || $type == "7") { // Only services and programs $name = $xml->name; if (!self::datapathWriteable()) { exit("Cannot write in data path"); } $dom = new DOMDocument('1.0'); $service = $dom->createElement("records"); $attr_name = $dom->createAttribute("name"); $attr_name->value = $name; $service->appendChild($attr_name); $dom->appendChild($service); $attr_type = $dom->createAttribute("type"); $attr_type->value = $type; $service->appendChild($attr_type); $new_service = $dom->createElement("record"); $time = $dom->createAttribute("time"); $time->value = $xml->collected_sec; $new_service->appendChild($time); if ($type == "5") { // System $memory = $dom->createElement("memory", $xml->system->memory->percent); $new_service->appendChild($memory); $cpu_user = (double) $xml->system->cpu->user; $cpu_system = (double) $xml->system->cpu->system; $cpu_wait = (double) $xml->system->cpu->wait; $total_cpu = $cpu_user + $cpu_system + $cpu_wait; $cpu = $dom->createElement("cpu", $total_cpu); $new_service->appendChild($cpu); $swap = $dom->createElement("swap", $xml->system->swap->percent); $new_service->appendChild($swap); } else { if ($type == "7") { // Program $program_status = $dom->createElement("program_status", $xml->program->status); $new_service->appendChild($program_status); // Uncomment those lines to get program output logged into XML, // but keep in mind that it's not yet supported in front-end. // $program_output = $dom->createElement( "program_output", $xml->program->output ); // $new_service->appendChild($program_output); } else { // Process $memory = $dom->createElement("memory", self::getMonitPercentage($xml->memory)); $new_service->appendChild($memory); $cpu = $dom->createElement("cpu", self::getMonitPercentage($xml->cpu)); $new_service->appendChild($cpu); $pid = $dom->createElement("pid", $xml->pid); $new_service->appendChild($pid); $uptime = $dom->createElement("uptime", $xml->uptime); $new_service->appendChild($uptime); $children = $dom->createElement("children", $xml->children); $new_service->appendChild($children); } } $status = $dom->createElement("status", $xml->status); $new_service->appendChild($status); $alert = $dom->createElement("alert", intVal($xml->status > 0)); $new_service->appendChild($alert); $monitor = $dom->createElement("monitor", $xml->monitor); $new_service->appendChild($monitor); $service->appendChild($new_service); $dom->validate(); $dir = dirname(__FILE__) . "/" . self::data_path . "/" . $server_id; if (!is_dir($dir)) { if (!mkdir($dir)) { exit("Could not create data path {$dir}"); } } $filename = $dir . "/" . $name . ".xml"; if (file_exists($filename)) { if (!self::rotateFiles($filename, $chunk_size, $number_of_chunks)) { exit("Fatal error, could not rotate file {$filename}"); } /* Load in the previous xml */ if (file_exists($filename) && ($existing_xml = simplexml_load_string(file_get_contents($filename)))) { $dom_xml = dom_import_simplexml($existing_xml); foreach ($dom_xml->childNodes as $node) { $node = $dom->importNode($node, true); $node = $service->appendChild($node); } } } if (!($handle = fopen($filename, 'w'))) { error_log("[" . self::identifier . "] " . __FILE__ . " line " . __LINE__ . ": Cannot open {$filename}"); exit("Cannot open {$filename}"); } $dom->preserveWhiteSpace = false; $dom->formatOutput = false; if (fwrite($handle, $dom->saveXML()) === FALSE) { fclose($handle); error_log("[" . self::identifier . "] " . __FILE__ . " line " . __LINE__ . ": Cannot write to {$filename}"); exit("Cannot write to {$filename}"); } fclose($handle); } return true; }
<?php $xml = "<?xml version=\"1.0\"?>\n<!DOCTYPE note [\n<!ELEMENT note (to,from,heading,body)>\n<!ELEMENT to (#PCDATA)>\n<!ELEMENT from (#PCDATA)>\n<!ELEMENT heading (#PCDATA)>\n<!ELEMENT body (#PCDATA)>\n]>\n<note>\n<to>Tove</to>\n<from>Jani</from>\n<heading>Reminder</heading>\n<body>Don't forget me this weekend</body>\n</note>"; $dom = new DOMDocument('1.0'); $dom->loadXML($xml); var_dump($dom->validate());
/** * Checks whether XMLSchema is valid XML * @param DOMDocument $schemaDom source XMLSchema */ protected function checkXmlSchema(DOMDocument $schemaDom) { $this->useLibxmlErrors(); $schemaDom->validate(); $this->reachGoalOnNoLibxmlErrors(self::goalValidSchema, null); }
/** * проверяет возможности клиента и выдает как есть или выполняет трансформации сам * и выдает готовый html * @param string $data выходные данные в xml * @param boolean $html явное указание формата html * @param string $documentURI так как xml-документ $data передан строкой иногда требуется указать путь до него чтобы нашлись схемы * @param boolean $forceValidation NULL - валидация если в домашнем каталоге, TRUE: форсировать проверку по схеме/tidy всегда, FALSE - не проверять по схеме/tidy * @param string $htmlContentType миме-тип для вывода html, по-умолчанию text/html, для вывода html+xul передать application/xml */ public static function tryHTML($data, $html = FALSE, $documentURI = NULL, $forceValidation = NULL, $htmlContentType = "text/html") { $outputDom = NULL; $xsltResult = NULL; $debug = FALSE; $xsltProfiler = NULL; if (self::$done == TRUE) { trigger_error("Output::tryHTML() called twice?"); } $xsltStart = $xsltStop = 0; //минипрофайлер if ($html == FALSE && isset($_SERVER["HTTP_ACCEPT"])) { //тут пока неразбериха с text/xml по старому и application/xml по новому //опера по-новому, ие по-старому, мозиллы и так и сяк if (strpos($_SERVER["HTTP_ACCEPT"], "/xml") !== FALSE) { //тем кто явно грит "понимаю xml" сбросим флаг html $html = FALSE; if ("application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5" == $_SERVER["HTTP_ACCEPT"]) { //но некоторые говорят что понимают, но на самом деле не понимают, это андроиды 2.х их мы отлавливаем по кривому заголовку //под раздачу также попадают ближайщие родственники, которые реально умеют, но их не отличить от больных - сафари 4 (айфон 4). //остальные родственники успешно вылечились - сафари 5, хромы и хромиумы и другие вэбкитообразные. //используем заголовок Accept а не Usera-gent потому что //1. уже есть Vary: Accept - чтоб не плодить ветвление в прокси и кешах //2. у больных особей есть переключатель "mobile view" который влияет на User-agent-а // @seealso http://www.gethifi.com/blog/browser-rest-http-accept-headers // @seealso https://developer.mozilla.org/en-US/docs/HTTP/Content_negotiation $html = TRUE; } } elseif (strpos($_SERVER["HTTP_ACCEPT"], "text/html") !== FALSE) { //тем кто не понимает xml но явно грит что умеет html $html = TRUE; } } elseif (isset($_SERVER["HTTP_ACCEPT"])) { //"обратная автоматика" - даже если форсирован HTML но клиент его "не хочет" или "не может", но обещает что поймет XML - спрыгиваем на XML if (strpos($_SERVER["HTTP_ACCEPT"], "text/html") === FALSE && strpos($_SERVER["HTTP_ACCEPT"], "/xml") !== FALSE) { //тем кто явно заявляет что понимает xml и не умеет html $html = FALSE; } } //$html=TRUE; //подготовить стили для трансформации на php if ($debug || $html) { $outputDom = new \DOMDocument(); $outputDom->loadXML($data); if ($documentURI) { $outputDom->documentURI = $documentURI; } //валидация данных xml-схемой if ($debug) { $matches = NULL; //добываем имя схемы и проверяем по ней (или xmlreader?) if (preg_match("/schemaLocation=\".+\\s([a-zA-Z0-9_\\/\\.\\-]+)\"/", $data, $matches)) { $outputDom->schemaValidate(($documentURI ? dirname($documentURI) . "/" : "") . $matches[1]); // } else { // throw new \Exception("cant find schemaLocation"); } } $matches = NULL; //добываем имя стиля из хмл-а (или xmlreader?) if ($outputDom->firstChild->nodeType == XML_PI_NODE && $outputDom->firstChild->target == "xml-stylesheet") { if (preg_match("/href\\s*=\\s*\"(.+)\"/", $outputDom->firstChild->data, $matches)) { $oldHeaders = headers_list(); //время трансформации считаем общее - вместе с загрузкой документов $xsltStart = microtime(TRUE); $xsl = new \DomDocument(); // надо взять таблицу стилей локально $xsl_file = dirname($_SERVER["SCRIPT_FILENAME"]) . "/" . str_replace("http://" . $_SERVER["HTTP_HOST"] . dirname($_SERVER["PHP_SELF"]), "", $matches[1]); //error_log(dirname($_SERVER["SCRIPT_FILENAME"])); //error_log($_SERVER["PHP_SELF"]); //$xsl->load($matches[1]); $xsl->load("{$xsl_file}"); $proc = new \XSLTProcessor(); if ($xsltProfiler) { $proc->setProfiling($xsltProfiler); } $proc->importStyleSheet($xsl); //регистрируем на себя обращения к файлам stream_wrapper_unregister("file") or die(__FILE__ . __LINE__); stream_wrapper_register("file", static::CLASSNAME) or die(__FILE__ . __LINE__); //вешаем на обработчик выхода ловушку - если вложенный скрипт попытается сделать exit или die register_shutdown_function(array(static::CLASSNAME, "checkDone")); //на время трансформации ставим свой специальный обработчик ошибок set_error_handler(array(static::CLASSNAME, "xsltErrorHandler")); $xsltResult = $proc->transformToXML($outputDom); restore_error_handler(); if (self::$xsltErrors != NULL) { //а сообщаем об ошибках как обычно trigger_error("XSLTProcessor::transformToXml(): " . self::$xsltErrors); } //ставим маркер что управление нам вернули self::$done = TRUE; unset($proc, $xsl); //восстанавливаем дефолтный streamwrapper для file:// stream_wrapper_restore("file") or die(__FILE__ . __LINE__); //закончили трансформацию $xsltStop = microtime(TRUE); if ($xsltProfiler) { //ничего секретного там нет - даем всем почитать chmod($xsltProfiler, 0644); } //сравним хедеры до и после $diffHeaders = array_diff(headers_list(), $oldHeaders); //сбрасываем все хедеры которых "тут не стояло" foreach ($diffHeaders as $h) { $matches = explode(":", $h); header_remove($matches[0]); } //сбросим текущие чтобы добавить старые foreach ($oldHeaders as $h) { $matches = explode(":", $h); header_remove($matches[0]); } //востановим старые как были foreach ($oldHeaders as $h) { header($h, FALSE); } unset($diffHeaders, $oldHeaders, $h); } } else { //стиль не найден - html не получится - сбрасываем флаг $html = FALSE; } } self::$done = TRUE; //валидация выходного html с помощью tidy и по dtd-схеме if (1 != 1 && $debug && $xsltResult) { //http://dab.net.ilb.ru/doc/htmltidy-5.10.26-r2/html/quickref.html if (strncmp($xsltResult, "<!DOCTYPE html SYSTEM \"about:legacy-compat\">", 44)) { $config = array("output-xhtml" => TRUE, "doctype" => "strict"); $tidy = tidy_parse_string($xsltResult, $config, "UTF8"); //для tidy БЕЗ минуса $tidy->diagnose(); if (tidy_error_count($tidy) + tidy_warning_count($tidy)) { // tidy возвращает строку с ошибкой, пронумеровал для облегчения отладки $xsltResultLines = explode(PHP_EOL, $xsltResult); $xsltResultWithLines = ""; foreach ($xsltResultLines as $lineNumber => $line) { $xsltResultWithLines .= sprintf("%04d: ", $lineNumber + 1) . $line . PHP_EOL; } throw new Exception("tidy validation errors: " . $tidy->errorBuffer . PHP_EOL . $xsltResultWithLines); } //уберемся за собой unset($tidy, $config); } else { //html5 проверяем через локально развернутый сервис validator.nu $ch = curl_init(); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_VERBOSE, 0); curl_setopt($ch, CURLOPT_HEADER, 0); //TODO разобраться с нумерацией строк (с формы строки соответсвуют исходнику, а когда через сервис все в одну строку) curl_setopt($ch, CURLOPT_URL, "http://devel.net.ilb.ru:8888/?parser=html5&out=gnu"); curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: text/html")); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $xsltResult); ob_start(); curl_exec($ch); $out = ob_get_contents(); ob_end_clean(); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($code != 200) { trigger_error("curl failed " . curl_error($ch) . " HTTP" . $code . PHP_EOL . $out); } curl_close($ch); //исправление косяков html5-валидатора связанных с отсутствием стандарта //пропускаем предупреждения связанные с input type="date" $out = trim(preg_replace("/^:.+info warning: The “date” input type is so far supported properly.*/m", "", $out)); if ($out) { $xsltResultLines = explode(PHP_EOL, $xsltResult); $xsltResultWithLines = ""; foreach ($xsltResultLines as $lineNumber => $line) { $xsltResultWithLines .= sprintf("%04d: ", $lineNumber + 1) . $line . PHP_EOL; } throw new \Exception("validator.nu errors: " . PHP_EOL . $out . PHP_EOL . $xsltResultWithLines); } //уберемся за собой unset($ch, $out, $code); } $xsltResultDoc = new \DOMDocument(); //поиск схемы для проверки xhtml - ищем по обычным путям как и классы $schemasPath = NULL; foreach (explode(PATH_SEPARATOR, get_include_path()) as $p) { $p = $p . DIRECTORY_SEPARATOR . "schemas"; if (file_exists($p . DIRECTORY_SEPARATOR . "xhtml" . DIRECTORY_SEPARATOR . "dtd" . DIRECTORY_SEPARATOR . "xhtml1-strict.dtd")) { $schemasPath = $p; break; } } $xsltResultXml = str_replace(array("http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd", "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"), array($schemasPath . DIRECTORY_SEPARATOR . "xhtml" . DIRECTORY_SEPARATOR . "dtd" . DIRECTORY_SEPARATOR . "xhtml1-strict.dtd", $schemasPath . DIRECTORY_SEPARATOR . "xhtml11" . DIRECTORY_SEPARATOR . "dtd" . DIRECTORY_SEPARATOR . "xhtml11-flat.dtd"), $xsltResult); //поддерживается только Strict. как явно указать валидатору xml-catalog непонятно (с комстроки работает xmllint --catalog) $xsltResultDoc->loadXML($xsltResultXml); if ($documentURI) { $outputDom->documentURI = $documentURI; } if ($xsltResultDoc->doctype->systemId != "about:legacy-compat") { if (!$xsltResultDoc->validate()) { throw new \Exception("DTD validation errors"); } } unset($xsltResultDoc, $xsltResultXml, $schemasPath, $p); //тут можно и прочую статистику по внутренностям добавить header("X-XML-Output-tryHTML: HTML=" . ($html ? "TRUE" : "FALSE") . " XSLTtime=" . sprintf("%0.4f", $xsltStop - $xsltStart) . "s size=" . mb_strlen($data, "ASCII") . "/" . mb_strlen($xsltResult, "ASCII")); } unset($outputDom); //сообщаем клиенту что контент различен в зависимости от заголовка Accept - для кэширования нужно header("Vary: Accept"); if ($html) { unset($data); header("Content-type: {$htmlContentType};charset=UTF-8"); //header("Content-Length: ".mb_strlen($xsltResult,"ASCII")); //результат - сборная солянка из вывода нескольких скриптов и шаблонов //явно кешированием управлять не пытаемся: ставим хедеры на текущее время //TODO возможно и хитро проанализировать хедеры всех составляющих и вычислить общий //header("Last-Modified: ".gmdate(DATE_RFC1123)); //header("Etag: Output_".$_SERVER["UNIQUE_ID"]); echo $xsltResult; } else { unset($xsltResult); header("Content-type: application/xml"); //header("Content-Length: ".mb_strlen($data,"ASCII")); echo $data; } }
<?php ini_set('display_errors', 1); $xsldoc = new DOMDocument(); if ($foundAlbums == true) { $xsldoc->load('xml/albumfound.xsl'); } else { if ($edit_id == -1) { $xsldoc->load('xml/albumlib.xsl'); } else { $xsldoc->load('xml/albumlibedit.xsl'); } } $xmldoc = new DOMDocument(); $xmldoc->load('xml/albumlib.xml'); if (!$xmldoc->validate()) { echo "This document is valid!\n"; } $xsl = new XSLTProcessor(); $xsl->importStyleSheet($xsldoc); echo $xsl->transformToXML($xmldoc); ?>
/** * Loads and checks an XML document */ protected function loadXML($rootPath) { $archiveName = basename($rootPath); $this->dataBaseDir = $rootPath . '/' . $archiveName; // DTD validation $dom = new DOMDocument(); if (!$dom->load($rootPath . '/' . $archiveName . '.xml')) { $this->exitError("Failed to load XML document." . PHP_EOL); } if (!@$dom->validate()) { $this->warn("DTD Validation failed."); } $this->doc = simplexml_import_dom($dom); // Build the maps $this->buildMetadataMap(); // Import message metadata checks if ($this->importMessageMetadata != '') { if (!array_key_exists($this->importMessageMetadata, $this->metadataMap)) { $this->exitError("You specified an incorrect import message metadata: " . $this->importMessageMetadata . PHP_EOL); } else { $type = $this->metadataMap[$this->importMessageMetadata]['type']; if ($type != PLUGIN_DOCMAN_METADATA_TYPE_TEXT && $type != PLUGIN_DOCMAN_METADATA_TYPE_STRING) { $this->exitError("The import message metadata type must be 'string' or 'text'" . PHP_EOL); } } } $this->buildUserMap(); $this->buildUgroupMap(); // Sanity checks $this->log("Checking the XML document... "); $this->checkMetadataDefinition(); $this->checkHardCodedMetadataUsage(); $this->checkMetadataUsage(); $this->checkUgroupDefinition(); $this->checkUgroupsUsage(); $this->log("Done." . PHP_EOL); }
public function validate() { return $this->doc->validate(); }
protected function checkXMLValidity(\DOMDocument $xmlDom) { $this->useLibxmlErrors(); $xmlDom->validate(); return $this->reachGoalOnNoLibxmlErrors(self::goalValidXml, null); }
/** * @param \DOMDocument $doc XML document to be validated * * @throws \Exception */ public function validateWithDTD(\DOMDocument $doc) { libxml_use_internal_errors(true); if (!$doc->validate()) { throw new \Exception('Invalid XML: ' . json_encode(libxml_get_errors())); } libxml_use_internal_errors(false); }
// and doubled memory usage on Windows. $didLoad = $dom->load(realpath("{$ac['srcdir']}/{$ac["INPUT_FILENAME"]}"), $LIBXML_OPTS); // Check if the XML was simply broken, if so then just bail out if ($didLoad === false) { echo "failed.\n"; print_xml_errors(); errors_are_bad(1); } echo "done.\n"; echo "Validating {$ac["INPUT_FILENAME"]}... "; flush(); $dom->xinclude(); print_xml_errors(); if ($ac['PARTIAL'] != '' && $ac['PARTIAL'] != 'no') { // {{{ $dom->validate(); // we don't care if the validation works or not $node = $dom->getElementById($ac['PARTIAL']); if (!$node) { echo "failed.\n"; echo "Failed to find partial ID in source XML: {$ac['PARTIAL']}\n"; errors_are_bad(1); } if ($node->tagName !== 'book' && $node->tagName !== 'set') { // this node is not normally allowed here, attempt to wrap it // in something else $parents = array(); switch ($node->tagName) { case 'refentry': $parents[] = 'reference'; // Break omitted intentionally
private function loadXml($metafile, $generate) { $contents = file_get_contents($metafile); $contents = str_replace('"meta.dtd"', '"' . ONPHP_META_PATH . 'dtd/meta.dtd"', $contents); $doc = new DOMDocument('1.0'); $doc->loadXML($contents); try { $doc->validate(); } catch (BaseException $e) { $error = libxml_get_last_error(); throw new WrongArgumentException($error->message . ' in node placed on line ' . $error->line . ' in file ' . $metafile); } $xml = simplexml_import_dom($doc); // populate sources (if any) if (isset($xml->sources[0])) { foreach ($xml->sources[0] as $source) { $this->addSource($source); } } if (isset($xml->include['file'])) { $this->processIncludes($xml, $metafile); } // otherwise it's an includes-only config if (isset($xml->classes[0])) { return $this->processClasses($xml, $metafile, $generate); } return $this; }
public static function load($xmlfile, $prefix) { if (is_file($xmlfile)) { $dom = new DOMDocument(); $dom->load($xmlfile); if ($dom->validate()) { $root = $dom->documentElement; // Preliminary path modifications foreach ($root->getElementsByTagName("include") as $include) { $include->nodeValue = FileUtils::resolveRelativePath(FileUtils::getFileParent($xmlfile), $include->nodeValue); } // Reading attributes $actions = array(); foreach (XMLUtils::getChildrenByName($root, "action") as $child) { $actions[] = AbstractAction::parse($child); } $subsites = array(); foreach (XMLUtils::getChildrenByName($root, "subsite") as $child) { $subsites[] = Subsite::parse($child); } $targets = array(); foreach (XMLUtils::getChildrenByName($root, "target") as $child) { $targets[] = Target::parse($child); } return new Subsite($subsites, $targets, $actions, $prefix); } else { throw new Exception("Document validation failed for '" . $xmlfile . "'"); } } else { throw new Exception("Not a file '" . $xmlfile . "'"); } }