comments
[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  * @see http://xmlrpc.com/spec.md
11  *
12  * @todo implement an interface to allow for alternative implementations
13  *       - make access to $_xh protected, return more high-level data structures
14  *       - add parseRequest, parseResponse, parseValue methods
15  * @todo if iconv() or mb_string() are available, we could allow to convert the received xml to a custom charset encoding
16  *       while parsing, which is faster than doing it later by going over the rebuilt data structure
17  */
18 class XMLParser
19 {
20     const RETURN_XMLRPCVALS = 'xmlrpcvals';
21     const RETURN_EPIVALS = 'epivals';
22     const RETURN_PHP = 'phpvals';
23
24     const ACCEPT_REQUEST = 1;
25     const ACCEPT_RESPONSE = 2;
26     const ACCEPT_VALUE = 4;
27     const ACCEPT_FAULT = 8;
28
29     // Used to store state during parsing and to pass parsing results to callers.
30     // Quick explanation of components:
31     //  private:
32     //    ac - used to accumulate values
33     //    stack - array with genealogy of xml elements names used to validate nesting of xmlrpc elements
34     //    valuestack - array used for parsing arrays and structs
35     //    lv - used to indicate "looking for a value": implements the logic to allow values with no types to be strings
36     //  public:
37     //    isf - used to indicate an xml parsing fault (3), invalid xmlrpc fault (2) or xmlrpc response fault (1)
38     //    isf_reason - used for storing xmlrpc response fault string
39     //    value - used to store the value in responses
40     //    method - used to store method name in requests
41     //    params - used to store parameters in requests
42     //    pt - used to store the type of each received parameter. Useful if parameters are automatically decoded to php values
43     //    rt  - 'methodcall', 'methodresponse', 'value' or 'fault' (the last one used only in EPI emulation mode)
44     public $_xh = array(
45         'ac' => '',
46         'stack' => array(),
47         'valuestack' => array(),
48         'isf' => 0,
49         'isf_reason' => '',
50         'value' => null,
51         'method' => false,
52         'params' => array(),
53         'pt' => array(),
54         'rt' => '',
55     );
56
57     public $xmlrpc_valid_parents = array(
58         'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT'),
59         'BOOLEAN' => array('VALUE'),
60         'I4' => array('VALUE'),
61         'I8' => array('VALUE'),
62         'EX:I8' => array('VALUE'),
63         'INT' => array('VALUE'),
64         'STRING' => array('VALUE'),
65         'DOUBLE' => array('VALUE'),
66         'DATETIME.ISO8601' => array('VALUE'),
67         'BASE64' => array('VALUE'),
68         'MEMBER' => array('STRUCT'),
69         'NAME' => array('MEMBER'),
70         'DATA' => array('ARRAY'),
71         'ARRAY' => array('VALUE'),
72         'STRUCT' => array('VALUE'),
73         'PARAM' => array('PARAMS'),
74         'METHODNAME' => array('METHODCALL'),
75         'PARAMS' => array('METHODCALL', 'METHODRESPONSE'),
76         'FAULT' => array('METHODRESPONSE'),
77         'NIL' => array('VALUE'), // only used when extension activated
78         'EX:NIL' => array('VALUE'), // only used when extension activated
79     );
80
81     /** @var array $parsing_options */
82     protected $parsing_options = array();
83     /** @var int $accept self::ACCEPT_REQUEST | self::ACCEPT_RESPONSE by default */
84     protected $accept = 3;
85     /** @var int $maxChunkLength 4 MB by default. Any value below 10MB should be good */
86     protected $maxChunkLength = 4194304;
87
88     /**
89      * @param array $options passed to the xml parser
90      */
91     public function __construct(array $options = array())
92     {
93         $this->parsing_options = $options;
94     }
95
96     /**
97      * @param string $data
98      * @param string $returnType
99      * @param int $accept a bit-combination of self::ACCEPT_REQUEST, self::ACCEPT_RESPONSE, self::ACCEPT_VALUE
100      */
101     public function parse($data, $returnType = self::RETURN_XMLRPCVALS, $accept = 3)
102     {
103         $this->_xh = array(
104             'ac' => '',
105             'stack' => array(),
106             'valuestack' => array(),
107             'isf' => 0,
108             'isf_reason' => '',
109             'value' => null,
110             'method' => false, // so we can check later if we got a methodname or not
111             'params' => array(),
112             'pt' => array(),
113             'rt' => '',
114         );
115
116         $len = strlen($data);
117
118         // we test for empty documents here to save on resource allocation and simply the chunked-parsing loop below
119         if ($len == 0) {
120             $this->_xh['isf'] = 3;
121             $this->_xh['isf_reason'] = 'XML error 5: empty document';
122             return;
123         }
124
125         $parser = xml_parser_create();
126
127         foreach ($this->parsing_options as $key => $val) {
128             xml_parser_set_option($parser, $key, $val);
129         }
130         // always set this, in case someone tries to disable it via options...
131         xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 1);
132
133         xml_set_object($parser, $this);
134
135         switch($returnType) {
136             case self::RETURN_PHP:
137                 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
138                 break;
139             case self::RETURN_EPIVALS:
140                 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_epi');
141                 break;
142             default:
143                 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');
144         }
145
146         xml_set_character_data_handler($parser, 'xmlrpc_cd');
147         xml_set_default_handler($parser, 'xmlrpc_dh');
148
149         $this->accept = $accept;
150
151         // @see ticket #70 - we have to parse big xml docks in chunks to avoid errors
152         for ($offset = 0; $offset < $len; $offset += $this->maxChunkLength) {
153             $chunk = substr($data, $offset, $this->maxChunkLength);
154             // error handling: xml not well formed
155             if (!xml_parse($parser, $chunk, $offset + $this->maxChunkLength >= $len)) {
156                 $errCode = xml_get_error_code($parser);
157                 $errStr = sprintf('XML error %s: %s at line %d, column %d', $errCode, xml_error_string($errCode),
158                     xml_get_current_line_number($parser), xml_get_current_column_number($parser));
159
160                 $this->_xh['isf'] = 3;
161                 $this->_xh['isf_reason'] = $errStr;
162                 break;
163             }
164         }
165
166         xml_parser_free($parser);
167     }
168
169     /**
170      * xml parser handler function for opening element tags.
171      * @internal
172      * @param resource $parser
173      * @param string $name
174      * @param $attrs
175      * @param bool $acceptSingleVals DEPRECATED use the $accept parameter instead
176      */
177     public function xmlrpc_se($parser, $name, $attrs, $acceptSingleVals = false)
178     {
179         // if invalid xmlrpc already detected, skip all processing
180         if ($this->_xh['isf'] < 2) {
181
182             // check for correct element nesting
183             if (count($this->_xh['stack']) == 0) {
184                 // top level element can only be of 2 types
185                 /// @todo optimization creep: save this check into a bool variable, instead of using count() every time:
186                 ///       there is only a single top level element in xml anyway
187                 // BC
188                 if ($acceptSingleVals === false) {
189                     $accept = $this->accept;
190                 } else {
191                     $accept = self::ACCEPT_REQUEST | self::ACCEPT_RESPONSE | self::ACCEPT_VALUE;
192                 }
193                 if (($name == 'METHODCALL' && ($accept & self::ACCEPT_REQUEST)) ||
194                     ($name == 'METHODRESPONSE' && ($accept & self::ACCEPT_RESPONSE)) ||
195                     ($name == 'VALUE' && ($accept & self::ACCEPT_VALUE)) ||
196                     ($name == 'FAULT' && ($accept & self::ACCEPT_FAULT))) {
197                     $this->_xh['rt'] = strtolower($name);
198                 } else {
199                     $this->_xh['isf'] = 2;
200                     $this->_xh['isf_reason'] = 'missing top level xmlrpc element. Found: ' . $name;
201
202                     return;
203                 }
204             } else {
205                 // not top level element: see if parent is OK
206                 $parent = end($this->_xh['stack']);
207                 if (!array_key_exists($name, $this->xmlrpc_valid_parents) || !in_array($parent, $this->xmlrpc_valid_parents[$name])) {
208                     $this->_xh['isf'] = 2;
209                     $this->_xh['isf_reason'] = "xmlrpc element $name cannot be child of $parent";
210
211                     return;
212                 }
213             }
214
215             switch ($name) {
216                 // optimize for speed switch cases: most common cases first
217                 case 'VALUE':
218                     /// @todo we could check for 2 VALUE elements inside a MEMBER or PARAM element
219                     $this->_xh['vt'] = 'value'; // indicator: no value found yet
220                     $this->_xh['ac'] = '';
221                     $this->_xh['lv'] = 1;
222                     $this->_xh['php_class'] = null;
223                     break;
224                 case 'I8':
225                 case 'EX:I8':
226                     if (PHP_INT_SIZE === 4) {
227                         // INVALID ELEMENT: RAISE ISF so that it is later recognized!!!
228                         $this->_xh['isf'] = 2;
229                         $this->_xh['isf_reason'] = "Received i8 element but php is compiled in 32 bit mode";
230
231                         return;
232                     }
233                     // fall through voluntarily
234                 case 'I4':
235                 case 'INT':
236                 case 'STRING':
237                 case 'BOOLEAN':
238                 case 'DOUBLE':
239                 case 'DATETIME.ISO8601':
240                 case 'BASE64':
241                     if ($this->_xh['vt'] != 'value') {
242                         // two data elements inside a value: an error occurred!
243                         $this->_xh['isf'] = 2;
244                         $this->_xh['isf_reason'] = "$name element following a {$this->_xh['vt']} element inside a single value";
245
246                         return;
247                     }
248                     $this->_xh['ac'] = ''; // reset the accumulator
249                     break;
250                 case 'STRUCT':
251                 case 'ARRAY':
252                     if ($this->_xh['vt'] != 'value') {
253                         // two data elements inside a value: an error occurred!
254                         $this->_xh['isf'] = 2;
255                         $this->_xh['isf_reason'] = "$name element following a {$this->_xh['vt']} element inside a single value";
256
257                         return;
258                     }
259                     // create an empty array to hold child values, and push it onto appropriate stack
260                     $curVal = array();
261                     $curVal['values'] = array();
262                     $curVal['type'] = $name;
263                     // check for out-of-band information to rebuild php objs
264                     // and in case it is found, save it
265                     if (@isset($attrs['PHP_CLASS'])) {
266                         $curVal['php_class'] = $attrs['PHP_CLASS'];
267                     }
268                     $this->_xh['valuestack'][] = $curVal;
269                     $this->_xh['vt'] = 'data'; // be prepared for a data element next
270                     break;
271                 case 'DATA':
272                     if ($this->_xh['vt'] != 'data') {
273                         // two data elements inside a value: an error occurred!
274                         $this->_xh['isf'] = 2;
275                         $this->_xh['isf_reason'] = "found two data elements inside an array element";
276
277                         return;
278                     }
279                 case 'METHODCALL':
280                 case 'METHODRESPONSE':
281                 case 'PARAMS':
282                     // valid elements that add little to processing
283                     break;
284                 case 'METHODNAME':
285                 case 'NAME':
286                     /// @todo we could check for 2 NAME elements inside a MEMBER element
287                     $this->_xh['ac'] = '';
288                     break;
289                 case 'FAULT':
290                     $this->_xh['isf'] = 1;
291                     break;
292                 case 'MEMBER':
293                     // set member name to null, in case we do not find in the xml later on
294                     $this->_xh['valuestack'][count($this->_xh['valuestack']) - 1]['name'] = '';
295                     //$this->_xh['ac']='';
296                 // Drop trough intentionally
297                 case 'PARAM':
298                     // clear value type, so we can check later if no value has been passed for this param/member
299                     $this->_xh['vt'] = null;
300                     break;
301                 case 'NIL':
302                 case 'EX:NIL':
303                     if (PhpXmlRpc::$xmlrpc_null_extension) {
304                         if ($this->_xh['vt'] != 'value') {
305                             // two data elements inside a value: an error occurred!
306                             $this->_xh['isf'] = 2;
307                             $this->_xh['isf_reason'] = "$name element following a {$this->_xh['vt']} element inside a single value";
308
309                             return;
310                         }
311                         $this->_xh['ac'] = ''; // reset the accumulator
312                         break;
313                     }
314                 // we do not support the <NIL/> extension, so
315                 // drop through intentionally
316                 default:
317                     // INVALID ELEMENT: RAISE ISF so that it is later recognized!!!
318                     $this->_xh['isf'] = 2;
319                     $this->_xh['isf_reason'] = "found not-xmlrpc xml element $name";
320                     break;
321             }
322
323             // Save current element name to stack, to validate nesting
324             $this->_xh['stack'][] = $name;
325
326             /// @todo optimization creep: move this inside the big switch() above
327             if ($name != 'VALUE') {
328                 $this->_xh['lv'] = 0;
329             }
330         }
331     }
332
333     /**
334      * xml parser handler function for opening element tags.
335      * Used in decoding xml chunks that might represent single xmlrpc values as well as requests, responses.
336      * @deprecated
337      * @param resource $parser
338      * @param $name
339      * @param $attrs
340      */
341     public function xmlrpc_se_any($parser, $name, $attrs)
342     {
343         $this->xmlrpc_se($parser, $name, $attrs, true);
344     }
345
346     /**
347      * xml parser handler function for close element tags.
348      * @internal
349      * @param resource $parser
350      * @param string $name
351      * @param int $rebuildXmlrpcvals >1 for rebuilding xmlrpcvals, 0 for rebuilding php values, -1 for xmlrpc-extension compatibility
352      */
353     public function xmlrpc_ee($parser, $name, $rebuildXmlrpcvals = 1)
354     {
355         if ($this->_xh['isf'] < 2) {
356             // push this element name from stack
357             // NB: if XML validates, correct opening/closing is guaranteed and
358             // we do not have to check for $name == $currElem.
359             // we also checked for proper nesting at start of elements...
360             $currElem = array_pop($this->_xh['stack']);
361
362             switch ($name) {
363                 case 'VALUE':
364                     // This if() detects if no scalar was inside <VALUE></VALUE>
365                     if ($this->_xh['vt'] == 'value') {
366                         $this->_xh['value'] = $this->_xh['ac'];
367                         $this->_xh['vt'] = Value::$xmlrpcString;
368                     }
369
370                     if ($rebuildXmlrpcvals > 0) {
371                         // build the xmlrpc val out of the data received, and substitute it
372                         $temp = new Value($this->_xh['value'], $this->_xh['vt']);
373                         // in case we got info about underlying php class, save it
374                         // in the object we're rebuilding
375                         if (isset($this->_xh['php_class'])) {
376                             $temp->_php_class = $this->_xh['php_class'];
377                         }
378                         $this->_xh['value'] = $temp;
379                     } elseif ($rebuildXmlrpcvals < 0) {
380                         if ($this->_xh['vt'] == Value::$xmlrpcDateTime) {
381                             $this->_xh['value'] = (object)array(
382                                 'xmlrpc_type' => 'datetime',
383                                 'scalar' => $this->_xh['value'],
384                                 'timestamp' => \PhpXmlRpc\Helper\Date::iso8601Decode($this->_xh['value'])
385                             );
386                         } elseif ($this->_xh['vt'] == Value::$xmlrpcBase64) {
387                             $this->_xh['value'] = (object)array(
388                                 'xmlrpc_type' => 'base64',
389                                 'scalar' => $this->_xh['value']
390                             );
391                         }
392                     } else {
393                         /// @todo this should handle php-serialized objects,
394                         /// since std deserializing is done by php_xmlrpc_decode,
395                         /// which we will not be calling...
396                         //if (isset($this->_xh['php_class'])) {
397                         //}
398                     }
399
400                     // check if we are inside an array or struct:
401                     // if value just built is inside an array, let's move it into array on the stack
402                     $vscount = count($this->_xh['valuestack']);
403                     if ($vscount && $this->_xh['valuestack'][$vscount - 1]['type'] == 'ARRAY') {
404                         $this->_xh['valuestack'][$vscount - 1]['values'][] = $this->_xh['value'];
405                     }
406                     break;
407                 case 'BOOLEAN':
408                 case 'I4':
409                 case 'I8':
410                 case 'EX:I8':
411                 case 'INT':
412                 case 'STRING':
413                 case 'DOUBLE':
414                 case 'DATETIME.ISO8601':
415                 case 'BASE64':
416                     $this->_xh['vt'] = strtolower($name);
417                     /// @todo: optimization creep - remove the if/elseif cycle below
418                     /// since the case() in which we are already did that
419                     if ($name == 'STRING') {
420                         $this->_xh['value'] = $this->_xh['ac'];
421                     } elseif ($name == 'DATETIME.ISO8601') {
422                         if (!preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $this->_xh['ac'])) {
423                             Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': invalid value received in DATETIME: ' . $this->_xh['ac']);
424                         }
425                         $this->_xh['vt'] = Value::$xmlrpcDateTime;
426                         $this->_xh['value'] = $this->_xh['ac'];
427                     } elseif ($name == 'BASE64') {
428                         /// @todo check for failure of base64 decoding / catch warnings
429                         $this->_xh['value'] = base64_decode($this->_xh['ac']);
430                     } elseif ($name == 'BOOLEAN') {
431                         // special case here: we translate boolean 1 or 0 into PHP
432                         // constants true or false.
433                         // Strings 'true' and 'false' are accepted, even though the
434                         // spec never mentions them (see eg. Blogger api docs)
435                         // NB: this simple checks helps a lot sanitizing input, ie no
436                         // security problems around here
437                         if ($this->_xh['ac'] == '1' || strcasecmp($this->_xh['ac'], 'true') == 0) {
438                             $this->_xh['value'] = true;
439                         } else {
440                             // log if receiving something strange, even though we set the value to false anyway
441                             if ($this->_xh['ac'] != '0' && strcasecmp($this->_xh['ac'], 'false') != 0) {
442                                 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': invalid value received in BOOLEAN: ' . $this->_xh['ac']);
443                             }
444                             $this->_xh['value'] = false;
445                         }
446                     } elseif ($name == 'DOUBLE') {
447                         // we have a DOUBLE
448                         // we must check that only 0123456789-.<space> are characters here
449                         // NOTE: regexp could be much stricter than this...
450                         if (!preg_match('/^[+-eE0123456789 \t.]+$/', $this->_xh['ac'])) {
451                             /// @todo: find a better way of throwing an error than this!
452                             Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': non numeric value received in DOUBLE: ' . $this->_xh['ac']);
453                             $this->_xh['value'] = 'ERROR_NON_NUMERIC_FOUND';
454                         } else {
455                             // it's ok, add it on
456                             $this->_xh['value'] = (double)$this->_xh['ac'];
457                         }
458                     } else {
459                         // we have an I4/I8/INT
460                         // we must check that only 0123456789-<space> are characters here
461                         if (!preg_match('/^[+-]?[0123456789 \t]+$/', $this->_xh['ac'])) {
462                             /// @todo find a better way of throwing an error than this!
463                             Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': non numeric value received in INT: ' . $this->_xh['ac']);
464                             $this->_xh['value'] = 'ERROR_NON_NUMERIC_FOUND';
465                         } else {
466                             // it's ok, add it on
467                             $this->_xh['value'] = (int)$this->_xh['ac'];
468                         }
469                     }
470                     $this->_xh['lv'] = 3; // indicate we've found a value
471                     break;
472                 case 'NAME':
473                     $this->_xh['valuestack'][count($this->_xh['valuestack']) - 1]['name'] = $this->_xh['ac'];
474                     break;
475                 case 'MEMBER':
476                     // add to array in the stack the last element built,
477                     // unless no VALUE was found
478                     if ($this->_xh['vt']) {
479                         $vscount = count($this->_xh['valuestack']);
480                         $this->_xh['valuestack'][$vscount - 1]['values'][$this->_xh['valuestack'][$vscount - 1]['name']] = $this->_xh['value'];
481                     } else {
482                         Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': missing VALUE inside STRUCT in received xml');
483                     }
484                     break;
485                 case 'DATA':
486                     $this->_xh['vt'] = null; // reset this to check for 2 data elements in a row - even if they're empty
487                     break;
488                 case 'STRUCT':
489                 case 'ARRAY':
490                     // fetch out of stack array of values, and promote it to current value
491                     $currVal = array_pop($this->_xh['valuestack']);
492                     $this->_xh['value'] = $currVal['values'];
493                     $this->_xh['vt'] = strtolower($name);
494                     if (isset($currVal['php_class'])) {
495                         $this->_xh['php_class'] = $currVal['php_class'];
496                     }
497                     break;
498                 case 'PARAM':
499                     // add to array of params the current value,
500                     // unless no VALUE was found
501                     if ($this->_xh['vt']) {
502                         $this->_xh['params'][] = $this->_xh['value'];
503                         $this->_xh['pt'][] = $this->_xh['vt'];
504                     } else {
505                         Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': missing VALUE inside PARAM in received xml');
506                     }
507                     break;
508                 case 'METHODNAME':
509                     $this->_xh['method'] = preg_replace('/^[\n\r\t ]+/', '', $this->_xh['ac']);
510                     break;
511                 case 'NIL':
512                 case 'EX:NIL':
513                     if (PhpXmlRpc::$xmlrpc_null_extension) {
514                         $this->_xh['vt'] = 'null';
515                         $this->_xh['value'] = null;
516                         $this->_xh['lv'] = 3;
517                         break;
518                     }
519                 // drop through intentionally if nil extension not enabled
520                 case 'PARAMS':
521                 case 'FAULT':
522                 case 'METHODCALL':
523                 case 'METHORESPONSE':
524                     break;
525                 default:
526                     // End of INVALID ELEMENT!
527                     // shall we add an assert here for unreachable code???
528                     break;
529             }
530         }
531     }
532
533     /**
534      * Used in decoding xmlrpc requests/responses without rebuilding xmlrpc Values.
535      * @internal
536      * @param resource $parser
537      * @param string $name
538      */
539     public function xmlrpc_ee_fast($parser, $name)
540     {
541         $this->xmlrpc_ee($parser, $name, 0);
542     }
543
544     /**
545      * Used in decoding xmlrpc requests/responses while building xmlrpc-extension Values (plain php for all but base64 and datetime).
546      * @internal
547      * @param resource $parser
548      * @param string $name
549      */
550     public function xmlrpc_ee_epi($parser, $name)
551     {
552         $this->xmlrpc_ee($parser, $name, -1);
553     }
554
555     /**
556      * xml parser handler function for character data.
557      * @internal
558      * @param resource $parser
559      * @param string $data
560      */
561     public function xmlrpc_cd($parser, $data)
562     {
563         // skip processing if xml fault already detected
564         if ($this->_xh['isf'] < 2) {
565             // "lookforvalue==3" means that we've found an entire value
566             // and should discard any further character data
567             if ($this->_xh['lv'] != 3) {
568                 $this->_xh['ac'] .= $data;
569             }
570         }
571     }
572
573     /**
574      * xml parser handler function for 'other stuff', ie. not char data or
575      * element start/end tag. In fact it only gets called on unknown entities...
576      * @internal
577      * @param $parser
578      * @param string data
579      */
580     public function xmlrpc_dh($parser, $data)
581     {
582         // skip processing if xml fault already detected
583         if ($this->_xh['isf'] < 2) {
584             if (substr($data, 0, 1) == '&' && substr($data, -1, 1) == ';') {
585                 $this->_xh['ac'] .= $data;
586             }
587         }
588
589         //return true;
590     }
591
592     /**
593      * xml charset encoding guessing helper function.
594      * Tries to determine the charset encoding of an XML chunk received over HTTP.
595      * NB: according to the spec (RFC 3023), if text/xml content-type is received over HTTP without a content-type,
596      * we SHOULD assume it is strictly US-ASCII. But we try to be more tolerant of non conforming (legacy?) clients/servers,
597      * which will be most probably using UTF-8 anyway...
598      * In order of importance checks:
599      * 1. http headers
600      * 2. BOM
601      * 3. XML declaration
602      * 4. guesses using mb_detect_encoding()
603      *
604      * @param string $httpHeader the http Content-type header
605      * @param string $xmlChunk xml content buffer
606      * @param string $encodingPrefs comma separated list of character encodings to be used as default (when mb extension is enabled).
607      *                              This can also be set globally using PhpXmlRpc::$xmlrpc_detectencodings
608      * @return string the encoding determined. Null if it can't be determined and mbstring is enabled,
609      *                PhpXmlRpc::$xmlrpc_defencoding if it can't be determined and mbstring is not enabled
610      *
611      * @todo explore usage of mb_http_input(): does it detect http headers + post data? if so, use it instead of hand-detection!!!
612      */
613     public static function guessEncoding($httpHeader = '', $xmlChunk = '', $encodingPrefs = null)
614     {
615         // discussion: see http://www.yale.edu/pclt/encoding/
616         // 1 - test if encoding is specified in HTTP HEADERS
617
618         // Details:
619         // LWS:           (\13\10)?( |\t)+
620         // token:         (any char but excluded stuff)+
621         // quoted string: " (any char but double quotes and control chars)* "
622         // header:        Content-type = ...; charset=value(; ...)*
623         //   where value is of type token, no LWS allowed between 'charset' and value
624         // Note: we do not check for invalid chars in VALUE:
625         //   this had better be done using pure ereg as below
626         // Note 2: we might be removing whitespace/tabs that ought to be left in if
627         //   the received charset is a quoted string. But nobody uses such charset names...
628
629         /// @todo this test will pass if ANY header has charset specification, not only Content-Type. Fix it?
630         $matches = array();
631         if (preg_match('/;\s*charset\s*=([^;]+)/i', $httpHeader, $matches)) {
632             return strtoupper(trim($matches[1], " \t\""));
633         }
634
635         // 2 - scan the first bytes of the data for a UTF-16 (or other) BOM pattern
636         //     (source: http://www.w3.org/TR/2000/REC-xml-20001006)
637         //     NOTE: actually, according to the spec, even if we find the BOM and determine
638         //     an encoding, we should check if there is an encoding specified
639         //     in the xml declaration, and verify if they match.
640         /// @todo implement check as described above?
641         /// @todo implement check for first bytes of string even without a BOM? (It sure looks harder than for cases WITH a BOM)
642         if (preg_match('/^(\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\x00\x00\xFF\xFE|\xFE\xFF\x00\x00)/', $xmlChunk)) {
643             return 'UCS-4';
644         } elseif (preg_match('/^(\xFE\xFF|\xFF\xFE)/', $xmlChunk)) {
645             return 'UTF-16';
646         } elseif (preg_match('/^(\xEF\xBB\xBF)/', $xmlChunk)) {
647             return 'UTF-8';
648         }
649
650         // 3 - test if encoding is specified in the xml declaration
651         // Details:
652         // SPACE:         (#x20 | #x9 | #xD | #xA)+ === [ \x9\xD\xA]+
653         // EQ:            SPACE?=SPACE? === [ \x9\xD\xA]*=[ \x9\xD\xA]*
654         if (preg_match('/^<\?xml\s+version\s*=\s*' . "((?:\"[a-zA-Z0-9_.:-]+\")|(?:'[a-zA-Z0-9_.:-]+'))" .
655             '\s+encoding\s*=\s*' . "((?:\"[A-Za-z][A-Za-z0-9._-]*\")|(?:'[A-Za-z][A-Za-z0-9._-]*'))/",
656             $xmlChunk, $matches)) {
657             return strtoupper(substr($matches[2], 1, -1));
658         }
659
660         // 4 - if mbstring is available, let it do the guesswork
661         if (extension_loaded('mbstring')) {
662             if ($encodingPrefs == null && PhpXmlRpc::$xmlrpc_detectencodings != null) {
663                 $encodingPrefs = PhpXmlRpc::$xmlrpc_detectencodings;
664             }
665             if ($encodingPrefs) {
666                 $enc = mb_detect_encoding($xmlChunk, $encodingPrefs);
667             } else {
668                 $enc = mb_detect_encoding($xmlChunk);
669             }
670             // NB: mb_detect likes to call it ascii, xml parser likes to call it US_ASCII...
671             // IANA also likes better US-ASCII, so go with it
672             if ($enc == 'ASCII') {
673                 $enc = 'US-' . $enc;
674             }
675
676             return $enc;
677         } else {
678             // no encoding specified: as per HTTP1.1 assume it is iso-8859-1?
679             // Both RFC 2616 (HTTP 1.1) and 1945 (HTTP 1.0) clearly state that for text/xxx content types
680             // this should be the standard. And we should be getting text/xml as request and response.
681             // BUT we have to be backward compatible with the lib, which always used UTF-8 as default...
682             return PhpXmlRpc::$xmlrpc_defencoding;
683         }
684     }
685
686     /**
687      * Helper function: checks if an xml chunk as a charset declaration (BOM or in the xml declaration)
688      *
689      * @param string $xmlChunk
690      * @return bool
691      */
692     public static function hasEncoding($xmlChunk)
693     {
694         // scan the first bytes of the data for a UTF-16 (or other) BOM pattern
695         //     (source: http://www.w3.org/TR/2000/REC-xml-20001006)
696         if (preg_match('/^(\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\x00\x00\xFF\xFE|\xFE\xFF\x00\x00)/', $xmlChunk)) {
697             return true;
698         } elseif (preg_match('/^(\xFE\xFF|\xFF\xFE)/', $xmlChunk)) {
699             return true;
700         } elseif (preg_match('/^(\xEF\xBB\xBF)/', $xmlChunk)) {
701             return true;
702         }
703
704         // test if encoding is specified in the xml declaration
705         // Details:
706         // SPACE:         (#x20 | #x9 | #xD | #xA)+ === [ \x9\xD\xA]+
707         // EQ:            SPACE?=SPACE? === [ \x9\xD\xA]*=[ \x9\xD\xA]*
708         if (preg_match('/^<\?xml\s+version\s*=\s*' . "((?:\"[a-zA-Z0-9_.:-]+\")|(?:'[a-zA-Z0-9_.:-]+'))" .
709             '\s+encoding\s*=\s*' . "((?:\"[A-Za-z][A-Za-z0-9._-]*\")|(?:'[A-Za-z][A-Za-z0-9._-]*'))/",
710             $xmlChunk, $matches)) {
711             return true;
712         }
713
714         return false;
715     }
716 }