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