OSDN Git Service

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