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