Minor cleanup in variable names
[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::iso8601Decode($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), $options);
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 $phpVal 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 decodeXml($xmlVal, $options = array())
234     {
235         // 'guestimate' encoding
236         $valEncoding = XMLParser::guessEncoding('', $xmlVal);
237         if ($valEncoding != '') {
238
239             // Since parsing will fail if charset is not specified in the xml prologue,
240             // the encoding is not UTF8 and there are non-ascii chars in the text, we try to work round that...
241             // The following code might be better for mb_string enabled installs, but
242             // makes the lib about 200% slower...
243             //if (!is_valid_charset($valEncoding, array('UTF-8'))
244             if (!in_array($valEncoding, array('UTF-8', 'US-ASCII')) && !XMLParser::hasEncoding($xmlVal)) {
245                 if ($valEncoding == 'ISO-8859-1') {
246                     $xmlVal = utf8_encode($xmlVal);
247                 } else {
248                     if (extension_loaded('mbstring')) {
249                         $xmlVal = mb_convert_encoding($xmlVal, 'UTF-8', $valEncoding);
250                     } else {
251                         error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of xml text: ' . $valEncoding);
252                     }
253                 }
254             }
255         }
256
257         $parser = xml_parser_create();
258         xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
259         // What if internal encoding is not in one of the 3 allowed?
260         // we use the broadest one, ie. utf8!
261         if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
262             xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
263         } else {
264             xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding);
265         }
266
267         $xmlRpcParser = new XMLParser();
268         xml_set_object($parser, $xmlRpcParser);
269
270         xml_set_element_handler($parser, 'xmlrpc_se_any', 'xmlrpc_ee');
271         xml_set_character_data_handler($parser, 'xmlrpc_cd');
272         xml_set_default_handler($parser, 'xmlrpc_dh');
273         if (!xml_parse($parser, $xmlVal, 1)) {
274             $errstr = sprintf('XML error: %s at line %d, column %d',
275                 xml_error_string(xml_get_error_code($parser)),
276                 xml_get_current_line_number($parser), xml_get_current_column_number($parser));
277             error_log($errstr);
278             xml_parser_free($parser);
279
280             return false;
281         }
282         xml_parser_free($parser);
283         if ($xmlRpcParser->_xh['isf'] > 1) {
284             // test that $xmlrpc->_xh['value'] is an obj, too???
285
286             error_log($xmlRpcParser->_xh['isf_reason']);
287
288             return false;
289         }
290         switch ($xmlRpcParser->_xh['rt']) {
291             case 'methodresponse':
292                 $v = &$xmlRpcParser->_xh['value'];
293                 if ($xmlRpcParser->_xh['isf'] == 1) {
294                     $vc = $v->structmem('faultCode');
295                     $vs = $v->structmem('faultString');
296                     $r = new Response(0, $vc->scalarval(), $vs->scalarval());
297                 } else {
298                     $r = new Response($v);
299                 }
300
301                 return $r;
302             case 'methodcall':
303                 $req = new Request($xmlRpcParser->_xh['method']);
304                 for ($i = 0; $i < count($xmlRpcParser->_xh['params']); $i++) {
305                     $req->addParam($xmlRpcParser->_xh['params'][$i]);
306                 }
307
308                 return $req;
309             case 'value':
310                 return $xmlRpcParser->_xh['value'];
311             default:
312                 return false;
313         }
314     }
315
316 }