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