/** * @param string $xml * * @return \DOMDocument */ public static function fromString($xml) { if (!is_string($xml) || trim($xml) === '') { throw InvalidArgumentException::invalidType('non-empty string', $xml); } $entityLoader = libxml_disable_entity_loader(true); $internalErrors = libxml_use_internal_errors(true); libxml_clear_errors(); $domDocument = self::create(); $options = LIBXML_DTDLOAD | LIBXML_DTDATTR | LIBXML_NONET; if (defined(LIBXML_COMPACT)) { $options |= LIBXML_COMPACT; } $loaded = $domDocument->loadXML($xml, $options); libxml_use_internal_errors($internalErrors); libxml_disable_entity_loader($entityLoader); if (!$loaded) { $error = libxml_get_last_error(); libxml_clear_errors(); throw new UnparseableXmlException($error); } libxml_clear_errors(); foreach ($domDocument->childNodes as $child) { if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) { throw new RuntimeException('Dangerous XML detected, DOCTYPE nodes are not allowed in the XML body'); } } return $domDocument; }
/** * Transform a node with a stylesheet. * * @param DOMNode The node to transform. * * @return DOMDocument The resulting DOMDocument. * * @author Noah Fontes <*****@*****.**> * @author David Zülke <*****@*****.**> * @since 1.0.0 */ public function transformToDoc($doc) { $luie = libxml_use_internal_errors(true); libxml_clear_errors(); $result = parent::transformToDoc($doc); // check if result is false, too, as that means the transformation failed for reasons like infinite template recursion if ($result === false || libxml_get_last_error() !== false || count(libxml_get_errors())) { $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 Exception(sprintf('Error%s occurred while transforming the document using an XSL stylesheet: ' . "\n\n%s", count($errors) > 1 ? 's' : '', implode("\n", $errors))); } libxml_use_internal_errors($luie); // turn this into an instance of the class that was passed in, rather than a regular DOMDocument $class = $doc instanceof DOMDocument ? $doc : ($doc->ownerDocument ?: 'DOMDocument'); $document = new $class(); $document->loadXML($result->saveXML()); // save the URI just in case $document->documentURI = $result->documentURI; unset($result); return $document; }
/** Initializes the form. @param $sFilename The filename of the form XML (without path and extension). @param $sAction The action to be performed by the form (usually 'add', 'update' or 'delete'). */ public function __construct($sFilename, $sAction = 'add') { class_exists('XSLTProcessor') or burn('ConfigurationException', _WT('The XSL PHP extension is required by weeForm.')); is_callable('simplexml_load_file') or burn('ConfigurationException', _WT('The SimpleXML extension is required by weeForm.')); ctype_print($sAction) or burn('InvalidArgumentException', _WT('The action name must be printable.')); $sFilename = FORM_PATH . $sFilename . FORM_EXT; file_exists($sFilename) or burn('FileNotFoundException', sprintf(_WT('The file "%s" does not exist.'), $sFilename)); // simplexml_load_file triggers a warning if the file is not a well-formed XML. $this->oXML = @simplexml_load_file($sFilename); if ($this->oXML === false) { throw new BadXMLException(sprintf(_WT('File "%s" is not a well-formed XML document.'), $sFilename), libxml_get_last_error()); } isset($this->oXML->widgets) or burn('BadXMLException', sprintf(_WT('The file "%s" is not a valid form document.'), $sFilename)); if (!isset($this->oXML->formkey)) { $this->oXML->addChild('formkey', 1); } if (!isset($this->oXML->method)) { $this->oXML->addChild('method', 'post'); } if (!isset($this->oXML->uri)) { $this->oXML->addChild('uri', !empty($_SERVER['REQUEST_URI']) ? xmlspecialchars($_SERVER['REQUEST_URI']) : null); } // Delete elements with wrong action $this->removeNodes('//*[@action!="' . xmlspecialchars($sAction) . '"]'); // Replace the external tags with their respective nodes $this->loadExternals(); }
/** * Add an xml file to the bean definition * @param $xml * @param $relatifPath * @return unknown_type */ public function addConfig($xmlFile) { $xmlFile = $this->getFullPath($xmlFile); $xml = @simplexml_load_file($xmlFile); if ($xml == false) { $str = "Error parsing file (" . libxml_get_last_error()->file . ") on line (" . libxml_get_last_error()->line . ") : " . libxml_get_last_error()->message; echo $str; throw new \org\equinox\exception\EquinoxException($str); } $currentContextPath = dirname($xmlFile); foreach ($xml->{'component-scan'} as $scan) { $this->getComponentScan()->scanPackage((string) $scan['base-package']); } foreach ($xml->{'ini-file'} as $iniFile) { $this->addIniFile($currentContextPath, $iniFile); } foreach ($xml->bean as $bean) { $this->addBean($bean, $xmlFile); } foreach ($xml->import as $import) { $resource = $currentContextPath . '/' . (string) $import['resource']; $this->addConfig($resource); } foreach ($xml->modules as $module) { $this->loadModules($this->applicationContext->getIniValue((string) $module->iniValue)); } }
public static function static__escaped_fragment_($_escaped_fragment_) { \libxml_use_internal_errors(true); $html = new \DOMDocument(); $html->loadHTML(static::default_page($_escaped_fragment_ ? $_escaped_fragment_ : true)); if ($error = \libxml_get_last_error()) { //new \SYSTEM\LOG\ERROR('Parse Error: '.$error->message.' line:'.$error->line.' html: '.$html->saveHTML()); \libxml_clear_errors(); } $state = \SYSTEM\PAGE\State::get(static::get_apigroup(), $_escaped_fragment_ ? $_escaped_fragment_ : static::get_default_state(), false); foreach ($state as $row) { $frag = new \DOMDocument(); parse_str(\parse_url($row['url'], PHP_URL_QUERY), $params); $class = static::get_class($params); if ($class) { $frag->loadHTML(\SYSTEM\API\api::run('\\SYSTEM\\API\\verify', $class, static::get_params($params), static::get_apigroup(), true, false)); if ($error = \libxml_get_last_error()) { //new \SYSTEM\LOG\ERROR('Parse Error: '.$error->message.' line:'.$error->line.' html: '.$frag->saveHTML()); \libxml_clear_errors(); } $html->getElementById(substr($row['div'], 1))->appendChild($html->importNode($frag->documentElement, true)); //Load subpage css foreach ($row['css'] as $css) { $css_frag = new \DOMDocument(); $css_frag->loadHTML('<link href="' . $css . '" rel="stylesheet" type="text/css">'); $html->getElementsByTagName('head')[0]->appendChild($html->importNode($css_frag->documentElement, true)); } } } echo $html->saveHTML(); new \SYSTEM\LOG\COUNTER("API was called sucessfully."); die; }
/** * parse xml to array */ public static function toArray($strXml) { try { libxml_use_internal_errors(true); ini_set("display_errors", "Off"); $parser_res = @new SimpleXMLElement($strXml, LIBXML_NOCDATA); } catch (Exception $e) { $error = libxml_get_last_error(); //logWARNING( "load xml failed! reason:".$e->getMessage()); return false; } if ($parser_res === false) { //echo("xml parse failed!"); return false; } $arr = (array) $parser_res; if (!is_array($arr)) { logWARNING("xml_to_array fail,the parse result is not array!"); return false; } foreach ($arr as $key => $item) { $arr[$key] = self::struct_to_array((array) $item); } return $arr; }
function __construct($data) { libxml_use_internal_errors(true); libxml_clear_errors(); $this->doc = new DOMDocument(); $this->doc->loadXML($data); $error = libxml_get_last_error(); // libxml compiled without iconv? if ($error && $error->code == 32) { if (preg_match('/^(<\\?xml[\\t\\n\\r ].*?encoding=["\'])(.+?)(["\'].*?\\?>)/s', $data, $matches) === 1) { libxml_clear_errors(); $enc = $matches[2]; $data = iconv($enc, 'UTF-8//IGNORE', $data); $data = preg_replace('/^<\\?xml[\\t\\n\\r ].*?\\?>/s', $matches[1] . "UTF-8" . $matches[3], $data); $this->doc = new DOMDocument(); $this->doc->loadXML($data); $error = libxml_get_last_error(); } } // some terrible invalid unicode entity? if ($error && $error->code == 9) { libxml_clear_errors(); // we might want to try guessing input encoding here too $data = iconv("UTF-8", "UTF-8//IGNORE", $data); $this->doc = new DOMDocument(); $this->doc->loadXML($data); $error = libxml_get_last_error(); } $this->error = $this->format_error($error); libxml_clear_errors(); $this->items = array(); }
/** * Response parsing method * * @return $this */ private function decodeResponse() { // storing libxml state $oldState = libxml_use_internal_errors(true); // errors cleanup libxml_clear_errors(); // response has XML format, we have to parse it $this->xml = simplexml_load_string($this->body); // restoring default state libxml_use_internal_errors($oldState); // we have xml error if (libxml_get_last_error()) { $this->error = new \Exception('XML error: ' . libxml_get_last_error()->message); return $this; } // we have format error if (!isset($this->xml->code) || !isset($this->xml->tech_message)) { $this->error = new \UnexpectedValueException('Response code/tech_message is not found'); return $this; } $code = (string) $this->xml->code; if ($code < 0) { $this->error = (string) $this->xml->tech_message; } return $this; }
/** * {@inheritdoc} */ public function decode($data, $format) { $internalErrors = libxml_use_internal_errors(true); $disableEntities = libxml_disable_entity_loader(true); libxml_clear_errors(); $dom = new \DOMDocument(); $dom->loadXML($data, LIBXML_NONET); libxml_use_internal_errors($internalErrors); libxml_disable_entity_loader($disableEntities); foreach ($dom->childNodes as $child) { if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) { throw new UnexpectedValueException('Document types are not allowed.'); } } $xml = simplexml_import_dom($dom); if ($error = libxml_get_last_error()) { throw new UnexpectedValueException($error->message); } if (!$xml->count()) { if (!$xml->attributes()) { return (string) $xml; } $data = array(); foreach ($xml->attributes() as $attrkey => $attr) { $data['@' . $attrkey] = (string) $attr; } $data['#'] = (string) $xml; return $data; } return $this->parseXml($xml); }
/** * @covers \DCarbone\Camel\Camel::__toString * @covers \DCarbone\Camel\Hump\OrderBy::__toString * @covers \DCarbone\Camel\Hump\GroupBy::__toString * @covers \DCarbone\Camel\Hump\Where::__toString * @uses \DCarbone\Camel\Camel * @uses \DCarbone\Camel\Hump\OrderBy * @uses \DCarbone\Camel\Hump\GroupBy * @depends testCanConstructCamel * @param \DCarbone\Camel\Camel $camel */ public function testCanGetXMLStringViaTypecasting(\DCarbone\Camel\Camel $camel) { $xmlString = (string) $camel; $sxe = new \SimpleXMLElement($xmlString); $this->assertInstanceOf('\\SimpleXMLElement', $sxe); $this->assertFalse(libxml_get_last_error()); $sxe = null; }
/** * @param mixed $resource * @param string $locale * @param string $domain * @return MessageCatalogue */ public function load($resource, $locale, $domain = 'messages') { $previous = libxml_use_internal_errors(true); if (false === ($doc = simplexml_load_file($resource))) { libxml_use_internal_errors($previous); $libxmlError = libxml_get_last_error(); throw new RuntimeException(sprintf('Could not load XML-file "%s": %s', $resource, $libxmlError->message)); } libxml_use_internal_errors($previous); $doc->registerXPathNamespace('xliff', 'urn:oasis:names:tc:xliff:document:1.2'); $doc->registerXPathNamespace('jms', 'urn:jms:translation'); $hasReferenceFiles = in_array('urn:jms:translation', $doc->getNamespaces(true)); $catalogue = new MessageCatalogue(); $catalogue->setLocale($locale); /** @var \SimpleXMLElement $trans */ foreach ($doc->xpath('//xliff:trans-unit') as $trans) { $id = ($resName = (string) $trans->attributes()->resname) ? $resName : (string) $trans->source; /** @var Message $m */ $m = Message::create($id, $domain)->setDesc((string) $trans->source)->setLocaleString((string) $trans->target); $m->setApproved($trans['approved'] == 'yes'); if (isset($trans->target['state'])) { $m->setState((string) $trans->target['state']); } // Create closure $addNoteToMessage = function (Message $m, $note) { $m->addNote((string) $note, isset($note['from']) ? (string) $note['from'] : null); }; // If the translation has a note if (isset($trans->note)) { // If we have more than one note. We can't use is_array becuase $trans->note is a \SimpleXmlElement if (count($trans->note) > 1) { foreach ($trans->note as $note) { $addNoteToMessage($m, $note); } } else { $addNoteToMessage($m, $trans->note); } } $catalogue->add($m); if ($hasReferenceFiles) { foreach ($trans->xpath('./jms:reference-file') as $file) { $line = (string) $file->attributes()->line; $column = (string) $file->attributes()->column; $m->addSource(new FileSource((string) $file, $line ? (int) $line : null, $column ? (int) $column : null)); } } if ($meaning = (string) $trans->attributes()->extradata) { if (0 === strpos($meaning, 'Meaning: ')) { $meaning = substr($meaning, 9); } $m->setMeaning($meaning); } if (!($state = (string) $trans->target->attributes()->state) || 'new' !== $state) { $m->setNew(false); } } return $catalogue; }
/** * Returns the error message for the last XML error that occured. * @see libxml_get_last_error * * @return String|null Last XML error message or null if no error */ private function getLastXMLErrorMessage() { $errorMessage = null; $error = libxml_get_last_error(); if ($error !== false) { $errorMessage = trim($error->message); } return $errorMessage; }
/** * Callback for a validation or parsing error. * * @param string $n * @param string $message * @param string $file * @param string $line * @param string $context */ public function validationError($n, $message, $file, $line, $context) { $lxml = libxml_get_last_error(); if ($lxml) { $this->errors[] = array('message' => $lxml->message, 'file' => $lxml->file, 'line' => $lxml->line); } else { $this->errors[] = array('message' => $message, 'file' => $file, 'line' => $line); } }
/** * @covers \DCarbone\Camel\Hump\GroupBy::__toString * @covers \DCarbone\Camel\Node\AbstractNode::__toString * @covers \DCarbone\Camel\Node\FieldRef::nodeName * @uses \DCarbone\Camel\Hump\GroupBy * @uses \DCarbone\Camel\Node\AbstractNode * @uses \DCarbone\Camel\Node\FieldRef * @depends testCanGetGroupByInstance * @param \DCarbone\Camel\Hump\GroupBy $groupBy */ public function testCanGetGroupByXMLStringViaTypecasting(\DCarbone\Camel\Hump\GroupBy $groupBy) { $xml = (string) $groupBy; $this->assertInternalType('string', $xml); $sxe = new \SimpleXMLElement($xml); $this->assertInstanceOf('\\SimpleXMLElement', $sxe); $this->assertFalse(libxml_get_last_error()); $sxe = null; }
public function doValidation(Response $response) { $domDocument = new \DOMDocument(); $success = @$domDocument->loadXML((string) $response->getBody()); if (!$success) { $lastError = libxml_get_last_error(); throw new ValidationFailedException('The xml file ' . $response->getUri() . ' is not well formed (last error: ' . str_replace("\n", '', $lastError->message) . ').'); } }
static function xml($value) { try { @new SimpleXMLElement($value); } catch (Exception $e) { return "{t}Error{/t}: " . $e->getMessage() . " " . libxml_get_last_error()->message; } return ""; }
/** * Creates a simple xml instance for the xml contents that are located under * the given path name. * * @param string $pathName Qualified path name of a coverage report file. * @return \SimpleXMLElement * @throws \RuntimeException When the given path name does not point to a * valid xml file. */ private function loadXml($pathName) { $mode = libxml_use_internal_errors(true); $sxml = simplexml_load_file($pathName); libxml_use_internal_errors($mode); if ($sxml === false) { throw new \RuntimeException(trim(libxml_get_last_error()->message)); } return $sxml; }
/** * Checks whether the given value is a valid XML string. * * @param mixed $data Value to check if XML. * @return boolean TRUE if value is a valid XML string, otherwise false. */ function is_xml($data) { if (!is_string($data) || '<?xml ' !== substr($data, 0, 6)) { return false; } $xml_errors = libxml_use_internal_errors(true); $value = simplexml_load_string($data) instanceof SimpleXMLElement && false === libxml_get_last_error(); libxml_use_internal_errors($xml_errors); return (bool) $value; }
private function validateBody($body, $filename, $isIndex = true) { $dom = new \DOMDocument(); @$dom->loadXML($body); $valid = @$dom->schemaValidate($this->getSchema($isIndex)); if (!$valid) { $lastError = libxml_get_last_error(); throw new ValidationFailedException('The given sitemap file (' . $filename . ') did not validate against the sitemap schema (last error: ' . str_replace("\n", '', $lastError->message) . ').'); } }
public function validateXml($xmlString, $schemaFileName, $errorMessageIntro = "Error validating XML: ") { $domXml = new DOMDocument(); $domXml->loadXml($xmlString); $schemaFilePath = realpath("../application/schema") . '/' . $schemaFileName; if (!$domXml->schemaValidate(realpath($schemaFilePath))) { throw new ZendExt_XmlRequestBodyException($errorMessageIntro . libxml_get_last_error()->message); } return $domXml; }
protected function loadMappingFile($file) { $previous = libxml_use_internal_errors(true); $elem = simplexml_load_file($file); libxml_use_internal_errors($previous); if (false === $elem) { throw new \RuntimeException(libxml_get_last_error()); } return $elem; }
/** * @return void */ private function load() { $xmlContents = file_get_contents($this->xmlFilename); try { $this->xmlElement = new SimpleXMLElement($this->fixDtdPath($xmlContents), LIBXML_DTDATTR | LIBXML_DTDLOAD | LIBXML_DTDVALID); } catch (ExecutionContextException $e) { $xmlError = libxml_get_last_error(); throw new OrmModelIntegrityException('Malformed XML: ' . $xmlError->message . ' in ' . $this->xmlFilename . ':' . $xmlError->line); } }
private function throwError() { $error = libxml_get_last_error(); if (!empty($error)) { // https://bugs.php.net/bug.php?id=46465 if ($error->message != 'Validation failed: no DTD found !') { throw new \DomException($error->message . ' at line ' . $error->line); } } }
public function validate($content) { $xml = @simplexml_load_string('<?xml version="1.0"?>' . '<container>' . $content . '</container>'); if ($xml instanceof \SimpleXMLElement) { return $content; } else { $error = libxml_get_last_error(); throw new Exception(sprintf('Validation Error %s', $error->message)); } }
public function prepare($data) { $previous = libxml_use_internal_errors(true); $doc = simplexml_load_string($data); libxml_use_internal_errors($previous); if (false === $doc) { throw new XmlErrorException(libxml_get_last_error()); } return $doc; }
public function test(Response $response, Request $request) { libxml_clear_errors(); $dom = new \DOMDocument(); @$dom->loadXML($response->getBody()); $lastError = libxml_get_last_error(); if ($lastError) { throw new Exception("The given xml file is not well formed (last error: " . str_replace("\n", '', $lastError->message) . ")."); } }
/** * Checks for internal libxml errors and throws them in form of a single DOMException. * If no errors occured, then nothing happens. * * @param string $msg_prefix Is prepended to the libxml error message. * @param string $msg_suffix Is appended to the libxml error message. * @param bool $user_error_handling Allows to enable or disable internal libxml error handling. * * @throws DOMException */ public function handleErrors($msg_prefix = '', $msg_suffix = '', $user_error_handling = false) { if (libxml_get_last_error() !== false) { $errors = libxml_get_errors(); libxml_clear_errors(); libxml_use_internal_errors($user_error_handling); throw new DOMException($msg_prefix . $this->getErrorMessage($errors) . $msg_suffix); } libxml_use_internal_errors($user_error_handling); }
/** * Create a new XML node. * * \param XMLReader $reader * XML reader object that will be used to create * this node. * * \param bool $validate * Whether an exception should be raised (\c true) * or not (\c false) if the current node is not valid. * * \param bool $subtrees * Whether to explore subtrees (\c true) or not (\c false). */ public function __construct(\XMLReader $reader, $validate, $subtrees) { do { // We must silence read()/next() as old PHPs (5.3.x) emit warnings // which get caught by PHPUnit and other custom error handlers // when the methods fail and this is known to cause some issues. if ($subtrees && !@$reader->read() || !$subtrees && !@$reader->next()) { $error = libxml_get_last_error(); // We reached the end of the document. // This is not an error per-se, // but it causes read() to fail anyway. // We throw a special error which gets caught // and dealt with appropriately by the caller. if ($error === false) { throw new \InvalidArgumentException('End of document'); } switch ($error->code) { case self::XML_ERR_UNKNOWN_ENCODING: case self::XML_ERR_UNSUPPORTED_ENCODING: throw new \fpoirotte\XRL\Faults\UnsupportedEncodingException(); // Internal & memory errors are too hard to recreate // and are thus excluded from code coverage analysis. // @codeCoverageIgnoreStart // Internal & memory errors are too hard to recreate // and are thus excluded from code coverage analysis. // @codeCoverageIgnoreStart case self::XML_ERR_INTERNAL_ERROR: case self::XML_ERR_NO_MEMORY: throw new \fpoirotte\XRL\Faults\InternalErrorException(); // @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd case self::XML_ERR_INVALID_CHAR: throw new \fpoirotte\XRL\Faults\InvalidCharacterException(); // Generic error handling. // Generic error handling. default: throw new \fpoirotte\XRL\Faults\NotWellFormedException(); } } if ($validate && !$reader->isValid()) { throw new \fpoirotte\XRL\Faults\InvalidXmlRpcException(); } $subtrees = true; } while ($reader->nodeType === \XMLReader::SIGNIFICANT_WHITESPACE); $fields = array('isEmptyElement', 'localName', 'namespaceURI', 'nodeType', 'value'); $this->properties = array(); foreach ($fields as $field) { $this->properties[$field] = $reader->{$field}; } $name = $reader->localName; if ($reader->namespaceURI !== '') { $name = '{' . $reader->namespaceURI . '}' . $name; } $this->properties['name'] = $name; }
/** * @param string $result * @throws Exceptions\LogicException */ public function process($result) { if (!($xml = @simplexml_load_string($result)) && libxml_get_last_error() instanceof LibXMLError) { throw new LogicException('SMS Response is not valid XML'); } if (!isset($xml->id) || !isset($xml->message)) { throw new LogicException('SMS Response is not valid. Some parts are missing.'); } $this->id = (string) $xml->id; $this->message = (string) $xml->message; }
/** * Reads the configuration file and creates the class attributes * */ protected function initialize() { $reader = new XMLReader(); $reader->open(parent::getConfigFilePath()); $reader->setRelaxNGSchemaSource(self::WURFL_CONF_SCHEMA); libxml_use_internal_errors(TRUE); while ($reader->read()) { if (!$reader->isValid()) { throw new Exception(libxml_get_last_error()->message); } $name = $reader->name; switch ($reader->nodeType) { case XMLReader::ELEMENT: $this->_handleStartElement($name); break; case XMLReader::TEXT: $this->_handleTextElement($reader->value); break; case XMLReader::END_ELEMENT: $this->_handleEndElement($name); break; } } $reader->close(); if (isset($this->cache["dir"])) { $this->logDir = $this->cache["dir"]; } }