b02eae2fb41012bb3099912c72c091df45d52279
[plcapi.git] / lib / xmlrpc.inc
1 <?php\r
2 // by Edd Dumbill (C) 1999-2002\r
3 // <edd@usefulinc.com>\r
4 // $Id: xmlrpc.inc,v 1.174 2009/03/16 19:36:38 ggiunta Exp $\r
5 \r
6 // Copyright (c) 1999,2000,2002 Edd Dumbill.\r
7 // All rights reserved.\r
8 //\r
9 // Redistribution and use in source and binary forms, with or without\r
10 // modification, are permitted provided that the following conditions\r
11 // are met:\r
12 //\r
13 //    * Redistributions of source code must retain the above copyright\r
14 //      notice, this list of conditions and the following disclaimer.\r
15 //\r
16 //    * Redistributions in binary form must reproduce the above\r
17 //      copyright notice, this list of conditions and the following\r
18 //      disclaimer in the documentation and/or other materials provided\r
19 //      with the distribution.\r
20 //\r
21 //    * Neither the name of the "XML-RPC for PHP" nor the names of its\r
22 //      contributors may be used to endorse or promote products derived\r
23 //      from this software without specific prior written permission.\r
24 //\r
25 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
26 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r
27 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\r
28 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\r
29 // REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\r
30 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r
31 // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\r
32 // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\r
33 // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\r
34 // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
35 // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\r
36 // OF THE POSSIBILITY OF SUCH DAMAGE.\r
37 \r
38         if(!function_exists('xml_parser_create'))\r
39         {\r
40                 // For PHP 4 onward, XML functionality is always compiled-in on windows:\r
41                 // no more need to dl-open it. It might have been compiled out on *nix...\r
42                 if(strtoupper(substr(PHP_OS, 0, 3) != 'WIN'))\r
43                 {\r
44                         dl('xml.so');\r
45                 }\r
46         }\r
47 \r
48         // G. Giunta 2005/01/29: declare global these variables,\r
49         // so that xmlrpc.inc will work even if included from within a function\r
50         // Milosch: 2005/08/07 - explicitly request these via $GLOBALS where used.\r
51         $GLOBALS['xmlrpcI4']='i4';\r
52         $GLOBALS['xmlrpcInt']='int';\r
53         $GLOBALS['xmlrpcBoolean']='boolean';\r
54         $GLOBALS['xmlrpcDouble']='double';\r
55         $GLOBALS['xmlrpcString']='string';\r
56         $GLOBALS['xmlrpcDateTime']='dateTime.iso8601';\r
57         $GLOBALS['xmlrpcBase64']='base64';\r
58         $GLOBALS['xmlrpcArray']='array';\r
59         $GLOBALS['xmlrpcStruct']='struct';\r
60         $GLOBALS['xmlrpcValue']='undefined';\r
61 \r
62         $GLOBALS['xmlrpcTypes']=array(\r
63                 $GLOBALS['xmlrpcI4']       => 1,\r
64                 $GLOBALS['xmlrpcInt']      => 1,\r
65                 $GLOBALS['xmlrpcBoolean']  => 1,\r
66                 $GLOBALS['xmlrpcString']   => 1,\r
67                 $GLOBALS['xmlrpcDouble']   => 1,\r
68                 $GLOBALS['xmlrpcDateTime'] => 1,\r
69                 $GLOBALS['xmlrpcBase64']   => 1,\r
70                 $GLOBALS['xmlrpcArray']    => 2,\r
71                 $GLOBALS['xmlrpcStruct']   => 3\r
72         );\r
73 \r
74         $GLOBALS['xmlrpc_valid_parents'] = array(\r
75                 'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT'),\r
76                 'BOOLEAN' => array('VALUE'),\r
77                 'I4' => array('VALUE'),\r
78                 'INT' => array('VALUE'),\r
79                 'STRING' => array('VALUE'),\r
80                 'DOUBLE' => array('VALUE'),\r
81                 'DATETIME.ISO8601' => array('VALUE'),\r
82                 'BASE64' => array('VALUE'),\r
83                 'MEMBER' => array('STRUCT'),\r
84                 'NAME' => array('MEMBER'),\r
85                 'DATA' => array('ARRAY'),\r
86                 'ARRAY' => array('VALUE'),\r
87                 'STRUCT' => array('VALUE'),\r
88                 'PARAM' => array('PARAMS'),\r
89                 'METHODNAME' => array('METHODCALL'),\r
90                 'PARAMS' => array('METHODCALL', 'METHODRESPONSE'),\r
91                 'FAULT' => array('METHODRESPONSE'),\r
92                 'NIL' => array('VALUE') // only used when extension activated\r
93         );\r
94 \r
95         // define extra types for supporting NULL (useful for json or <NIL/>)\r
96         $GLOBALS['xmlrpcNull']='null';\r
97         $GLOBALS['xmlrpcTypes']['null']=1;\r
98 \r
99         // Not in use anymore since 2.0. Shall we remove it?\r
100         /// @deprecated\r
101         $GLOBALS['xmlEntities']=array(\r
102                 'amp'  => '&',\r
103                 'quot' => '"',\r
104                 'lt'   => '<',\r
105                 'gt'   => '>',\r
106                 'apos' => "'"\r
107         );\r
108 \r
109         // tables used for transcoding different charsets into us-ascii xml\r
110 \r
111         $GLOBALS['xml_iso88591_Entities']=array();\r
112         $GLOBALS['xml_iso88591_Entities']['in'] = array();\r
113         $GLOBALS['xml_iso88591_Entities']['out'] = array();\r
114         for ($i = 0; $i < 32; $i++)\r
115         {\r
116                 $GLOBALS['xml_iso88591_Entities']['in'][] = chr($i);\r
117                 $GLOBALS['xml_iso88591_Entities']['out'][] = '&#'.$i.';';\r
118         }\r
119         for ($i = 160; $i < 256; $i++)\r
120         {\r
121                 $GLOBALS['xml_iso88591_Entities']['in'][] = chr($i);\r
122                 $GLOBALS['xml_iso88591_Entities']['out'][] = '&#'.$i.';';\r
123         }\r
124 \r
125         /// @todo add to iso table the characters from cp_1252 range, i.e. 128 to 159?\r
126         /// These will NOT be present in true ISO-8859-1, but will save the unwary\r
127         /// windows user from sending junk (though no luck when reciving them...)\r
128   /*\r
129         $GLOBALS['xml_cp1252_Entities']=array();\r
130         for ($i = 128; $i < 160; $i++)\r
131         {\r
132                 $GLOBALS['xml_cp1252_Entities']['in'][] = chr($i);\r
133         }\r
134         $GLOBALS['xml_cp1252_Entities']['out'] = array(\r
135                 '&#x20AC;', '?',        '&#x201A;', '&#x0192;',\r
136                 '&#x201E;', '&#x2026;', '&#x2020;', '&#x2021;',\r
137                 '&#x02C6;', '&#x2030;', '&#x0160;', '&#x2039;',\r
138                 '&#x0152;', '?',        '&#x017D;', '?',\r
139                 '?',        '&#x2018;', '&#x2019;', '&#x201C;',\r
140                 '&#x201D;', '&#x2022;', '&#x2013;', '&#x2014;',\r
141                 '&#x02DC;', '&#x2122;', '&#x0161;', '&#x203A;',\r
142                 '&#x0153;', '?',        '&#x017E;', '&#x0178;'\r
143         );\r
144   */\r
145 \r
146         $GLOBALS['xmlrpcerr'] = array(\r
147         'unknown_method'=>1,\r
148         'invalid_return'=>2,\r
149         'incorrect_params'=>3,\r
150         'introspect_unknown'=>4,\r
151         'http_error'=>5,\r
152         'no_data'=>6,\r
153         'no_ssl'=>7,\r
154         'curl_fail'=>8,\r
155         'invalid_request'=>15,\r
156         'no_curl'=>16,\r
157         'server_error'=>17,\r
158         'multicall_error'=>18,\r
159         'multicall_notstruct'=>9,\r
160         'multicall_nomethod'=>10,\r
161         'multicall_notstring'=>11,\r
162         'multicall_recursion'=>12,\r
163         'multicall_noparams'=>13,\r
164         'multicall_notarray'=>14,\r
165 \r
166         'cannot_decompress'=>103,\r
167         'decompress_fail'=>104,\r
168         'dechunk_fail'=>105,\r
169         'server_cannot_decompress'=>106,\r
170         'server_decompress_fail'=>107\r
171         );\r
172 \r
173         $GLOBALS['xmlrpcstr'] = array(\r
174         'unknown_method'=>'Unknown method',\r
175         'invalid_return'=>'Invalid return payload: enable debugging to examine incoming payload',\r
176         'incorrect_params'=>'Incorrect parameters passed to method',\r
177         'introspect_unknown'=>"Can't introspect: method unknown",\r
178         'http_error'=>"Didn't receive 200 OK from remote server.",\r
179         'no_data'=>'No data received from server.',\r
180         'no_ssl'=>'No SSL support compiled in.',\r
181         'curl_fail'=>'CURL error',\r
182         'invalid_request'=>'Invalid request payload',\r
183         'no_curl'=>'No CURL support compiled in.',\r
184         'server_error'=>'Internal server error',\r
185         'multicall_error'=>'Received from server invalid multicall response',\r
186         'multicall_notstruct'=>'system.multicall expected struct',\r
187         'multicall_nomethod'=>'missing methodName',\r
188         'multicall_notstring'=>'methodName is not a string',\r
189         'multicall_recursion'=>'recursive system.multicall forbidden',\r
190         'multicall_noparams'=>'missing params',\r
191         'multicall_notarray'=>'params is not an array',\r
192 \r
193         'cannot_decompress'=>'Received from server compressed HTTP and cannot decompress',\r
194         'decompress_fail'=>'Received from server invalid compressed HTTP',\r
195         'dechunk_fail'=>'Received from server invalid chunked HTTP',\r
196         'server_cannot_decompress'=>'Received from client compressed HTTP request and cannot decompress',\r
197         'server_decompress_fail'=>'Received from client invalid compressed HTTP request'\r
198         );\r
199 \r
200         // The charset encoding used by the server for received messages and\r
201         // by the client for received responses when received charset cannot be determined\r
202         // or is not supported\r
203         $GLOBALS['xmlrpc_defencoding']='UTF-8';\r
204 \r
205         // The encoding used internally by PHP.\r
206         // String values received as xml will be converted to this, and php strings will be converted to xml\r
207         // as if having been coded with this\r
208         $GLOBALS['xmlrpc_internalencoding']='ISO-8859-1';\r
209 \r
210         $GLOBALS['xmlrpcName']='XML-RPC for PHP';\r
211         $GLOBALS['xmlrpcVersion']='3.0.0.beta';\r
212 \r
213         // let user errors start at 800\r
214         $GLOBALS['xmlrpcerruser']=800;\r
215         // let XML parse errors start at 100\r
216         $GLOBALS['xmlrpcerrxml']=100;\r
217 \r
218         // formulate backslashes for escaping regexp\r
219         // Not in use anymore since 2.0. Shall we remove it?\r
220         /// @deprecated\r
221         $GLOBALS['xmlrpc_backslash']=chr(92).chr(92);\r
222 \r
223         // set to TRUE to enable correct decoding of <NIL/> values\r
224         $GLOBALS['xmlrpc_null_extension']=false;\r
225 \r
226         // used to store state during parsing\r
227         // quick explanation of components:\r
228         //   ac - used to accumulate values\r
229         //   isf - used to indicate a parsing fault (2) or xmlrpcresp fault (1)\r
230         //   isf_reason - used for storing xmlrpcresp fault string\r
231         //   lv - used to indicate "looking for a value": implements\r
232         //        the logic to allow values with no types to be strings\r
233         //   params - used to store parameters in method calls\r
234         //   method - used to store method name\r
235         //   stack - array with genealogy of xml elements names:\r
236         //           used to validate nesting of xmlrpc elements\r
237         $GLOBALS['_xh']=null;\r
238 \r
239         /**\r
240         * Convert a string to the correct XML representation in a target charset\r
241         * To help correct communication of non-ascii chars inside strings, regardless\r
242         * of the charset used when sending requests, parsing them, sending responses\r
243         * and parsing responses, an option is to convert all non-ascii chars present in the message\r
244         * into their equivalent 'charset entity'. Charset entities enumerated this way\r
245         * are independent of the charset encoding used to transmit them, and all XML\r
246         * parsers are bound to understand them.\r
247         * Note that in the std case we are not sending a charset encoding mime type\r
248         * along with http headers, so we are bound by RFC 3023 to emit strict us-ascii.\r
249         *\r
250         * @todo do a bit of basic benchmarking (strtr vs. str_replace)\r
251         * @todo make usage of iconv() or recode_string() or mb_string() where available\r
252         */\r
253         function xmlrpc_encode_entitites($data, $src_encoding='', $dest_encoding='')\r
254         {\r
255                 if ($src_encoding == '')\r
256                 {\r
257                         // lame, but we know no better...\r
258                         $src_encoding = $GLOBALS['xmlrpc_internalencoding'];\r
259                 }\r
260 \r
261                 switch(strtoupper($src_encoding.'_'.$dest_encoding))\r
262                 {\r
263                         case 'ISO-8859-1_':\r
264                         case 'ISO-8859-1_US-ASCII':\r
265                                 $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);\r
266                                 $escaped_data = str_replace($GLOBALS['xml_iso88591_Entities']['in'], $GLOBALS['xml_iso88591_Entities']['out'], $escaped_data);\r
267                                 break;\r
268                         case 'ISO-8859-1_UTF-8':\r
269                                 $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);\r
270                                 $escaped_data = utf8_encode($escaped_data);\r
271                                 break;\r
272                         case 'ISO-8859-1_ISO-8859-1':\r
273                         case 'US-ASCII_US-ASCII':\r
274                         case 'US-ASCII_UTF-8':\r
275                         case 'US-ASCII_':\r
276                         case 'US-ASCII_ISO-8859-1':\r
277                         case 'UTF-8_UTF-8':\r
278                         //case 'CP1252_CP1252':\r
279                                 $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);\r
280                                 break;\r
281                         case 'UTF-8_':\r
282                         case 'UTF-8_US-ASCII':\r
283                         case 'UTF-8_ISO-8859-1':\r
284         // NB: this will choke on invalid UTF-8, going most likely beyond EOF\r
285         $escaped_data = '';\r
286         // be kind to users creating string xmlrpcvals out of different php types\r
287         $data = (string) $data;\r
288         $ns = strlen ($data);\r
289         for ($nn = 0; $nn < $ns; $nn++)\r
290         {\r
291                 $ch = $data[$nn];\r
292                 $ii = ord($ch);\r
293                 //1 7 0bbbbbbb (127)\r
294                 if ($ii < 128)\r
295                 {\r
296                         /// @todo shall we replace this with a (supposedly) faster str_replace?\r
297                         switch($ii){\r
298                                 case 34:\r
299                                         $escaped_data .= '&quot;';\r
300                                         break;\r
301                                 case 38:\r
302                                         $escaped_data .= '&amp;';\r
303                                         break;\r
304                                 case 39:\r
305                                         $escaped_data .= '&apos;';\r
306                                         break;\r
307                                 case 60:\r
308                                         $escaped_data .= '&lt;';\r
309                                         break;\r
310                                 case 62:\r
311                                         $escaped_data .= '&gt;';\r
312                                         break;\r
313                                 default:\r
314                                         $escaped_data .= $ch;\r
315                         } // switch\r
316                 }\r
317                 //2 11 110bbbbb 10bbbbbb (2047)\r
318                 else if ($ii>>5 == 6)\r
319                 {\r
320                         $b1 = ($ii & 31);\r
321                         $ii = ord($data[$nn+1]);\r
322                         $b2 = ($ii & 63);\r
323                         $ii = ($b1 * 64) + $b2;\r
324                         $ent = sprintf ('&#%d;', $ii);\r
325                         $escaped_data .= $ent;\r
326                         $nn += 1;\r
327                 }\r
328                 //3 16 1110bbbb 10bbbbbb 10bbbbbb\r
329                 else if ($ii>>4 == 14)\r
330                 {\r
331                         $b1 = ($ii & 15);\r
332                         $ii = ord($data[$nn+1]);\r
333                         $b2 = ($ii & 63);\r
334                         $ii = ord($data[$nn+2]);\r
335                         $b3 = ($ii & 63);\r
336                         $ii = ((($b1 * 64) + $b2) * 64) + $b3;\r
337                         $ent = sprintf ('&#%d;', $ii);\r
338                         $escaped_data .= $ent;\r
339                         $nn += 2;\r
340                 }\r
341                 //4 21 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb\r
342                 else if ($ii>>3 == 30)\r
343                 {\r
344                         $b1 = ($ii & 7);\r
345                         $ii = ord($data[$nn+1]);\r
346                         $b2 = ($ii & 63);\r
347                         $ii = ord($data[$nn+2]);\r
348                         $b3 = ($ii & 63);\r
349                         $ii = ord($data[$nn+3]);\r
350                         $b4 = ($ii & 63);\r
351                         $ii = ((((($b1 * 64) + $b2) * 64) + $b3) * 64) + $b4;\r
352                         $ent = sprintf ('&#%d;', $ii);\r
353                         $escaped_data .= $ent;\r
354                         $nn += 3;\r
355                 }\r
356         }\r
357                                 break;\r
358 /*\r
359                         case 'CP1252_':\r
360                         case 'CP1252_US-ASCII':\r
361                                 $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);\r
362                                 $escaped_data = str_replace($GLOBALS['xml_iso88591_Entities']['in'], $GLOBALS['xml_iso88591_Entities']['out'], $escaped_data);\r
363                                 $escaped_data = str_replace($GLOBALS['xml_cp1252_Entities']['in'], $GLOBALS['xml_cp1252_Entities']['out'], $escaped_data);\r
364                                 break;\r
365                         case 'CP1252_UTF-8':\r
366                                 $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);\r
367                                 /// @todo we could use real UTF8 chars here instead of xml entities... (note that utf_8 encode all allone will NOT convert them)\r
368                                 $escaped_data = str_replace($GLOBALS['xml_cp1252_Entities']['in'], $GLOBALS['xml_cp1252_Entities']['out'], $escaped_data);\r
369                                 $escaped_data = utf8_encode($escaped_data);\r
370                                 break;\r
371                         case 'CP1252_ISO-8859-1':\r
372                                 $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);\r
373                                 // we might as well replave all funky chars with a '?' here, but we are kind and leave it to the receiving application layer to decide what to do with these weird entities...\r
374                                 $escaped_data = str_replace($GLOBALS['xml_cp1252_Entities']['in'], $GLOBALS['xml_cp1252_Entities']['out'], $escaped_data);\r
375                                 break;\r
376 */\r
377                         default:\r
378                                 $escaped_data = '';\r
379                                 error_log("Converting from $src_encoding to $dest_encoding: not supported...");\r
380                 }\r
381                 return $escaped_data;\r
382         }\r
383 \r
384         /// xml parser handler function for opening element tags\r
385         function xmlrpc_se($parser, $name, $attrs, $accept_single_vals=false)\r
386         {\r
387                 // if invalid xmlrpc already detected, skip all processing\r
388                 if ($GLOBALS['_xh']['isf'] < 2)\r
389                 {\r
390                         // check for correct element nesting\r
391                         // top level element can only be of 2 types\r
392                         /// @todo optimization creep: save this check into a bool variable, instead of using count() every time:\r
393                         ///       there is only a single top level element in xml anyway\r
394                         if (count($GLOBALS['_xh']['stack']) == 0)\r
395                         {\r
396                                 if ($name != 'METHODRESPONSE' && $name != 'METHODCALL' && (\r
397                                         $name != 'VALUE' && !$accept_single_vals))\r
398                                 {\r
399                                         $GLOBALS['_xh']['isf'] = 2;\r
400                                         $GLOBALS['_xh']['isf_reason'] = 'missing top level xmlrpc element';\r
401                                         return;\r
402                                 }\r
403                                 else\r
404                                 {\r
405                                         $GLOBALS['_xh']['rt'] = strtolower($name);\r
406                                 }\r
407                         }\r
408                         else\r
409                         {\r
410                                 // not top level element: see if parent is OK\r
411                                 $parent = end($GLOBALS['_xh']['stack']);\r
412                                 if (!array_key_exists($name, $GLOBALS['xmlrpc_valid_parents']) || !in_array($parent, $GLOBALS['xmlrpc_valid_parents'][$name]))\r
413                                 {\r
414                                         $GLOBALS['_xh']['isf'] = 2;\r
415                                         $GLOBALS['_xh']['isf_reason'] = "xmlrpc element $name cannot be child of $parent";\r
416                                         return;\r
417                                 }\r
418                         }\r
419 \r
420                         switch($name)\r
421                         {\r
422                                 // optimize for speed switch cases: most common cases first\r
423                                 case 'VALUE':\r
424                                         /// @todo we could check for 2 VALUE elements inside a MEMBER or PARAM element\r
425                                         $GLOBALS['_xh']['vt']='value'; // indicator: no value found yet\r
426                                         $GLOBALS['_xh']['ac']='';\r
427                                         $GLOBALS['_xh']['lv']=1;\r
428                                         $GLOBALS['_xh']['php_class']=null;\r
429                                         break;\r
430                                 case 'I4':\r
431                                 case 'INT':\r
432                                 case 'STRING':\r
433                                 case 'BOOLEAN':\r
434                                 case 'DOUBLE':\r
435                                 case 'DATETIME.ISO8601':\r
436                                 case 'BASE64':\r
437                                         if ($GLOBALS['_xh']['vt']!='value')\r
438                                         {\r
439                                                 //two data elements inside a value: an error occurred!\r
440                                                 $GLOBALS['_xh']['isf'] = 2;\r
441                                                 $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value";\r
442                                                 return;\r
443                                         }\r
444                                         $GLOBALS['_xh']['ac']=''; // reset the accumulator\r
445                                         break;\r
446                                 case 'STRUCT':\r
447                                 case 'ARRAY':\r
448                                         if ($GLOBALS['_xh']['vt']!='value')\r
449                                         {\r
450                                                 //two data elements inside a value: an error occurred!\r
451                                                 $GLOBALS['_xh']['isf'] = 2;\r
452                                                 $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value";\r
453                                                 return;\r
454                                         }\r
455                                         // create an empty array to hold child values, and push it onto appropriate stack\r
456                                         $cur_val = array();\r
457                                         $cur_val['values'] = array();\r
458                                         $cur_val['type'] = $name;\r
459                                         // check for out-of-band information to rebuild php objs\r
460                                         // and in case it is found, save it\r
461                                         if (@isset($attrs['PHP_CLASS']))\r
462                                         {\r
463                                                 $cur_val['php_class'] = $attrs['PHP_CLASS'];\r
464                                         }\r
465                                         $GLOBALS['_xh']['valuestack'][] = $cur_val;\r
466                                         $GLOBALS['_xh']['vt']='data'; // be prepared for a data element next\r
467                                         break;\r
468                                 case 'DATA':\r
469                                         if ($GLOBALS['_xh']['vt']!='data')\r
470                                         {\r
471                                                 //two data elements inside a value: an error occurred!\r
472                                                 $GLOBALS['_xh']['isf'] = 2;\r
473                                                 $GLOBALS['_xh']['isf_reason'] = "found two data elements inside an array element";\r
474                                                 return;\r
475                                         }\r
476                                 case 'METHODCALL':\r
477                                 case 'METHODRESPONSE':\r
478                                 case 'PARAMS':\r
479                                         // valid elements that add little to processing\r
480                                         break;\r
481                                 case 'METHODNAME':\r
482                                 case 'NAME':\r
483                                         /// @todo we could check for 2 NAME elements inside a MEMBER element\r
484                                         $GLOBALS['_xh']['ac']='';\r
485                                         break;\r
486                                 case 'FAULT':\r
487                                         $GLOBALS['_xh']['isf']=1;\r
488                                         break;\r
489                                 case 'MEMBER':\r
490                                         $GLOBALS['_xh']['valuestack'][count($GLOBALS['_xh']['valuestack'])-1]['name']=''; // set member name to null, in case we do not find in the xml later on\r
491                                         //$GLOBALS['_xh']['ac']='';\r
492                                         // Drop trough intentionally\r
493                                 case 'PARAM':\r
494                                         // clear value type, so we can check later if no value has been passed for this param/member\r
495                                         $GLOBALS['_xh']['vt']=null;\r
496                                         break;\r
497                                 case 'NIL':\r
498                                         if ($GLOBALS['xmlrpc_null_extension'])\r
499                                         {\r
500                                                 if ($GLOBALS['_xh']['vt']!='value')\r
501                                                 {\r
502                                                         //two data elements inside a value: an error occurred!\r
503                                                         $GLOBALS['_xh']['isf'] = 2;\r
504                                                         $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value";\r
505                                                         return;\r
506                                                 }\r
507                                                 $GLOBALS['_xh']['ac']=''; // reset the accumulator\r
508                                                 break;\r
509                                         }\r
510                                         // we do not support the <NIL/> extension, so\r
511                                         // drop through intentionally\r
512                                 default:\r
513                                         /// INVALID ELEMENT: RAISE ISF so that it is later recognized!!!\r
514                                         $GLOBALS['_xh']['isf'] = 2;\r
515                                         $GLOBALS['_xh']['isf_reason'] = "found not-xmlrpc xml element $name";\r
516                                         break;\r
517                         }\r
518 \r
519                         // Save current element name to stack, to validate nesting\r
520                         $GLOBALS['_xh']['stack'][] = $name;\r
521 \r
522                         /// @todo optimization creep: move this inside the big switch() above\r
523                         if($name!='VALUE')\r
524                         {\r
525                                 $GLOBALS['_xh']['lv']=0;\r
526                         }\r
527                 }\r
528         }\r
529 \r
530         /// Used in decoding xml chunks that might represent single xmlrpc values\r
531         function xmlrpc_se_any($parser, $name, $attrs)\r
532         {\r
533                 xmlrpc_se($parser, $name, $attrs, true);\r
534         }\r
535 \r
536         /// xml parser handler function for close element tags\r
537         function xmlrpc_ee($parser, $name, $rebuild_xmlrpcvals = true)\r
538         {\r
539                 if ($GLOBALS['_xh']['isf'] < 2)\r
540                 {\r
541                         // push this element name from stack\r
542                         // NB: if XML validates, correct opening/closing is guaranteed and\r
543                         // we do not have to check for $name == $curr_elem.\r
544                         // we also checked for proper nesting at start of elements...\r
545                         $curr_elem = array_pop($GLOBALS['_xh']['stack']);\r
546 \r
547                         switch($name)\r
548                         {\r
549                                 case 'VALUE':\r
550                                         // This if() detects if no scalar was inside <VALUE></VALUE>\r
551                                         if ($GLOBALS['_xh']['vt']=='value')\r
552                                         {\r
553                                                 $GLOBALS['_xh']['value']=$GLOBALS['_xh']['ac'];\r
554                                                 $GLOBALS['_xh']['vt']=$GLOBALS['xmlrpcString'];\r
555                                         }\r
556 \r
557                                         if ($rebuild_xmlrpcvals)\r
558                                         {\r
559                                                 // build the xmlrpc val out of the data received, and substitute it\r
560                                                 $temp = new xmlrpcval($GLOBALS['_xh']['value'], $GLOBALS['_xh']['vt']);\r
561                                                 // in case we got info about underlying php class, save it\r
562                                                 // in the object we're rebuilding\r
563                                                 if (isset($GLOBALS['_xh']['php_class']))\r
564                                                         $temp->_php_class = $GLOBALS['_xh']['php_class'];\r
565                                                 // check if we are inside an array or struct:\r
566                                                 // if value just built is inside an array, let's move it into array on the stack\r
567                                                 $vscount = count($GLOBALS['_xh']['valuestack']);\r
568                                                 if ($vscount && $GLOBALS['_xh']['valuestack'][$vscount-1]['type']=='ARRAY')\r
569                                                 {\r
570                                                         $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][] = $temp;\r
571                                                 }\r
572                                                 else\r
573                                                 {\r
574                                                         $GLOBALS['_xh']['value'] = $temp;\r
575                                                 }\r
576                                         }\r
577                                         else\r
578                                         {\r
579                                                 /// @todo this needs to treat correctly php-serialized objects,\r
580                                                 /// since std deserializing is done by php_xmlrpc_decode,\r
581                                                 /// which we will not be calling...\r
582                                                 if (isset($GLOBALS['_xh']['php_class']))\r
583                                                 {\r
584                                                 }\r
585 \r
586                                                 // check if we are inside an array or struct:\r
587                                                 // if value just built is inside an array, let's move it into array on the stack\r
588                                                 $vscount = count($GLOBALS['_xh']['valuestack']);\r
589                                                 if ($vscount && $GLOBALS['_xh']['valuestack'][$vscount-1]['type']=='ARRAY')\r
590                                                 {\r
591                                                         $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][] = $GLOBALS['_xh']['value'];\r
592                                                 }\r
593                                         }\r
594                                         break;\r
595                                 case 'BOOLEAN':\r
596                                 case 'I4':\r
597                                 case 'INT':\r
598                                 case 'STRING':\r
599                                 case 'DOUBLE':\r
600                                 case 'DATETIME.ISO8601':\r
601                                 case 'BASE64':\r
602                                         $GLOBALS['_xh']['vt']=strtolower($name);\r
603                                         /// @todo: optimization creep - remove the if/elseif cycle below\r
604                                         /// since the case() in which we are already did that\r
605                                         if ($name=='STRING')\r
606                                         {\r
607                                                 $GLOBALS['_xh']['value']=$GLOBALS['_xh']['ac'];\r
608                                         }\r
609                                         elseif ($name=='DATETIME.ISO8601')\r
610                                         {\r
611                                                 if (!preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $GLOBALS['_xh']['ac']))\r
612                                                 {\r
613                                                         error_log('XML-RPC: invalid value received in DATETIME: '.$GLOBALS['_xh']['ac']);\r
614                                                 }\r
615                                                 $GLOBALS['_xh']['vt']=$GLOBALS['xmlrpcDateTime'];\r
616                                                 $GLOBALS['_xh']['value']=$GLOBALS['_xh']['ac'];\r
617                                         }\r
618                                         elseif ($name=='BASE64')\r
619                                         {\r
620                                                 /// @todo check for failure of base64 decoding / catch warnings\r
621                                                 $GLOBALS['_xh']['value']=base64_decode($GLOBALS['_xh']['ac']);\r
622                                         }\r
623                                         elseif ($name=='BOOLEAN')\r
624                                         {\r
625                                                 // special case here: we translate boolean 1 or 0 into PHP\r
626                                                 // constants true or false.\r
627                                                 // Strings 'true' and 'false' are accepted, even though the\r
628                                                 // spec never mentions them (see eg. Blogger api docs)\r
629                                                 // NB: this simple checks helps a lot sanitizing input, ie no\r
630                                                 // security problems around here\r
631                                                 if ($GLOBALS['_xh']['ac']=='1' || strcasecmp($GLOBALS['_xh']['ac'], 'true') == 0)\r
632                                                 {\r
633                                                         $GLOBALS['_xh']['value']=true;\r
634                                                 }\r
635                                                 else\r
636                                                 {\r
637                                                         // log if receiveing something strange, even though we set the value to false anyway\r
638                                                         if ($GLOBALS['_xh']['ac']!='0' && strcasecmp($GLOBALS['_xh']['ac'], 'false') != 0)\r
639                                                                 error_log('XML-RPC: invalid value received in BOOLEAN: '.$GLOBALS['_xh']['ac']);\r
640                                                         $GLOBALS['_xh']['value']=false;\r
641                                                 }\r
642                                         }\r
643                                         elseif ($name=='DOUBLE')\r
644                                         {\r
645                                                 // we have a DOUBLE\r
646                                                 // we must check that only 0123456789-.<space> are characters here\r
647                                                 // NOTE: regexp could be much stricter than this...\r
648                                                 if (!preg_match('/^[+-eE0123456789 \t.]+$/', $GLOBALS['_xh']['ac']))\r
649                                                 {\r
650                                                         /// @todo: find a better way of throwing an error than this!\r
651                                                         error_log('XML-RPC: non numeric value received in DOUBLE: '.$GLOBALS['_xh']['ac']);\r
652                                                         $GLOBALS['_xh']['value']='ERROR_NON_NUMERIC_FOUND';\r
653                                                 }\r
654                                                 else\r
655                                                 {\r
656                                                         // it's ok, add it on\r
657                                                         $GLOBALS['_xh']['value']=(double)$GLOBALS['_xh']['ac'];\r
658                                                 }\r
659                                         }\r
660                                         else\r
661                                         {\r
662                                                 // we have an I4/INT\r
663                                                 // we must check that only 0123456789-<space> are characters here\r
664                                                 if (!preg_match('/^[+-]?[0123456789 \t]+$/', $GLOBALS['_xh']['ac']))\r
665                                                 {\r
666                                                         /// @todo find a better way of throwing an error than this!\r
667                                                         error_log('XML-RPC: non numeric value received in INT: '.$GLOBALS['_xh']['ac']);\r
668                                                         $GLOBALS['_xh']['value']='ERROR_NON_NUMERIC_FOUND';\r
669                                                 }\r
670                                                 else\r
671                                                 {\r
672                                                         // it's ok, add it on\r
673                                                         $GLOBALS['_xh']['value']=(int)$GLOBALS['_xh']['ac'];\r
674                                                 }\r
675                                         }\r
676                                         //$GLOBALS['_xh']['ac']=''; // is this necessary?\r
677                                         $GLOBALS['_xh']['lv']=3; // indicate we've found a value\r
678                                         break;\r
679                                 case 'NAME':\r
680                                         $GLOBALS['_xh']['valuestack'][count($GLOBALS['_xh']['valuestack'])-1]['name'] = $GLOBALS['_xh']['ac'];\r
681                                         break;\r
682                                 case 'MEMBER':\r
683                                         //$GLOBALS['_xh']['ac']=''; // is this necessary?\r
684                                         // add to array in the stack the last element built,\r
685                                         // unless no VALUE was found\r
686                                         if ($GLOBALS['_xh']['vt'])\r
687                                         {\r
688                                                 $vscount = count($GLOBALS['_xh']['valuestack']);\r
689                                                 $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][$GLOBALS['_xh']['valuestack'][$vscount-1]['name']] = $GLOBALS['_xh']['value'];\r
690                                         } else\r
691                                                 error_log('XML-RPC: missing VALUE inside STRUCT in received xml');\r
692                                         break;\r
693                                 case 'DATA':\r
694                                         //$GLOBALS['_xh']['ac']=''; // is this necessary?\r
695                                         $GLOBALS['_xh']['vt']=null; // reset this to check for 2 data elements in a row - even if they're empty\r
696                                         break;\r
697                                 case 'STRUCT':\r
698                                 case 'ARRAY':\r
699                                         // fetch out of stack array of values, and promote it to current value\r
700                                         $curr_val = array_pop($GLOBALS['_xh']['valuestack']);\r
701                                         $GLOBALS['_xh']['value'] = $curr_val['values'];\r
702                                         $GLOBALS['_xh']['vt']=strtolower($name);\r
703                                         if (isset($curr_val['php_class']))\r
704                                         {\r
705                                                 $GLOBALS['_xh']['php_class'] = $curr_val['php_class'];\r
706                                         }\r
707                                         break;\r
708                                 case 'PARAM':\r
709                                         // add to array of params the current value,\r
710                                         // unless no VALUE was found\r
711                                         if ($GLOBALS['_xh']['vt'])\r
712                                         {\r
713                                                 $GLOBALS['_xh']['params'][]=$GLOBALS['_xh']['value'];\r
714                                                 $GLOBALS['_xh']['pt'][]=$GLOBALS['_xh']['vt'];\r
715                                         }\r
716                                         else\r
717                                                 error_log('XML-RPC: missing VALUE inside PARAM in received xml');\r
718                                         break;\r
719                                 case 'METHODNAME':\r
720                                         $GLOBALS['_xh']['method']=preg_replace('/^[\n\r\t ]+/', '', $GLOBALS['_xh']['ac']);\r
721                                         break;\r
722                                 case 'NIL':\r
723                                         if ($GLOBALS['xmlrpc_null_extension'])\r
724                                         {\r
725                                                 $GLOBALS['_xh']['vt']='null';\r
726                                                 $GLOBALS['_xh']['value']=null;\r
727                                                 $GLOBALS['_xh']['lv']=3;\r
728                                                 break;\r
729                                         }\r
730                                         // drop through intentionally if nil extension not enabled\r
731                                 case 'PARAMS':\r
732                                 case 'FAULT':\r
733                                 case 'METHODCALL':\r
734                                 case 'METHORESPONSE':\r
735                                         break;\r
736                                 default:\r
737                                         // End of INVALID ELEMENT!\r
738                                         // shall we add an assert here for unreachable code???\r
739                                         break;\r
740                         }\r
741                 }\r
742         }\r
743 \r
744         /// Used in decoding xmlrpc requests/responses without rebuilding xmlrpc values\r
745         function xmlrpc_ee_fast($parser, $name)\r
746         {\r
747                 xmlrpc_ee($parser, $name, false);\r
748         }\r
749 \r
750         /// xml parser handler function for character data\r
751         function xmlrpc_cd($parser, $data)\r
752         {\r
753                 // skip processing if xml fault already detected\r
754                 if ($GLOBALS['_xh']['isf'] < 2)\r
755                 {\r
756                         // "lookforvalue==3" means that we've found an entire value\r
757                         // and should discard any further character data\r
758                         if($GLOBALS['_xh']['lv']!=3)\r
759                         {\r
760                                 // G. Giunta 2006-08-23: useless change of 'lv' from 1 to 2\r
761                                 //if($GLOBALS['_xh']['lv']==1)\r
762                                 //{\r
763                                         // if we've found text and we're just in a <value> then\r
764                                         // say we've found a value\r
765                                         //$GLOBALS['_xh']['lv']=2;\r
766                                 //}\r
767                                 // we always initialize the accumulator before starting parsing, anyway...\r
768                                 //if(!@isset($GLOBALS['_xh']['ac']))\r
769                                 //{\r
770                                 //      $GLOBALS['_xh']['ac'] = '';\r
771                                 //}\r
772                                 $GLOBALS['_xh']['ac'].=$data;\r
773                         }\r
774                 }\r
775         }\r
776 \r
777         /// xml parser handler function for 'other stuff', ie. not char data or\r
778         /// element start/end tag. In fact it only gets called on unknown entities...\r
779         function xmlrpc_dh($parser, $data)\r
780         {\r
781                 // skip processing if xml fault already detected\r
782                 if ($GLOBALS['_xh']['isf'] < 2)\r
783                 {\r
784                         if(substr($data, 0, 1) == '&' && substr($data, -1, 1) == ';')\r
785                         {\r
786                                 // G. Giunta 2006-08-25: useless change of 'lv' from 1 to 2\r
787                                 //if($GLOBALS['_xh']['lv']==1)\r
788                                 //{\r
789                                 //      $GLOBALS['_xh']['lv']=2;\r
790                                 //}\r
791                                 $GLOBALS['_xh']['ac'].=$data;\r
792                         }\r
793                 }\r
794                 return true;\r
795         }\r
796 \r
797         class xmlrpc_client\r
798         {\r
799                 var $path;\r
800                 var $server;\r
801                 var $port=0;\r
802                 var $method='http';\r
803                 var $errno;\r
804                 var $errstr;\r
805                 var $debug=0;\r
806                 var $username='';\r
807                 var $password='';\r
808                 var $authtype=1;\r
809                 var $cert='';\r
810                 var $certpass='';\r
811                 var $cacert='';\r
812                 var $cacertdir='';\r
813                 var $key='';\r
814                 var $keypass='';\r
815                 var $verifypeer=true;\r
816                 var $verifyhost=1;\r
817                 var $no_multicall=false;\r
818                 var $proxy='';\r
819                 var $proxyport=0;\r
820                 var $proxy_user='';\r
821                 var $proxy_pass='';\r
822                 var $proxy_authtype=1;\r
823                 var $cookies=array();\r
824                 /**\r
825                 * List of http compression methods accepted by the client for responses.\r
826                 * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib\r
827                 *\r
828                 * NNB: you can set it to any non-empty array for HTTP11 and HTTPS, since\r
829                 * in those cases it will be up to CURL to decide the compression methods\r
830                 * it supports. You might check for the presence of 'zlib' in the output of\r
831                 * curl_version() to determine wheter compression is supported or not\r
832                 */\r
833                 var $accepted_compression = array();\r
834                 /**\r
835                 * Name of compression scheme to be used for sending requests.\r
836                 * Either null, gzip or deflate\r
837                 */\r
838                 var $request_compression = '';\r
839                 /**\r
840                 * CURL handle: used for keep-alive connections (PHP 4.3.8 up, see:\r
841                 * http://curl.haxx.se/docs/faq.html#7.3)\r
842                 */\r
843                 var $xmlrpc_curl_handle = null;\r
844                 /// Wheter to use persistent connections for http 1.1 and https\r
845                 var $keepalive = false;\r
846                 /// Charset encodings that can be decoded without problems by the client\r
847                 var $accepted_charset_encodings = array();\r
848                 /// Charset encoding to be used in serializing request. NULL = use ASCII\r
849                 var $request_charset_encoding = '';\r
850                 /**\r
851                 * Decides the content of xmlrpcresp objects returned by calls to send()\r
852                 * valid strings are 'xmlrpcvals', 'phpvals' or 'xml'\r
853                 */\r
854                 var $return_type = 'xmlrpcvals';\r
855 \r
856                 /**\r
857                 * @param string $path either the complete server URL or the PATH part of the xmlrc server URL, e.g. /xmlrpc/server.php\r
858                 * @param string $server the server name / ip address\r
859                 * @param integer $port the port the server is listening on, defaults to 80 or 443 depending on protocol used\r
860                 * @param string $method the http protocol variant: defaults to 'http', 'https' and 'http11' can be used if CURL is installed\r
861                 */\r
862                 function xmlrpc_client($path, $server='', $port='', $method='')\r
863                 {\r
864                         // allow user to specify all params in $path\r
865                         if($server == '' and $port == '' and $method == '')\r
866                         {\r
867                                 $parts = parse_url($path);\r
868                                 $server = $parts['host'];\r
869                                 $path = isset($parts['path']) ? $parts['path'] : '';\r
870                                 if(isset($parts['query']))\r
871                                 {\r
872                                         $path .= '?'.$parts['query'];\r
873                                 }\r
874                                 if(isset($parts['fragment']))\r
875                                 {\r
876                                         $path .= '#'.$parts['fragment'];\r
877                                 }\r
878                                 if(isset($parts['port']))\r
879                                 {\r
880                                         $port = $parts['port'];\r
881                                 }\r
882                                 if(isset($parts['scheme']))\r
883                                 {\r
884                                         $method = $parts['scheme'];\r
885                                 }\r
886                                 if(isset($parts['user']))\r
887                                 {\r
888                                         $this->username = $parts['user'];\r
889                                 }\r
890                                 if(isset($parts['pass']))\r
891                                 {\r
892                                         $this->password = $parts['pass'];\r
893                                 }\r
894                         }\r
895                         if($path == '' || $path[0] != '/')\r
896                         {\r
897                                 $this->path='/'.$path;\r
898                         }\r
899                         else\r
900                         {\r
901                                 $this->path=$path;\r
902                         }\r
903                         $this->server=$server;\r
904                         if($port != '')\r
905                         {\r
906                                 $this->port=$port;\r
907                         }\r
908                         if($method != '')\r
909                         {\r
910                                 $this->method=$method;\r
911                         }\r
912 \r
913                         // if ZLIB is enabled, let the client by default accept compressed responses\r
914                         if(function_exists('gzinflate') || (\r
915                                 function_exists('curl_init') && (($info = curl_version()) &&\r
916                                 ((is_string($info) && strpos($info, 'zlib') !== null) || isset($info['libz_version'])))\r
917                         ))\r
918                         {\r
919                                 $this->accepted_compression = array('gzip', 'deflate');\r
920                         }\r
921 \r
922                         // keepalives: enabled by default ONLY for PHP >= 4.3.8\r
923                         $this->keepalive = true;\r
924 \r
925                         // by default the xml parser can support these 3 charset encodings\r
926                         $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII');\r
927                 }\r
928 \r
929                 /**\r
930                 * Enables/disables the echoing to screen of the xmlrpc responses received\r
931                 * @param integer $debug values 0, 1 and 2 are supported (2 = echo sent msg too, before received response)\r
932                 * @access public\r
933                 */\r
934                 function setDebug($in)\r
935                 {\r
936                         $this->debug=$in;\r
937                 }\r
938 \r
939                 /**\r
940                 * Add some http BASIC AUTH credentials, used by the client to authenticate\r
941                 * @param string $u username\r
942                 * @param string $p password\r
943                 * @param integer $t auth type. See curl_setopt man page for supported auth types. Defaults to CURLAUTH_BASIC (basic auth)\r
944                 * @access public\r
945                 */\r
946                 function setCredentials($u, $p, $t=1)\r
947                 {\r
948                         $this->username=$u;\r
949                         $this->password=$p;\r
950                         $this->authtype=$t;\r
951                 }\r
952 \r
953                 /**\r
954                 * Add a client-side https certificate\r
955                 * @param string $cert\r
956                 * @param string $certpass\r
957                 * @access public\r
958                 */\r
959                 function setCertificate($cert, $certpass)\r
960                 {\r
961                         $this->cert = $cert;\r
962                         $this->certpass = $certpass;\r
963                 }\r
964 \r
965                 /**\r
966                 * Add a CA certificate to verify server with (see man page about\r
967                 * CURLOPT_CAINFO for more details\r
968                 * @param string $cacert certificate file name (or dir holding certificates)\r
969                 * @param bool $is_dir set to true to indicate cacert is a dir. defaults to false\r
970                 * @access public\r
971                 */\r
972                 function setCaCertificate($cacert, $is_dir=false)\r
973                 {\r
974                         if ($is_dir)\r
975                         {\r
976                                 $this->cacertdir = $cacert;\r
977                         }\r
978                         else\r
979                         {\r
980                                 $this->cacert = $cacert;\r
981                         }\r
982                 }\r
983 \r
984                 /**\r
985                 * Set attributes for SSL communication: private SSL key\r
986                 * NB: does not work in older php/curl installs\r
987                 * Thanks to Daniel Convissor\r
988                 * @param string $key The name of a file containing a private SSL key\r
989                 * @param string $keypass The secret password needed to use the private SSL key\r
990                 * @access public\r
991                 */\r
992                 function setKey($key, $keypass)\r
993                 {\r
994                         $this->key = $key;\r
995                         $this->keypass = $keypass;\r
996                 }\r
997 \r
998                 /**\r
999                 * Set attributes for SSL communication: verify server certificate\r
1000                 * @param bool $i enable/disable verification of peer certificate\r
1001                 * @access public\r
1002                 */\r
1003                 function setSSLVerifyPeer($i)\r
1004                 {\r
1005                         $this->verifypeer = $i;\r
1006                 }\r
1007 \r
1008                 /**\r
1009                 * Set attributes for SSL communication: verify match of server cert w. hostname\r
1010                 * @param int $i\r
1011                 * @access public\r
1012                 */\r
1013                 function setSSLVerifyHost($i)\r
1014                 {\r
1015                         $this->verifyhost = $i;\r
1016                 }\r
1017 \r
1018                 /**\r
1019                 * Set proxy info\r
1020                 * @param string $proxyhost\r
1021                 * @param string $proxyport Defaults to 8080 for HTTP and 443 for HTTPS\r
1022                 * @param string $proxyusername Leave blank if proxy has public access\r
1023                 * @param string $proxypassword Leave blank if proxy has public access\r
1024                 * @param int $proxyauthtype set to constant CURLAUTH_NTLM to use NTLM auth with proxy\r
1025                 * @access public\r
1026                 */\r
1027                 function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '', $proxyauthtype = 1)\r
1028                 {\r
1029                         $this->proxy = $proxyhost;\r
1030                         $this->proxyport = $proxyport;\r
1031                         $this->proxy_user = $proxyusername;\r
1032                         $this->proxy_pass = $proxypassword;\r
1033                         $this->proxy_authtype = $proxyauthtype;\r
1034                 }\r
1035 \r
1036                 /**\r
1037                 * Enables/disables reception of compressed xmlrpc responses.\r
1038                 * Note that enabling reception of compressed responses merely adds some standard\r
1039                 * http headers to xmlrpc requests. It is up to the xmlrpc server to return\r
1040                 * compressed responses when receiving such requests.\r
1041                 * @param string $compmethod either 'gzip', 'deflate', 'any' or ''\r
1042                 * @access public\r
1043                 */\r
1044                 function setAcceptedCompression($compmethod)\r
1045                 {\r
1046                         if ($compmethod == 'any')\r
1047                                 $this->accepted_compression = array('gzip', 'deflate');\r
1048                         else\r
1049                                 $this->accepted_compression = array($compmethod);\r
1050                 }\r
1051 \r
1052                 /**\r
1053                 * Enables/disables http compression of xmlrpc request.\r
1054                 * Take care when sending compressed requests: servers might not support them\r
1055                 * (and automatic fallback to uncompressed requests is not yet implemented)\r
1056                 * @param string $compmethod either 'gzip', 'deflate' or ''\r
1057                 * @access public\r
1058                 */\r
1059                 function setRequestCompression($compmethod)\r
1060                 {\r
1061                         $this->request_compression = $compmethod;\r
1062                 }\r
1063 \r
1064                 /**\r
1065                 * Adds a cookie to list of cookies that will be sent to server.\r
1066                 * NB: setting any param but name and value will turn the cookie into a 'version 1' cookie:\r
1067                 * do not do it unless you know what you are doing\r
1068                 * @param string $name\r
1069                 * @param string $value\r
1070                 * @param string $path\r
1071                 * @param string $domain\r
1072                 * @param int $port\r
1073                 * @access public\r
1074                 *\r
1075                 * @todo check correctness of urlencoding cookie value (copied from php way of doing it...)\r
1076                 */\r
1077                 function setCookie($name, $value='', $path='', $domain='', $port=null)\r
1078                 {\r
1079                         $this->cookies[$name]['value'] = urlencode($value);\r
1080                         if ($path || $domain || $port)\r
1081                         {\r
1082                                 $this->cookies[$name]['path'] = $path;\r
1083                                 $this->cookies[$name]['domain'] = $domain;\r
1084                                 $this->cookies[$name]['port'] = $port;\r
1085                                 $this->cookies[$name]['version'] = 1;\r
1086                         }\r
1087                         else\r
1088                         {\r
1089                                 $this->cookies[$name]['version'] = 0;\r
1090                         }\r
1091                 }\r
1092 \r
1093                 /**\r
1094                 * Send an xmlrpc request\r
1095                 * @param mixed $msg The message object, or an array of messages for using multicall, or the complete xml representation of a request\r
1096                 * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply\r
1097                 * @param string $method if left unspecified, the http protocol chosen during creation of the object will be used\r
1098                 * @return xmlrpcresp\r
1099                 * @access public\r
1100                 */\r
1101                 function& send($msg, $timeout=0, $method='')\r
1102                 {\r
1103                         // if user deos not specify http protocol, use native method of this client\r
1104                         // (i.e. method set during call to constructor)\r
1105                         if($method == '')\r
1106                         {\r
1107                                 $method = $this->method;\r
1108                         }\r
1109 \r
1110                         if(is_array($msg))\r
1111                         {\r
1112                                 // $msg is an array of xmlrpcmsg's\r
1113                                 $r = $this->multicall($msg, $timeout, $method);\r
1114                                 return $r;\r
1115                         }\r
1116                         elseif(is_string($msg))\r
1117                         {\r
1118                                 $n = new xmlrpcmsg('');\r
1119                                 $n->payload = $msg;\r
1120                                 $msg = $n;\r
1121                         }\r
1122 \r
1123                         // where msg is an xmlrpcmsg\r
1124                         $msg->debug=$this->debug;\r
1125 \r
1126                         if($method == 'https')\r
1127                         {\r
1128                                 $r =& $this->sendPayloadHTTPS(\r
1129                                         $msg,\r
1130                                         $this->server,\r
1131                                         $this->port,\r
1132                                         $timeout,\r
1133                                         $this->username,\r
1134                                         $this->password,\r
1135                                         $this->authtype,\r
1136                                         $this->cert,\r
1137                                         $this->certpass,\r
1138                                         $this->cacert,\r
1139                                         $this->cacertdir,\r
1140                                         $this->proxy,\r
1141                                         $this->proxyport,\r
1142                                         $this->proxy_user,\r
1143                                         $this->proxy_pass,\r
1144                                         $this->proxy_authtype,\r
1145                                         $this->keepalive,\r
1146                                         $this->key,\r
1147                                         $this->keypass\r
1148                                 );\r
1149                         }\r
1150                         elseif($method == 'http11')\r
1151                         {\r
1152                                 $r =& $this->sendPayloadCURL(\r
1153                                         $msg,\r
1154                                         $this->server,\r
1155                                         $this->port,\r
1156                                         $timeout,\r
1157                                         $this->username,\r
1158                                         $this->password,\r
1159                                         $this->authtype,\r
1160                                         null,\r
1161                                         null,\r
1162                                         null,\r
1163                                         null,\r
1164                                         $this->proxy,\r
1165                                         $this->proxyport,\r
1166                                         $this->proxy_user,\r
1167                                         $this->proxy_pass,\r
1168                                         $this->proxy_authtype,\r
1169                                         'http',\r
1170                                         $this->keepalive\r
1171                                 );\r
1172                         }\r
1173                         else\r
1174                         {\r
1175                                 $r =& $this->sendPayloadHTTP10(\r
1176                                         $msg,\r
1177                                         $this->server,\r
1178                                         $this->port,\r
1179                                         $timeout,\r
1180                                         $this->username,\r
1181                                         $this->password,\r
1182                                         $this->authtype,\r
1183                                         $this->proxy,\r
1184                                         $this->proxyport,\r
1185                                         $this->proxy_user,\r
1186                                         $this->proxy_pass,\r
1187                                         $this->proxy_authtype\r
1188                                 );\r
1189                         }\r
1190 \r
1191                         return $r;\r
1192                 }\r
1193 \r
1194                 /**\r
1195                 * @access private\r
1196                 */\r
1197                 function &sendPayloadHTTP10($msg, $server, $port, $timeout=0,\r
1198                         $username='', $password='', $authtype=1, $proxyhost='',\r
1199                         $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1)\r
1200                 {\r
1201                         if($port==0)\r
1202                         {\r
1203                                 $port=80;\r
1204                         }\r
1205 \r
1206                         // Only create the payload if it was not created previously\r
1207                         if(empty($msg->payload))\r
1208                         {\r
1209                                 $msg->createPayload($this->request_charset_encoding);\r
1210                         }\r
1211 \r
1212                         $payload = $msg->payload;\r
1213                         // Deflate request body and set appropriate request headers\r
1214                         if(function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate'))\r
1215                         {\r
1216                                 if($this->request_compression == 'gzip')\r
1217                                 {\r
1218                                         $a = @gzencode($payload);\r
1219                                         if($a)\r
1220                                         {\r
1221                                                 $payload = $a;\r
1222                                                 $encoding_hdr = "Content-Encoding: gzip\r\n";\r
1223                                         }\r
1224                                 }\r
1225                                 else\r
1226                                 {\r
1227                                         $a = @gzcompress($payload);\r
1228                                         if($a)\r
1229                                         {\r
1230                                                 $payload = $a;\r
1231                                                 $encoding_hdr = "Content-Encoding: deflate\r\n";\r
1232                                         }\r
1233                                 }\r
1234                         }\r
1235                         else\r
1236                         {\r
1237                                 $encoding_hdr = '';\r
1238                         }\r
1239 \r
1240                         // thanks to Grant Rauscher <grant7@firstworld.net> for this\r
1241                         $credentials='';\r
1242                         if($username!='')\r
1243                         {\r
1244                                 $credentials='Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n";\r
1245                                 if ($authtype != 1)\r
1246                                 {\r
1247                                         error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth is supported with HTTP 1.0');\r
1248                                 }\r
1249                         }\r
1250 \r
1251                         $accepted_encoding = '';\r
1252                         if(is_array($this->accepted_compression) && count($this->accepted_compression))\r
1253                         {\r
1254                                 $accepted_encoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n";\r
1255                         }\r
1256 \r
1257                         $proxy_credentials = '';\r
1258                         if($proxyhost)\r
1259                         {\r
1260                                 if($proxyport == 0)\r
1261                                 {\r
1262                                         $proxyport = 8080;\r
1263                                 }\r
1264                                 $connectserver = $proxyhost;\r
1265                                 $connectport = $proxyport;\r
1266                                 $uri = 'http://'.$server.':'.$port.$this->path;\r
1267                                 if($proxyusername != '')\r
1268                                 {\r
1269                                         if ($proxyauthtype != 1)\r
1270                                         {\r
1271                                                 error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth to proxy is supported with HTTP 1.0');\r
1272                                         }\r
1273                                         $proxy_credentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyusername.':'.$proxypassword) . "\r\n";\r
1274                                 }\r
1275                         }\r
1276                         else\r
1277                         {\r
1278                                 $connectserver = $server;\r
1279                                 $connectport = $port;\r
1280                                 $uri = $this->path;\r
1281                         }\r
1282 \r
1283                         // Cookie generation, as per rfc2965 (version 1 cookies) or\r
1284                         // netscape's rules (version 0 cookies)\r
1285                         $cookieheader='';\r
1286                         if (count($this->cookies))\r
1287                         {\r
1288                                 $version = '';\r
1289                                 foreach ($this->cookies as $name => $cookie)\r
1290                                 {\r
1291                                         if ($cookie['version'])\r
1292                                         {\r
1293                                                 $version = ' $Version="' . $cookie['version'] . '";';\r
1294                                                 $cookieheader .= ' ' . $name . '="' . $cookie['value'] . '";';\r
1295                                                 if ($cookie['path'])\r
1296                                                         $cookieheader .= ' $Path="' . $cookie['path'] . '";';\r
1297                                                 if ($cookie['domain'])\r
1298                                                         $cookieheader .= ' $Domain="' . $cookie['domain'] . '";';\r
1299                                                 if ($cookie['port'])\r
1300                                                         $cookieheader .= ' $Port="' . $cookie['port'] . '";';\r
1301                                         }\r
1302                                         else\r
1303                                         {\r
1304                                                 $cookieheader .= ' ' . $name . '=' . $cookie['value'] . ";";\r
1305                                         }\r
1306                                 }\r
1307                                 $cookieheader = 'Cookie:' . $version . substr($cookieheader, 0, -1) . "\r\n";\r
1308                         }\r
1309 \r
1310                         $op= 'POST ' . $uri. " HTTP/1.0\r\n" .\r
1311                                 'User-Agent: ' . $GLOBALS['xmlrpcName'] . ' ' . $GLOBALS['xmlrpcVersion'] . "\r\n" .\r
1312                                 'Host: '. $server . ':' . $port . "\r\n" .\r
1313                                 $credentials .\r
1314                                 $proxy_credentials .\r
1315                                 $accepted_encoding .\r
1316                                 $encoding_hdr .\r
1317                                 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings) . "\r\n" .\r
1318                                 $cookieheader .\r
1319                                 'Content-Type: ' . $msg->content_type . "\r\nContent-Length: " .\r
1320                                 strlen($payload) . "\r\n\r\n" .\r
1321                                 $payload;\r
1322 \r
1323                         if($this->debug > 1)\r
1324                         {\r
1325                                 print "<PRE>\n---SENDING---\n" . htmlentities($op) . "\n---END---\n</PRE>";\r
1326                                 // let the client see this now in case http times out...\r
1327                                 flush();\r
1328                         }\r
1329 \r
1330                         if($timeout>0)\r
1331                         {\r
1332                                 $fp=@fsockopen($connectserver, $connectport, $this->errno, $this->errstr, $timeout);\r
1333                         }\r
1334                         else\r
1335                         {\r
1336                                 $fp=@fsockopen($connectserver, $connectport, $this->errno, $this->errstr);\r
1337                         }\r
1338                         if($fp)\r
1339                         {\r
1340                                 if($timeout>0 && function_exists('stream_set_timeout'))\r
1341                                 {\r
1342                                         stream_set_timeout($fp, $timeout);\r
1343                                 }\r
1344                         }\r
1345                         else\r
1346                         {\r
1347                                 $this->errstr='Connect error: '.$this->errstr;\r
1348                                 $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $this->errstr . ' (' . $this->errno . ')');\r
1349                                 return $r;\r
1350                         }\r
1351 \r
1352                         if(!fputs($fp, $op, strlen($op)))\r
1353                         {\r
1354                         fclose($fp);\r
1355                                 $this->errstr='Write error';\r
1356                                 $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $this->errstr);\r
1357                                 return $r;\r
1358                         }\r
1359                         else\r
1360                         {\r
1361                                 // reset errno and errstr on succesful socket connection\r
1362                                 $this->errstr = '';\r
1363                         }\r
1364                         // G. Giunta 2005/10/24: close socket before parsing.\r
1365                         // should yeld slightly better execution times, and make easier recursive calls (e.g. to follow http redirects)\r
1366                         $ipd='';\r
1367                         do\r
1368                         {\r
1369                                 // shall we check for $data === FALSE?\r
1370                                 // as per the manual, it signals an error\r
1371                                 $ipd.=fread($fp, 32768);\r
1372                         } while(!feof($fp));\r
1373                         fclose($fp);\r
1374                         $r =& $msg->parseResponse($ipd, false, $this->return_type);\r
1375                         return $r;\r
1376 \r
1377                 }\r
1378 \r
1379                 /**\r
1380                 * @access private\r
1381                 */\r
1382                 function &sendPayloadHTTPS($msg, $server, $port, $timeout=0, $username='',\r
1383                         $password='', $authtype=1, $cert='',$certpass='', $cacert='', $cacertdir='',\r
1384                         $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1,\r
1385                         $keepalive=false, $key='', $keypass='')\r
1386                 {\r
1387                         $r =& $this->sendPayloadCURL($msg, $server, $port, $timeout, $username,\r
1388                                 $password, $authtype, $cert, $certpass, $cacert, $cacertdir, $proxyhost, $proxyport,\r
1389                                 $proxyusername, $proxypassword, $proxyauthtype, 'https', $keepalive, $key, $keypass);\r
1390                         return $r;\r
1391                 }\r
1392 \r
1393                 /**\r
1394                 * Contributed by Justin Miller <justin@voxel.net>\r
1395                 * Requires curl to be built into PHP\r
1396                 * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers!\r
1397                 * @access private\r
1398                 */\r
1399                 function &sendPayloadCURL($msg, $server, $port, $timeout=0, $username='',\r
1400                         $password='', $authtype=1, $cert='', $certpass='', $cacert='', $cacertdir='',\r
1401                         $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1, $method='https',\r
1402                         $keepalive=false, $key='', $keypass='')\r
1403                 {\r
1404                         if(!function_exists('curl_init'))\r
1405                         {\r
1406                                 $this->errstr='CURL unavailable on this install';\r
1407                                 $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['no_curl'], $GLOBALS['xmlrpcstr']['no_curl']);\r
1408                                 return $r;\r
1409                         }\r
1410                         if($method == 'https')\r
1411                         {\r
1412                                 if(($info = curl_version()) &&\r
1413                                         ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version']))))\r
1414                                 {\r
1415                                         $this->errstr='SSL unavailable on this install';\r
1416                                         $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['no_ssl'], $GLOBALS['xmlrpcstr']['no_ssl']);\r
1417                                         return $r;\r
1418                                 }\r
1419                         }\r
1420 \r
1421                         if($port == 0)\r
1422                         {\r
1423                                 if($method == 'http')\r
1424                                 {\r
1425                                         $port = 80;\r
1426                                 }\r
1427                                 else\r
1428                                 {\r
1429                                         $port = 443;\r
1430                                 }\r
1431                         }\r
1432 \r
1433                         // Only create the payload if it was not created previously\r
1434                         if(empty($msg->payload))\r
1435                         {\r
1436                                 $msg->createPayload($this->request_charset_encoding);\r
1437                         }\r
1438 \r
1439                         // Deflate request body and set appropriate request headers\r
1440                         $payload = $msg->payload;\r
1441                         if(function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate'))\r
1442                         {\r
1443                                 if($this->request_compression == 'gzip')\r
1444                                 {\r
1445                                         $a = @gzencode($payload);\r
1446                                         if($a)\r
1447                                         {\r
1448                                                 $payload = $a;\r
1449                                                 $encoding_hdr = 'Content-Encoding: gzip';\r
1450                                         }\r
1451                                 }\r
1452                                 else\r
1453                                 {\r
1454                                         $a = @gzcompress($payload);\r
1455                                         if($a)\r
1456                                         {\r
1457                                                 $payload = $a;\r
1458                                                 $encoding_hdr = 'Content-Encoding: deflate';\r
1459                                         }\r
1460                                 }\r
1461                         }\r
1462                         else\r
1463                         {\r
1464                                 $encoding_hdr = '';\r
1465                         }\r
1466 \r
1467                         if($this->debug > 1)\r
1468                         {\r
1469                                 print "<PRE>\n---SENDING---\n" . htmlentities($payload) . "\n---END---\n</PRE>";\r
1470                                 // let the client see this now in case http times out...\r
1471                                 flush();\r
1472                         }\r
1473 \r
1474                         if(!$keepalive || !$this->xmlrpc_curl_handle)\r
1475                         {\r
1476                                 $curl = curl_init($method . '://' . $server . ':' . $port . $this->path);\r
1477                                 if($keepalive)\r
1478                                 {\r
1479                                         $this->xmlrpc_curl_handle = $curl;\r
1480                                 }\r
1481                         }\r
1482                         else\r
1483                         {\r
1484                                 $curl = $this->xmlrpc_curl_handle;\r
1485                         }\r
1486 \r
1487                         // results into variable\r
1488                         curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);\r
1489 \r
1490                         if($this->debug)\r
1491                         {\r
1492                                 curl_setopt($curl, CURLOPT_VERBOSE, 1);\r
1493                         }\r
1494                         curl_setopt($curl, CURLOPT_USERAGENT, $GLOBALS['xmlrpcName'].' '.$GLOBALS['xmlrpcVersion']);\r
1495                         // required for XMLRPC: post the data\r
1496                         curl_setopt($curl, CURLOPT_POST, 1);\r
1497                         // the data\r
1498                         curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);\r
1499 \r
1500                         // return the header too\r
1501                         curl_setopt($curl, CURLOPT_HEADER, 1);\r
1502 \r
1503                         // will only work with PHP >= 5.0\r
1504                         // NB: if we set an empty string, CURL will add http header indicating\r
1505                         // ALL methods it is supporting. This is possibly a better option than\r
1506                         // letting the user tell what curl can / cannot do...\r
1507                         if(is_array($this->accepted_compression) && count($this->accepted_compression))\r
1508                         {\r
1509                                 //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression));\r
1510                                 // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?)\r
1511                                 if (count($this->accepted_compression) == 1)\r
1512                                 {\r
1513                                         curl_setopt($curl, CURLOPT_ENCODING, $this->accepted_compression[0]);\r
1514                                 }\r
1515                                 else\r
1516                                         curl_setopt($curl, CURLOPT_ENCODING, '');\r
1517                         }\r
1518                         // extra headers\r
1519                         $headers = array('Content-Type: ' . $msg->content_type , 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings));\r
1520                         // if no keepalive is wanted, let the server know it in advance\r
1521                         if(!$keepalive)\r
1522                         {\r
1523                                 $headers[] = 'Connection: close';\r
1524                         }\r
1525                         // request compression header\r
1526                         if($encoding_hdr)\r
1527                         {\r
1528                                 $headers[] = $encoding_hdr;\r
1529                         }\r
1530 \r
1531                         curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);\r
1532                         // timeout is borked\r
1533                         if($timeout)\r
1534                         {\r
1535                                 curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : $timeout - 1);\r
1536                         }\r
1537 \r
1538                         if($username && $password)\r
1539                         {\r
1540                                 curl_setopt($curl, CURLOPT_USERPWD, $username.':'.$password);\r
1541                                 if (defined('CURLOPT_HTTPAUTH'))\r
1542                                 {\r
1543                                         curl_setopt($curl, CURLOPT_HTTPAUTH, $authtype);\r
1544                                 }\r
1545                                 else if ($authtype != 1)\r
1546                                 {\r
1547                                         error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth is supported by the current PHP/curl install');\r
1548                                 }\r
1549                         }\r
1550 \r
1551                         if($method == 'https')\r
1552                         {\r
1553                                 // set cert file\r
1554                                 if($cert)\r
1555                                 {\r
1556                                         curl_setopt($curl, CURLOPT_SSLCERT, $cert);\r
1557                                 }\r
1558                                 // set cert password\r
1559                                 if($certpass)\r
1560                                 {\r
1561                                         curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certpass);\r
1562                                 }\r
1563                                 // whether to verify remote host's cert\r
1564                                 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer);\r
1565                                 // set ca certificates file/dir\r
1566                                 if($cacert)\r
1567                                 {\r
1568                                         curl_setopt($curl, CURLOPT_CAINFO, $cacert);\r
1569                                 }\r
1570                                 if($cacertdir)\r
1571                                 {\r
1572                                         curl_setopt($curl, CURLOPT_CAPATH, $cacertdir);\r
1573                                 }\r
1574                                 // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?)\r
1575                                 if($key)\r
1576                                 {\r
1577                                         curl_setopt($curl, CURLOPT_SSLKEY, $key);\r
1578                                 }\r
1579                                 // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?)\r
1580                                 if($keypass)\r
1581                                 {\r
1582                                         curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keypass);\r
1583                                 }\r
1584                                 // whether to verify cert's common name (CN); 0 for no, 1 to verify that it exists, and 2 to verify that it matches the hostname used\r
1585                                 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost);\r
1586                         }\r
1587 \r
1588                         // proxy info\r
1589                         if($proxyhost)\r
1590                         {\r
1591                                 if($proxyport == 0)\r
1592                                 {\r
1593                                         $proxyport = 8080; // NB: even for HTTPS, local connection is on port 8080\r
1594                                 }\r
1595                                 curl_setopt($curl, CURLOPT_PROXY, $proxyhost.':'.$proxyport);\r
1596                                 //curl_setopt($curl, CURLOPT_PROXYPORT,$proxyport);\r
1597                                 if($proxyusername)\r
1598                                 {\r
1599                                         curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyusername.':'.$proxypassword);\r
1600                                         if (defined('CURLOPT_PROXYAUTH'))\r
1601                                         {\r
1602                                                 curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyauthtype);\r
1603                                         }\r
1604                                         else if ($proxyauthtype != 1)\r
1605                                         {\r
1606                                                 error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth to proxy is supported by the current PHP/curl install');\r
1607                                         }\r
1608                                 }\r
1609                         }\r
1610 \r
1611                         // NB: should we build cookie http headers by hand rather than let CURL do it?\r
1612                         // the following code does not honour 'expires', 'path' and 'domain' cookie attributes\r
1613                         // set to client obj the the user...\r
1614                         if (count($this->cookies))\r
1615                         {\r
1616                                 $cookieheader = '';\r
1617                                 foreach ($this->cookies as $name => $cookie)\r
1618                                 {\r
1619                                         $cookieheader .= $name . '=' . $cookie['value'] . '; ';\r
1620                                 }\r
1621                                 curl_setopt($curl, CURLOPT_COOKIE, substr($cookieheader, 0, -2));\r
1622                         }\r
1623 \r
1624                         $result = curl_exec($curl);\r
1625 \r
1626                         if ($this->debug > 1)\r
1627                         {\r
1628                                 print "<PRE>\n---CURL INFO---\n";\r
1629                                 foreach(curl_getinfo($curl) as $name => $val)\r
1630                                          print $name . ': ' . htmlentities($val). "\n";\r
1631                                 print "---END---\n</PRE>";\r
1632                         }\r
1633 \r
1634                         if(!$result) /// @todo we should use a better check here - what if we get back '' or '0'?\r
1635                         {\r
1636                                 $this->errstr='no response';\r
1637                                 $resp=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['curl_fail'], $GLOBALS['xmlrpcstr']['curl_fail']. ': '. curl_error($curl));\r
1638                                 curl_close($curl);\r
1639                                 if($keepalive)\r
1640                                 {\r
1641                                         $this->xmlrpc_curl_handle = null;\r
1642                                 }\r
1643                         }\r
1644                         else\r
1645                         {\r
1646                                 if(!$keepalive)\r
1647                                 {\r
1648                                         curl_close($curl);\r
1649                                 }\r
1650                                 $resp =& $msg->parseResponse($result, true, $this->return_type);\r
1651                         }\r
1652                         return $resp;\r
1653                 }\r
1654 \r
1655                 /**\r
1656                 * Send an array of request messages and return an array of responses.\r
1657                 * Unless $this->no_multicall has been set to true, it will try first\r
1658                 * to use one single xmlrpc call to server method system.multicall, and\r
1659                 * revert to sending many successive calls in case of failure.\r
1660                 * This failure is also stored in $this->no_multicall for subsequent calls.\r
1661                 * Unfortunately, there is no server error code universally used to denote\r
1662                 * the fact that multicall is unsupported, so there is no way to reliably\r
1663                 * distinguish between that and a temporary failure.\r
1664                 * If you are sure that server supports multicall and do not want to\r
1665                 * fallback to using many single calls, set the fourth parameter to FALSE.\r
1666                 *\r
1667                 * NB: trying to shoehorn extra functionality into existing syntax has resulted\r
1668                 * in pretty much convoluted code...\r
1669                 *\r
1670                 * @param array $msgs an array of xmlrpcmsg objects\r
1671                 * @param integer $timeout connection timeout (in seconds)\r
1672                 * @param string $method the http protocol variant to be used\r
1673                 * @param boolean fallback When true, upon receiveing an error during multicall, multiple single calls will be attempted\r
1674                 * @return array\r
1675                 * @access public\r
1676                 */\r
1677                 function multicall($msgs, $timeout=0, $method='', $fallback=true)\r
1678                 {\r
1679                         if ($method == '')\r
1680                         {\r
1681                                 $method = $this->method;\r
1682                         }\r
1683                         if(!$this->no_multicall)\r
1684                         {\r
1685                                 $results = $this->_try_multicall($msgs, $timeout, $method);\r
1686                                 if(is_array($results))\r
1687                                 {\r
1688                                         // System.multicall succeeded\r
1689                                         return $results;\r
1690                                 }\r
1691                                 else\r
1692                                 {\r
1693                                         // either system.multicall is unsupported by server,\r
1694                                         // or call failed for some other reason.\r
1695                                         if ($fallback)\r
1696                                         {\r
1697                                                 // Don't try it next time...\r
1698                                                 $this->no_multicall = true;\r
1699                                         }\r
1700                                         else\r
1701                                         {\r
1702                                                 if (is_a($results, 'xmlrpcresp'))\r
1703                                                 {\r
1704                                                         $result = $results;\r
1705                                                 }\r
1706                                                 else\r
1707                                                 {\r
1708                                                         $result = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['multicall_error'], $GLOBALS['xmlrpcstr']['multicall_error']);\r
1709                                                 }\r
1710                                         }\r
1711                                 }\r
1712                         }\r
1713                         else\r
1714                         {\r
1715                                 // override fallback, in case careless user tries to do two\r
1716                                 // opposite things at the same time\r
1717                                 $fallback = true;\r
1718                         }\r
1719 \r
1720                         $results = array();\r
1721                         if ($fallback)\r
1722                         {\r
1723                                 // system.multicall is (probably) unsupported by server:\r
1724                                 // emulate multicall via multiple requests\r
1725                                 foreach($msgs as $msg)\r
1726                                 {\r
1727                                         $results[] =& $this->send($msg, $timeout, $method);\r
1728                                 }\r
1729                         }\r
1730                         else\r
1731                         {\r
1732                                 // user does NOT want to fallback on many single calls:\r
1733                                 // since we should always return an array of responses,\r
1734                                 // return an array with the same error repeated n times\r
1735                                 foreach($msgs as $msg)\r
1736                                 {\r
1737                                         $results[] = $result;\r
1738                                 }\r
1739                         }\r
1740                         return $results;\r
1741                 }\r
1742 \r
1743                 /**\r
1744                 * Attempt to boxcar $msgs via system.multicall.\r
1745                 * Returns either an array of xmlrpcreponses, an xmlrpc error response\r
1746                 * or false (when received response does not respect valid multicall syntax)\r
1747                 * @access private\r
1748                 */\r
1749                 function _try_multicall($msgs, $timeout, $method)\r
1750                 {\r
1751                         // Construct multicall message\r
1752                         $calls = array();\r
1753                         foreach($msgs as $msg)\r
1754                         {\r
1755                                 $call['methodName'] = new xmlrpcval($msg->method(),'string');\r
1756                                 $numParams = $msg->getNumParams();\r
1757                                 $params = array();\r
1758                                 for($i = 0; $i < $numParams; $i++)\r
1759                                 {\r
1760                                         $params[$i] = $msg->getParam($i);\r
1761                                 }\r
1762                                 $call['params'] = new xmlrpcval($params, 'array');\r
1763                                 $calls[] = new xmlrpcval($call, 'struct');\r
1764                         }\r
1765                         $multicall = new xmlrpcmsg('system.multicall');\r
1766                         $multicall->addParam(new xmlrpcval($calls, 'array'));\r
1767 \r
1768                         // Attempt RPC call\r
1769                         $result =& $this->send($multicall, $timeout, $method);\r
1770 \r
1771                         if($result->faultCode() != 0)\r
1772                         {\r
1773                                 // call to system.multicall failed\r
1774                                 return $result;\r
1775                         }\r
1776 \r
1777                         // Unpack responses.\r
1778                         $rets = $result->value();\r
1779 \r
1780                         if ($this->return_type == 'xml')\r
1781                         {\r
1782                                         return $rets;\r
1783                         }\r
1784                         else if ($this->return_type == 'phpvals')\r
1785                         {\r
1786                                 ///@todo test this code branch...\r
1787                                 $rets = $result->value();\r
1788                                 if(!is_array($rets))\r
1789                                 {\r
1790                                         return false;           // bad return type from system.multicall\r
1791                                 }\r
1792                                 $numRets = count($rets);\r
1793                                 if($numRets != count($msgs))\r
1794                                 {\r
1795                                         return false;           // wrong number of return values.\r
1796                                 }\r
1797 \r
1798                                 $response = array();\r
1799                                 for($i = 0; $i < $numRets; $i++)\r
1800                                 {\r
1801                                         $val = $rets[$i];\r
1802                                         if (!is_array($val)) {\r
1803                                                 return false;\r
1804                                         }\r
1805                                         switch(count($val))\r
1806                                         {\r
1807                                                 case 1:\r
1808                                                         if(!isset($val[0]))\r
1809                                                         {\r
1810                                                                 return false;           // Bad value\r
1811                                                         }\r
1812                                                         // Normal return value\r
1813                                                         $response[$i] = new xmlrpcresp($val[0], 0, '', 'phpvals');\r
1814                                                         break;\r
1815                                                 case 2:\r
1816                                                         ///     @todo remove usage of @: it is apparently quite slow\r
1817                                                         $code = @$val['faultCode'];\r
1818                                                         if(!is_int($code))\r
1819                                                         {\r
1820                                                                 return false;\r
1821                                                         }\r
1822                                                         $str = @$val['faultString'];\r
1823                                                         if(!is_string($str))\r
1824                                                         {\r
1825                                                                 return false;\r
1826                                                         }\r
1827                                                         $response[$i] = new xmlrpcresp(0, $code, $str);\r
1828                                                         break;\r
1829                                                 default:\r
1830                                                         return false;\r
1831                                         }\r
1832                                 }\r
1833                                 return $response;\r
1834                         }\r
1835                         else // return type == 'xmlrpcvals'\r
1836                         {\r
1837                                 $rets = $result->value();\r
1838                                 if($rets->kindOf() != 'array')\r
1839                                 {\r
1840                                         return false;           // bad return type from system.multicall\r
1841                                 }\r
1842                                 $numRets = $rets->arraysize();\r
1843                                 if($numRets != count($msgs))\r
1844                                 {\r
1845                                         return false;           // wrong number of return values.\r
1846                                 }\r
1847 \r
1848                                 $response = array();\r
1849                                 for($i = 0; $i < $numRets; $i++)\r
1850                                 {\r
1851                                         $val = $rets->arraymem($i);\r
1852                                         switch($val->kindOf())\r
1853                                         {\r
1854                                                 case 'array':\r
1855                                                         if($val->arraysize() != 1)\r
1856                                                         {\r
1857                                                                 return false;           // Bad value\r
1858                                                         }\r
1859                                                         // Normal return value\r
1860                                                         $response[$i] = new xmlrpcresp($val->arraymem(0));\r
1861                                                         break;\r
1862                                                 case 'struct':\r
1863                                                         $code = $val->structmem('faultCode');\r
1864                                                         if($code->kindOf() != 'scalar' || $code->scalartyp() != 'int')\r
1865                                                         {\r
1866                                                                 return false;\r
1867                                                         }\r
1868                                                         $str = $val->structmem('faultString');\r
1869                                                         if($str->kindOf() != 'scalar' || $str->scalartyp() != 'string')\r
1870                                                         {\r
1871                                                                 return false;\r
1872                                                         }\r
1873                                                         $response[$i] = new xmlrpcresp(0, $code->scalarval(), $str->scalarval());\r
1874                                                         break;\r
1875                                                 default:\r
1876                                                         return false;\r
1877                                         }\r
1878                                 }\r
1879                                 return $response;\r
1880                         }\r
1881                 }\r
1882         } // end class xmlrpc_client\r
1883 \r
1884         class xmlrpcresp\r
1885         {\r
1886                 var $val = 0;\r
1887                 var $valtyp;\r
1888                 var $errno = 0;\r
1889                 var $errstr = '';\r
1890                 var $payload;\r
1891                 var $hdrs = array();\r
1892                 var $_cookies = array();\r
1893                 var $content_type = 'text/xml';\r
1894                 var $raw_data = '';\r
1895 \r
1896                 /**\r
1897                 * @param mixed $val either an xmlrpcval obj, a php value or the xml serialization of an xmlrpcval (a string)\r
1898                 * @param integer $fcode set it to anything but 0 to create an error response\r
1899                 * @param string $fstr the error string, in case of an error response\r
1900                 * @param string $valtyp either 'xmlrpcvals', 'phpvals' or 'xml'\r
1901                 *\r
1902                 * @todo add check that $val / $fcode / $fstr is of correct type???\r
1903                 * NB: as of now we do not do it, since it might be either an xmlrpcval or a plain\r
1904                 * php val, or a complete xml chunk, depending on usage of xmlrpc_client::send() inside which creator is called...\r
1905                 */\r
1906                 function xmlrpcresp($val, $fcode = 0, $fstr = '', $valtyp='')\r
1907                 {\r
1908                         if($fcode != 0)\r
1909                         {\r
1910                                 // error response\r
1911                                 $this->errno = $fcode;\r
1912                                 $this->errstr = $fstr;\r
1913                                 //$this->errstr = htmlspecialchars($fstr); // XXX: encoding probably shouldn't be done here; fix later.\r
1914                         }\r
1915                         else\r
1916                         {\r
1917                                 // successful response\r
1918                                 $this->val = $val;\r
1919                                 if ($valtyp == '')\r
1920                                 {\r
1921                                         // user did not declare type of response value: try to guess it\r
1922                                         if (is_object($this->val) && is_a($this->val, 'xmlrpcval'))\r
1923                                         {\r
1924                                                 $this->valtyp = 'xmlrpcvals';\r
1925                                         }\r
1926                                         else if (is_string($this->val))\r
1927                                         {\r
1928                                                 $this->valtyp = 'xml';\r
1929 \r
1930                                         }\r
1931                                         else\r
1932                                         {\r
1933                                                 $this->valtyp = 'phpvals';\r
1934                                         }\r
1935                                 }\r
1936                                 else\r
1937                                 {\r
1938                                         // user declares type of resp value: believe him\r
1939                                         $this->valtyp = $valtyp;\r
1940                                 }\r
1941                         }\r
1942                 }\r
1943 \r
1944                 /**\r
1945                 * Returns the error code of the response.\r
1946                 * @return integer the error code of this response (0 for not-error responses)\r
1947                 * @access public\r
1948                 */\r
1949                 function faultCode()\r
1950                 {\r
1951                         return $this->errno;\r
1952                 }\r
1953 \r
1954                 /**\r
1955                 * Returns the error code of the response.\r
1956                 * @return string the error string of this response ('' for not-error responses)\r
1957                 * @access public\r
1958                 */\r
1959                 function faultString()\r
1960                 {\r
1961                         return $this->errstr;\r
1962                 }\r
1963 \r
1964                 /**\r
1965                 * Returns the value received by the server.\r
1966                 * @return mixed the xmlrpcval object returned by the server. Might be an xml string or php value if the response has been created by specially configured xmlrpc_client objects\r
1967                 * @access public\r
1968                 */\r
1969                 function value()\r
1970                 {\r
1971                         return $this->val;\r
1972                 }\r
1973 \r
1974                 /**\r
1975                 * Returns an array with the cookies received from the server.\r
1976                 * Array has the form: $cookiename => array ('value' => $val, $attr1 => $val1, $attr2 = $val2, ...)\r
1977                 * with attributes being e.g. 'expires', 'path', domain'.\r
1978                 * NB: cookies sent as 'expired' by the server (i.e. with an expiry date in the past)\r
1979                 * are still present in the array. It is up to the user-defined code to decide\r
1980                 * how to use the received cookies, and wheter they have to be sent back with the next\r
1981                 * request to the server (using xmlrpc_client::setCookie) or not\r
1982                 * @return array array of cookies received from the server\r
1983                 * @access public\r
1984                 */\r
1985                 function cookies()\r
1986                 {\r
1987                         return $this->_cookies;\r
1988                 }\r
1989 \r
1990                 /**\r
1991                 * Returns xml representation of the response. XML prologue not included\r
1992                 * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed\r
1993                 * @return string the xml representation of the response\r
1994                 * @access public\r
1995                 */\r
1996                 function serialize($charset_encoding='')\r
1997                 {\r
1998                         if ($charset_encoding != '')\r
1999                                 $this->content_type = 'text/xml; charset=' . $charset_encoding;\r
2000                         else\r
2001                                 $this->content_type = 'text/xml';\r
2002                         $result = "<methodResponse>\n";\r
2003                         if($this->errno)\r
2004                         {\r
2005                                 // G. Giunta 2005/2/13: let non-ASCII response messages be tolerated by clients\r
2006                                 // by xml-encoding non ascii chars\r
2007                                 $result .= "<fault>\n" .\r
2008 "<value>\n<struct><member><name>faultCode</name>\n<value><int>" . $this->errno .\r
2009 "</int></value>\n</member>\n<member>\n<name>faultString</name>\n<value><string>" .\r
2010 xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $charset_encoding) . "</string></value>\n</member>\n" .\r
2011 "</struct>\n</value>\n</fault>";\r
2012                         }\r
2013                         else\r
2014                         {\r
2015                                 if(!is_object($this->val) || !is_a($this->val, 'xmlrpcval'))\r
2016                                 {\r
2017                                         if (is_string($this->val) && $this->valtyp == 'xml')\r
2018                                         {\r
2019                                                 $result .= "<params>\n<param>\n" .\r
2020                                                         $this->val .\r
2021                                                         "</param>\n</params>";\r
2022                                         }\r
2023                                         else\r
2024                                         {\r
2025                                                 /// @todo try to build something serializable?\r
2026                                                 die('cannot serialize xmlrpcresp objects whose content is native php values');\r
2027                                         }\r
2028                                 }\r
2029                                 else\r
2030                                 {\r
2031                                         $result .= "<params>\n<param>\n" .\r
2032                                                 $this->val->serialize($charset_encoding) .\r
2033                                                 "</param>\n</params>";\r
2034                                 }\r
2035                         }\r
2036                         $result .= "\n</methodResponse>";\r
2037                         $this->payload = $result;\r
2038                         return $result;\r
2039                 }\r
2040         }\r
2041 \r
2042         class xmlrpcmsg\r
2043         {\r
2044                 var $payload;\r
2045                 var $methodname;\r
2046                 var $params=array();\r
2047                 var $debug=0;\r
2048                 var $content_type = 'text/xml';\r
2049 \r
2050                 /**\r
2051                 * @param string $meth the name of the method to invoke\r
2052                 * @param array $pars array of parameters to be paased to the method (xmlrpcval objects)\r
2053                 */\r
2054                 function xmlrpcmsg($meth, $pars=0)\r
2055                 {\r
2056                         $this->methodname=$meth;\r
2057                         if(is_array($pars) && count($pars)>0)\r
2058                         {\r
2059                                 for($i=0; $i<count($pars); $i++)\r
2060                                 {\r
2061                                         $this->addParam($pars[$i]);\r
2062                                 }\r
2063                         }\r
2064                 }\r
2065 \r
2066                 /**\r
2067                 * @access private\r
2068                 */\r
2069                 function xml_header($charset_encoding='')\r
2070                 {\r
2071                         if ($charset_encoding != '')\r
2072                         {\r
2073                                 return "<?xml version=\"1.0\" encoding=\"$charset_encoding\" ?" . ">\n<methodCall>\n";\r
2074                         }\r
2075                         else\r
2076                         {\r
2077                                 return "<?xml version=\"1.0\"?" . ">\n<methodCall>\n";\r
2078                         }\r
2079                 }\r
2080 \r
2081                 /**\r
2082                 * @access private\r
2083                 */\r
2084                 function xml_footer()\r
2085                 {\r
2086                         return '</methodCall>';\r
2087                 }\r
2088 \r
2089                 /**\r
2090                 * @access private\r
2091                 */\r
2092                 function kindOf()\r
2093                 {\r
2094                         return 'msg';\r
2095                 }\r
2096 \r
2097                 /**\r
2098                 * @access private\r
2099                 */\r
2100                 function createPayload($charset_encoding='')\r
2101                 {\r
2102                         if ($charset_encoding != '')\r
2103                                 $this->content_type = 'text/xml; charset=' . $charset_encoding;\r
2104                         else\r
2105                                 $this->content_type = 'text/xml';\r
2106                         $this->payload=$this->xml_header($charset_encoding);\r
2107                         $this->payload.='<methodName>' . $this->methodname . "</methodName>\n";\r
2108                         $this->payload.="<params>\n";\r
2109                         for($i=0; $i<count($this->params); $i++)\r
2110                         {\r
2111                                 $p=$this->params[$i];\r
2112                                 $this->payload.="<param>\n" . $p->serialize($charset_encoding) .\r
2113                                 "</param>\n";\r
2114                         }\r
2115                         $this->payload.="</params>\n";\r
2116                         $this->payload.=$this->xml_footer();\r
2117                 }\r
2118 \r
2119                 /**\r
2120                 * Gets/sets the xmlrpc method to be invoked\r
2121                 * @param string $meth the method to be set (leave empty not to set it)\r
2122                 * @return string the method that will be invoked\r
2123                 * @access public\r
2124                 */\r
2125                 function method($meth='')\r
2126                 {\r
2127                         if($meth!='')\r
2128                         {\r
2129                                 $this->methodname=$meth;\r
2130                         }\r
2131                         return $this->methodname;\r
2132                 }\r
2133 \r
2134                 /**\r
2135                 * Returns xml representation of the message. XML prologue included\r
2136                 * @return string the xml representation of the message, xml prologue included\r
2137                 * @access public\r
2138                 */\r
2139                 function serialize($charset_encoding='')\r
2140                 {\r
2141                         $this->createPayload($charset_encoding);\r
2142                         return $this->payload;\r
2143                 }\r
2144 \r
2145                 /**\r
2146                 * Add a parameter to the list of parameters to be used upon method invocation\r
2147                 * @param xmlrpcval $par\r
2148                 * @return boolean false on failure\r
2149                 * @access public\r
2150                 */\r
2151                 function addParam($par)\r
2152                 {\r
2153                         // add check: do not add to self params which are not xmlrpcvals\r
2154                         if(is_object($par) && is_a($par, 'xmlrpcval'))\r
2155                         {\r
2156                                 $this->params[]=$par;\r
2157                                 return true;\r
2158                         }\r
2159                         else\r
2160                         {\r
2161                                 return false;\r
2162                         }\r
2163                 }\r
2164 \r
2165                 /**\r
2166                 * Returns the nth parameter in the message. The index zero-based.\r
2167                 * @param integer $i the index of the parameter to fetch (zero based)\r
2168                 * @return xmlrpcval the i-th parameter\r
2169                 * @access public\r
2170                 */\r
2171                 function getParam($i) { return $this->params[$i]; }\r
2172 \r
2173                 /**\r
2174                 * Returns the number of parameters in the messge.\r
2175                 * @return integer the number of parameters currently set\r
2176                 * @access public\r
2177                 */\r
2178                 function getNumParams() { return count($this->params); }\r
2179 \r
2180                 /**\r
2181                 * Given an open file handle, read all data available and parse it as axmlrpc response.\r
2182                 * NB: the file handle is not closed by this function.\r
2183                 * NNB: might have trouble in rare cases to work on network streams, as we\r
2184         *      check for a read of 0 bytes instead of feof($fp).\r
2185                 *      But since checking for feof(null) returns false, we would risk an\r
2186                 *      infinite loop in that case, because we cannot trust the caller\r
2187                 *      to give us a valid pointer to an open file...\r
2188                 * @access public\r
2189                 * @return xmlrpcresp\r
2190                 * @todo add 2nd & 3rd param to be passed to ParseResponse() ???\r
2191                 */\r
2192                 function &parseResponseFile($fp)\r
2193                 {\r
2194                         $ipd='';\r
2195                         while($data=fread($fp, 32768))\r
2196                         {\r
2197                                 $ipd.=$data;\r
2198                         }\r
2199                         //fclose($fp);\r
2200                         $r =& $this->parseResponse($ipd);\r
2201                         return $r;\r
2202                 }\r
2203 \r
2204                 /**\r
2205                 * Parses HTTP headers and separates them from data.\r
2206                 * @access private\r
2207                 */\r
2208                 function &parseResponseHeaders(&$data, $headers_processed=false)\r
2209                 {\r
2210                                 // Support "web-proxy-tunelling" connections for https through proxies\r
2211                                 if(preg_match('/^HTTP\/1\.[0-1] 200 Connection established/', $data))\r
2212                                 {\r
2213                                         // Look for CR/LF or simple LF as line separator,\r
2214                                         // (even though it is not valid http)\r
2215                                         $pos = strpos($data,"\r\n\r\n");\r
2216                                         if($pos || is_int($pos))\r
2217                                         {\r
2218                                                 $bd = $pos+4;\r
2219                                         }\r
2220                                         else\r
2221                                         {\r
2222                                                 $pos = strpos($data,"\n\n");\r
2223                                                 if($pos || is_int($pos))\r
2224                                                 {\r
2225                                                         $bd = $pos+2;\r
2226                                                 }\r
2227                                                 else\r
2228                                                 {\r
2229                                                         // No separation between response headers and body: fault?\r
2230                                                         $bd = 0;\r
2231                                                 }\r
2232                                         }\r
2233                                         if ($bd)\r
2234                                         {\r
2235                                                 // this filters out all http headers from proxy.\r
2236                                                 // maybe we could take them into account, too?\r
2237                                                 $data = substr($data, $bd);\r
2238                                         }\r
2239                                         else\r
2240                                         {\r
2241                                                 error_log('XML-RPC: xmlrpcmsg::parseResponse: HTTPS via proxy error, tunnel connection possibly failed');\r
2242                                                 $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $GLOBALS['xmlrpcstr']['http_error']. ' (HTTPS via proxy error, tunnel connection possibly failed)');\r
2243                                                 return $r;\r
2244                                         }\r
2245                                 }\r
2246 \r
2247                                 // Strip HTTP 1.1 100 Continue header if present\r
2248                                 while(preg_match('/^HTTP\/1\.1 1[0-9]{2} /', $data))\r
2249                                 {\r
2250                                         $pos = strpos($data, 'HTTP', 12);\r
2251                                         // server sent a Continue header without any (valid) content following...\r
2252                                         // give the client a chance to know it\r
2253                                         if(!$pos && !is_int($pos)) // works fine in php 3, 4 and 5\r
2254                                         {\r
2255                                                 break;\r
2256                                         }\r
2257                                         $data = substr($data, $pos);\r
2258                                 }\r
2259                                 if(!preg_match('/^HTTP\/[0-9.]+ 200 /', $data))\r
2260                                 {\r
2261                                         $errstr= substr($data, 0, strpos($data, "\n")-1);\r
2262                                         error_log('XML-RPC: xmlrpcmsg::parseResponse: HTTP error, got response: ' .$errstr);\r
2263                                         $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $GLOBALS['xmlrpcstr']['http_error']. ' (' . $errstr . ')');\r
2264                                         return $r;\r
2265                                 }\r
2266 \r
2267                                 $GLOBALS['_xh']['headers'] = array();\r
2268                                 $GLOBALS['_xh']['cookies'] = array();\r
2269 \r
2270                                 // be tolerant to usage of \n instead of \r\n to separate headers and data\r
2271                                 // (even though it is not valid http)\r
2272                                 $pos = strpos($data,"\r\n\r\n");\r
2273                                 if($pos || is_int($pos))\r
2274                                 {\r
2275                                         $bd = $pos+4;\r
2276                                 }\r
2277                                 else\r
2278                                 {\r
2279                                         $pos = strpos($data,"\n\n");\r
2280                                         if($pos || is_int($pos))\r
2281                                         {\r
2282                                                 $bd = $pos+2;\r
2283                                         }\r
2284                                         else\r
2285                                         {\r
2286                                                 // No separation between response headers and body: fault?\r
2287                                                 // we could take some action here instead of going on...\r
2288                                                 $bd = 0;\r
2289                                         }\r
2290                                 }\r
2291                                 // be tolerant to line endings, and extra empty lines\r
2292                                 $ar = split("\r?\n", trim(substr($data, 0, $pos)));\r
2293                                 while(list(,$line) = @each($ar))\r
2294                                 {\r
2295                                         // take care of multi-line headers and cookies\r
2296                                         $arr = explode(':',$line,2);\r
2297                                         if(count($arr) > 1)\r
2298                                         {\r
2299                                                 $header_name = strtolower(trim($arr[0]));\r
2300                                                 /// @todo some other headers (the ones that allow a CSV list of values)\r
2301                                                 /// do allow many values to be passed using multiple header lines.\r
2302                                                 /// We should add content to $GLOBALS['_xh']['headers'][$header_name]\r
2303                                                 /// instead of replacing it for those...\r
2304                                                 if ($header_name == 'set-cookie' || $header_name == 'set-cookie2')\r
2305                                                 {\r
2306                                                         if ($header_name == 'set-cookie2')\r
2307                                                         {\r
2308                                                                 // version 2 cookies:\r
2309                                                                 // there could be many cookies on one line, comma separated\r
2310                                                                 $cookies = explode(',', $arr[1]);\r
2311                                                         }\r
2312                                                         else\r
2313                                                         {\r
2314                                                                 $cookies = array($arr[1]);\r
2315                                                         }\r
2316                                                         foreach ($cookies as $cookie)\r
2317                                                         {\r
2318                                                                 // glue together all received cookies, using a comma to separate them\r
2319                                                                 // (same as php does with getallheaders())\r
2320                                                                 if (isset($GLOBALS['_xh']['headers'][$header_name]))\r
2321                                                                         $GLOBALS['_xh']['headers'][$header_name] .= ', ' . trim($cookie);\r
2322                                                                 else\r
2323                                                                         $GLOBALS['_xh']['headers'][$header_name] = trim($cookie);\r
2324                                                                 // parse cookie attributes, in case user wants to correctly honour them\r
2325                                                                 // feature creep: only allow rfc-compliant cookie attributes?\r
2326                                                                 // @todo support for server sending multiple time cookie with same name, but using different PATHs\r
2327                                                                 $cookie = explode(';', $cookie);\r
2328                                                                 foreach ($cookie as $pos => $val)\r
2329                                                                 {\r
2330                                                                         $val = explode('=', $val, 2);\r
2331                                                                         $tag = trim($val[0]);\r
2332                                                                         $val = trim(@$val[1]);\r
2333                                                                         /// @todo with version 1 cookies, we should strip leading and trailing " chars\r
2334                                                                         if ($pos == 0)\r
2335                                                                         {\r
2336                                                                                 $cookiename = $tag;\r
2337                                                                                 $GLOBALS['_xh']['cookies'][$tag] = array();\r
2338                                                                                 $GLOBALS['_xh']['cookies'][$cookiename]['value'] = urldecode($val);\r
2339                                                                         }\r
2340                                                                         else\r
2341                                                                         {\r
2342                                                                                 if ($tag != 'value')\r
2343                                                                                 {\r
2344                                                                                   $GLOBALS['_xh']['cookies'][$cookiename][$tag] = $val;\r
2345                                                                                 }\r
2346                                                                         }\r
2347                                                                 }\r
2348                                                         }\r
2349                                                 }\r
2350                                                 else\r
2351                                                 {\r
2352                                                         $GLOBALS['_xh']['headers'][$header_name] = trim($arr[1]);\r
2353                                                 }\r
2354                                         }\r
2355                                         elseif(isset($header_name))\r
2356                                         {\r
2357                                                 ///     @todo version1 cookies might span multiple lines, thus breaking the parsing above\r
2358                                                 $GLOBALS['_xh']['headers'][$header_name] .= ' ' . trim($line);\r
2359                                         }\r
2360                                 }\r
2361 \r
2362                                 $data = substr($data, $bd);\r
2363 \r
2364                                 if($this->debug && count($GLOBALS['_xh']['headers']))\r
2365                                 {\r
2366                                         print '<PRE>';\r
2367                                         foreach($GLOBALS['_xh']['headers'] as $header => $value)\r
2368                                         {\r
2369                                                 print htmlentities("HEADER: $header: $value\n");\r
2370                                         }\r
2371                                         foreach($GLOBALS['_xh']['cookies'] as $header => $value)\r
2372                                         {\r
2373                                                 print htmlentities("COOKIE: $header={$value['value']}\n");\r
2374                                         }\r
2375                                         print "</PRE>\n";\r
2376                                 }\r
2377 \r
2378                                 // if CURL was used for the call, http headers have been processed,\r
2379                                 // and dechunking + reinflating have been carried out\r
2380                                 if(!$headers_processed)\r
2381                                 {\r
2382                                         // Decode chunked encoding sent by http 1.1 servers\r
2383                                         if(isset($GLOBALS['_xh']['headers']['transfer-encoding']) && $GLOBALS['_xh']['headers']['transfer-encoding'] == 'chunked')\r
2384                                         {\r
2385                                                 if(!$data = decode_chunked($data))\r
2386                                                 {\r
2387                                                         error_log('XML-RPC: xmlrpcmsg::parseResponse: errors occurred when trying to rebuild the chunked data received from server');\r
2388                                                         $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['dechunk_fail'], $GLOBALS['xmlrpcstr']['dechunk_fail']);\r
2389                                                         return $r;\r
2390                                                 }\r
2391                                         }\r
2392 \r
2393                                         // Decode gzip-compressed stuff\r
2394                                         // code shamelessly inspired from nusoap library by Dietrich Ayala\r
2395                                         if(isset($GLOBALS['_xh']['headers']['content-encoding']))\r
2396                                         {\r
2397                                                 $GLOBALS['_xh']['headers']['content-encoding'] = str_replace('x-', '', $GLOBALS['_xh']['headers']['content-encoding']);\r
2398                                                 if($GLOBALS['_xh']['headers']['content-encoding'] == 'deflate' || $GLOBALS['_xh']['headers']['content-encoding'] == 'gzip')\r
2399                                                 {\r
2400                                                         // if decoding works, use it. else assume data wasn't gzencoded\r
2401                                                         if(function_exists('gzinflate'))\r
2402                                                         {\r
2403                                                                 if($GLOBALS['_xh']['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data))\r
2404                                                                 {\r
2405                                                                         $data = $degzdata;\r
2406                                                                         if($this->debug)\r
2407                                                                         print "<PRE>---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---</PRE>";\r
2408                                                                 }\r
2409                                                                 elseif($GLOBALS['_xh']['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10)))\r
2410                                                                 {\r
2411                                                                         $data = $degzdata;\r
2412                                                                         if($this->debug)\r
2413                                                                         print "<PRE>---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---</PRE>";\r
2414                                                                 }\r
2415                                                                 else\r
2416                                                                 {\r
2417                                                                         error_log('XML-RPC: xmlrpcmsg::parseResponse: errors occurred when trying to decode the deflated data received from server');\r
2418                                                                         $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['decompress_fail'], $GLOBALS['xmlrpcstr']['decompress_fail']);\r
2419                                                                         return $r;\r
2420                                                                 }\r
2421                                                         }\r
2422                                                         else\r
2423                                                         {\r
2424                                                                 error_log('XML-RPC: xmlrpcmsg::parseResponse: the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');\r
2425                                                                 $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['cannot_decompress'], $GLOBALS['xmlrpcstr']['cannot_decompress']);\r
2426                                                                 return $r;\r
2427                                                         }\r
2428                                                 }\r
2429                                         }\r
2430                                 } // end of 'if needed, de-chunk, re-inflate response'\r
2431 \r
2432                                 // real stupid hack to avoid PHP 4 complaining about returning NULL by ref\r
2433                                 $r = null;\r
2434                                 $r =& $r;\r
2435                                 return $r;\r
2436                 }\r
2437 \r
2438                 /**\r
2439                 * Parse the xmlrpc response contained in the string $data and return an xmlrpcresp object.\r
2440                 * @param string $data the xmlrpc response, eventually including http headers\r
2441                 * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding\r
2442                 * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals'\r
2443                 * @return xmlrpcresp\r
2444                 * @access public\r
2445                 */\r
2446                 function &parseResponse($data='', $headers_processed=false, $return_type='xmlrpcvals')\r
2447                 {\r
2448                         if($this->debug)\r
2449                         {\r
2450                                 //by maHo, replaced htmlspecialchars with htmlentities\r
2451                                 print "<PRE>---GOT---\n" . htmlentities($data) . "\n---END---\n</PRE>";\r
2452                         }\r
2453 \r
2454                         if($data == '')\r
2455                         {\r
2456                                 error_log('XML-RPC: xmlrpcmsg::parseResponse: no response received from server.');\r
2457                                 $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['no_data'], $GLOBALS['xmlrpcstr']['no_data']);\r
2458                                 return $r;\r
2459                         }\r
2460 \r
2461                         $GLOBALS['_xh']=array();\r
2462 \r
2463                         $raw_data = $data;\r
2464                         // parse the HTTP headers of the response, if present, and separate them from data\r
2465                         if(substr($data, 0, 4) == 'HTTP')\r
2466                         {\r
2467                                 $r =& $this->parseResponseHeaders($data, $headers_processed);\r
2468                                 if ($r)\r
2469                                 {\r
2470                                         // failed processing of HTTP response headers\r
2471                                         // save into response obj the full payload received, for debugging\r
2472                                         $r->raw_data = $data;\r
2473                                         return $r;\r
2474                                 }\r
2475                         }\r
2476                         else\r
2477                         {\r
2478                                 $GLOBALS['_xh']['headers'] = array();\r
2479                                 $GLOBALS['_xh']['cookies'] = array();\r
2480                         }\r
2481 \r
2482                         if($this->debug)\r
2483                         {\r
2484                                 $start = strpos($data, '<!-- SERVER DEBUG INFO (BASE64 ENCODED):');\r
2485                                 if ($start)\r
2486                                 {\r
2487                                         $start += strlen('<!-- SERVER DEBUG INFO (BASE64 ENCODED):');\r
2488                                         $end = strpos($data, '-->', $start);\r
2489                                         $comments = substr($data, $start, $end-$start);\r
2490                                         print "<PRE>---SERVER DEBUG INFO (DECODED) ---\n\t".htmlentities(str_replace("\n", "\n\t", base64_decode($comments)))."\n---END---\n</PRE>";\r
2491                                 }\r
2492                         }\r
2493 \r
2494                         // be tolerant of extra whitespace in response body\r
2495                         $data = trim($data);\r
2496 \r
2497                         /// @todo return an error msg if $data=='' ?\r
2498 \r
2499                         // be tolerant of junk after methodResponse (e.g. javascript ads automatically inserted by free hosts)\r
2500                         // idea from Luca Mariano <luca.mariano@email.it> originally in PEARified version of the lib\r
2501                         $bd = false;\r
2502                         // Poor man's version of strrpos for php 4...\r
2503                         $pos = strpos($data, '</methodResponse>');\r
2504                         while($pos || is_int($pos))\r
2505                         {\r
2506                                 $bd = $pos+17;\r
2507                                 $pos = strpos($data, '</methodResponse>', $bd);\r
2508                         }\r
2509                         if($bd)\r
2510                         {\r
2511                                 $data = substr($data, 0, $bd);\r
2512                         }\r
2513 \r
2514                         // if user wants back raw xml, give it to him\r
2515                         if ($return_type == 'xml')\r
2516                         {\r
2517                                 $r = new xmlrpcresp($data, 0, '', 'xml');\r
2518                                 $r->hdrs = $GLOBALS['_xh']['headers'];\r
2519                                 $r->_cookies = $GLOBALS['_xh']['cookies'];\r
2520                                 $r->raw_data = $raw_data;\r
2521                                 return $r;\r
2522                         }\r
2523 \r
2524                         // try to 'guestimate' the character encoding of the received response\r
2525                         $resp_encoding = guess_encoding(@$GLOBALS['_xh']['headers']['content-type'], $data);\r
2526 \r
2527                         $GLOBALS['_xh']['ac']='';\r
2528                         //$GLOBALS['_xh']['qt']=''; //unused...\r
2529                         $GLOBALS['_xh']['stack'] = array();\r
2530                         $GLOBALS['_xh']['valuestack'] = array();\r
2531                         $GLOBALS['_xh']['isf']=0; // 0 = OK, 1 for xmlrpc fault responses, 2 = invalid xmlrpc\r
2532                         $GLOBALS['_xh']['isf_reason']='';\r
2533                         $GLOBALS['_xh']['rt']=''; // 'methodcall or 'methodresponse'\r
2534 \r
2535                         // if response charset encoding is not known / supported, try to use\r
2536                         // the default encoding and parse the xml anyway, but log a warning...\r
2537                         if (!in_array($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))\r
2538                         // the following code might be better for mb_string enabled installs, but\r
2539                         // makes the lib about 200% slower...\r
2540                         //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))\r
2541                         {\r
2542                                 error_log('XML-RPC: xmlrpcmsg::parseResponse: invalid charset encoding of received response: '.$resp_encoding);\r
2543                                 $resp_encoding = $GLOBALS['xmlrpc_defencoding'];\r
2544                         }\r
2545                         $parser = xml_parser_create($resp_encoding);\r
2546                         xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);\r
2547                         // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell\r
2548                         // the xml parser to give us back data in the expected charset.\r
2549                         // What if internal encoding is not in one of the 3 allowed?\r
2550                         // we use the broadest one, ie. utf8\r
2551                         // This allows to send data which is native in various charset,\r
2552                         // by extending xmlrpc_encode_entitites() and setting xmlrpc_internalencoding\r
2553                         if (!in_array($GLOBALS['xmlrpc_internalencoding'], array('UTF-8', 'ISO-8859-1', 'US-ASCII')))\r
2554                         {\r
2555                                 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');\r
2556                         }\r
2557                         else\r
2558                         {\r
2559                                 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $GLOBALS['xmlrpc_internalencoding']);\r
2560                         }\r
2561 \r
2562                         if ($return_type == 'phpvals')\r
2563                         {\r
2564                                 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');\r
2565                         }\r
2566                         else\r
2567                         {\r
2568                                 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');\r
2569                         }\r
2570 \r
2571                         xml_set_character_data_handler($parser, 'xmlrpc_cd');\r
2572                         xml_set_default_handler($parser, 'xmlrpc_dh');\r
2573 \r
2574                         // first error check: xml not well formed\r
2575                         if(!xml_parse($parser, $data, count($data)))\r
2576                         {\r
2577                                 // thanks to Peter Kocks <peter.kocks@baygate.com>\r
2578                                 if((xml_get_current_line_number($parser)) == 1)\r
2579                                 {\r
2580                                         $errstr = 'XML error at line 1, check URL';\r
2581                                 }\r
2582                                 else\r
2583                                 {\r
2584                                         $errstr = sprintf('XML error: %s at line %d, column %d',\r
2585                                                 xml_error_string(xml_get_error_code($parser)),\r
2586                                                 xml_get_current_line_number($parser), xml_get_current_column_number($parser));\r
2587                                 }\r
2588                                 error_log($errstr);\r
2589                                 $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['invalid_return'], $GLOBALS['xmlrpcstr']['invalid_return'].' ('.$errstr.')');\r
2590                                 xml_parser_free($parser);\r
2591                                 if($this->debug)\r
2592                                 {\r
2593                                         print $errstr;\r
2594                                 }\r
2595                                 $r->hdrs = $GLOBALS['_xh']['headers'];\r
2596                                 $r->_cookies = $GLOBALS['_xh']['cookies'];\r
2597                                 $r->raw_data = $raw_data;\r
2598                                 return $r;\r
2599                         }\r
2600                         xml_parser_free($parser);\r
2601                         // second error check: xml well formed but not xml-rpc compliant\r
2602                         if ($GLOBALS['_xh']['isf'] > 1)\r
2603                         {\r
2604                                 if ($this->debug)\r
2605                                 {\r
2606                                         /// @todo echo something for user?\r
2607                                 }\r
2608 \r
2609                                 $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['invalid_return'],\r
2610                                 $GLOBALS['xmlrpcstr']['invalid_return'] . ' ' . $GLOBALS['_xh']['isf_reason']);\r
2611                         }\r
2612                         // third error check: parsing of the response has somehow gone boink.\r
2613                         // NB: shall we omit this check, since we trust the parsing code?\r
2614                         elseif ($return_type == 'xmlrpcvals' && !is_object($GLOBALS['_xh']['value']))\r
2615                         {\r
2616                                 // something odd has happened\r
2617                                 // and it's time to generate a client side error\r
2618                                 // indicating something odd went on\r
2619                                 $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['invalid_return'],\r
2620                                         $GLOBALS['xmlrpcstr']['invalid_return']);\r
2621                         }\r
2622                         else\r
2623                         {\r
2624                                 if ($this->debug)\r
2625                                 {\r
2626                                         print "<PRE>---PARSED---\n";\r
2627                                         // somehow htmlentities chokes on var_export, and some full html string...\r
2628                                         //print htmlentitites(var_export($GLOBALS['_xh']['value'], true));\r
2629                                         print htmlspecialchars(var_export($GLOBALS['_xh']['value'], true));\r
2630                                         print "\n---END---</PRE>";\r
2631                                 }\r
2632 \r
2633                                 // note that using =& will raise an error if $GLOBALS['_xh']['st'] does not generate an object.\r
2634                                 $v =& $GLOBALS['_xh']['value'];\r
2635 \r
2636                                 if($GLOBALS['_xh']['isf'])\r
2637                                 {\r
2638                                         /// @todo we should test here if server sent an int and a string,\r
2639                                         /// and/or coerce them into such...\r
2640                                         if ($return_type == 'xmlrpcvals')\r
2641                                         {\r
2642                                                 $errno_v = $v->structmem('faultCode');\r
2643                                                 $errstr_v = $v->structmem('faultString');\r
2644                                                 $errno = $errno_v->scalarval();\r
2645                                                 $errstr = $errstr_v->scalarval();\r
2646                                         }\r
2647                                         else\r
2648                                         {\r
2649                                                 $errno = $v['faultCode'];\r
2650                                                 $errstr = $v['faultString'];\r
2651                                         }\r
2652 \r
2653                                         if($errno == 0)\r
2654                                         {\r
2655                                                 // FAULT returned, errno needs to reflect that\r
2656                                                 $errno = -1;\r
2657                                         }\r
2658 \r
2659                                         $r = new xmlrpcresp(0, $errno, $errstr);\r
2660                                 }\r
2661                                 else\r
2662                                 {\r
2663                                         $r=new xmlrpcresp($v, 0, '', $return_type);\r
2664                                 }\r
2665                         }\r
2666 \r
2667                         $r->hdrs = $GLOBALS['_xh']['headers'];\r
2668                         $r->_cookies = $GLOBALS['_xh']['cookies'];\r
2669                         $r->raw_data = $raw_data;\r
2670                         return $r;\r
2671                 }\r
2672         }\r
2673 \r
2674         class xmlrpcval\r
2675         {\r
2676                 var $me=array();\r
2677                 var $mytype=0;\r
2678                 var $_php_class=null;\r
2679 \r
2680                 /**\r
2681                 * @param mixed $val\r
2682                 * @param string $type any valid xmlrpc type name (lowercase). If null, 'string' is assumed\r
2683                 */\r
2684                 function xmlrpcval($val=-1, $type='')\r
2685                 {\r
2686                         /// @todo: optimization creep - do not call addXX, do it all inline.\r
2687                         /// downside: booleans will not be coerced anymore\r
2688                         if($val!==-1 || $type!='')\r
2689                         {\r
2690                                 // optimization creep: inlined all work done by constructor\r
2691                                 switch($type)\r
2692                                 {\r
2693                                         case '':\r
2694                                                 $this->mytype=1;\r
2695                                                 $this->me['string']=$val;\r
2696                                                 break;\r
2697                                         case 'i4':\r
2698                                         case 'int':\r
2699                                         case 'double':\r
2700                                         case 'string':\r
2701                                         case 'boolean':\r
2702                                         case 'dateTime.iso8601':\r
2703                                         case 'base64':\r
2704                                         case 'null':\r
2705                                                 $this->mytype=1;\r
2706                                                 $this->me[$type]=$val;\r
2707                                                 break;\r
2708                                         case 'array':\r
2709                                                 $this->mytype=2;\r
2710                                                 $this->me['array']=$val;\r
2711                                                 break;\r
2712                                         case 'struct':\r
2713                                                 $this->mytype=3;\r
2714                                                 $this->me['struct']=$val;\r
2715                                                 break;\r
2716                                         default:\r
2717                                                 error_log("XML-RPC: xmlrpcval::xmlrpcval: not a known type ($type)");\r
2718                                 }\r
2719                                 /*if($type=='')\r
2720                                 {\r
2721                                         $type='string';\r
2722                                 }\r
2723                                 if($GLOBALS['xmlrpcTypes'][$type]==1)\r
2724                                 {\r
2725                                         $this->addScalar($val,$type);\r
2726                                 }\r
2727                                 elseif($GLOBALS['xmlrpcTypes'][$type]==2)\r
2728                                 {\r
2729                                         $this->addArray($val);\r
2730                                 }\r
2731                                 elseif($GLOBALS['xmlrpcTypes'][$type]==3)\r
2732                                 {\r
2733                                         $this->addStruct($val);\r
2734                                 }*/\r
2735                         }\r
2736                 }\r
2737 \r
2738                 /**\r
2739                 * Add a single php value to an (unitialized) xmlrpcval\r
2740                 * @param mixed $val\r
2741                 * @param string $type\r
2742                 * @return int 1 or 0 on failure\r
2743                 */\r
2744                 function addScalar($val, $type='string')\r
2745                 {\r
2746                         $typeof=@$GLOBALS['xmlrpcTypes'][$type];\r
2747                         if($typeof!=1)\r
2748                         {\r
2749                                 error_log("XML-RPC: xmlrpcval::addScalar: not a scalar type ($type)");\r
2750                                 return 0;\r
2751                         }\r
2752 \r
2753                         // coerce booleans into correct values\r
2754                         // NB: we should iether do it for datetimes, integers and doubles, too,\r
2755                         // or just plain remove this check, implemnted on booleans only...\r
2756                         if($type==$GLOBALS['xmlrpcBoolean'])\r
2757                         {\r
2758                                 if(strcasecmp($val,'true')==0 || $val==1 || ($val==true && strcasecmp($val,'false')))\r
2759                                 {\r
2760                                         $val=true;\r
2761                                 }\r
2762                                 else\r
2763                                 {\r
2764                                         $val=false;\r
2765                                 }\r
2766                         }\r
2767 \r
2768                         switch($this->mytype)\r
2769                         {\r
2770                                 case 1:\r
2771                                         error_log('XML-RPC: xmlrpcval::addScalar: scalar xmlrpcval can have only one value');\r
2772                                         return 0;\r
2773                                 case 3:\r
2774                                         error_log('XML-RPC: xmlrpcval::addScalar: cannot add anonymous scalar to struct xmlrpcval');\r
2775                                         return 0;\r
2776                                 case 2:\r
2777                                         // we're adding a scalar value to an array here\r
2778                                         //$ar=$this->me['array'];\r
2779                                         //$ar[]=new xmlrpcval($val, $type);\r
2780                                         //$this->me['array']=$ar;\r
2781                                         // Faster (?) avoid all the costly array-copy-by-val done here...\r
2782                                         $this->me['array'][]=new xmlrpcval($val, $type);\r
2783                                         return 1;\r
2784                                 default:\r
2785                                         // a scalar, so set the value and remember we're scalar\r
2786                                         $this->me[$type]=$val;\r
2787                                         $this->mytype=$typeof;\r
2788                                         return 1;\r
2789                         }\r
2790                 }\r
2791 \r
2792                 /**\r
2793                 * Add an array of xmlrpcval objects to an xmlrpcval\r
2794                 * @param array $vals\r
2795                 * @return int 1 or 0 on failure\r
2796                 * @access public\r
2797                 *\r
2798                 * @todo add some checking for $vals to be an array of xmlrpcvals?\r
2799                 */\r
2800                 function addArray($vals)\r
2801                 {\r
2802                         if($this->mytype==0)\r
2803                         {\r
2804                                 $this->mytype=$GLOBALS['xmlrpcTypes']['array'];\r
2805                                 $this->me['array']=$vals;\r
2806                                 return 1;\r
2807                         }\r
2808                         elseif($this->mytype==2)\r
2809                         {\r
2810                                 // we're adding to an array here\r
2811                                 $this->me['array'] = array_merge($this->me['array'], $vals);\r
2812                                 return 1;\r
2813                         }\r
2814                         else\r
2815                         {\r
2816                                 error_log('XML-RPC: xmlrpcval::addArray: already initialized as a [' . $this->kindOf() . ']');\r
2817                                 return 0;\r
2818                         }\r
2819                 }\r
2820 \r
2821                 /**\r
2822                 * Add an array of named xmlrpcval objects to an xmlrpcval\r
2823                 * @param array $vals\r
2824                 * @return int 1 or 0 on failure\r
2825                 * @access public\r
2826                 *\r
2827                 * @todo add some checking for $vals to be an array?\r
2828                 */\r
2829                 function addStruct($vals)\r
2830                 {\r
2831                         if($this->mytype==0)\r
2832                         {\r
2833                                 $this->mytype=$GLOBALS['xmlrpcTypes']['struct'];\r
2834                                 $this->me['struct']=$vals;\r
2835                                 return 1;\r
2836                         }\r
2837                         elseif($this->mytype==3)\r
2838                         {\r
2839                                 // we're adding to a struct here\r
2840                                 $this->me['struct'] = array_merge($this->me['struct'], $vals);\r
2841                                 return 1;\r
2842                         }\r
2843                         else\r
2844                         {\r
2845                                 error_log('XML-RPC: xmlrpcval::addStruct: already initialized as a [' . $this->kindOf() . ']');\r
2846                                 return 0;\r
2847                         }\r
2848                 }\r
2849 \r
2850                 // poor man's version of print_r ???\r
2851                 // DEPRECATED!\r
2852                 function dump($ar)\r
2853                 {\r
2854                         foreach($ar as $key => $val)\r
2855                         {\r
2856                                 echo "$key => $val<br />";\r
2857                                 if($key == 'array')\r
2858                                 {\r
2859                                         while(list($key2, $val2) = each($val))\r
2860                                         {\r
2861                                                 echo "-- $key2 => $val2<br />";\r
2862                                         }\r
2863                                 }\r
2864                         }\r
2865                 }\r
2866 \r
2867                 /**\r
2868                 * Returns a string containing "struct", "array" or "scalar" describing the base type of the value\r
2869                 * @return string\r
2870                 * @access public\r
2871                 */\r
2872                 function kindOf()\r
2873                 {\r
2874                         switch($this->mytype)\r
2875                         {\r
2876                                 case 3:\r
2877                                         return 'struct';\r
2878                                         break;\r
2879                                 case 2:\r
2880                                         return 'array';\r
2881                                         break;\r
2882                                 case 1:\r
2883                                         return 'scalar';\r
2884                                         break;\r
2885                                 default:\r
2886                                         return 'undef';\r
2887                         }\r
2888                 }\r
2889 \r
2890                 /**\r
2891                 * @access private\r
2892                 */\r
2893                 function serializedata($typ, $val, $charset_encoding='')\r
2894                 {\r
2895                         $rs='';\r
2896                         switch(@$GLOBALS['xmlrpcTypes'][$typ])\r
2897                         {\r
2898                                 case 1:\r
2899                                         switch($typ)\r
2900                                         {\r
2901                                                 case $GLOBALS['xmlrpcBase64']:\r
2902                                                         $rs.="<${typ}>" . base64_encode($val) . "</${typ}>";\r
2903                                                         break;\r
2904                                                 case $GLOBALS['xmlrpcBoolean']:\r
2905                                                         $rs.="<${typ}>" . ($val ? '1' : '0') . "</${typ}>";\r
2906                                                         break;\r
2907                                                 case $GLOBALS['xmlrpcString']:\r
2908                                                         // G. Giunta 2005/2/13: do NOT use htmlentities, since\r
2909                                                         // it will produce named html entities, which are invalid xml\r
2910                                                         $rs.="<${typ}>" . xmlrpc_encode_entitites($val, $GLOBALS['xmlrpc_internalencoding'], $charset_encoding). "</${typ}>";\r
2911                                                         break;\r
2912                                                 case $GLOBALS['xmlrpcInt']:\r
2913                                                 case $GLOBALS['xmlrpcI4']:\r
2914                                                         $rs.="<${typ}>".(int)$val."</${typ}>";\r
2915                                                         break;\r
2916                                                 case $GLOBALS['xmlrpcDouble']:\r
2917                                                 // avoid using standard conversion of float to string because it is locale-dependent,\r
2918                                                 // and also because the xmlrpc spec forbids exponential notation\r
2919                                                 // sprintf('%F') would be most likely ok but it is only available since PHP 4.3.10 and PHP 5.0.3.\r
2920                                                 // The code below tries its best at keeping max precision while avoiding exp notation,\r
2921                                                 // but there is of course no limit in the number of decimal places to be used...\r
2922                                                 $rs.="<${typ}>".preg_replace('/\\.?0+$/','',number_format((double)$val, 128, '.', ''))."</${typ}>";\r
2923                                                         break;\r
2924                                                 case $GLOBALS['xmlrpcNull']:\r
2925                                                         $rs.="<nil/>";\r
2926                                                         break;\r
2927                                                 default:\r
2928                                                         // no standard type value should arrive here, but provide a possibility\r
2929                                                         // for xmlrpcvals of unknown type...\r
2930                                                         $rs.="<${typ}>${val}</${typ}>";\r
2931                                         }\r
2932                                         break;\r
2933                                 case 3:\r
2934                                         // struct\r
2935                                         if ($this->_php_class)\r
2936                                         {\r
2937                                                 $rs.='<struct php_class="' . $this->_php_class . "\">\n";\r
2938                                         }\r
2939                                         else\r
2940                                         {\r
2941                                                 $rs.="<struct>\n";\r
2942                                         }\r
2943                                         foreach($val as $key2 => $val2)\r
2944                                         {\r
2945                                                 $rs.='<member><name>'.xmlrpc_encode_entitites($key2, $GLOBALS['xmlrpc_internalencoding'], $charset_encoding)."</name>\n";\r
2946                                                 //$rs.=$this->serializeval($val2);\r
2947                                                 $rs.=$val2->serialize($charset_encoding);\r
2948                                                 $rs.="</member>\n";\r
2949                                         }\r
2950                                         $rs.='</struct>';\r
2951                                         break;\r
2952                                 case 2:\r
2953                                         // array\r
2954                                         $rs.="<array>\n<data>\n";\r
2955                                         for($i=0; $i<count($val); $i++)\r
2956                                         {\r
2957                                                 //$rs.=$this->serializeval($val[$i]);\r
2958                                                 $rs.=$val[$i]->serialize($charset_encoding);\r
2959                                         }\r
2960                                         $rs.="</data>\n</array>";\r
2961                                         break;\r
2962                                 default:\r
2963                                         break;\r
2964                         }\r
2965                         return $rs;\r
2966                 }\r
2967 \r
2968                 /**\r
2969                 * Returns xml representation of the value. XML prologue not included\r
2970                 * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed\r
2971                 * @return string\r
2972                 * @access public\r
2973                 */\r
2974                 function serialize($charset_encoding='')\r
2975                 {\r
2976                         // add check? slower, but helps to avoid recursion in serializing broken xmlrpcvals...\r
2977                         //if (is_object($o) && (get_class($o) == 'xmlrpcval' || is_subclass_of($o, 'xmlrpcval')))\r
2978                         //{\r
2979                                 reset($this->me);\r
2980                                 list($typ, $val) = each($this->me);\r
2981                                 return '<value>' . $this->serializedata($typ, $val, $charset_encoding) . "</value>\n";\r
2982                         //}\r
2983                 }\r
2984 \r
2985                 // DEPRECATED\r
2986                 function serializeval($o)\r
2987                 {\r
2988                         // add check? slower, but helps to avoid recursion in serializing broken xmlrpcvals...\r
2989                         //if (is_object($o) && (get_class($o) == 'xmlrpcval' || is_subclass_of($o, 'xmlrpcval')))\r
2990                         //{\r
2991                                 $ar=$o->me;\r
2992                                 reset($ar);\r
2993                                 list($typ, $val) = each($ar);\r
2994                                 return '<value>' . $this->serializedata($typ, $val) . "</value>\n";\r
2995                         //}\r
2996                 }\r
2997 \r
2998                 /**\r
2999                 * Checks wheter a struct member with a given name is present.\r
3000                 * Works only on xmlrpcvals of type struct.\r
3001                 * @param string $m the name of the struct member to be looked up\r
3002                 * @return boolean\r
3003                 * @access public\r
3004                 */\r
3005                 function structmemexists($m)\r
3006                 {\r
3007                         return array_key_exists($m, $this->me['struct']);\r
3008                 }\r
3009 \r
3010                 /**\r
3011                 * Returns the value of a given struct member (an xmlrpcval object in itself).\r
3012                 * Will raise a php warning if struct member of given name does not exist\r
3013                 * @param string $m the name of the struct member to be looked up\r
3014                 * @return xmlrpcval\r
3015                 * @access public\r
3016                 */\r
3017                 function structmem($m)\r
3018                 {\r
3019                         return $this->me['struct'][$m];\r
3020                 }\r
3021 \r
3022                 /**\r
3023                 * Reset internal pointer for xmlrpcvals of type struct.\r
3024                 * @access public\r
3025                 */\r
3026                 function structreset()\r
3027                 {\r
3028                         reset($this->me['struct']);\r
3029                 }\r
3030 \r
3031                 /**\r
3032                 * Return next member element for xmlrpcvals of type struct.\r
3033                 * @return xmlrpcval\r
3034                 * @access public\r
3035                 */\r
3036                 function structeach()\r
3037                 {\r
3038                         return each($this->me['struct']);\r
3039                 }\r
3040 \r
3041                 // DEPRECATED! this code looks like it is very fragile and has not been fixed\r
3042                 // for a long long time. Shall we remove it for 2.0?\r
3043                 function getval()\r
3044                 {\r
3045                         // UNSTABLE\r
3046                         reset($this->me);\r
3047                         list($a,$b)=each($this->me);\r
3048                         // contributed by I Sofer, 2001-03-24\r
3049                         // add support for nested arrays to scalarval\r
3050                         // i've created a new method here, so as to\r
3051                         // preserve back compatibility\r
3052 \r
3053                         if(is_array($b))\r
3054                         {\r
3055                                 @reset($b);\r
3056                                 while(list($id,$cont) = @each($b))\r
3057                                 {\r
3058                                         $b[$id] = $cont->scalarval();\r
3059                                 }\r
3060                         }\r
3061 \r
3062                         // add support for structures directly encoding php objects\r
3063                         if(is_object($b))\r
3064                         {\r
3065                                 $t = get_object_vars($b);\r
3066                                 @reset($t);\r
3067                                 while(list($id,$cont) = @each($t))\r
3068                                 {\r
3069                                         $t[$id] = $cont->scalarval();\r
3070                                 }\r
3071                                 @reset($t);\r
3072                                 while(list($id,$cont) = @each($t))\r
3073                                 {\r
3074                                         @$b->$id = $cont;\r
3075                                 }\r
3076                         }\r
3077                         // end contrib\r
3078                         return $b;\r
3079                 }\r
3080 \r
3081                 /**\r
3082                 * Returns the value of a scalar xmlrpcval\r
3083                 * @return mixed\r
3084                 * @access public\r
3085                 */\r
3086                 function scalarval()\r
3087                 {\r
3088                         reset($this->me);\r
3089                         list(,$b)=each($this->me);\r
3090                         return $b;\r
3091                 }\r
3092 \r
3093                 /**\r
3094                 * Returns the type of the xmlrpcval.\r
3095                 * For integers, 'int' is always returned in place of 'i4'\r
3096                 * @return string\r
3097                 * @access public\r
3098                 */\r
3099                 function scalartyp()\r
3100                 {\r
3101                         reset($this->me);\r
3102                         list($a,)=each($this->me);\r
3103                         if($a==$GLOBALS['xmlrpcI4'])\r
3104                         {\r
3105                                 $a=$GLOBALS['xmlrpcInt'];\r
3106                         }\r
3107                         return $a;\r
3108                 }\r
3109 \r
3110                 /**\r
3111                 * Returns the m-th member of an xmlrpcval of struct type\r
3112                 * @param integer $m the index of the value to be retrieved (zero based)\r
3113                 * @return xmlrpcval\r
3114                 * @access public\r
3115                 */\r
3116                 function arraymem($m)\r
3117                 {\r
3118                         return $this->me['array'][$m];\r
3119                 }\r
3120 \r
3121                 /**\r
3122                 * Returns the number of members in an xmlrpcval of array type\r
3123                 * @return integer\r
3124                 * @access public\r
3125                 */\r
3126                 function arraysize()\r
3127                 {\r
3128                         return count($this->me['array']);\r
3129                 }\r
3130 \r
3131                 /**\r
3132                 * Returns the number of members in an xmlrpcval of struct type\r
3133                 * @return integer\r
3134                 * @access public\r
3135                 */\r
3136                 function structsize()\r
3137                 {\r
3138                         return count($this->me['struct']);\r
3139                 }\r
3140         }\r
3141 \r
3142 \r
3143         // date helpers\r
3144 \r
3145         /**\r
3146         * Given a timestamp, return the corresponding ISO8601 encoded string.\r
3147         *\r
3148         * Really, timezones ought to be supported\r
3149         * but the XML-RPC spec says:\r
3150         *\r
3151         * "Don't assume a timezone. It should be specified by the server in its\r
3152         * documentation what assumptions it makes about timezones."\r
3153         *\r
3154         * These routines always assume localtime unless\r
3155         * $utc is set to 1, in which case UTC is assumed\r
3156         * and an adjustment for locale is made when encoding\r
3157         *\r
3158         * @param int $timet (timestamp)\r
3159         * @param int $utc (0 or 1)\r
3160         * @return string\r
3161         */\r
3162         function iso8601_encode($timet, $utc=0)\r
3163         {\r
3164                 if(!$utc)\r
3165                 {\r
3166                         $t=strftime("%Y%m%dT%H:%M:%S", $timet);\r
3167                 }\r
3168                 else\r
3169                 {\r
3170                         if(function_exists('gmstrftime'))\r
3171                         {\r
3172                                 // gmstrftime doesn't exist in some versions\r
3173                                 // of PHP\r
3174                                 $t=gmstrftime("%Y%m%dT%H:%M:%S", $timet);\r
3175                         }\r
3176                         else\r
3177                         {\r
3178                                 $t=strftime("%Y%m%dT%H:%M:%S", $timet-date('Z'));\r
3179                         }\r
3180                 }\r
3181                 return $t;\r
3182         }\r
3183 \r
3184         /**\r
3185         * Given an ISO8601 date string, return a timet in the localtime, or UTC\r
3186         * @param string $idate\r
3187         * @param int $utc either 0 or 1\r
3188         * @return int (datetime)\r
3189         */\r
3190         function iso8601_decode($idate, $utc=0)\r
3191         {\r
3192                 $t=0;\r
3193                 if(preg_match('/([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})/', $idate, $regs))\r
3194                 {\r
3195                         if($utc)\r
3196                         {\r
3197                                 $t=gmmktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);\r
3198                         }\r
3199                         else\r
3200                         {\r
3201                                 $t=mktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);\r
3202                         }\r
3203                 }\r
3204                 return $t;\r
3205         }\r
3206 \r
3207         /**\r
3208         * Takes an xmlrpc value in PHP xmlrpcval object format and translates it into native PHP types.\r
3209         *\r
3210         * Works with xmlrpc message objects as input, too.\r
3211         *\r
3212         * Given proper options parameter, can rebuild generic php object instances\r
3213         * (provided those have been encoded to xmlrpc format using a corresponding\r
3214         * option in php_xmlrpc_encode())\r
3215         * PLEASE NOTE that rebuilding php objects involves calling their constructor function.\r
3216         * This means that the remote communication end can decide which php code will\r
3217         * get executed on your server, leaving the door possibly open to 'php-injection'\r
3218         * style of attacks (provided you have some classes defined on your server that\r
3219         * might wreak havoc if instances are built outside an appropriate context).\r
3220         * Make sure you trust the remote server/client before eanbling this!\r
3221         *\r
3222         * @author Dan Libby (dan@libby.com)\r
3223         *\r
3224         * @param xmlrpcval $xmlrpc_val\r
3225         * @param array $options if 'decode_php_objs' is set in the options array, xmlrpc structs can be decoded into php objects\r
3226         * @return mixed\r
3227         */\r
3228         function php_xmlrpc_decode($xmlrpc_val, $options=array())\r
3229         {\r
3230                 switch($xmlrpc_val->kindOf())\r
3231                 {\r
3232                         case 'scalar':\r
3233                                 if (in_array('extension_api', $options))\r
3234                                 {\r
3235                                         reset($xmlrpc_val->me);\r
3236                                         list($typ,$val) = each($xmlrpc_val->me);\r
3237                                         switch ($typ)\r
3238                                         {\r
3239                                                 case 'dateTime.iso8601':\r
3240                                                         $xmlrpc_val->scalar = $val;\r
3241                                                         $xmlrpc_val->xmlrpc_type = 'datetime';\r
3242                                                         $xmlrpc_val->timestamp = iso8601_decode($val);\r
3243                                                         return $xmlrpc_val;\r
3244                                                 case 'base64':\r
3245                                                         $xmlrpc_val->scalar = $val;\r
3246                                                         $xmlrpc_val->type = $typ;\r
3247                                                         return $xmlrpc_val;\r
3248                                                 default:\r
3249                                                         return $xmlrpc_val->scalarval();\r
3250                                         }\r
3251                                 }\r
3252                                 return $xmlrpc_val->scalarval();\r
3253                         case 'array':\r
3254                                 $size = $xmlrpc_val->arraysize();\r
3255                                 $arr = array();\r
3256                                 for($i = 0; $i < $size; $i++)\r
3257                                 {\r
3258                                         $arr[] = php_xmlrpc_decode($xmlrpc_val->arraymem($i), $options);\r
3259                                 }\r
3260                                 return $arr;\r
3261                         case 'struct':\r
3262                                 $xmlrpc_val->structreset();\r
3263                                 // If user said so, try to rebuild php objects for specific struct vals.\r
3264                                 /// @todo should we raise a warning for class not found?\r
3265                                 // shall we check for proper subclass of xmlrpcval instead of\r
3266                                 // presence of _php_class to detect what we can do?\r
3267                                 if (in_array('decode_php_objs', $options) && $xmlrpc_val->_php_class != ''\r
3268                                         && class_exists($xmlrpc_val->_php_class))\r
3269                                 {\r
3270                                         $obj = @new $xmlrpc_val->_php_class;\r
3271                                         while(list($key,$value)=$xmlrpc_val->structeach())\r
3272                                         {\r
3273                                                 $obj->$key = php_xmlrpc_decode($value, $options);\r
3274                                         }\r
3275                                         return $obj;\r
3276                                 }\r
3277                                 else\r
3278                                 {\r
3279                                         $arr = array();\r
3280                                         while(list($key,$value)=$xmlrpc_val->structeach())\r
3281                                         {\r
3282                                                 $arr[$key] = php_xmlrpc_decode($value, $options);\r
3283                                         }\r
3284                                         return $arr;\r
3285                                 }\r
3286                         case 'msg':\r
3287                                 $paramcount = $xmlrpc_val->getNumParams();\r
3288                                 $arr = array();\r
3289                                 for($i = 0; $i < $paramcount; $i++)\r
3290                                 {\r
3291                                         $arr[] = php_xmlrpc_decode($xmlrpc_val->getParam($i));\r
3292                                 }\r
3293                                 return $arr;\r
3294                         }\r
3295         }\r
3296 \r
3297         // This constant left here only for historical reasons...\r
3298         // it was used to decide if we have to define xmlrpc_encode on our own, but\r
3299         // we do not do it anymore\r
3300         if(function_exists('xmlrpc_decode'))\r
3301         {\r
3302                 define('XMLRPC_EPI_ENABLED','1');\r
3303         }\r
3304         else\r
3305         {\r
3306                 define('XMLRPC_EPI_ENABLED','0');\r
3307         }\r
3308 \r
3309         /**\r
3310         * Takes native php types and encodes them into xmlrpc PHP object format.\r
3311         * It will not re-encode xmlrpcval objects.\r
3312         *\r
3313         * Feature creep -- could support more types via optional type argument\r
3314         * (string => datetime support has been added, ??? => base64 not yet)\r
3315         *\r
3316         * If given a proper options parameter, php object instances will be encoded\r
3317         * into 'special' xmlrpc values, that can later be decoded into php objects\r
3318         * by calling php_xmlrpc_decode() with a corresponding option\r
3319         *\r
3320         * @author Dan Libby (dan@libby.com)\r
3321         *\r
3322         * @param mixed $php_val the value to be converted into an xmlrpcval object\r
3323         * @param array $options can include 'encode_php_objs', 'auto_dates', 'null_extension' or 'extension_api'\r
3324         * @return xmlrpcval\r
3325         */\r
3326         function &php_xmlrpc_encode($php_val, $options=array())\r
3327         {\r
3328                 $type = gettype($php_val);\r
3329                 switch($type)\r
3330                 {\r
3331                         case 'string':\r
3332                                 if (in_array('auto_dates', $options) && preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $php_val))\r
3333                                         $xmlrpc_val = new xmlrpcval($php_val, $GLOBALS['xmlrpcDateTime']);\r
3334                                 else\r
3335                                         $xmlrpc_val = new xmlrpcval($php_val, $GLOBALS['xmlrpcString']);\r
3336                                 break;\r
3337                         case 'integer':\r
3338                                 $xmlrpc_val = new xmlrpcval($php_val, $GLOBALS['xmlrpcInt']);\r
3339                                 break;\r
3340                         case 'double':\r
3341                                 $xmlrpc_val = new xmlrpcval($php_val, $GLOBALS['xmlrpcDouble']);\r
3342                                 break;\r
3343                                 // <G_Giunta_2001-02-29>\r
3344                                 // Add support for encoding/decoding of booleans, since they are supported in PHP\r
3345                         case 'boolean':\r
3346                                 $xmlrpc_val = new xmlrpcval($php_val, $GLOBALS['xmlrpcBoolean']);\r
3347                                 break;\r
3348                                 // </G_Giunta_2001-02-29>\r
3349                         case 'array':\r
3350                                 // PHP arrays can be encoded to either xmlrpc structs or arrays,\r
3351                                 // depending on wheter they are hashes or plain 0..n integer indexed\r
3352                                 // A shorter one-liner would be\r
3353                                 // $tmp = array_diff(array_keys($php_val), range(0, count($php_val)-1));\r
3354                                 // but execution time skyrockets!\r
3355                                 $j = 0;\r
3356                                 $arr = array();\r
3357                                 $ko = false;\r
3358                                 foreach($php_val as $key => $val)\r
3359                                 {\r
3360                                         $arr[$key] =& php_xmlrpc_encode($val, $options);\r
3361                                         if(!$ko && $key !== $j)\r
3362                                         {\r
3363                                                 $ko = true;\r
3364                                         }\r
3365                                         $j++;\r
3366                                 }\r
3367                                 if($ko)\r
3368                                 {\r
3369                                         $xmlrpc_val = new xmlrpcval($arr, $GLOBALS['xmlrpcStruct']);\r
3370                                 }\r
3371                                 else\r
3372                                 {\r
3373                                         $xmlrpc_val = new xmlrpcval($arr, $GLOBALS['xmlrpcArray']);\r
3374                                 }\r
3375                                 break;\r
3376                         case 'object':\r
3377                                 if(is_a($php_val, 'xmlrpcval'))\r
3378                                 {\r
3379                                         $xmlrpc_val = $php_val;\r
3380                                 }\r
3381                                 else\r
3382                                 {\r
3383                                         $arr = array();\r
3384                                         while(list($k,$v) = each($php_val))\r
3385                                         {\r
3386                                                 $arr[$k] = php_xmlrpc_encode($v, $options);\r
3387                                         }\r
3388                                         $xmlrpc_val = new xmlrpcval($arr, $GLOBALS['xmlrpcStruct']);\r
3389                                         if (in_array('encode_php_objs', $options))\r
3390                                         {\r
3391                                                 // let's save original class name into xmlrpcval:\r
3392                                                 // might be useful later on...\r
3393                                                 $xmlrpc_val->_php_class = get_class($php_val);\r
3394                                         }\r
3395                                 }\r
3396                                 break;\r
3397                         case 'NULL':\r
3398                                 if (in_array('extension_api', $options))\r
3399                                 {\r
3400                                         $xmlrpc_val = new xmlrpcval('', $GLOBALS['xmlrpcString']);\r
3401                                 }\r
3402                                 if (in_array('null_extension', $options))\r
3403                                 {\r
3404                                         $xmlrpc_val = new xmlrpcval('', $GLOBALS['xmlrpcNull']);\r
3405                                 }\r
3406                                 else\r
3407                                 {\r
3408                                         $xmlrpc_val = new xmlrpcval();\r
3409                                 }\r
3410                                 break;\r
3411                         case 'resource':\r
3412                                 if (in_array('extension_api', $options))\r
3413                                 {\r
3414                                         $xmlrpc_val = new xmlrpcval((int)$php_val, $GLOBALS['xmlrpcInt']);\r
3415                                 }\r
3416                                 else\r
3417                                 {\r
3418                                         $xmlrpc_val = new xmlrpcval();\r
3419                                 }\r
3420                         // catch "user function", "unknown type"\r
3421                         default:\r
3422                                 // giancarlo pinerolo <ping@alt.it>\r
3423                                 // it has to return\r
3424                                 // an empty object in case, not a boolean.\r
3425                                 $xmlrpc_val = new xmlrpcval();\r
3426                                 break;\r
3427                         }\r
3428                         return $xmlrpc_val;\r
3429         }\r
3430 \r
3431         /**\r
3432         * Convert the xml representation of a method response, method request or single\r
3433         * xmlrpc value into the appropriate object (a.k.a. deserialize)\r
3434         * @param string $xml_val\r
3435         * @param array $options\r
3436         * @return mixed false on error, or an instance of either xmlrpcval, xmlrpcmsg or xmlrpcresp\r
3437         */\r
3438         function php_xmlrpc_decode_xml($xml_val, $options=array())\r
3439         {\r
3440                 $GLOBALS['_xh'] = array();\r
3441                 $GLOBALS['_xh']['ac'] = '';\r
3442                 $GLOBALS['_xh']['stack'] = array();\r
3443                 $GLOBALS['_xh']['valuestack'] = array();\r
3444                 $GLOBALS['_xh']['params'] = array();\r
3445                 $GLOBALS['_xh']['pt'] = array();\r
3446                 $GLOBALS['_xh']['isf'] = 0;\r
3447                 $GLOBALS['_xh']['isf_reason'] = '';\r
3448                 $GLOBALS['_xh']['method'] = false;\r
3449                 $GLOBALS['_xh']['rt'] = '';\r
3450                 /// @todo 'guestimate' encoding\r
3451                 $parser = xml_parser_create();\r
3452                 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);\r
3453                 // What if internal encoding is not in one of the 3 allowed?\r
3454                 // we use the broadest one, ie. utf8!\r
3455                 if (!in_array($GLOBALS['xmlrpc_internalencoding'], array('UTF-8', 'ISO-8859-1', 'US-ASCII')))\r
3456                 {\r
3457                         xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');\r
3458                 }\r
3459                 else\r
3460                 {\r
3461                         xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $GLOBALS['xmlrpc_internalencoding']);\r
3462                 }\r
3463                 xml_set_element_handler($parser, 'xmlrpc_se_any', 'xmlrpc_ee');\r
3464                 xml_set_character_data_handler($parser, 'xmlrpc_cd');\r
3465                 xml_set_default_handler($parser, 'xmlrpc_dh');\r
3466                 if(!xml_parse($parser, $xml_val, 1))\r
3467                 {\r
3468                         $errstr = sprintf('XML error: %s at line %d, column %d',\r
3469                                                 xml_error_string(xml_get_error_code($parser)),\r
3470                                                 xml_get_current_line_number($parser), xml_get_current_column_number($parser));\r
3471                         error_log($errstr);\r
3472                         xml_parser_free($parser);\r
3473                         return false;\r
3474                 }\r
3475                 xml_parser_free($parser);\r
3476                 if ($GLOBALS['_xh']['isf'] > 1) // test that $GLOBALS['_xh']['value'] is an obj, too???\r
3477                 {\r
3478                         error_log($GLOBALS['_xh']['isf_reason']);\r
3479                         return false;\r
3480                 }\r
3481                 switch ($GLOBALS['_xh']['rt'])\r
3482                 {\r
3483                         case 'methodresponse':\r
3484                                 $v =& $GLOBALS['_xh']['value'];\r
3485                                 if ($GLOBALS['_xh']['isf'] == 1)\r
3486                                 {\r
3487                                         $vc = $v->structmem('faultCode');\r
3488                                         $vs = $v->structmem('faultString');\r
3489                                         $r = new xmlrpcresp(0, $vc->scalarval(), $vs->scalarval());\r
3490                                 }\r
3491                                 else\r
3492                                 {\r
3493                                         $r = new xmlrpcresp($v);\r
3494                                 }\r
3495                                 return $r;\r
3496                         case 'methodcall':\r
3497                                 $m = new xmlrpcmsg($GLOBALS['_xh']['method']);\r
3498                                 for($i=0; $i < count($GLOBALS['_xh']['params']); $i++)\r
3499                                 {\r
3500                                         $m->addParam($GLOBALS['_xh']['params'][$i]);\r
3501                                 }\r
3502                                 return $m;\r
3503                         case 'value':\r
3504                                 return $GLOBALS['_xh']['value'];\r
3505                         default:\r
3506                                 return false;\r
3507                 }\r
3508         }\r
3509 \r
3510         /**\r
3511         * decode a string that is encoded w/ "chunked" transfer encoding\r
3512         * as defined in rfc2068 par. 19.4.6\r
3513         * code shamelessly stolen from nusoap library by Dietrich Ayala\r
3514         *\r
3515         * @param string $buffer the string to be decoded\r
3516         * @return string\r
3517         */\r
3518         function decode_chunked($buffer)\r
3519         {\r
3520                 // length := 0\r
3521                 $length = 0;\r
3522                 $new = '';\r
3523 \r
3524                 // read chunk-size, chunk-extension (if any) and crlf\r
3525                 // get the position of the linebreak\r
3526                 $chunkend = strpos($buffer,"\r\n") + 2;\r
3527                 $temp = substr($buffer,0,$chunkend);\r
3528                 $chunk_size = hexdec( trim($temp) );\r
3529                 $chunkstart = $chunkend;\r
3530                 while($chunk_size > 0)\r
3531                 {\r
3532                         $chunkend = strpos($buffer, "\r\n", $chunkstart + $chunk_size);\r
3533 \r
3534                         // just in case we got a broken connection\r
3535                         if($chunkend == false)\r
3536                         {\r
3537                                 $chunk = substr($buffer,$chunkstart);\r
3538                                 // append chunk-data to entity-body\r
3539                                 $new .= $chunk;\r
3540                                 $length += strlen($chunk);\r
3541                                 break;\r
3542                         }\r
3543 \r
3544                         // read chunk-data and crlf\r
3545                         $chunk = substr($buffer,$chunkstart,$chunkend-$chunkstart);\r
3546                         // append chunk-data to entity-body\r
3547                         $new .= $chunk;\r
3548                         // length := length + chunk-size\r
3549                         $length += strlen($chunk);\r
3550                         // read chunk-size and crlf\r
3551                         $chunkstart = $chunkend + 2;\r
3552 \r
3553                         $chunkend = strpos($buffer,"\r\n",$chunkstart)+2;\r
3554                         if($chunkend == false)\r
3555                         {\r
3556                                 break; //just in case we got a broken connection\r
3557                         }\r
3558                         $temp = substr($buffer,$chunkstart,$chunkend-$chunkstart);\r
3559                         $chunk_size = hexdec( trim($temp) );\r
3560                         $chunkstart = $chunkend;\r
3561                 }\r
3562                 return $new;\r
3563         }\r
3564 \r
3565         /**\r
3566         * xml charset encoding guessing helper function.\r
3567         * Tries to determine the charset encoding of an XML chunk received over HTTP.\r
3568         * NB: according to the spec (RFC 3023), if text/xml content-type is received over HTTP without a content-type,\r
3569         * we SHOULD assume it is strictly US-ASCII. But we try to be more tolerant of unconforming (legacy?) clients/servers,\r
3570         * which will be most probably using UTF-8 anyway...\r
3571         *\r
3572         * @param string $httpheaders the http Content-type header\r
3573         * @param string $xmlchunk xml content buffer\r
3574         * @param string $encoding_prefs comma separated list of character encodings to be used as default (when mb extension is enabled)\r
3575         *\r
3576         * @todo explore usage of mb_http_input(): does it detect http headers + post data? if so, use it instead of hand-detection!!!\r
3577         */\r
3578         function guess_encoding($httpheader='', $xmlchunk='', $encoding_prefs=null)\r
3579         {\r
3580                 // discussion: see http://www.yale.edu/pclt/encoding/\r
3581                 // 1 - test if encoding is specified in HTTP HEADERS\r
3582 \r
3583                 //Details:\r
3584                 // LWS:           (\13\10)?( |\t)+\r
3585                 // token:         (any char but excluded stuff)+\r
3586                 // quoted string: " (any char but double quotes and cointrol chars)* "\r
3587                 // header:        Content-type = ...; charset=value(; ...)*\r
3588                 //   where value is of type token, no LWS allowed between 'charset' and value\r
3589                 // Note: we do not check for invalid chars in VALUE:\r
3590                 //   this had better be done using pure ereg as below\r
3591                 // Note 2: we might be removing whitespace/tabs that ought to be left in if\r
3592         //   the received charset is a quoted string. But nobody uses such charset names...\r
3593 \r
3594                 /// @todo this test will pass if ANY header has charset specification, not only Content-Type. Fix it?\r
3595                 $matches = array();\r
3596                 if(preg_match('/;\s*charset\s*=([^;]+)/i', $httpheader, $matches))\r
3597                 {\r
3598                         return strtoupper(trim($matches[1], " \t\""));\r
3599                 }\r
3600 \r
3601                 // 2 - scan the first bytes of the data for a UTF-16 (or other) BOM pattern\r
3602                 //     (source: http://www.w3.org/TR/2000/REC-xml-20001006)\r
3603                 //     NOTE: actually, according to the spec, even if we find the BOM and determine\r
3604                 //     an encoding, we should check if there is an encoding specified\r
3605                 //     in the xml declaration, and verify if they match.\r
3606                 /// @todo implement check as described above?\r
3607                 /// @todo implement check for first bytes of string even without a BOM? (It sure looks harder than for cases WITH a BOM)\r
3608                 if(preg_match('/^(\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\x00\x00\xFF\xFE|\xFE\xFF\x00\x00)/', $xmlchunk))\r
3609                 {\r
3610                         return 'UCS-4';\r
3611                 }\r
3612                 elseif(preg_match('/^(\xFE\xFF|\xFF\xFE)/', $xmlchunk))\r
3613                 {\r
3614                         return 'UTF-16';\r
3615                 }\r
3616                 elseif(preg_match('/^(\xEF\xBB\xBF)/', $xmlchunk))\r
3617                 {\r
3618                         return 'UTF-8';\r
3619                 }\r
3620 \r
3621                 // 3 - test if encoding is specified in the xml declaration\r
3622                 // Details:\r
3623                 // SPACE:         (#x20 | #x9 | #xD | #xA)+ === [ \x9\xD\xA]+\r
3624                 // EQ:            SPACE?=SPACE? === [ \x9\xD\xA]*=[ \x9\xD\xA]*\r
3625                 if (preg_match('/^<\?xml\s+version\s*=\s*'. "((?:\"[a-zA-Z0-9_.:-]+\")|(?:'[a-zA-Z0-9_.:-]+'))".\r
3626                         '\s+encoding\s*=\s*' . "((?:\"[A-Za-z][A-Za-z0-9._-]*\")|(?:'[A-Za-z][A-Za-z0-9._-]*'))/",\r
3627                         $xmlchunk, $matches))\r
3628                 {\r
3629                         return strtoupper(substr($matches[2], 1, -1));\r
3630                 }\r
3631 \r
3632                 // 4 - if mbstring is available, let it do the guesswork\r
3633                 // NB: we favour finding an encoding that is compatible with what we can process\r
3634                 if(extension_loaded('mbstring'))\r
3635                 {\r
3636                         if($encoding_prefs)\r
3637                         {\r
3638                                 $enc = mb_detect_encoding($xmlchunk, $encoding_prefs);\r
3639                         }\r
3640                         else\r
3641                         {\r
3642                                 $enc = mb_detect_encoding($xmlchunk);\r
3643                         }\r
3644                         // NB: mb_detect likes to call it ascii, xml parser likes to call it US_ASCII...\r
3645                         // IANA also likes better US-ASCII, so go with it\r
3646                         if($enc == 'ASCII')\r
3647                         {\r
3648                                 $enc = 'US-'.$enc;\r
3649                         }\r
3650                         return $enc;\r
3651                 }\r
3652                 else\r
3653                 {\r
3654                         // no encoding specified: as per HTTP1.1 assume it is iso-8859-1?\r
3655                         // Both RFC 2616 (HTTP 1.1) and 1945 (HTTP 1.0) clearly state that for text/xxx content types\r
3656                         // this should be the standard. And we should be getting text/xml as request and response.\r
3657                         // BUT we have to be backward compatible with the lib, which always used UTF-8 as default...\r
3658                         return $GLOBALS['xmlrpc_defencoding'];\r
3659                 }\r
3660         }\r
3661 \r
3662         /**\r
3663         * Checks if a given charset encoding is present in a list of encodings or\r
3664         * if it is a valid subset of any encoding in the list\r
3665         * @param string $encoding charset to be tested\r
3666         * @param mixed $validlist comma separated list of valid charsets (or array of charsets)\r
3667         */\r
3668         function is_valid_charset($encoding, $validlist)\r
3669         {\r
3670                 $charset_supersets = array(\r
3671                         'US-ASCII' => array ('ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4',\r
3672                                 'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8',\r
3673                                 'ISO-8859-9', 'ISO-8859-10', 'ISO-8859-11', 'ISO-8859-12',\r
3674                                 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'UTF-8',\r
3675                                 'EUC-JP', 'EUC-', 'EUC-KR', 'EUC-CN')\r
3676                 );\r
3677                 if (is_string($validlist))\r
3678                         $validlist = explode(',', $validlist);\r
3679                 if (@in_array(strtoupper($encoding), $validlist))\r
3680                         return true;\r
3681                 else\r
3682                 {\r
3683                         if (array_key_exists($encoding, $charset_supersets))\r
3684                                 foreach ($validlist as $allowed)\r
3685                                         if (in_array($allowed, $charset_supersets[$encoding]))\r
3686                                                 return true;\r
3687                                 return false;\r
3688                 }\r
3689         }\r
3690 \r
3691 ?>