function open($xml, $encoding = null)
 {
     if (!empty($encoding) && strtolower($encoding) != 'utf-8' && !Utils_Unicode::validate($xml)) {
         if (preg_match('/^<\\?xml[^<]*\\s+encoding=["\']?([\\w-]+)["\']?/', $xml, $matches)) {
             $encoding = $matches[1];
             $xml = preg_replace('/^(<\\?xml[^<]*\\s+encoding=)["\']?[\\w-]+["\']?/', '$1"utf-8"', $xml, 1);
         }
         if (strcasecmp($encoding, 'utf-8')) {
             $xml = Utils_Unicode::bring($xml, $encoding);
             if (is_null($xml)) {
                 $this->error = XML_ERROR_UNKNOWN_ENCODING;
                 return false;
             }
         }
     } else {
         if (substr($xml, 0, 3) == "") {
             $xml = substr($xml, 3);
         }
     }
     $p = xml_parser_create();
     xml_set_object($p, $this);
     xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
     xml_set_element_handler($p, 'o', 'c');
     xml_set_character_data_handler($p, 'd');
     xml_set_default_handler($p, 'x');
     $this->tree = array('children' => array());
     $this->_cursor =& $this->tree;
     $this->_cdata = false;
     xml_parse($p, $xml);
     unset($this->_cursor);
     unset($this->_cdata);
     $this->error = xml_get_error_code($p);
     xml_parser_free($p);
     return $this->error == XML_ERROR_NONE;
 }
 public function parse($html)
 {
     // replace entities
     $html = preg_replace('/&([a-z0-9#]{2,5});/i', '+$1;', $html);
     //before sending to xml parser make sure we have valid xml by tidying it up
     $html = Kwf_Util_Tidy::repairHtml($html);
     $this->_stack = array();
     $this->_ret = '';
     $this->_parser = xml_parser_create();
     xml_set_object($this->_parser, $this);
     xml_set_element_handler($this->_parser, 'startElement', 'endElement');
     xml_set_character_data_handler($this->_parser, 'characterData');
     xml_set_default_handler($this->_parser, 'characterData');
     $result = xml_parse($this->_parser, '<body>' . $html . '</body>', true);
     if (!$result) {
         // wenn man ein nicht geschlossenes <br> rein gibt, schreit er hier,
         // macht aber normal weiter. wenns zu oft vorkommt, evtl. exception
         // entfernen und ignorieren, oder was andres überlegen :-)
         $errorCode = xml_get_error_code($this->_parser);
         $ex = new Kwf_Exception("HtmlExport UrlParser XML Error {$errorCode}: " . xml_error_string($errorCode) . "in line " . xml_get_current_line_number($this->_parser) . " parsed html: " . $html);
         $ex->logOrThrow();
     }
     // re-replace entities
     $this->_ret = preg_replace('/\\+([a-z0-9#]{2,5});/i', '&$1;', $this->_ret);
     return $this->_ret;
 }
Example #3
0
 function parse()
 {
     set_error_handler(array(&$this, 'error_handler'));
     array_unshift($this->ns_contexts, array());
     $parser = xml_parser_create_ns();
     xml_set_object($parser, $this);
     xml_set_element_handler($parser, "start_element", "end_element");
     xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
     xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
     xml_set_character_data_handler($parser, "cdata");
     xml_set_default_handler($parser, "_default");
     xml_set_start_namespace_decl_handler($parser, "start_ns");
     xml_set_end_namespace_decl_handler($parser, "end_ns");
     $this->content = '';
     $ret = true;
     $fp = fopen($this->FILE, "r");
     while ($data = fread($fp, 4096)) {
         if ($this->debug) {
             $this->content .= $data;
         }
         if (!xml_parse($parser, $data, feof($fp))) {
             trigger_error(sprintf(__('XML error: %s at line %d') . "\n", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser)));
             $ret = false;
             break;
         }
     }
     fclose($fp);
     xml_parser_free($parser);
     restore_error_handler();
     return $ret;
 }
Example #4
0
 public function __construct($input, $maxDepth = 20)
 {
     if (!is_string($input)) {
         throw new XmlToArrayException('No valid input.');
     }
     $this->_maxDepth = $maxDepth;
     $XMLParser = xml_parser_create();
     xml_parser_set_option($XMLParser, XML_OPTION_SKIP_WHITE, false);
     xml_parser_set_option($XMLParser, XML_OPTION_CASE_FOLDING, false);
     xml_parser_set_option($XMLParser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
     xml_set_character_data_handler($XMLParser, array($this, '_contents'));
     xml_set_default_handler($XMLParser, array($this, '_default'));
     xml_set_element_handler($XMLParser, array($this, '_start'), array($this, '_end'));
     xml_set_external_entity_ref_handler($XMLParser, array($this, '_externalEntity'));
     xml_set_notation_decl_handler($XMLParser, array($this, '_notationDecl'));
     xml_set_processing_instruction_handler($XMLParser, array($this, '_processingInstruction'));
     xml_set_unparsed_entity_decl_handler($XMLParser, array($this, '_unparsedEntityDecl'));
     if (!xml_parse($XMLParser, $input, true)) {
         $errorCode = xml_get_error_code($XMLParser);
         $message = sprintf('%s. line: %d, char: %d' . ($this->_tagStack ? ', tag: %s' : ''), xml_error_string($errorCode), xml_get_current_line_number($XMLParser), xml_get_current_column_number($XMLParser) + 1, implode('->', $this->_tagStack));
         xml_parser_free($XMLParser);
         throw new XmlToArrayException($message, $errorCode);
     }
     xml_parser_free($XMLParser);
 }
Example #5
0
 function XMLParser()
 {
     $this->parser = xml_parser_create();
     xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, FALSE);
     xml_set_element_handler($this->parser, "startElementhandler", "endElementHandler");
     xml_set_character_data_handler($this->parser, "cdataHandler");
     xml_set_processing_instruction_handler($this->parser, "processingInstructionHandler");
     xml_set_default_handler($this->parser, "defaultHandler");
 }
Example #6
0
 function txpXmlParser()
 {
     $this->xml = xml_parser_create('UTF-8');
     xml_parser_set_option($this->xml, XML_OPTION_CASE_FOLDING, 0);
     xml_set_object($this->xml, $this);
     xml_set_character_data_handler($this->xml, 'dataHandler');
     xml_set_element_handler($this->xml, "startHandler", "endHandler");
     xml_set_default_handler($this->xml, 'defaultHandler');
 }
Example #7
0
function createParser($filename)
{
    $fh = fopen($filename, 'r');
    $parser = xml_parser_create();
    xml_set_element_handler($parser, "startElement", "endElement");
    xml_set_character_data_handler($parser, "characterData");
    xml_set_processing_instruction_handler($parser, "processingInstruction");
    xml_set_default_handler($parser, "default");
    return array($parser, $fh);
}
 function soap_parser($xml = '', $encoding = 'UTF-8')
 {
     global $soapTypes;
     $this->soapTypes = $soapTypes;
     $this->xml = $xml;
     $this->xml_encoding = $encoding;
     $this->root_struct = "";
     // options: envelope,header,body,method
     // determines where in the message we are (envelope,header,body,method)
     $this->status = '';
     $this->position = 0;
     $this->pos_stat = 0;
     $this->depth = 0;
     $this->default_namespace = '';
     $this->namespaces = array();
     $this->message = array();
     $this->fault = false;
     $this->fault_code = '';
     $this->fault_str = '';
     $this->fault_detail = '';
     $this->eval_str = '';
     $this->depth_array = array();
     $this->debug_flag = True;
     $this->debug_str = '';
     $this->previous_element = '';
     $this->entities = array('&' => '&amp;', '<' => '&lt;', '>' => '&gt;', "'" => '&apos;', '"' => '&quot;');
     // Check whether content has been read.
     if (!empty($xml)) {
         $this->debug('Entering soap_parser()');
         //$this->debug("DATA DUMP:\n\n$xml");
         // Create an XML parser.
         $this->parser = xml_parser_create($this->xml_encoding);
         // Set the options for parsing the XML data.
         //xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
         xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
         // Set the object for the parser.
         xml_set_object($this->parser, &$this);
         // Set the element handlers for the parser.
         xml_set_element_handler($this->parser, 'start_element', 'end_element');
         xml_set_character_data_handler($this->parser, 'character_data');
         xml_set_default_handler($this->parser, 'default_handler');
         // Parse the XML file.
         if (!xml_parse($this->parser, $xml, true)) {
             // Display an error message.
             $this->debug(sprintf("XML error on line %d: %s", xml_get_current_line_number($this->parser), xml_error_string(xml_get_error_code($this->parser))));
             $this->fault = true;
         } else {
             // get final eval string
             $this->eval_str = "\$response = " . trim($this->build_eval($this->root_struct)) . ";";
         }
         xml_parser_free($this->parser);
     } else {
         $this->debug("xml was empty, didn't parse!");
     }
 }
Example #9
0
 function xml($encoding = "UTF-8")
 {
     $this->_parser = xml_parser_create($encoding);
     $this->_xml_data = "";
     $this->_actual_tag = $this;
     xml_set_object($this->_parser, $this);
     xml_parser_set_option($this->_parser, XML_OPTION_CASE_FOLDING, false);
     xml_set_element_handler($this->_parser, "tag_open", "tag_close");
     xml_set_character_data_handler($this->_parser, "tag_data");
     xml_set_default_handler($this->_parser, "tag_data");
 }
 /**
  * @since 2.0
  */
 public function __construct()
 {
     $this->parser = xml_parser_create();
     xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 0);
     xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
     xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
     xml_set_object($this->parser, $this);
     xml_set_element_handler($this->parser, 'handleOpenElement', 'handleCloseElement');
     xml_set_character_data_handler($this->parser, 'handleCharacterData');
     xml_set_default_handler($this->parser, 'handleDefault');
     //xml_set_start_namespace_decl_handler($parser, 'handleNsDeclaration' );
 }
Example #11
0
 /**
  * Class constructor
  * 
  * @param   string  The path of the file to parse
  * @param   string  A prefix path to add to all 'src' and 'href' attributes, if relative
  * @param   string  The output charset (default is UTF-8)
  * @return  void
  */
 public function __construct($file, $charset = 'UTF-8')
 {
     // The charset must be uppercase
     $charset = strtoupper($charset);
     // Checks if the file exists
     if (!file_exists($file) || !is_file($file)) {
         // The file does not exist
         throw new Woops_Xml_Parser_Exception('The specified XML file (\'' . $file . '\') does not exist', Woops_Xml_Parser_Exception::EXCEPTION_NO_FILE);
     }
     // Checks if the file is readable
     if (!is_readable($file)) {
         // Cannot read the file
         throw new Woops_Xml_Parser_Exception('The specified XML file (\'' . $file . '\') is not readable', Woops_Xml_Parser_Exception::EXCEPTION_FILE_NOT_READABLE);
     }
     // Checks if the charset is supported
     if (!isset(self::$_charsets[$charset])) {
         // Unsupported charset
         throw new Woops_Xml_Parser_Exception('The specified charset (' . $charset . ') is not supported', Woops_Xml_Parser_Exception::EXCEPTION_INVALID_CHARSET);
     }
     // Creates an XML parser
     $this->_parser = xml_parser_create($charset);
     // Sets the current instance as the XML parser object
     xml_set_object($this->_parser, $this);
     // Disables case-folding
     xml_parser_set_option($this->_parser, XML_OPTION_CASE_FOLDING, false);
     // Sets the element handler methods
     xml_set_element_handler($this->_parser, '_startElementHandler', '_endElementHandler');
     // Sets the character data handler method
     xml_set_character_data_handler($this->_parser, '_characterDataHandler');
     // Sets the processing instruction handler method
     xml_set_processing_instruction_handler($this->_parser, '_processingInstructionHandler');
     // Sets the default data handler method
     xml_set_default_handler($this->_parser, '_defaultHandler');
     // Tries to open a file handler
     if ($fileHandler = fopen($file, 'r')) {
         // Reads data from the file
         while ($data = fread($fileHandler, 4096)) {
             // Tries to parse the data
             if (!xml_parse($this->_parser, $data, feof($fileHandler))) {
                 // Gets the error string and line number
                 $errorString = xml_error_string(xml_get_error_code($this->_parser));
                 $errorLine = xml_get_current_line_number($this->_parser);
                 // Throws an exception, as we have an XML error
                 throw new Woops_Xml_Parser_Exception('XML parser error: ' . $errorString . ' at line number ' . $errorLine, Woops_Xml_Parser_Exception::EXCEPTION_XML_PARSER_ERROR);
             }
         }
         // Closes the file handler
         fclose($fileHandler);
     }
     // Frees the parser
     xml_parser_free($this->_parser);
 }
Example #12
0
 function SaxParser(&$input)
 {
     $this->level = 0;
     $this->parser = xml_parser_create('UTF-8');
     xml_set_object($this->parser, $this);
     $this->input =& $input;
     $this->setCaseFolding(false);
     $this->useUtfEncoding();
     xml_set_element_handler($this->parser, 'handleBeginElement', 'handleEndElement');
     xml_set_character_data_handler($this->parser, 'handleCharacterData');
     xml_set_processing_instruction_handler($this->parser, 'handleProcessingInstruction');
     xml_set_default_handler($this->parser, 'handleDefault');
     xml_set_unparsed_entity_decl_handler($this->parser, 'handleUnparsedEntityDecl');
     xml_set_notation_decl_handler($this->parser, 'handleNotationDecl');
     xml_set_external_entity_ref_handler($this->parser, 'handleExternalEntityRef');
 }
 function parse($xml)
 {
     $this->node_list = array(0 => array('type' => 'start', 'children' => array()));
     $this->cur_nodeid = 0;
     $this->parser = xml_parser_create();
     xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
     xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);
     xml_set_element_handler($this->parser, array(&$this, 'handle_element_open'), array(&$this, 'handle_element_close'));
     xml_set_character_data_handler($this->parser, array(&$this, 'handle_cdata'));
     xml_set_processing_instruction_handler($this->parser, array(&$this, 'handle_instruction'));
     xml_set_default_handler($this->parser, array(&$this, 'handle_default'));
     xml_parse($this->parser, $xml, true);
     xml_parser_free($this->parser);
     $this->parser = null;
     return $this->node_list;
 }
function showXML($data, $display)
{
    if ($display) {
        for ($i = 0; $i < $postVars[numHosts]; $i++) {
            $xml_parser = xml_parser_create();
            xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 1);
            xml_set_element_handler($xml_parser, "startElement", "endElement");
            xml_set_character_data_handler($xml_parser, "characterData");
            xml_set_default_handler($xml_parser, "defaultHandler");
            echo "<pre>";
            if (!xml_parse($xml_parser, $data[$i])) {
                die(sprintf("XML error: %s at line %d\n", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser)));
            }
            echo "</pre>";
            xml_parser_free($xml_parser);
        }
    }
}
 /**
  * Parse the given XML result and return an SMWSparqlResultWrapper for
  * the contained data.
  *
  * @param $xmlQueryResult string
  */
 public function makeResultFromXml($xmlQueryResult)
 {
     $parser = xml_parser_create();
     xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
     xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
     xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
     xml_set_object($parser, $this);
     xml_set_element_handler($parser, 'xmlHandleOpen', 'xmlHandleClose');
     xml_set_character_data_handler($parser, 'xmlHandleCData');
     xml_set_default_handler($parser, 'xmlHandleDefault');
     //xml_set_start_namespace_decl_handler($parser, 'xmlHandleNsDeclaration' );
     $this->m_xml_opentags = array();
     $this->m_header = array();
     $this->m_data = array();
     $this->m_comments = array();
     xml_parse($parser, $xmlQueryResult, true);
     xml_parser_free($parser);
     return new SMWSparqlResultWrapper($this->m_header, $this->m_data, $this->m_comments);
 }
Example #16
0
 protected function parse($xmlData)
 {
     $this->parser = xml_parser_create();
     xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);
     xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, "ISO-8859-1");
     xml_set_object($this->parser, $this);
     xml_set_element_handler($this->parser, 'onTagStart', 'onTagEnd');
     xml_set_character_data_handler($this->parser, 'onTagContent');
     xml_set_processing_instruction_handler($this->parser, "onPiHandler");
     xml_set_default_handler($this->parser, "onDefaultHandler");
     if (!xml_parse($this->parser, $xmlData)) {
         $xmlErroCode = xml_get_error_code($this->parser);
         $xmlErroString = xml_error_string($xmlErroCode);
         $xmlLine = xml_get_current_line_number($this->parser);
         die(sprintf("XML error: %s at line %d", $xmlErroString, $xmlLine));
     }
     xml_parser_free($this->parser);
     $this->parser = NULL;
 }
Example #17
0
 protected final function init()
 {
     if ($this instanceof Features\IXmlNamespaceParser) {
         $this->parser = xml_parser_create_ns('UTF-8');
         // Set up start namespace declaration handler
         xml_set_start_namespace_decl_handler($this->parser, 'ns_start');
         // Set up end namespace declaration handler
         xml_set_end_namespace_decl_handler($this->parser, 'ns_end');
     } elseif ($this instanceof Features\IXmlBasicParser) {
         $this->parser = xml_parser_create('UTF-8');
     } else {
         throw new \BadMethodCallException('This class does not implements the XML Parser capabilities. Please implement either IXmlBasicParser or IXmlNamespaceParser.');
     }
     xml_set_object($this->parser, $this);
     foreach ($this->options as $option => $value) {
         xml_parser_set_option($this->parser, $option, $value);
     }
     if ($this instanceof Features\IXmlProcessorParser) {
         // Set up processing instruction (PI) handler
         xml_set_processing_instruction_handler($this->parser, 'pi_handler');
     }
     if ($this instanceof Features\IXmlEntityHandler) {
         // Set up external entity reference handler
         xml_set_external_entity_ref_handler($this->parser, 'entity_handler');
     }
     if ($this instanceof Features\IXmlNdataHandler) {
         // Set up notation declaration handler
         xml_set_notation_decl_handler($this->parser, 'notation_handler');
         // Set up unparsed entity declaration handler
         xml_set_unparsed_entity_decl_handler($this->parser, 'ndata_handler');
     }
     xml_set_element_handler($this->parser, "element_start", "element_end");
     xml_set_character_data_handler($this->parser, "cdata_handler");
     if ($this instanceof Features\IXmlDefaultHandler) {
         if (!defined('ACTIVATE_XML_PARSER_DEFAULT_HANDLER_I_KNOW_WHAT_AM_I_DOING')) {
             trigger_error('Active default handler interferes with many XML features like internal parsable entities.', E_USER_WARNING);
         }
         // Set up default (fallback) handler.
         // Warning: Interferes with INTERNAL ENTITY declarations like
         // <!ENTITY a 'b'>
         xml_set_default_handler($this->parser, "default_handler");
     }
 }
 /**
  * Constructor.
  *
  * @param String $configFile
  *        	The path of the config file
  */
 public function __construct($configFile)
 {
     // If the path is a valid file we use it as is
     if (is_file($configFile)) {
         $this->file = $configFile;
     } else {
         // Otherwise we look in the config directory
         $this->file = PHPCHECKSTYLE_HOME_DIR . "/config/" . $configFile;
         if (!is_file($this->file)) {
             echo "Config file not found : " . $configFile;
             exit(0);
         }
     }
     $this->xmlParser = xml_parser_create();
     xml_set_object($this->xmlParser, $this);
     xml_set_element_handler($this->xmlParser, "_startElement", "_endElement");
     xml_set_character_data_handler($this->xmlParser, "_gotCdata");
     xml_set_default_handler($this->xmlParser, "_gotCdata");
 }
Example #19
0
 /**
  * Import HTML from $source to $target node.
  *
  * @param \DOMElement $source
  * @param \DOMElement $target
  *
  * @since 1.0
  */
 public static function import(\DOMElement $source, \DOMElement $target)
 {
     /* Prepare container */
     $container = $target->ownerDocument->createElement('xhtml:div');
     $container->setAttributeNS(Atom::XMLNS, 'xmlns:xhtml', Atom::XHTML);
     $target->appendChild($container);
     /* Prefix all source tags with "xhtml:" */
     $xmlFrom = $source->ownerDocument->saveXML($source);
     $xmlTo = '';
     $xhtmlNsSet = false;
     $parser = xml_parser_create('UTF-8');
     xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
     xml_set_element_handler($parser, function ($parser, $name, array $attrs) use($xmlFrom, &$xmlTo, &$xhtmlNsSet) {
         $selfClosing = '/>' === substr($xmlFrom, xml_get_current_byte_index($parser), 2);
         $xmlTo .= '<xhtml:' . $name;
         if (false === $xhtmlNsSet) {
             $attrs['xmlns:xhtml'] = Atom::XHTML;
             $xhtmlNsSet = true;
         }
         foreach ($attrs as $attr => $value) {
             $xmlTo .= sprintf(' %s="%s"', $attr, htmlspecialchars($value, ENT_COMPAT | ENT_XML1));
         }
         $xmlTo .= $selfClosing ? '/>' : '>';
     }, function ($parser, $name) use($xmlFrom, &$xmlTo) {
         $selfClosing = '/>' === substr($xmlFrom, xml_get_current_byte_index($parser) - 2, 2);
         if ($selfClosing) {
             return;
         }
         $xmlTo .= '</xhtml:' . $name . '>';
     });
     xml_set_default_handler($parser, function ($parser, $data) use(&$xmlTo) {
         $xmlTo .= $data;
     });
     xml_parse($parser, $xmlFrom, true);
     xml_parser_free($parser);
     /* Import prefixed XML into container */
     $tmpDoc = new \DOMDocument('1.0', 'utf-8');
     $tmpDoc->loadXML($xmlTo);
     foreach ($tmpDoc->documentElement->childNodes as $node) {
         $container->appendChild($container->ownerDocument->importNode($node, true));
     }
 }
Example #20
0
 function runtest($num, $i)
 {
     $this->readfile($num);
     echo "parsing xml data file {$this->currentFile} iteration {$i}\n";
     $xml_parser = xml_parser_create();
     xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 1);
     xml_set_object($xml_parser, $this);
     xml_set_element_handler($xml_parser, 'startElement', 'endElement');
     xml_set_character_data_handler($xml_parser, 'cDataHandler');
     xml_set_external_entity_ref_handler($xml_parser, 'externalEntityRefHandler');
     xml_set_processing_instruction_handler($xml_parser, 'piHandler');
     xml_set_unparsed_entity_decl_handler($xml_parser, 'unparsedEntityDeclHandler');
     xml_set_notation_decl_handler($xml_parser, 'entityDeclHandler');
     xml_set_default_handler($xml_parser, 'defaultHandler');
     if (!xml_parse($xml_parser, $this->contentBuffer, true)) {
         $this->currentFile != '' ? $inFile = "in file {$this->currentFile}" : ($inFile = '');
         $this->fatalErrorPage(sprintf(get_class($this) . ": XML error: %s at line %d {$inFile}", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser)));
     }
     xml_parser_free($xml_parser);
 }
Example #21
0
 /**
  * Parses the XML provided using streaming and callbacks
  *
  * @param mixed $data      Either a stream resource or string containing XML
  * @param int   $chunkSize The size of data to read in at a time. Only
  *                         relevant if $data is a stream
  *
  * @return Parser
  * @throws Exception
  */
 public function parse($data, $chunkSize = 1024)
 {
     //Ensure that the $data var is of the right type
     if (!is_string($data) && (!is_resource($data) || get_resource_type($data) !== 'stream')) {
         throw new Exception('Data must be a string or a stream resource');
     }
     //Ensure $chunkSize is the right type
     if (!is_int($chunkSize)) {
         throw new Exception('Chunk size must be an integer');
     }
     //Initialise the object
     $this->init();
     //Create the parser and set the parsing flag
     $this->parse = TRUE;
     $parser = xml_parser_create();
     //Set the parser up, ready to stream through the XML
     xml_set_object($parser, $this);
     //Set up the protected methods _start and _end to deal with the start
     //and end tags respectively
     xml_set_element_handler($parser, 'start', 'end');
     //Set up the _addCdata method to parse any CDATA tags
     xml_set_character_data_handler($parser, 'addCdata');
     //For general purpose data, use the _addData method
     xml_set_default_handler($parser, 'addData');
     //If the data is a resource then loop through it, otherwise just parse
     //the string
     if (is_resource($data)) {
         //Not all resources support fseek. For those that don't, suppress
         // /the error
         @fseek($data, 0);
         while ($this->parse && ($chunk = fread($data, $chunkSize))) {
             $this->parseString($parser, $chunk, feof($data));
         }
     } else {
         $this->parseString($parser, $data, TRUE);
     }
     //Free up the parser
     xml_parser_free($parser);
     return $this;
 }
Example #22
0
 /**
  *   -------------------------------------------------------------------------------------------
  *   @desc Парсит и возвращает структуру
  *   @return
  *   -------------------------------------------------------------------------------------------
  */
 public function parse()
 {
     if (empty($this->szCode)) {
         throw new Exception('Empty XML-data', XMLPARSER_E_EMPTY);
     }
     // инициализируем парсер
     $this->aCurrent = new XMLNode();
     $this->aCurrent->child = array();
     $xml_parser = xml_parser_create();
     xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 0);
     xml_set_element_handler($xml_parser, array($this, "_parseXMLStartElement"), array($this, "_parseXMLEndElement"));
     xml_set_character_data_handler($xml_parser, array($this, "_parseXMLData"));
     xml_set_default_handler($xml_parser, array($this, "_parseXMLDefault"));
     // парсим
     if (!xml_parse($xml_parser, $this->szCode, true)) {
         throw new Exception(sprintf("XML error: %s at line %d\n", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser)));
     }
     // освобождаем парсер
     xml_parser_free($xml_parser);
     // возращаем результата
     return $this->aCurrent->child[0];
 }
Example #23
0
 function parse($data, $is_final = TRUE)
 {
     if ($this->parser == NULL) {
         $this->parser = xml_parser_create();
         xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);
         xml_set_object($this->parser, $this);
         xml_set_character_data_handler($this->parser, '_charData');
         xml_set_default_handler($this->parser, '_charData');
         xml_set_element_handler($this->parser, '_openTag', '_closeTag');
     }
     $data = preg_replace('/&([a-zA-Z0-9#]+);/', '{ent{$1}}', $data);
     if (!($ret = xml_parse($this->parser, $data, $is_final))) {
         $code = xml_get_error_code($this->parser);
         Error::pitch(new FAError(xml_error_string($code), __FILE__, __LINE__));
     }
     if ($is_final) {
         xml_parser_free($this->parser);
         $this->parser = NULL;
         $this->finalize();
     }
     return $ret;
 }
Example #24
0
 function __construct($xml = '', $params = self::XML_ENCLOSE)
 {
     $this->_params = $params;
     if ($xml) {
         if ($this->_params & self::XML_ARRAY2XML_FORMAT) {
             $domDocument = new CMS_DOMDocument();
             $domDocument->loadXML($xml, 0, false, false);
             $this->_arrOutput = $this->_xml2Array($domDocument->documentElement, $domDocument->encoding);
         } else {
             $parser = xml_parser_create(APPLICATION_DEFAULT_ENCODING);
             xml_set_object($parser, $this);
             xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
             xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
             xml_set_element_handler($parser, "_tagOpen", "_tagClosed");
             xml_set_character_data_handler($parser, "_charData");
             xml_set_processing_instruction_handler($parser, "_piData");
             xml_set_default_handler($parser, "_tagData");
             //enclose with html tag
             if ($this->_params & self::XML_ENCLOSE) {
                 $xml = '<html>' . $xml . '</html>';
             }
             //add encoding declaration
             if ($this->_params ^ self::XML_DONT_ADD_XMLDECL) {
                 $xml = '<?xml version="1.0" encoding="' . APPLICATION_DEFAULT_ENCODING . '"?>' . "\n" . $xml;
             }
             if ($this->_params & self::XML_PROTECT_ENTITIES) {
                 $xml = $this->_codeEntities($xml);
             }
             if (!xml_parse($parser, $xml)) {
                 $this->_parsingError = sprintf("Parse error %s at line %d", xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser));
                 if ($this->_params & ~self::XML_DONT_THROW_ERROR) {
                     $this->raiseError($this->_parsingError . " :\n" . $xml, true);
                 }
             }
             xml_parser_free($parser);
             unset($parser);
         }
     }
 }
 /**
  * Initializes the parser.
  *
  * The constructor method instantiates and configures the underlying XML
  * parser and its handlers.
  *
  * \param $encoding The character encoding to use for this parser. This
  * parameter is optional (defaults to null) and can be safely omitted. See
  * the PHP manual for xml_parser_create for more information about
  * encodings.
  */
 public function __construct($encoding = null)
 {
     $this->finalized = false;
     $this->cdata_buffer = array();
     $this->tags = array();
     /* Create the parser instance */
     if (is_null($encoding)) {
         $this->parser = xml_parser_create();
     } else {
         assert('is_string($encoding)');
         $this->parser = xml_parser_create($encoding);
     }
     /* Set some options */
     xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);
     xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);
     /* Always use UTF-8 */
     xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
     /* Setup the handlers */
     xml_set_element_handler($this->parser, array(&$this, 'start_element_handler'), array(&$this, 'end_element_handler'));
     xml_set_character_data_handler($this->parser, array(&$this, '_handle_data'));
     xml_set_processing_instruction_handler($this->parser, array(&$this, 'handle_pi'));
     xml_set_default_handler($this->parser, array(&$this, '_default_handler'));
 }
Example #26
0
 function parse()
 {
     // Creates the object tree from XML code
     $success = true;
     $error = array();
     $this->parser = xml_parser_create($this->encoding);
     xml_set_object($this->parser, $this);
     xml_set_element_handler($this->parser, "startElement", "endElement");
     xml_set_character_data_handler($this->parser, "characterData");
     xml_set_default_handler($this->parser, "defaultHandler");
     if (!xml_parse($this->parser, $this->xml)) {
         // Error while parsing document
         $success = false;
         $error['err_code'] = $err_code = xml_get_error_code($this->parser);
         $error['err_string'] = xml_error_string($err_code);
         $error['err_line'] = xml_get_current_line_number($this->parser);
         $error['err_col'] = xml_get_current_column_number($this->parser);
         $error['err_byte'] = xml_get_current_byte_index($this->parser);
         //print "<p><b>Error Code:</b> $err_code<br>$err_string<br><b>Line:</b> $err_line<br><b>Column: $err_col</p>";
     }
     xml_parser_free($this->parser);
     return $success === true ? true : $error;
 }
Example #27
0
File: sax.php Project: nursit/SPIP
function xml_sax_dist($page, $apply = false, $phraseur = NULL, $doctype = '', $charset = null)
{
    if (is_null($charset)) {
        $charset = $GLOBALS['meta']['charset'];
    }
    if ($apply) {
        ob_start();
        if (is_array($apply)) {
            $r = call_user_func_array($page, $apply);
        } else {
            $r = $page();
        }
        $page = ob_get_contents();
        ob_end_clean();
        // fonction sans aucun "echo", ca doit etre le resultat
        if (!$page) {
            $page = $r;
        }
    }
    if (!$page) {
        return '';
    }
    // charger la DTD et transcoder les entites,
    // et escamoter le doctype que sax mange en php5 mais pas en  php4
    if (!$doctype) {
        if (!($r = analyser_doctype($page))) {
            $page = _MESSAGE_DOCTYPE . _DOCTYPE_ECRIRE . preg_replace(_REGEXP_DOCTYPE, '', $page);
            $r = analyser_doctype($page);
        }
        list($entete, $avail, $grammaire, $rotlvl) = array_pad($r, 4, null);
        $page = substr($page, strlen($entete));
    } else {
        $avail = 'SYSTEM';
        $grammaire = $doctype;
        $rotlvl = basename($grammaire);
    }
    include_spip('xml/analyser_dtd');
    $dtc = charger_dtd($grammaire, $avail, $rotlvl);
    $page = sax_bug($page, $dtc, $charset);
    // compatibilite Tidy espace public
    if (!$phraseur) {
        $indenter_xml = charger_fonction('indenter', 'xml');
        return $indenter_xml($page, $apply);
    }
    $xml_parser = xml_parser_create($charset);
    xml_set_element_handler($xml_parser, array($phraseur, "debutElement"), array($phraseur, "finElement"));
    xml_set_character_data_handler($xml_parser, array($phraseur, "textElement"));
    xml_set_processing_instruction_handler($xml_parser, array($phraseur, 'piElement'));
    xml_set_default_handler($xml_parser, array($phraseur, "defaultElement"));
    xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, false);
    $phraseur->sax = $xml_parser;
    if (isset($entete)) {
        $phraseur->entete = $entete;
    }
    $phraseur->page = $page;
    $phraseur->dtc = $dtc;
    $phraseur->phraserTout($xml_parser, $page);
    xml_parser_free($xml_parser);
    $phraseur->sax = '';
    return $phraseur;
}
    /**
     * Main class of Spell Checker plugin for Typo3 CMS
     *
     * @return string content produced by the plugin
     */
    public function main()
    {
        $this->csConvObj = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Charset\CharsetConverter::class);
        // Setting start time
        $time_start = microtime(TRUE);
        $this->pspell_is_available = in_array('pspell', get_loaded_extensions());
        $this->AspellDirectory = trim($GLOBALS['TYPO3_CONF_VARS']['EXTCONF'][$this->extKey]['plugins']['SpellChecker']['AspellDirectory']) ?: '/usr/bin/aspell';
        // Setting command mode if requested and available
        $this->forceCommandMode = trim($GLOBALS['TYPO3_CONF_VARS']['EXTCONF'][$this->extKey]['plugins']['SpellChecker']['forceCommandMode']) ?: 0;
        if (!$this->pspell_is_available || $this->forceCommandMode) {
            $AspellVersionString = explode('Aspell', shell_exec($this->AspellDirectory . ' -v'));
            $AspellVersion = substr($AspellVersionString[1], 0, 4);
            if (doubleval($AspellVersion) < doubleval('0.5') && (!$this->pspell_is_available || $this->forceCommandMode)) {
                echo 'Configuration problem: Aspell version ' . $AspellVersion . ' too old. Spell checking cannot be performed in command mode.';
            }
            $this->defaultAspellEncoding = trim(shell_exec($this->AspellDirectory . ' config encoding'));
        }
        // Setting the list of dictionaries
        $dictionaryList = shell_exec($this->AspellDirectory . ' dump dicts');
        $dictionaryList = implode(',', GeneralUtility::trimExplode(LF, $dictionaryList, TRUE));
        $dictionaryArray = GeneralUtility::trimExplode(',', $dictionaryList, TRUE);
        $restrictToDictionaries = GeneralUtility::_POST('restrictToDictionaries');
        if ($restrictToDictionaries) {
            $dictionaryArray = array_intersect($dictionaryArray, GeneralUtility::trimExplode(',', $restrictToDictionaries, 1));
        }
        if (!count($dictionaryArray)) {
            $dictionaryArray[] = 'en';
        }
        $this->dictionary = GeneralUtility::_POST('dictionary');
        $defaultDictionary = $this->dictionary;
        if (!$defaultDictionary || !in_array($defaultDictionary, $dictionaryArray)) {
            $defaultDictionary = 'en';
        }
        uasort($dictionaryArray, 'strcoll');
        $dictionaryList = implode(',', $dictionaryArray);
        // Setting the dictionary
        if (empty($this->dictionary) || !in_array($this->dictionary, $dictionaryArray)) {
            $this->dictionary = 'en';
        }
        // Setting the pspell suggestion mode
        $this->pspellMode = GeneralUtility::_POST('pspell_mode') ? GeneralUtility::_POST('pspell_mode') : $this->pspellMode;
        // Now sanitize $this->pspellMode
        $this->pspellMode = GeneralUtility::inList('ultra,fast,normal,bad-spellers', $this->pspellMode) ? $this->pspellMode : 'normal';
        switch ($this->pspellMode) {
            case 'ultra':
            case 'fast':
                $pspellModeFlag = PSPELL_FAST;
                break;
            case 'bad-spellers':
                $pspellModeFlag = PSPELL_BAD_SPELLERS;
                break;
            case 'normal':
            default:
                $pspellModeFlag = PSPELL_NORMAL;
        }
        // Setting the charset
        if (GeneralUtility::_POST('pspell_charset')) {
            $this->charset = trim(GeneralUtility::_POST('pspell_charset'));
        }
        if (strtolower($this->charset) == 'iso-8859-1') {
            $this->parserCharset = strtolower($this->charset);
        }
        // In some configurations, Aspell uses 'iso8859-1' instead of 'iso-8859-1'
        $this->aspellEncoding = $this->parserCharset;
        if ($this->parserCharset == 'iso-8859-1' && strstr($this->defaultAspellEncoding, '8859-1')) {
            $this->aspellEncoding = $this->defaultAspellEncoding;
        }
        // However, we are going to work only in the parser charset
        if ($this->pspell_is_available && !$this->forceCommandMode) {
            $this->pspell_link = pspell_new($this->dictionary, '', '', $this->parserCharset, $pspellModeFlag);
        }
        // Setting the path to main dictionary
        $this->setMainDictionaryPath();
        // Setting the path to user personal dictionary, if any
        $this->setPersonalDictionaryPath();
        $this->fixPersonalDictionaryCharacterSet();
        $cmd = GeneralUtility::_POST('cmd');
        if ($cmd == 'learn') {
            // Only availble for BE_USERS, die silently if someone has gotten here by accident
            if (TYPO3_MODE !== 'BE' || !is_object($GLOBALS['BE_USER'])) {
                die('');
            }
            // Updating the personal word list
            $to_p_dict = GeneralUtility::_POST('to_p_dict');
            $to_p_dict = $to_p_dict ? $to_p_dict : array();
            $to_r_list = GeneralUtility::_POST('to_r_list');
            $to_r_list = $to_r_list ? $to_r_list : array();
            header('Content-Type: text/plain; charset=' . strtoupper($this->parserCharset));
            header('Pragma: no-cache');
            if ($to_p_dict || $to_r_list) {
                $tmpFileName = GeneralUtility::tempnam($this->filePrefix);
                $filehandle = fopen($tmpFileName, 'wb');
                if ($filehandle) {
                    // Get the character set of the main dictionary
                    // We need to convert the input into the character set of the main dictionary
                    $mainDictionaryCharacterSet = $this->getMainDictionaryCharacterSet();
                    // Write the personal words addition commands to the temporary file
                    foreach ($to_p_dict as $personal_word) {
                        $cmd = '&' . $this->csConvObj->conv($personal_word, $this->parserCharset, $mainDictionaryCharacterSet) . LF;
                        fwrite($filehandle, $cmd, strlen($cmd));
                    }
                    // Write the replacent pairs addition commands to the temporary file
                    foreach ($to_r_list as $replace_pair) {
                        $cmd = '$$ra ' . $this->csConvObj->conv($replace_pair[0], $this->parserCharset, $mainDictionaryCharacterSet) . ' , ' . $this->csConvObj->conv($replace_pair[1], $this->parserCharset, $mainDictionaryCharacterSet) . LF;
                        fwrite($filehandle, $cmd, strlen($cmd));
                    }
                    $cmd = '#' . LF;
                    $result = fwrite($filehandle, $cmd, strlen($cmd));
                    if ($result === FALSE) {
                        GeneralUtility::sysLog('SpellChecker tempfile write error: ' . $tmpFileName, $this->extKey, GeneralUtility::SYSLOG_SEVERITY_ERROR);
                    } else {
                        // Assemble the Aspell command
                        $aspellCommand = (TYPO3_OS === 'WIN' ? 'type ' : 'cat ') . escapeshellarg($tmpFileName) . ' | ' . $this->AspellDirectory . ' -a --mode=none' . ($this->personalDictionaryPath ? ' --home-dir=' . escapeshellarg($this->personalDictionaryPath) : '') . ' --lang=' . escapeshellarg($this->dictionary) . ' --encoding=' . escapeshellarg($mainDictionaryCharacterSet) . ' 2>&1';
                        $aspellResult = shell_exec($aspellCommand);
                        // Close and delete the temporary file
                        fclose($filehandle);
                        GeneralUtility::unlink_tempfile($tmpFileName);
                    }
                } else {
                    GeneralUtility::sysLog('SpellChecker tempfile open error: ' . $tmpFileName, $this->extKey, GeneralUtility::SYSLOG_SEVERITY_ERROR);
                }
            }
            flush();
            die;
        } else {
            // Check spelling content
            // Initialize output
            $this->result = '<?xml version="1.0" encoding="' . $this->parserCharset . '"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="' . substr($this->dictionary, 0, 2) . '" lang="' . substr($this->dictionary, 0, 2) . '">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=' . $this->parserCharset . '" />
<link rel="stylesheet" type="text/css" media="all" href="' . (TYPO3_MODE == 'BE' ? '../' : '') . \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath($this->extKey) . '/Resources/Public/Css/Skin/Plugins/spell-checker-iframe.css" />
<script type="text/javascript">
/*<![CDATA[*/
<!--
';
            // Getting the input content
            $content = GeneralUtility::_POST('content');
            // Parsing the input HTML
            $parser = xml_parser_create(strtoupper($this->parserCharset));
            xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
            xml_set_object($parser, $this);
            if (!xml_set_element_handler($parser, 'startHandler', 'endHandler')) {
                echo 'Bad xml handler setting';
            }
            if (!xml_set_character_data_handler($parser, 'collectDataHandler')) {
                echo 'Bad xml handler setting';
            }
            if (!xml_set_default_handler($parser, 'defaultHandler')) {
                echo 'Bad xml handler setting';
            }
            if (!xml_parse($parser, '<?xml version="1.0" encoding="' . $this->parserCharset . '"?><spellchecker> ' . preg_replace('/&nbsp;/' . ($this->parserCharset == 'utf-8' ? 'u' : ''), ' ', $content) . ' </spellchecker>')) {
                echo 'Bad parsing';
            }
            if (xml_get_error_code($parser)) {
                throw new \UnexpectedException('Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser)), 1294585788);
            }
            xml_parser_free($parser);
            if ($this->pspell_is_available && !$this->forceCommandMode) {
                pspell_clear_session($this->pspell_link);
            }
            $this->result .= 'var suggestedWords = {' . $this->suggestedWords . '};
var dictionaries = "' . $dictionaryList . '";
var selectedDictionary = "' . $this->dictionary . '";
';
            // Calculating parsing and spell checkting time
            $time = number_format(microtime(TRUE) - $time_start, 2, ',', ' ');
            // Insert spellcheck info
            $this->result .= 'var spellcheckInfo = { "Total words":"' . $this->wordCount . '","Misspelled words":"' . sizeof($this->misspelled) . '","Total suggestions":"' . $this->suggestionCount . '","Total words suggested":"' . $this->suggestedWordCount . '","Spelling checked in":"' . $time . '" };
// -->
/*]]>*/
</script>
</head>
';
            $this->result .= '<body onload="window.parent.RTEarea[\'' . GeneralUtility::_POST('editorId') . '\'].editor.getPlugin(\'SpellChecker\').spellCheckComplete();">';
            $this->result .= preg_replace('/' . preg_quote('<?xml') . '.*' . preg_quote('?>') . '[' . preg_quote(LF . CR . chr(32)) . ']*/' . ($this->parserCharset == 'utf-8' ? 'u' : ''), '', $this->text);
            $this->result .= '<div style="display: none;">' . $dictionaries . '</div>';
            // Closing
            $this->result .= '
</body></html>';
            // Outputting
            header('Content-Type: text/html; charset=' . strtoupper($this->parserCharset));
            echo $this->result;
        }
    }
Example #29
0
 /**
  * Parse an xml chunk containing an xmlrpc request and execute the corresponding
  * php function registered with the server
  * @param string $data the xml request
  * @param string $req_encoding (optional) the charset encoding of the xml request
  * @return xmlrpcresp
  * @access private
  */
 function parseRequest($data, $req_encoding = '')
 {
     // 2005/05/07 commented and moved into caller function code
     //if($data=='')
     //{
     //	$data=$GLOBALS['HTTP_RAW_POST_DATA'];
     //}
     // G. Giunta 2005/02/13: we do NOT expect to receive html entities
     // so we do not try to convert them into xml character entities
     //$data = xmlrpc_html_entity_xlate($data);
     $GLOBALS['_xh'] = array();
     $GLOBALS['_xh']['ac'] = '';
     $GLOBALS['_xh']['stack'] = array();
     $GLOBALS['_xh']['valuestack'] = array();
     $GLOBALS['_xh']['params'] = array();
     $GLOBALS['_xh']['pt'] = array();
     $GLOBALS['_xh']['isf'] = 0;
     $GLOBALS['_xh']['isf_reason'] = '';
     $GLOBALS['_xh']['method'] = false;
     // so we can check later if we got a methodname or not
     $GLOBALS['_xh']['rt'] = '';
     // decompose incoming XML into request structure
     if ($req_encoding != '') {
         if (!in_array($req_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
             error_log('XML-RPC: xmlrpc_server::parseRequest: invalid charset encoding of received request: ' . $req_encoding);
             $req_encoding = $GLOBALS['xmlrpc_defencoding'];
         }
         /// @BUG this will fail on PHP 5 if charset is not specified in the xml prologue,
         // the encoding is not UTF8 and there are non-ascii chars in the text...
         $parser = xml_parser_create($req_encoding);
     } else {
         $parser = xml_parser_create();
     }
     xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
     // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell
     // the xml parser to give us back data in the expected charset
     xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $GLOBALS['xmlrpc_internalencoding']);
     if ($this->functions_parameters_type != 'xmlrpcvals') {
         xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
     } else {
         xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');
     }
     xml_set_character_data_handler($parser, 'xmlrpc_cd');
     xml_set_default_handler($parser, 'xmlrpc_dh');
     if (!xml_parse($parser, $data, 1)) {
         // return XML error as a faultCode
         $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerrxml'] + xml_get_error_code($parser), sprintf('XML error: %s at line %d, column %d', xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser), xml_get_current_column_number($parser)));
         xml_parser_free($parser);
     } elseif ($GLOBALS['_xh']['isf']) {
         xml_parser_free($parser);
         $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['invalid_request'], $GLOBALS['xmlrpcstr']['invalid_request'] . ' ' . $GLOBALS['_xh']['isf_reason']);
     } else {
         xml_parser_free($parser);
         if ($this->functions_parameters_type != 'xmlrpcvals') {
             if ($this->debug > 1) {
                 $this->debugmsg("\n+++PARSED+++\n" . var_export($GLOBALS['_xh']['params'], true) . "\n+++END+++");
             }
             $r = $this->execute($GLOBALS['_xh']['method'], $GLOBALS['_xh']['params'], $GLOBALS['_xh']['pt']);
         } else {
             // build an xmlrpcmsg object with data parsed from xml
             $m = new xmlrpcmsg($GLOBALS['_xh']['method']);
             // now add parameters in
             for ($i = 0; $i < count($GLOBALS['_xh']['params']); $i++) {
                 $m->addParam($GLOBALS['_xh']['params'][$i]);
             }
             if ($this->debug > 1) {
                 $this->debugmsg("\n+++PARSED+++\n" . var_export($m, true) . "\n+++END+++");
             }
             $r = $this->execute($m);
         }
     }
     return $r;
 }
 /**
  * Reads a string and parses the XML data.
  *
  * Parse the XML source and (upon success) store the information into an internal structure.
  * If a parent xpath is given this means that XML data is to be *appended* to that parent.
  *
  * ### If a function uses setLastError(), then say in the function header that getLastError() is useful.
  *
  * @param  $xmlString           (string) Name of the string to be read and parsed.
  * @param  $absoluteParentPath  (string) Node to append data too (see above)
  * @return                      (bool)   TRUE on success, FALSE on failure 
  *                                       (check getLastError())
  */
 function importFromString($xmlString, $absoluteParentPath = '')
 {
     $bDebugThisFunction = FALSE;
     if ($bDebugThisFunction) {
         $aStartTime = $this->_beginDebugFunction("importFromString");
         echo "Importing from string of length " . strlen($xmlString) . " to node '{$absoluteParentPath}'\n<br>";
         echo "Parser options:\n<br>";
         print_r($this->parseOptions);
     }
     $status = FALSE;
     $errStr = '';
     do {
         // try-block
         // If we already have content, then complain.
         if (!empty($this->nodeRoot) and empty($absoluteParentPath)) {
             $errStr = 'Called when this object already contains xml data. Use reset() or pass the parent Xpath as 2ed param to where tie data will append.';
             break;
             // try-block
         }
         // Check whether content has been read.
         if (empty($xmlString)) {
             // Nothing to do!!
             $status = TRUE;
             // If we were importing to root, build a blank root.
             if (empty($absoluteParentPath)) {
                 $this->_createSuperRoot();
             }
             $this->reindexNodeTree();
             //        $errStr = 'This xml document (string) was empty';
             break;
             // try-block
         } else {
             $xmlString = $this->_translateAmpersand($xmlString);
         }
         // Restart our node index with a root entry.
         $nodeStack = array();
         $this->parseStackIndex = 0;
         // If a parent xpath is given this means that XML data is to be *appended* to that parent.
         if (!empty($absoluteParentPath)) {
             // Check if parent exists
             if (!isset($nodeIndex[$absoluteParentPath])) {
                 $errStr = "You tried to append XML data to a parent '{$absoluteParentPath}' that does not exist.";
                 break;
                 // try-block
             }
             // Add it as the starting point in our array.
             $this->nodeStack[0] =& $nodeIndex[$absoluteParentPath];
         } else {
             // Build a 'super-root'
             $this->_createSuperRoot();
             // Put it in as the start of our node stack.
             $this->nodeStack[0] =& $this->nodeRoot;
         }
         // Point our text buffer reference at the next text part of the root
         $this->parsedTextLocation =& $this->nodeStack[0]['textParts'][];
         $this->parsInCData = 0;
         // We cache this now.
         $this->parseSkipWhiteCache = isset($this->parseOptions[XML_OPTION_SKIP_WHITE]) ? $this->parseOptions[XML_OPTION_SKIP_WHITE] : FALSE;
         // Create an XML parser.
         $parser = xml_parser_create();
         // Set default XML parser options.
         if (is_array($this->parseOptions)) {
             foreach ($this->parseOptions as $key => $val) {
                 xml_parser_set_option($parser, $key, $val);
             }
         }
         // Set the object and the element handlers for the XML parser.
         xml_set_object($parser, $this);
         xml_set_element_handler($parser, '_handleStartElement', '_handleEndElement');
         xml_set_character_data_handler($parser, '_handleCharacterData');
         xml_set_default_handler($parser, '_handleDefaultData');
         xml_set_processing_instruction_handler($parser, '_handlePI');
         if ($bDebugThisFunction) {
             $this->_profileFunction($aStartTime, "Setup for parse");
         }
         // Parse the XML source and on error generate an error message.
         if (!xml_parse($parser, $xmlString, TRUE)) {
             $source = empty($this->properties['xmlFile']) ? 'string' : 'file ' . basename($this->properties['xmlFile']) . "'";
             $errStr = "XML error in given {$source} on line " . xml_get_current_line_number($parser) . '  column ' . xml_get_current_column_number($parser) . '. Reason:' . xml_error_string(xml_get_error_code($parser));
             break;
             // try-block
         }
         // Free the parser.
         @xml_parser_free($parser);
         // And we don't need this any more.
         $this->nodeStack = array();
         if ($bDebugThisFunction) {
             $this->_profileFunction($aStartTime, "Parse Object");
         }
         $this->reindexNodeTree();
         if ($bDebugThisFunction) {
             print_r(array_keys($this->nodeIndex));
         }
         if ($bDebugThisFunction) {
             $this->_profileFunction($aStartTime, "Reindex Object");
         }
         $status = TRUE;
     } while (FALSE);
     if (!$status) {
         $this->_displayError('In importFromString(): ' . $errStr, __LINE__, __FILE__, FALSE);
         $bResult = FALSE;
     } else {
         $bResult = TRUE;
     }
     ////////////////////////////////////////////
     if ($bDebugThisFunction) {
         $this->_closeDebugFunction($aStartTime, $bResult);
     }
     return $bResult;
 }