3 namespace PhpXmlRpc\Helper;
5 use PhpXmlRpc\PhpXmlRpc;
9 * Deals with parsing the XML.
13 const RETURN_XMLRPCVALS = 'xmlrpcvals';
14 const RETURN_PHP = 'phpvals';
16 const ACCEPT_REQUEST = 1;
17 const ACCEPT_RESPONSE = 2;
18 const ACCEPT_VALUE = 4;
20 // Used to store state during parsing.
21 // Quick explanation of components:
23 // ac - used to accumulate values
24 // stack - array with genealogy of xml elements names used to validate nesting of xmlrpc elements
25 // valuestack - array used for parsing arrays and structs
26 // lv - used to indicate "looking for a value": implements the logic to allow values with no types to be strings
28 // isf - used to indicate an xml parsing fault (3), invalid xmlrpc fault (2) or xmlrpc response fault (1)
29 // isf_reason - used for storing xmlrpc response fault string
30 // method - used to store method name
31 // params - used to store parameters in method calls
32 // pt - used to store the type of each received parameter. Useful if parameters are automatically decoded to php values
33 // rt - 'methodcall', 'methodresponse' or 'value'
37 'valuestack' => array(),
46 public $xmlrpc_valid_parents = array(
47 'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT'),
48 'BOOLEAN' => array('VALUE'),
49 'I4' => array('VALUE'),
50 'I8' => array('VALUE'),
51 'EX:I8' => array('VALUE'),
52 'INT' => array('VALUE'),
53 'STRING' => array('VALUE'),
54 'DOUBLE' => array('VALUE'),
55 'DATETIME.ISO8601' => array('VALUE'),
56 'BASE64' => array('VALUE'),
57 'MEMBER' => array('STRUCT'),
58 'NAME' => array('MEMBER'),
59 'DATA' => array('ARRAY'),
60 'ARRAY' => array('VALUE'),
61 'STRUCT' => array('VALUE'),
62 'PARAM' => array('PARAMS'),
63 'METHODNAME' => array('METHODCALL'),
64 'PARAMS' => array('METHODCALL', 'METHODRESPONSE'),
65 'FAULT' => array('METHODRESPONSE'),
66 'NIL' => array('VALUE'), // only used when extension activated
67 'EX:NIL' => array('VALUE'), // only used when extension activated
70 /** @var array $parsing_options */
71 protected $parsing_options = array();
72 /** @var int $accept */
73 protected $accept = 3; // self::ACCEPT_REQUEST | self::ACCEPT_RESPONSE;
74 /** @var int $maxChunkLength */
75 protected $maxChunkLength = 4194304; // 4 MB
78 * @param array $options passed to the xml parser
80 public function __construct(array $options = array())
82 $this->parsing_options = $options;
86 * @param array $options passed to the xml parser
88 public function setParsingOptions(array $options)
90 $this->parsing_options = $options;
95 * @param string $returnType
96 * @param int $accept a bit-combination of self::ACCEPT_REQUEST, self::ACCEPT_RESPONSE, self::ACCEPT_VALUE
99 public function parse($data, $returnType = self::RETURN_XMLRPCVALS, $accept = 3)
101 $parser = xml_parser_create();
103 foreach ($this->parsing_options as $key => $val) {
104 xml_parser_set_option($parser, $key, $val);
107 xml_set_object($parser, $this);
109 if ($returnType == self::RETURN_PHP) {
110 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
112 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');
115 xml_set_character_data_handler($parser, 'xmlrpc_cd');
116 xml_set_default_handler($parser, 'xmlrpc_dh');
118 $this->accept = $accept;
123 'valuestack' => array(),
126 'method' => false, // so we can check later if we got a methodname or not
132 $len = strlen($data);
133 for ($offset = 0; $offset < $len; $offset += $this->maxChunkLength) {
134 $chunk = substr($data, $offset, $this->maxChunkLength);
135 // error handling: xml not well formed
136 if (!xml_parse($parser, $chunk, $offset + $this->maxChunkLength >= $len)) {
137 $errCode = xml_get_error_code($parser);
138 $errStr = sprintf('XML error %s: %s at line %d, column %d', $errCode, xml_error_string($errCode),
139 xml_get_current_line_number($parser), xml_get_current_column_number($parser));
141 $this->_xh['isf'] = 3;
142 $this->_xh['isf_reason'] = $errStr;
147 xml_parser_free($parser);
151 * xml parser handler function for opening element tags.
152 * @param resource $parser
153 * @param string $name
155 * @param bool $acceptSingleVals DEPRECATED use the $accept parameter instead
157 public function xmlrpc_se($parser, $name, $attrs, $acceptSingleVals = false)
159 // if invalid xmlrpc already detected, skip all processing
160 if ($this->_xh['isf'] < 2) {
162 // check for correct element nesting
163 if (count($this->_xh['stack']) == 0) {
164 // top level element can only be of 2 types
165 /// @todo optimization creep: save this check into a bool variable, instead of using count() every time:
166 /// there is only a single top level element in xml anyway
168 if ($acceptSingleVals === false) {
169 $accept = $this->accept;
171 $accept = self::ACCEPT_REQUEST | self::ACCEPT_RESPONSE | self::ACCEPT_VALUE;
173 if (($name == 'METHODCALL' && ($accept & self::ACCEPT_REQUEST)) ||
174 ($name == 'METHODRESPONSE' && ($accept & self::ACCEPT_RESPONSE)) ||
175 ($name == 'VALUE' && ($accept & self::ACCEPT_VALUE))) {
176 $this->_xh['rt'] = strtolower($name);
178 $this->_xh['isf'] = 2;
179 $this->_xh['isf_reason'] = 'missing top level xmlrpc element. Found: ' . $name;
184 // not top level element: see if parent is OK
185 $parent = end($this->_xh['stack']);
186 if (!array_key_exists($name, $this->xmlrpc_valid_parents) || !in_array($parent, $this->xmlrpc_valid_parents[$name])) {
187 $this->_xh['isf'] = 2;
188 $this->_xh['isf_reason'] = "xmlrpc element $name cannot be child of $parent";
195 // optimize for speed switch cases: most common cases first
197 /// @todo we could check for 2 VALUE elements inside a MEMBER or PARAM element
198 $this->_xh['vt'] = 'value'; // indicator: no value found yet
199 $this->_xh['ac'] = '';
200 $this->_xh['lv'] = 1;
201 $this->_xh['php_class'] = null;
205 if (PHP_INT_SIZE === 4) {
206 // INVALID ELEMENT: RAISE ISF so that it is later recognized!!!
207 $this->_xh['isf'] = 2;
208 $this->_xh['isf_reason'] = "Received i8 element but php is compiled in 32 bit mode";
212 // fall through voluntarily
218 case 'DATETIME.ISO8601':
220 if ($this->_xh['vt'] != 'value') {
221 // two data elements inside a value: an error occurred!
222 $this->_xh['isf'] = 2;
223 $this->_xh['isf_reason'] = "$name element following a {$this->_xh['vt']} element inside a single value";
227 $this->_xh['ac'] = ''; // reset the accumulator
231 if ($this->_xh['vt'] != 'value') {
232 // two data elements inside a value: an error occurred!
233 $this->_xh['isf'] = 2;
234 $this->_xh['isf_reason'] = "$name element following a {$this->_xh['vt']} element inside a single value";
238 // create an empty array to hold child values, and push it onto appropriate stack
240 $curVal['values'] = array();
241 $curVal['type'] = $name;
242 // check for out-of-band information to rebuild php objs
243 // and in case it is found, save it
244 if (@isset($attrs['PHP_CLASS'])) {
245 $curVal['php_class'] = $attrs['PHP_CLASS'];
247 $this->_xh['valuestack'][] = $curVal;
248 $this->_xh['vt'] = 'data'; // be prepared for a data element next
251 if ($this->_xh['vt'] != 'data') {
252 // two data elements inside a value: an error occurred!
253 $this->_xh['isf'] = 2;
254 $this->_xh['isf_reason'] = "found two data elements inside an array element";
259 case 'METHODRESPONSE':
261 // valid elements that add little to processing
265 /// @todo we could check for 2 NAME elements inside a MEMBER element
266 $this->_xh['ac'] = '';
269 $this->_xh['isf'] = 1;
272 // set member name to null, in case we do not find in the xml later on
273 $this->_xh['valuestack'][count($this->_xh['valuestack']) - 1]['name'] = '';
274 //$this->_xh['ac']='';
275 // Drop trough intentionally
277 // clear value type, so we can check later if no value has been passed for this param/member
278 $this->_xh['vt'] = null;
282 if (PhpXmlRpc::$xmlrpc_null_extension) {
283 if ($this->_xh['vt'] != 'value') {
284 // two data elements inside a value: an error occurred!
285 $this->_xh['isf'] = 2;
286 $this->_xh['isf_reason'] = "$name element following a {$this->_xh['vt']} element inside a single value";
290 $this->_xh['ac'] = ''; // reset the accumulator
293 // we do not support the <NIL/> extension, so
294 // drop through intentionally
296 /// INVALID ELEMENT: RAISE ISF so that it is later recognized!!!
297 $this->_xh['isf'] = 2;
298 $this->_xh['isf_reason'] = "found not-xmlrpc xml element $name";
302 // Save current element name to stack, to validate nesting
303 $this->_xh['stack'][] = $name;
305 /// @todo optimization creep: move this inside the big switch() above
306 if ($name != 'VALUE') {
307 $this->_xh['lv'] = 0;
313 * xml parser handler function for opening element tags.
314 * Used in decoding xml chunks that might represent single xmlrpc values as well as requests, responses.
316 * @param resource $parser
320 public function xmlrpc_se_any($parser, $name, $attrs)
322 $this->xmlrpc_se($parser, $name, $attrs, true);
326 * xml parser handler function for close element tags.
327 * @param resource $parser
328 * @param string $name
329 * @param bool $rebuildXmlrpcvals
331 public function xmlrpc_ee($parser, $name, $rebuildXmlrpcvals = true)
333 if ($this->_xh['isf'] < 2) {
334 // push this element name from stack
335 // NB: if XML validates, correct opening/closing is guaranteed and
336 // we do not have to check for $name == $currElem.
337 // we also checked for proper nesting at start of elements...
338 $currElem = array_pop($this->_xh['stack']);
342 // This if() detects if no scalar was inside <VALUE></VALUE>
343 if ($this->_xh['vt'] == 'value') {
344 $this->_xh['value'] = $this->_xh['ac'];
345 $this->_xh['vt'] = Value::$xmlrpcString;
348 if ($rebuildXmlrpcvals) {
349 // build the xmlrpc val out of the data received, and substitute it
350 $temp = new Value($this->_xh['value'], $this->_xh['vt']);
351 // in case we got info about underlying php class, save it
352 // in the object we're rebuilding
353 if (isset($this->_xh['php_class'])) {
354 $temp->_php_class = $this->_xh['php_class'];
356 // check if we are inside an array or struct:
357 // if value just built is inside an array, let's move it into array on the stack
358 $vscount = count($this->_xh['valuestack']);
359 if ($vscount && $this->_xh['valuestack'][$vscount - 1]['type'] == 'ARRAY') {
360 $this->_xh['valuestack'][$vscount - 1]['values'][] = $temp;
362 $this->_xh['value'] = $temp;
365 /// @todo this needs to treat correctly php-serialized objects,
366 /// since std deserializing is done by php_xmlrpc_decode,
367 /// which we will not be calling...
368 if (isset($this->_xh['php_class'])) {
371 // check if we are inside an array or struct:
372 // if value just built is inside an array, let's move it into array on the stack
373 $vscount = count($this->_xh['valuestack']);
374 if ($vscount && $this->_xh['valuestack'][$vscount - 1]['type'] == 'ARRAY') {
375 $this->_xh['valuestack'][$vscount - 1]['values'][] = $this->_xh['value'];
386 case 'DATETIME.ISO8601':
388 $this->_xh['vt'] = strtolower($name);
389 /// @todo: optimization creep - remove the if/elseif cycle below
390 /// since the case() in which we are already did that
391 if ($name == 'STRING') {
392 $this->_xh['value'] = $this->_xh['ac'];
393 } elseif ($name == 'DATETIME.ISO8601') {
394 if (!preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $this->_xh['ac'])) {
395 error_log('XML-RPC: ' . __METHOD__ . ': invalid value received in DATETIME: ' . $this->_xh['ac']);
397 $this->_xh['vt'] = Value::$xmlrpcDateTime;
398 $this->_xh['value'] = $this->_xh['ac'];
399 } elseif ($name == 'BASE64') {
400 /// @todo check for failure of base64 decoding / catch warnings
401 $this->_xh['value'] = base64_decode($this->_xh['ac']);
402 } elseif ($name == 'BOOLEAN') {
403 // special case here: we translate boolean 1 or 0 into PHP
404 // constants true or false.
405 // Strings 'true' and 'false' are accepted, even though the
406 // spec never mentions them (see eg. Blogger api docs)
407 // NB: this simple checks helps a lot sanitizing input, ie no
408 // security problems around here
409 if ($this->_xh['ac'] == '1' || strcasecmp($this->_xh['ac'], 'true') == 0) {
410 $this->_xh['value'] = true;
412 // log if receiving something strange, even though we set the value to false anyway
413 if ($this->_xh['ac'] != '0' && strcasecmp($this->_xh['ac'], 'false') != 0) {
414 error_log('XML-RPC: ' . __METHOD__ . ': invalid value received in BOOLEAN: ' . $this->_xh['ac']);
416 $this->_xh['value'] = false;
418 } elseif ($name == 'DOUBLE') {
420 // we must check that only 0123456789-.<space> are characters here
421 // NOTE: regexp could be much stricter than this...
422 if (!preg_match('/^[+-eE0123456789 \t.]+$/', $this->_xh['ac'])) {
423 /// @todo: find a better way of throwing an error than this!
424 error_log('XML-RPC: ' . __METHOD__ . ': non numeric value received in DOUBLE: ' . $this->_xh['ac']);
425 $this->_xh['value'] = 'ERROR_NON_NUMERIC_FOUND';
427 // it's ok, add it on
428 $this->_xh['value'] = (double)$this->_xh['ac'];
431 // we have an I4/I8/INT
432 // we must check that only 0123456789-<space> are characters here
433 if (!preg_match('/^[+-]?[0123456789 \t]+$/', $this->_xh['ac'])) {
434 /// @todo find a better way of throwing an error than this!
435 error_log('XML-RPC: ' . __METHOD__ . ': non numeric value received in INT: ' . $this->_xh['ac']);
436 $this->_xh['value'] = 'ERROR_NON_NUMERIC_FOUND';
438 // it's ok, add it on
439 $this->_xh['value'] = (int)$this->_xh['ac'];
442 $this->_xh['lv'] = 3; // indicate we've found a value
445 $this->_xh['valuestack'][count($this->_xh['valuestack']) - 1]['name'] = $this->_xh['ac'];
448 // add to array in the stack the last element built,
449 // unless no VALUE was found
450 if ($this->_xh['vt']) {
451 $vscount = count($this->_xh['valuestack']);
452 $this->_xh['valuestack'][$vscount - 1]['values'][$this->_xh['valuestack'][$vscount - 1]['name']] = $this->_xh['value'];
454 error_log('XML-RPC: ' . __METHOD__ . ': missing VALUE inside STRUCT in received xml');
458 $this->_xh['vt'] = null; // reset this to check for 2 data elements in a row - even if they're empty
462 // fetch out of stack array of values, and promote it to current value
463 $currVal = array_pop($this->_xh['valuestack']);
464 $this->_xh['value'] = $currVal['values'];
465 $this->_xh['vt'] = strtolower($name);
466 if (isset($currVal['php_class'])) {
467 $this->_xh['php_class'] = $currVal['php_class'];
471 // add to array of params the current value,
472 // unless no VALUE was found
473 if ($this->_xh['vt']) {
474 $this->_xh['params'][] = $this->_xh['value'];
475 $this->_xh['pt'][] = $this->_xh['vt'];
477 error_log('XML-RPC: ' . __METHOD__ . ': missing VALUE inside PARAM in received xml');
481 $this->_xh['method'] = preg_replace('/^[\n\r\t ]+/', '', $this->_xh['ac']);
485 if (PhpXmlRpc::$xmlrpc_null_extension) {
486 $this->_xh['vt'] = 'null';
487 $this->_xh['value'] = null;
488 $this->_xh['lv'] = 3;
491 // drop through intentionally if nil extension not enabled
495 case 'METHORESPONSE':
498 // End of INVALID ELEMENT!
499 // shall we add an assert here for unreachable code???
506 * Used in decoding xmlrpc requests/responses without rebuilding xmlrpc Values.
507 * @param resource $parser
508 * @param string $name
510 public function xmlrpc_ee_fast($parser, $name)
512 $this->xmlrpc_ee($parser, $name, false);
516 * xml parser handler function for character data.
517 * @param resource $parser
518 * @param string $data
520 public function xmlrpc_cd($parser, $data)
522 // skip processing if xml fault already detected
523 if ($this->_xh['isf'] < 2) {
524 // "lookforvalue==3" means that we've found an entire value
525 // and should discard any further character data
526 if ($this->_xh['lv'] != 3) {
527 $this->_xh['ac'] .= $data;
533 * xml parser handler function for 'other stuff', ie. not char data or
534 * element start/end tag. In fact it only gets called on unknown entities...
538 public function xmlrpc_dh($parser, $data)
540 // skip processing if xml fault already detected
541 if ($this->_xh['isf'] < 2) {
542 if (substr($data, 0, 1) == '&' && substr($data, -1, 1) == ';') {
543 $this->_xh['ac'] .= $data;
551 * xml charset encoding guessing helper function.
552 * Tries to determine the charset encoding of an XML chunk received over HTTP.
553 * NB: according to the spec (RFC 3023), if text/xml content-type is received over HTTP without a content-type,
554 * we SHOULD assume it is strictly US-ASCII. But we try to be more tolerant of non conforming (legacy?) clients/servers,
555 * which will be most probably using UTF-8 anyway...
556 * In order of importance checks:
560 * 4. guesses using mb_detect_encoding()
562 * @param string $httpHeader the http Content-type header
563 * @param string $xmlChunk xml content buffer
564 * @param string $encodingPrefs comma separated list of character encodings to be used as default (when mb extension is enabled).
565 * This can also be set globally using PhpXmlRpc::$xmlrpc_detectencodings
566 * @return string the encoding determined. Null if it can't be determined and mbstring is enabled,
567 * PhpXmlRpc::$xmlrpc_defencoding if it can't be determined and mbstring is not enabled
569 * @todo explore usage of mb_http_input(): does it detect http headers + post data? if so, use it instead of hand-detection!!!
571 public static function guessEncoding($httpHeader = '', $xmlChunk = '', $encodingPrefs = null)
573 // discussion: see http://www.yale.edu/pclt/encoding/
574 // 1 - test if encoding is specified in HTTP HEADERS
577 // LWS: (\13\10)?( |\t)+
578 // token: (any char but excluded stuff)+
579 // quoted string: " (any char but double quotes and control chars)* "
580 // header: Content-type = ...; charset=value(; ...)*
581 // where value is of type token, no LWS allowed between 'charset' and value
582 // Note: we do not check for invalid chars in VALUE:
583 // this had better be done using pure ereg as below
584 // Note 2: we might be removing whitespace/tabs that ought to be left in if
585 // the received charset is a quoted string. But nobody uses such charset names...
587 /// @todo this test will pass if ANY header has charset specification, not only Content-Type. Fix it?
589 if (preg_match('/;\s*charset\s*=([^;]+)/i', $httpHeader, $matches)) {
590 return strtoupper(trim($matches[1], " \t\""));
593 // 2 - scan the first bytes of the data for a UTF-16 (or other) BOM pattern
594 // (source: http://www.w3.org/TR/2000/REC-xml-20001006)
595 // NOTE: actually, according to the spec, even if we find the BOM and determine
596 // an encoding, we should check if there is an encoding specified
597 // in the xml declaration, and verify if they match.
598 /// @todo implement check as described above?
599 /// @todo implement check for first bytes of string even without a BOM? (It sure looks harder than for cases WITH a BOM)
600 if (preg_match('/^(\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\x00\x00\xFF\xFE|\xFE\xFF\x00\x00)/', $xmlChunk)) {
602 } elseif (preg_match('/^(\xFE\xFF|\xFF\xFE)/', $xmlChunk)) {
604 } elseif (preg_match('/^(\xEF\xBB\xBF)/', $xmlChunk)) {
608 // 3 - test if encoding is specified in the xml declaration
610 // SPACE: (#x20 | #x9 | #xD | #xA)+ === [ \x9\xD\xA]+
611 // EQ: SPACE?=SPACE? === [ \x9\xD\xA]*=[ \x9\xD\xA]*
612 if (preg_match('/^<\?xml\s+version\s*=\s*' . "((?:\"[a-zA-Z0-9_.:-]+\")|(?:'[a-zA-Z0-9_.:-]+'))" .
613 '\s+encoding\s*=\s*' . "((?:\"[A-Za-z][A-Za-z0-9._-]*\")|(?:'[A-Za-z][A-Za-z0-9._-]*'))/",
614 $xmlChunk, $matches)) {
615 return strtoupper(substr($matches[2], 1, -1));
618 // 4 - if mbstring is available, let it do the guesswork
619 if (extension_loaded('mbstring')) {
620 if ($encodingPrefs == null && PhpXmlRpc::$xmlrpc_detectencodings != null) {
621 $encodingPrefs = PhpXmlRpc::$xmlrpc_detectencodings;
623 if ($encodingPrefs) {
624 $enc = mb_detect_encoding($xmlChunk, $encodingPrefs);
626 $enc = mb_detect_encoding($xmlChunk);
628 // NB: mb_detect likes to call it ascii, xml parser likes to call it US_ASCII...
629 // IANA also likes better US-ASCII, so go with it
630 if ($enc == 'ASCII') {
636 // no encoding specified: as per HTTP1.1 assume it is iso-8859-1?
637 // Both RFC 2616 (HTTP 1.1) and 1945 (HTTP 1.0) clearly state that for text/xxx content types
638 // this should be the standard. And we should be getting text/xml as request and response.
639 // BUT we have to be backward compatible with the lib, which always used UTF-8 as default...
640 return PhpXmlRpc::$xmlrpc_defencoding;
645 * Helper function: checks if an xml chunk as a charset declaration (BOM or in the xml declaration)
647 * @param string $xmlChunk
650 public static function hasEncoding($xmlChunk)
652 // scan the first bytes of the data for a UTF-16 (or other) BOM pattern
653 // (source: http://www.w3.org/TR/2000/REC-xml-20001006)
654 if (preg_match('/^(\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\x00\x00\xFF\xFE|\xFE\xFF\x00\x00)/', $xmlChunk)) {
656 } elseif (preg_match('/^(\xFE\xFF|\xFF\xFE)/', $xmlChunk)) {
658 } elseif (preg_match('/^(\xEF\xBB\xBF)/', $xmlChunk)) {
662 // test if encoding is specified in the xml declaration
664 // SPACE: (#x20 | #x9 | #xD | #xA)+ === [ \x9\xD\xA]+
665 // EQ: SPACE?=SPACE? === [ \x9\xD\xA]*=[ \x9\xD\xA]*
666 if (preg_match('/^<\?xml\s+version\s*=\s*' . "((?:\"[a-zA-Z0-9_.:-]+\")|(?:'[a-zA-Z0-9_.:-]+'))" .
667 '\s+encoding\s*=\s*' . "((?:\"[A-Za-z][A-Za-z0-9._-]*\")|(?:'[A-Za-z][A-Za-z0-9._-]*'))/",
668 $xmlChunk, $matches)) {