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