Merge branch 'master' of github.com:gggeek/phpxmlrpc
[plcapi.git] / src / Helper / XMLParser.php
1 <?php
2
3 namespace PhpXmlRpc\Helper;
4
5 use PhpXmlRpc\PhpXmlRpc;
6 use PhpXmlRpc\Value;
7
8 /**
9  * Deals with parsing the XML.
10  */
11 class XMLParser
12 {
13     const RETURN_XMLRPCVALS = 'xmlrpcvals';
14     const RETURN_PHP = 'phpvals';
15
16     const ACCEPT_REQUEST = 1;
17     const ACCEPT_RESPONSE = 2;
18     const ACCEPT_VALUE = 4;
19
20     // Used to store state during parsing.
21     // Quick explanation of components:
22     //  private:
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
27     //  public:
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'
34     public $_xh = array(
35         'ac' => '',
36         'stack' => array(),
37         'valuestack' => array(),
38         'isf' => 0,
39         'isf_reason' => '',
40         'method' => false,
41         'params' => array(),
42         'pt' => array(),
43         'rt' => '',
44     );
45
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
68     );
69
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
76
77     /**
78      * @param array $options passed to the xml parser
79      */
80     public function __construct(array $options = array())
81     {
82         $this->parsing_options = $options;
83     }
84
85     /**
86      * @param array $options passed to the xml parser
87      */
88     public function setParsingOptions(array $options)
89     {
90         $this->parsing_options = $options;
91     }
92
93     /**
94      * @param string $data
95      * @param string $returnType
96      * @param int $accept a bit-combination of self::ACCEPT_REQUEST, self::ACCEPT_RESPONSE, self::ACCEPT_VALUE
97      * @return string
98      */
99     public function parse($data, $returnType = self::RETURN_XMLRPCVALS, $accept = 3)
100     {
101         $parser = xml_parser_create();
102
103         foreach ($this->parsing_options as $key => $val) {
104             xml_parser_set_option($parser, $key, $val);
105         }
106
107         xml_set_object($parser, $this);
108
109         if ($returnType == self::RETURN_PHP) {
110             xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
111         } else {
112             xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');
113         }
114
115         xml_set_character_data_handler($parser, 'xmlrpc_cd');
116         xml_set_default_handler($parser, 'xmlrpc_dh');
117
118         $this->accept = $accept;
119
120         $this->_xh = array(
121             'ac' => '',
122             'stack' => array(),
123             'valuestack' => array(),
124             'isf' => 0,
125             'isf_reason' => '',
126             'method' => false, // so we can check later if we got a methodname or not
127             'params' => array(),
128             'pt' => array(),
129             'rt' => '',
130         );
131
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));
140
141                 $this->_xh['isf'] = 3;
142                 $this->_xh['isf_reason'] = $errStr;
143                 break;
144             }
145         }
146
147         xml_parser_free($parser);
148     }
149
150     /**
151      * xml parser handler function for opening element tags.
152      * @param resource $parser
153      * @param string $name
154      * @param $attrs
155      * @param bool $acceptSingleVals DEPRECATED use the $accept parameter instead
156      */
157     public function xmlrpc_se($parser, $name, $attrs, $acceptSingleVals = false)
158     {
159         // if invalid xmlrpc already detected, skip all processing
160         if ($this->_xh['isf'] < 2) {
161
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
167                 // BC
168                 if ($acceptSingleVals === false) {
169                     $accept = $this->accept;
170                 } else {
171                     $accept = self::ACCEPT_REQUEST | self::ACCEPT_RESPONSE | self::ACCEPT_VALUE;
172                 }
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);
177                 } else {
178                     $this->_xh['isf'] = 2;
179                     $this->_xh['isf_reason'] = 'missing top level xmlrpc element. Found: ' . $name;
180
181                     return;
182                 }
183             } else {
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";
189
190                     return;
191                 }
192             }
193
194             switch ($name) {
195                 // optimize for speed switch cases: most common cases first
196                 case 'VALUE':
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;
202                     break;
203                 case 'I8':
204                 case 'EX:I8':
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";
209
210                         return;
211                     }
212                 // fall through voluntarily
213                 case 'I4':
214                 case 'INT':
215                 case 'STRING':
216                 case 'BOOLEAN':
217                 case 'DOUBLE':
218                 case 'DATETIME.ISO8601':
219                 case 'BASE64':
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";
224
225                         return;
226                     }
227                     $this->_xh['ac'] = ''; // reset the accumulator
228                     break;
229                 case 'STRUCT':
230                 case 'ARRAY':
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";
235
236                         return;
237                     }
238                     // create an empty array to hold child values, and push it onto appropriate stack
239                     $curVal = array();
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'];
246                     }
247                     $this->_xh['valuestack'][] = $curVal;
248                     $this->_xh['vt'] = 'data'; // be prepared for a data element next
249                     break;
250                 case 'DATA':
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";
255
256                         return;
257                     }
258                 case 'METHODCALL':
259                 case 'METHODRESPONSE':
260                 case 'PARAMS':
261                     // valid elements that add little to processing
262                     break;
263                 case 'METHODNAME':
264                 case 'NAME':
265                     /// @todo we could check for 2 NAME elements inside a MEMBER element
266                     $this->_xh['ac'] = '';
267                     break;
268                 case 'FAULT':
269                     $this->_xh['isf'] = 1;
270                     break;
271                 case 'MEMBER':
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
276                 case 'PARAM':
277                     // clear value type, so we can check later if no value has been passed for this param/member
278                     $this->_xh['vt'] = null;
279                     break;
280                 case 'NIL':
281                 case 'EX:NIL':
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";
287
288                             return;
289                         }
290                         $this->_xh['ac'] = ''; // reset the accumulator
291                         break;
292                     }
293                 // we do not support the <NIL/> extension, so
294                 // drop through intentionally
295                 default:
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";
299                     break;
300             }
301
302             // Save current element name to stack, to validate nesting
303             $this->_xh['stack'][] = $name;
304
305             /// @todo optimization creep: move this inside the big switch() above
306             if ($name != 'VALUE') {
307                 $this->_xh['lv'] = 0;
308             }
309         }
310     }
311
312     /**
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.
315      * @deprecated
316      * @param resource $parser
317      * @param $name
318      * @param $attrs
319      */
320     public function xmlrpc_se_any($parser, $name, $attrs)
321     {
322         $this->xmlrpc_se($parser, $name, $attrs, true);
323     }
324
325     /**
326      * xml parser handler function for close element tags.
327      * @param resource $parser
328      * @param string $name
329      * @param bool $rebuildXmlrpcvals
330      */
331     public function xmlrpc_ee($parser, $name, $rebuildXmlrpcvals = true)
332     {
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']);
339
340             switch ($name) {
341                 case 'VALUE':
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;
346                     }
347
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'];
355                         }
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;
361                         } else {
362                             $this->_xh['value'] = $temp;
363                         }
364                     } else {
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'])) {
369                         }
370
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'];
376                         }
377                     }
378                     break;
379                 case 'BOOLEAN':
380                 case 'I4':
381                 case 'I8':
382                 case 'EX:I8':
383                 case 'INT':
384                 case 'STRING':
385                 case 'DOUBLE':
386                 case 'DATETIME.ISO8601':
387                 case 'BASE64':
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']);
396                         }
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;
411                         } else {
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']);
415                             }
416                             $this->_xh['value'] = false;
417                         }
418                     } elseif ($name == 'DOUBLE') {
419                         // we have a 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';
426                         } else {
427                             // it's ok, add it on
428                             $this->_xh['value'] = (double)$this->_xh['ac'];
429                         }
430                     } else {
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';
437                         } else {
438                             // it's ok, add it on
439                             $this->_xh['value'] = (int)$this->_xh['ac'];
440                         }
441                     }
442                     $this->_xh['lv'] = 3; // indicate we've found a value
443                     break;
444                 case 'NAME':
445                     $this->_xh['valuestack'][count($this->_xh['valuestack']) - 1]['name'] = $this->_xh['ac'];
446                     break;
447                 case 'MEMBER':
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'];
453                     } else {
454                         error_log('XML-RPC: ' . __METHOD__ . ': missing VALUE inside STRUCT in received xml');
455                     }
456                     break;
457                 case 'DATA':
458                     $this->_xh['vt'] = null; // reset this to check for 2 data elements in a row - even if they're empty
459                     break;
460                 case 'STRUCT':
461                 case 'ARRAY':
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'];
468                     }
469                     break;
470                 case 'PARAM':
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'];
476                     } else {
477                         error_log('XML-RPC: ' . __METHOD__ . ': missing VALUE inside PARAM in received xml');
478                     }
479                     break;
480                 case 'METHODNAME':
481                     $this->_xh['method'] = preg_replace('/^[\n\r\t ]+/', '', $this->_xh['ac']);
482                     break;
483                 case 'NIL':
484                 case 'EX:NIL':
485                     if (PhpXmlRpc::$xmlrpc_null_extension) {
486                         $this->_xh['vt'] = 'null';
487                         $this->_xh['value'] = null;
488                         $this->_xh['lv'] = 3;
489                         break;
490                     }
491                 // drop through intentionally if nil extension not enabled
492                 case 'PARAMS':
493                 case 'FAULT':
494                 case 'METHODCALL':
495                 case 'METHORESPONSE':
496                     break;
497                 default:
498                     // End of INVALID ELEMENT!
499                     // shall we add an assert here for unreachable code???
500                     break;
501             }
502         }
503     }
504
505     /**
506      * Used in decoding xmlrpc requests/responses without rebuilding xmlrpc Values.
507      * @param resource $parser
508      * @param string $name
509      */
510     public function xmlrpc_ee_fast($parser, $name)
511     {
512         $this->xmlrpc_ee($parser, $name, false);
513     }
514
515     /**
516      * xml parser handler function for character data.
517      * @param resource $parser
518      * @param string $data
519      */
520     public function xmlrpc_cd($parser, $data)
521     {
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;
528             }
529         }
530     }
531
532     /**
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...
535      * @param $parser
536      * @param string data
537      */
538     public function xmlrpc_dh($parser, $data)
539     {
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;
544             }
545         }
546
547         //return true;
548     }
549
550     /**
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:
557      * 1. http headers
558      * 2. BOM
559      * 3. XML declaration
560      * 4. guesses using mb_detect_encoding()
561      *
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
568      *
569      * @todo explore usage of mb_http_input(): does it detect http headers + post data? if so, use it instead of hand-detection!!!
570      */
571     public static function guessEncoding($httpHeader = '', $xmlChunk = '', $encodingPrefs = null)
572     {
573         // discussion: see http://www.yale.edu/pclt/encoding/
574         // 1 - test if encoding is specified in HTTP HEADERS
575
576         // Details:
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...
586
587         /// @todo this test will pass if ANY header has charset specification, not only Content-Type. Fix it?
588         $matches = array();
589         if (preg_match('/;\s*charset\s*=([^;]+)/i', $httpHeader, $matches)) {
590             return strtoupper(trim($matches[1], " \t\""));
591         }
592
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)) {
601             return 'UCS-4';
602         } elseif (preg_match('/^(\xFE\xFF|\xFF\xFE)/', $xmlChunk)) {
603             return 'UTF-16';
604         } elseif (preg_match('/^(\xEF\xBB\xBF)/', $xmlChunk)) {
605             return 'UTF-8';
606         }
607
608         // 3 - test if encoding is specified in the xml declaration
609         // Details:
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));
616         }
617
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;
622             }
623             if ($encodingPrefs) {
624                 $enc = mb_detect_encoding($xmlChunk, $encodingPrefs);
625             } else {
626                 $enc = mb_detect_encoding($xmlChunk);
627             }
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') {
631                 $enc = 'US-' . $enc;
632             }
633
634             return $enc;
635         } else {
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;
641         }
642     }
643
644     /**
645      * Helper function: checks if an xml chunk as a charset declaration (BOM or in the xml declaration)
646      *
647      * @param string $xmlChunk
648      * @return bool
649      */
650     public static function hasEncoding($xmlChunk)
651     {
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)) {
655             return true;
656         } elseif (preg_match('/^(\xFE\xFF|\xFF\xFE)/', $xmlChunk)) {
657             return true;
658         } elseif (preg_match('/^(\xEF\xBB\xBF)/', $xmlChunk)) {
659             return true;
660         }
661
662         // test if encoding is specified in the xml declaration
663         // Details:
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)) {
669             return true;
670         }
671
672         return false;
673     }
674 }