CamelCase everywhere!
[plcapi.git] / src / Encoder.php
1 <?php
2
3 namespace PhpXmlRpc;
4
5 use PhpXmlRpc\Helper\XMLParser;
6
7 class Encoder
8 {
9     /**
10      * Takes an xmlrpc value in object format and translates it into native PHP types.
11      *
12      * Works with xmlrpc requests objects as input, too.
13      *
14      * Given proper options parameter, can rebuild generic php object instances
15      * (provided those have been encoded to xmlrpc format using a corresponding
16      * option in php_xmlrpc_encode())
17      * PLEASE NOTE that rebuilding php objects involves calling their constructor function.
18      * This means that the remote communication end can decide which php code will
19      * get executed on your server, leaving the door possibly open to 'php-injection'
20      * style of attacks (provided you have some classes defined on your server that
21      * might wreak havoc if instances are built outside an appropriate context).
22      * Make sure you trust the remote server/client before eanbling this!
23      *
24      * @author Dan Libby (dan@libby.com)
25      *
26      * @param Value|Request $xmlrpcVal
27      * @param array $options if 'decode_php_objs' is set in the options array, xmlrpc structs can be decoded into php objects; if 'dates_as_objects' is set xmlrpc datetimes are decoded as php DateTime objects (standard is
28      *
29      * @return mixed
30      */
31     public function decode($xmlrpcVal, $options = array())
32     {
33         switch ($xmlrpcVal->kindOf()) {
34             case 'scalar':
35                 if (in_array('extension_api', $options)) {
36                     reset($xmlrpcVal->me);
37                     list($typ, $val) = each($xmlrpcVal->me);
38                     switch ($typ) {
39                         case 'dateTime.iso8601':
40                             $xmlrpcVal->scalar = $val;
41                             $xmlrpcVal->type = 'datetime';
42                             $xmlrpcVal->timestamp = \PhpXmlRpc\Helper\Date::iso8601_decode($val);
43
44                             return $xmlrpcVal;
45                         case 'base64':
46                             $xmlrpcVal->scalar = $val;
47                             $xmlrpcVal->type = $typ;
48
49                             return $xmlrpcVal;
50                         default:
51                             return $xmlrpcVal->scalarval();
52                     }
53                 }
54                 if (in_array('dates_as_objects', $options) && $xmlrpcVal->scalartyp() == 'dateTime.iso8601') {
55                     // we return a Datetime object instead of a string
56                     // since now the constructor of xmlrpc value accepts safely strings, ints and datetimes,
57                     // we cater to all 3 cases here
58                     $out = $xmlrpcVal->scalarval();
59                     if (is_string($out)) {
60                         $out = strtotime($out);
61                     }
62                     if (is_int($out)) {
63                         $result = new \Datetime();
64                         $result->setTimestamp($out);
65
66                         return $result;
67                     } elseif (is_a($out, 'Datetime')) {
68                         return $out;
69                     }
70                 }
71
72                 return $xmlrpcVal->scalarval();
73             case 'array':
74                 $size = $xmlrpcVal->arraysize();
75                 $arr = array();
76                 for ($i = 0; $i < $size; $i++) {
77                     $arr[] = $this->decode($xmlrpcVal->arraymem($i), $options);
78                 }
79
80                 return $arr;
81             case 'struct':
82                 $xmlrpcVal->structreset();
83                 // If user said so, try to rebuild php objects for specific struct vals.
84                 /// @todo should we raise a warning for class not found?
85                 // shall we check for proper subclass of xmlrpc value instead of
86                 // presence of _php_class to detect what we can do?
87                 if (in_array('decode_php_objs', $options) && $xmlrpcVal->_php_class != ''
88                     && class_exists($xmlrpcVal->_php_class)
89                 ) {
90                     $obj = @new $xmlrpcVal->_php_class();
91                     while (list($key, $value) = $xmlrpcVal->structeach()) {
92                         $obj->$key = $this->decode($value, $options);
93                     }
94
95                     return $obj;
96                 } else {
97                     $arr = array();
98                     while (list($key, $value) = $xmlrpcVal->structeach()) {
99                         $arr[$key] = $this->decode($value, $options);
100                     }
101
102                     return $arr;
103                 }
104             case 'msg':
105                 $paramCount = $xmlrpcVal->getNumParams();
106                 $arr = array();
107                 for ($i = 0; $i < $paramCount; $i++) {
108                     $arr[] = $this->decode($xmlrpcVal->getParam($i));
109                 }
110
111                 return $arr;
112         }
113     }
114
115     /**
116      * Takes native php types and encodes them into xmlrpc PHP object format.
117      * It will not re-encode xmlrpc value objects.
118      *
119      * Feature creep -- could support more types via optional type argument
120      * (string => datetime support has been added, ??? => base64 not yet)
121      *
122      * If given a proper options parameter, php object instances will be encoded
123      * into 'special' xmlrpc values, that can later be decoded into php objects
124      * by calling php_xmlrpc_decode() with a corresponding option
125      *
126      * @author Dan Libby (dan@libby.com)
127      *
128      * @param mixed $php_val the value to be converted into an xmlrpc value object
129      * @param array $options can include 'encode_php_objs', 'auto_dates', 'null_extension' or 'extension_api'
130      *
131      * @return \PhpXmlrpc\Value
132      */
133     public function encode($phpVal, $options = array())
134     {
135         $type = gettype($phpVal);
136         switch ($type) {
137             case 'string':
138                 if (in_array('auto_dates', $options) && preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $phpVal)) {
139                     $xmlrpcVal = new Value($phpVal, Value::$xmlrpcDateTime);
140                 } else {
141                     $xmlrpcVal = new Value($phpVal, Value::$xmlrpcString);
142                 }
143                 break;
144             case 'integer':
145                 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcInt);
146                 break;
147             case 'double':
148                 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcDouble);
149                 break;
150             // <G_Giunta_2001-02-29>
151             // Add support for encoding/decoding of booleans, since they are supported in PHP
152             case 'boolean':
153                 $xmlrpcVal = new Value($phpVal, Value::$xmlrpcBoolean);
154                 break;
155             // </G_Giunta_2001-02-29>
156             case 'array':
157                 // PHP arrays can be encoded to either xmlrpc structs or arrays,
158                 // depending on wheter they are hashes or plain 0..n integer indexed
159                 // A shorter one-liner would be
160                 // $tmp = array_diff(array_keys($phpVal), range(0, count($phpVal)-1));
161                 // but execution time skyrockets!
162                 $j = 0;
163                 $arr = array();
164                 $ko = false;
165                 foreach ($phpVal as $key => $val) {
166                     $arr[$key] = $this->encode($val, $options);
167                     if (!$ko && $key !== $j) {
168                         $ko = true;
169                     }
170                     $j++;
171                 }
172                 if ($ko) {
173                     $xmlrpcVal = new Value($arr, Value::$xmlrpcStruct);
174                 } else {
175                     $xmlrpcVal = new Value($arr, Value::$xmlrpcArray);
176                 }
177                 break;
178             case 'object':
179                 if (is_a($phpVal, 'PhpXmlRpc\Value')) {
180                     $xmlrpcVal = $phpVal;
181                 } elseif (is_a($phpVal, 'DateTime')) {
182                     $xmlrpcVal = new Value($phpVal->format('Ymd\TH:i:s'), Value::$xmlrpcStruct);
183                 } else {
184                     $arr = array();
185                     reset($phpVal);
186                     while (list($k, $v) = each($phpVal)) {
187                         $arr[$k] = $this->encode($v, $options);
188                     }
189                     $xmlrpcVal = new Value($arr, Value::$xmlrpcStruct);
190                     if (in_array('encode_php_objs', $options)) {
191                         // let's save original class name into xmlrpc value:
192                         // might be useful later on...
193                         $xmlrpcVal->_php_class = get_class($phpVal);
194                     }
195                 }
196                 break;
197             case 'NULL':
198                 if (in_array('extension_api', $options)) {
199                     $xmlrpcVal = new Value('', Value::$xmlrpcString);
200                 } elseif (in_array('null_extension', $options)) {
201                     $xmlrpcVal = new Value('', Value::$xmlrpcNull);
202                 } else {
203                     $xmlrpcVal = new Value();
204                 }
205                 break;
206             case 'resource':
207                 if (in_array('extension_api', $options)) {
208                     $xmlrpcVal = new Value((int)$phpVal, Value::$xmlrpcInt);
209                 } else {
210                     $xmlrpcVal = new Value();
211                 }
212             // catch "user function", "unknown type"
213             default:
214                 // giancarlo pinerolo <ping@alt.it>
215                 // it has to return
216                 // an empty object in case, not a boolean.
217                 $xmlrpcVal = new Value();
218                 break;
219         }
220
221         return $xmlrpcVal;
222     }
223
224     /**
225      * Convert the xml representation of a method response, method request or single
226      * xmlrpc value into the appropriate object (a.k.a. deserialize).
227      *
228      * @param string $xmlVal
229      * @param array $options
230      *
231      * @return mixed false on error, or an instance of either Value, Request or Response
232      */
233     public function decode_xml($xmlVal, $options = array())
234     {
235
236         /// @todo 'guestimate' encoding
237         $parser = xml_parser_create();
238         xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
239         // What if internal encoding is not in one of the 3 allowed?
240         // we use the broadest one, ie. utf8!
241         if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
242             xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
243         } else {
244             xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding);
245         }
246
247         $xmlRpcParser = new XMLParser();
248         xml_set_object($parser, $xmlRpcParser);
249
250         xml_set_element_handler($parser, 'xmlrpc_se_any', 'xmlrpc_ee');
251         xml_set_character_data_handler($parser, 'xmlrpc_cd');
252         xml_set_default_handler($parser, 'xmlrpc_dh');
253         if (!xml_parse($parser, $xmlVal, 1)) {
254             $errstr = sprintf('XML error: %s at line %d, column %d',
255                 xml_error_string(xml_get_error_code($parser)),
256                 xml_get_current_line_number($parser), xml_get_current_column_number($parser));
257             error_log($errstr);
258             xml_parser_free($parser);
259
260             return false;
261         }
262         xml_parser_free($parser);
263         if ($xmlRpcParser->_xh['isf'] > 1) {
264             // test that $xmlrpc->_xh['value'] is an obj, too???
265
266             error_log($xmlRpcParser->_xh['isf_reason']);
267
268             return false;
269         }
270         switch ($xmlRpcParser->_xh['rt']) {
271             case 'methodresponse':
272                 $v = &$xmlRpcParser->_xh['value'];
273                 if ($xmlRpcParser->_xh['isf'] == 1) {
274                     $vc = $v->structmem('faultCode');
275                     $vs = $v->structmem('faultString');
276                     $r = new Response(0, $vc->scalarval(), $vs->scalarval());
277                 } else {
278                     $r = new Response($v);
279                 }
280
281                 return $r;
282             case 'methodcall':
283                 $m = new Request($xmlRpcParser->_xh['method']);
284                 for ($i = 0; $i < count($xmlRpcParser->_xh['params']); $i++) {
285                     $m->addParam($xmlRpcParser->_xh['params'][$i]);
286                 }
287
288                 return $m;
289             case 'value':
290                 return $xmlRpcParser->_xh['value'];
291             default:
292                 return false;
293         }
294     }
295
296     /**
297      * xml charset encoding guessing helper function.
298      * Tries to determine the charset encoding of an XML chunk received over HTTP.
299      * NB: according to the spec (RFC 3023), if text/xml content-type is received over HTTP without a content-type,
300      * we SHOULD assume it is strictly US-ASCII. But we try to be more tolerant of unconforming (legacy?) clients/servers,
301      * which will be most probably using UTF-8 anyway...
302      *
303      * @param string $httpHeader the http Content-type header
304      * @param string $xmlChunk xml content buffer
305      * @param string $encodingPrefs comma separated list of character encodings to be used as default (when mb extension is enabled)
306      * @return string
307      *
308      * @todo explore usage of mb_http_input(): does it detect http headers + post data? if so, use it instead of hand-detection!!!
309      */
310     public static function guess_encoding($httpHeader = '', $xmlChunk = '', $encodingPrefs = null)
311     {
312         // discussion: see http://www.yale.edu/pclt/encoding/
313         // 1 - test if encoding is specified in HTTP HEADERS
314
315         //Details:
316         // LWS:           (\13\10)?( |\t)+
317         // token:         (any char but excluded stuff)+
318         // quoted string: " (any char but double quotes and cointrol chars)* "
319         // header:        Content-type = ...; charset=value(; ...)*
320         //   where value is of type token, no LWS allowed between 'charset' and value
321         // Note: we do not check for invalid chars in VALUE:
322         //   this had better be done using pure ereg as below
323         // Note 2: we might be removing whitespace/tabs that ought to be left in if
324         //   the received charset is a quoted string. But nobody uses such charset names...
325
326         /// @todo this test will pass if ANY header has charset specification, not only Content-Type. Fix it?
327         $matches = array();
328         if (preg_match('/;\s*charset\s*=([^;]+)/i', $httpHeader, $matches)) {
329             return strtoupper(trim($matches[1], " \t\""));
330         }
331
332         // 2 - scan the first bytes of the data for a UTF-16 (or other) BOM pattern
333         //     (source: http://www.w3.org/TR/2000/REC-xml-20001006)
334         //     NOTE: actually, according to the spec, even if we find the BOM and determine
335         //     an encoding, we should check if there is an encoding specified
336         //     in the xml declaration, and verify if they match.
337         /// @todo implement check as described above?
338         /// @todo implement check for first bytes of string even without a BOM? (It sure looks harder than for cases WITH a BOM)
339         if (preg_match('/^(\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\x00\x00\xFF\xFE|\xFE\xFF\x00\x00)/', $xmlChunk)) {
340             return 'UCS-4';
341         } elseif (preg_match('/^(\xFE\xFF|\xFF\xFE)/', $xmlChunk)) {
342             return 'UTF-16';
343         } elseif (preg_match('/^(\xEF\xBB\xBF)/', $xmlChunk)) {
344             return 'UTF-8';
345         }
346
347         // 3 - test if encoding is specified in the xml declaration
348         // Details:
349         // SPACE:         (#x20 | #x9 | #xD | #xA)+ === [ \x9\xD\xA]+
350         // EQ:            SPACE?=SPACE? === [ \x9\xD\xA]*=[ \x9\xD\xA]*
351         if (preg_match('/^<\?xml\s+version\s*=\s*' . "((?:\"[a-zA-Z0-9_.:-]+\")|(?:'[a-zA-Z0-9_.:-]+'))" .
352             '\s+encoding\s*=\s*' . "((?:\"[A-Za-z][A-Za-z0-9._-]*\")|(?:'[A-Za-z][A-Za-z0-9._-]*'))/",
353             $xmlChunk, $matches)) {
354             return strtoupper(substr($matches[2], 1, -1));
355         }
356
357         // 4 - if mbstring is available, let it do the guesswork
358         // NB: we favour finding an encoding that is compatible with what we can process
359         if (extension_loaded('mbstring')) {
360             if ($encodingPrefs) {
361                 $enc = mb_detect_encoding($xmlChunk, $encodingPrefs);
362             } else {
363                 $enc = mb_detect_encoding($xmlChunk);
364             }
365             // NB: mb_detect likes to call it ascii, xml parser likes to call it US_ASCII...
366             // IANA also likes better US-ASCII, so go with it
367             if ($enc == 'ASCII') {
368                 $enc = 'US-' . $enc;
369             }
370
371             return $enc;
372         } else {
373             // no encoding specified: as per HTTP1.1 assume it is iso-8859-1?
374             // Both RFC 2616 (HTTP 1.1) and 1945 (HTTP 1.0) clearly state that for text/xxx content types
375             // this should be the standard. And we should be getting text/xml as request and response.
376             // BUT we have to be backward compatible with the lib, which always used UTF-8 as default...
377             return PhpXmlRpc::$xmlrpc_defencoding;
378         }
379     }
380 }