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