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