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