Refactoring ongoing: move http headers parsing away from response into http class...
[plcapi.git] / src / Wrapper.php
1 <?php
2 /**
3  * @author Gaetano Giunta
4  * @copyright (C) 2006-2015 G. Giunta
5  * @license code licensed under the BSD License: see file license.txt
6  */
7
8 namespace PhpXmlRpc;
9
10 /**
11  * PHP-XMLRPC "wrapper" class.
12  * Generate stubs to transparently access xmlrpc methods as php functions and viceversa.
13  * Note: this class implements the PROXY pattern, but it is not named so to avoid confusion with http proxies.
14  *
15  * @todo separate introspection from code generation for func-2-method wrapping
16  * @todo use some better templating system for code generation?
17  * @todo implement method wrapping with preservation of php objs in calls
18  * @todo when wrapping methods without obj rebuilding, use return_type = 'phpvals' (faster)
19  */
20 class Wrapper
21 {
22     /**
23      * Given a string defining a php type or phpxmlrpc type (loosely defined: strings
24      * accepted come from javadoc blocks), return corresponding phpxmlrpc type.
25      * NB: for php 'resource' types returns empty string, since resources cannot be serialized;
26      * for php class names returns 'struct', since php objects can be serialized as xmlrpc structs
27      * for php arrays always return array, even though arrays sometimes serialize as json structs.
28      *
29      * @param string $phptype
30      *
31      * @return string
32      */
33     public function php_2_xmlrpc_type($phptype)
34     {
35         switch (strtolower($phptype)) {
36             case 'string':
37                 return Value::$xmlrpcString;
38             case 'integer':
39             case Value::$xmlrpcInt: // 'int'
40             case Value::$xmlrpcI4:
41                 return Value::$xmlrpcInt;
42             case 'double':
43                 return Value::$xmlrpcDouble;
44             case 'boolean':
45                 return Value::$xmlrpcBoolean;
46             case 'array':
47                 return Value::$xmlrpcArray;
48             case 'object':
49                 return Value::$xmlrpcStruct;
50             case Value::$xmlrpcBase64:
51             case Value::$xmlrpcStruct:
52                 return strtolower($phptype);
53             case 'resource':
54                 return '';
55             default:
56                 if (class_exists($phptype)) {
57                     return Value::$xmlrpcStruct;
58                 } else {
59                     // unknown: might be any 'extended' xmlrpc type
60                     return Value::$xmlrpcValue;
61                 }
62         }
63     }
64
65     /**
66      * Given a string defining a phpxmlrpc type return corresponding php type.
67      *
68      * @param string $xmlrpctype
69      *
70      * @return string
71      */
72     public function xmlrpc_2_php_type($xmlrpctype)
73     {
74         switch (strtolower($xmlrpctype)) {
75             case 'base64':
76             case 'datetime.iso8601':
77             case 'string':
78                 return Value::$xmlrpcString;
79             case 'int':
80             case 'i4':
81                 return 'integer';
82             case 'struct':
83             case 'array':
84                 return 'array';
85             case 'double':
86                 return 'float';
87             case 'undefined':
88                 return 'mixed';
89             case 'boolean':
90             case 'null':
91             default:
92                 // unknown: might be any xmlrpc type
93                 return strtolower($xmlrpctype);
94         }
95     }
96
97     /**
98      * Given a user-defined PHP function, create a PHP 'wrapper' function that can
99      * be exposed as xmlrpc method from an xmlrpc_server object and called from remote
100      * clients (as well as its corresponding signature info).
101      *
102      * Since php is a typeless language, to infer types of input and output parameters,
103      * it relies on parsing the javadoc-style comment block associated with the given
104      * function. Usage of xmlrpc native types (such as datetime.dateTime.iso8601 and base64)
105      * in the @param tag is also allowed, if you need the php function to receive/send
106      * data in that particular format (note that base64 encoding/decoding is transparently
107      * carried out by the lib, while datetime vals are passed around as strings)
108      *
109      * Known limitations:
110      * - only works for user-defined functions, not for PHP internal functions
111      *   (reflection does not support retrieving number/type of params for those)
112      * - functions returning php objects will generate special xmlrpc responses:
113      *   when the xmlrpc decoding of those responses is carried out by this same lib, using
114      *   the appropriate param in php_xmlrpc_decode, the php objects will be rebuilt.
115      *   In short: php objects can be serialized, too (except for their resource members),
116      *   using this function.
117      *   Other libs might choke on the very same xml that will be generated in this case
118      *   (i.e. it has a nonstandard attribute on struct element tags)
119      * - usage of javadoc @param tags using param names in a different order from the
120      *   function prototype is not considered valid (to be fixed?)
121      *
122      * Note that since rel. 2.0RC3 the preferred method to have the server call 'standard'
123      * php functions (ie. functions not expecting a single Request obj as parameter)
124      * is by making use of the functions_parameters_type class member.
125      *
126      * @param string $funcname the name of the PHP user function to be exposed as xmlrpc method; array($obj, 'methodname') and array('class', 'methodname') are ok too
127      * @param string $newfuncname (optional) name for function to be created
128      * @param array $extra_options (optional) array of options for conversion. valid values include:
129      *                              bool  return_source when true, php code w. function definition will be returned, not evaluated
130      *                              bool  encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
131      *                              bool  decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---
132      *                              bool  suppress_warnings  remove from produced xml any runtime warnings due to the php function being invoked
133      *
134      * @return false on error, or an array containing the name of the new php function,
135      *               its signature and docs, to be used in the server dispatch map
136      *
137      * @todo decide how to deal with params passed by ref: bomb out or allow?
138      * @todo finish using javadoc info to build method sig if all params are named but out of order
139      * @todo add a check for params of 'resource' type
140      * @todo add some trigger_errors / error_log when returning false?
141      * @todo what to do when the PHP function returns NULL? we are currently returning an empty string value...
142      * @todo add an option to suppress php warnings in invocation of user function, similar to server debug level 3?
143      * @todo if $newfuncname is empty, we could use create_user_func instead of eval, as it is possibly faster
144      * @todo add a verbatim_object_copy parameter to allow avoiding the same obj instance?
145      */
146     public function wrap_php_function($funcname, $newfuncname = '', $extra_options = array())
147     {
148         $buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true;
149         $prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc';
150         $encode_php_objects = isset($extra_options['encode_php_objs']) ? (bool)$extra_options['encode_php_objs'] : false;
151         $decode_php_objects = isset($extra_options['decode_php_objs']) ? (bool)$extra_options['decode_php_objs'] : false;
152         $catch_warnings = isset($extra_options['suppress_warnings']) && $extra_options['suppress_warnings'] ? '@' : '';
153
154         $exists = false;
155         if (is_string($funcname) && strpos($funcname, '::') !== false) {
156             $funcname = explode('::', $funcname);
157         }
158         if (is_array($funcname)) {
159             if (count($funcname) < 2 || (!is_string($funcname[0]) && !is_object($funcname[0]))) {
160                 error_log('XML-RPC: syntax for function to be wrapped is wrong');
161
162                 return false;
163             }
164             if (is_string($funcname[0])) {
165                 $plainfuncname = implode('::', $funcname);
166             } elseif (is_object($funcname[0])) {
167                 $plainfuncname = get_class($funcname[0]) . '->' . $funcname[1];
168             }
169             $exists = method_exists($funcname[0], $funcname[1]);
170         } else {
171             $plainfuncname = $funcname;
172             $exists = function_exists($funcname);
173         }
174
175         if (!$exists) {
176             error_log('XML-RPC: function to be wrapped is not defined: ' . $plainfuncname);
177
178             return false;
179         } else {
180             // determine name of new php function
181             if ($newfuncname == '') {
182                 if (is_array($funcname)) {
183                     if (is_string($funcname[0])) {
184                         $xmlrpcfuncname = "{$prefix}_" . implode('_', $funcname);
185                     } else {
186                         $xmlrpcfuncname = "{$prefix}_" . get_class($funcname[0]) . '_' . $funcname[1];
187                     }
188                 } else {
189                     $xmlrpcfuncname = "{$prefix}_$funcname";
190                 }
191             } else {
192                 $xmlrpcfuncname = $newfuncname;
193             }
194             while ($buildit && function_exists($xmlrpcfuncname)) {
195                 $xmlrpcfuncname .= 'x';
196             }
197
198             // start to introspect PHP code
199             if (is_array($funcname)) {
200                 $func = new \ReflectionMethod($funcname[0], $funcname[1]);
201                 if ($func->isPrivate()) {
202                     error_log('XML-RPC: method to be wrapped is private: ' . $plainfuncname);
203
204                     return false;
205                 }
206                 if ($func->isProtected()) {
207                     error_log('XML-RPC: method to be wrapped is protected: ' . $plainfuncname);
208
209                     return false;
210                 }
211                 if ($func->isConstructor()) {
212                     error_log('XML-RPC: method to be wrapped is the constructor: ' . $plainfuncname);
213
214                     return false;
215                 }
216                 if ($func->isDestructor()) {
217                     error_log('XML-RPC: method to be wrapped is the destructor: ' . $plainfuncname);
218
219                     return false;
220                 }
221                 if ($func->isAbstract()) {
222                     error_log('XML-RPC: method to be wrapped is abstract: ' . $plainfuncname);
223
224                     return false;
225                 }
226                 /// @todo add more checks for static vs. nonstatic?
227             } else {
228                 $func = new \ReflectionFunction($funcname);
229             }
230             if ($func->isInternal()) {
231                 // Note: from PHP 5.1.0 onward, we will possibly be able to use invokeargs
232                 // instead of getparameters to fully reflect internal php functions ?
233                 error_log('XML-RPC: function to be wrapped is internal: ' . $plainfuncname);
234
235                 return false;
236             }
237
238             // retrieve parameter names, types and description from javadoc comments
239
240             // function description
241             $desc = '';
242             // type of return val: by default 'any'
243             $returns = Value::$xmlrpcValue;
244             // desc of return val
245             $returnsDocs = '';
246             // type + name of function parameters
247             $paramDocs = array();
248
249             $docs = $func->getDocComment();
250             if ($docs != '') {
251                 $docs = explode("\n", $docs);
252                 $i = 0;
253                 foreach ($docs as $doc) {
254                     $doc = trim($doc, " \r\t/*");
255                     if (strlen($doc) && strpos($doc, '@') !== 0 && !$i) {
256                         if ($desc) {
257                             $desc .= "\n";
258                         }
259                         $desc .= $doc;
260                     } elseif (strpos($doc, '@param') === 0) {
261                         // syntax: @param type [$name] desc
262                         if (preg_match('/@param\s+(\S+)(\s+\$\S+)?\s+(.+)/', $doc, $matches)) {
263                             if (strpos($matches[1], '|')) {
264                                 //$paramDocs[$i]['type'] = explode('|', $matches[1]);
265                                 $paramDocs[$i]['type'] = 'mixed';
266                             } else {
267                                 $paramDocs[$i]['type'] = $matches[1];
268                             }
269                             $paramDocs[$i]['name'] = trim($matches[2]);
270                             $paramDocs[$i]['doc'] = $matches[3];
271                         }
272                         $i++;
273                     } elseif (strpos($doc, '@return') === 0) {
274                         // syntax: @return type desc
275                         //$returns = preg_split('/\s+/', $doc);
276                         if (preg_match('/@return\s+(\S+)\s+(.+)/', $doc, $matches)) {
277                             $returns = php_2_xmlrpc_type($matches[1]);
278                             if (isset($matches[2])) {
279                                 $returnsDocs = $matches[2];
280                             }
281                         }
282                     }
283                 }
284             }
285
286             // execute introspection of actual function prototype
287             $params = array();
288             $i = 0;
289             foreach ($func->getParameters() as $paramobj) {
290                 $params[$i] = array();
291                 $params[$i]['name'] = '$' . $paramobj->getName();
292                 $params[$i]['isoptional'] = $paramobj->isOptional();
293                 $i++;
294             }
295
296             // start  building of PHP code to be eval'd
297             $innercode = '';
298             $i = 0;
299             $parsvariations = array();
300             $pars = array();
301             $pnum = count($params);
302             foreach ($params as $param) {
303                 if (isset($paramDocs[$i]['name']) && $paramDocs[$i]['name'] && strtolower($paramDocs[$i]['name']) != strtolower($param['name'])) {
304                     // param name from phpdoc info does not match param definition!
305                     $paramDocs[$i]['type'] = 'mixed';
306                 }
307
308                 if ($param['isoptional']) {
309                     // this particular parameter is optional. save as valid previous list of parameters
310                     $innercode .= "if (\$paramcount > $i) {\n";
311                     $parsvariations[] = $pars;
312                 }
313                 $innercode .= "\$p$i = \$msg->getParam($i);\n";
314                 if ($decode_php_objects) {
315                     $innercode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = php_{$prefix}_decode(\$p$i, array('decode_php_objs'));\n";
316                 } else {
317                     $innercode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = php_{$prefix}_decode(\$p$i);\n";
318                 }
319
320                 $pars[] = "\$p$i";
321                 $i++;
322                 if ($param['isoptional']) {
323                     $innercode .= "}\n";
324                 }
325                 if ($i == $pnum) {
326                     // last allowed parameters combination
327                     $parsvariations[] = $pars;
328                 }
329             }
330
331             $sigs = array();
332             $psigs = array();
333             if (count($parsvariations) == 0) {
334                 // only known good synopsis = no parameters
335                 $parsvariations[] = array();
336                 $minpars = 0;
337             } else {
338                 $minpars = count($parsvariations[0]);
339             }
340
341             if ($minpars) {
342                 // add to code the check for min params number
343                 // NB: this check needs to be done BEFORE decoding param values
344                 $innercode = "\$paramcount = \$msg->getNumParams();\n" .
345                     "if (\$paramcount < $minpars) return new {$prefix}resp(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . "');\n" . $innercode;
346             } else {
347                 $innercode = "\$paramcount = \$msg->getNumParams();\n" . $innercode;
348             }
349
350             $innercode .= "\$np = false;\n";
351             // since there are no closures in php, if we are given an object instance,
352             // we store a pointer to it in a global var...
353             if (is_array($funcname) && is_object($funcname[0])) {
354                 $GLOBALS['xmlrpcWPFObjHolder'][$xmlrpcfuncname] = &$funcname[0];
355                 $innercode .= "\$obj =& \$GLOBALS['xmlrpcWPFObjHolder']['$xmlrpcfuncname'];\n";
356                 $realfuncname = '$obj->' . $funcname[1];
357             } else {
358                 $realfuncname = $plainfuncname;
359             }
360             foreach ($parsvariations as $pars) {
361                 $innercode .= "if (\$paramcount == " . count($pars) . ") \$retval = {$catch_warnings}$realfuncname(" . implode(',', $pars) . "); else\n";
362                 // build a 'generic' signature (only use an appropriate return type)
363                 $sig = array($returns);
364                 $psig = array($returnsDocs);
365                 for ($i = 0; $i < count($pars); $i++) {
366                     if (isset($paramDocs[$i]['type'])) {
367                         $sig[] = $this->php_2_xmlrpc_type($paramDocs[$i]['type']);
368                     } else {
369                         $sig[] = Value::$xmlrpcValue;
370                     }
371                     $psig[] = isset($paramDocs[$i]['doc']) ? $paramDocs[$i]['doc'] : '';
372                 }
373                 $sigs[] = $sig;
374                 $psigs[] = $psig;
375             }
376             $innercode .= "\$np = true;\n";
377             $innercode .= "if (\$np) return new {$prefix}resp(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . "'); else {\n";
378             //$innercode .= "if (\$_xmlrpcs_error_occurred) return new Response(0, $GLOBALS['xmlrpcerr']user, \$_xmlrpcs_error_occurred); else\n";
379             $innercode .= "if (is_a(\$retval, '{$prefix}resp')) return \$retval; else\n";
380             if ($returns == Value::$xmlrpcDateTime || $returns == Value::$xmlrpcBase64) {
381                 $innercode .= "return new {$prefix}resp(new {$prefix}val(\$retval, '$returns'));";
382             } else {
383                 if ($encode_php_objects) {
384                     $innercode .= "return new {$prefix}resp(php_{$prefix}_encode(\$retval, array('encode_php_objs')));\n";
385                 } else {
386                     $innercode .= "return new {$prefix}resp(php_{$prefix}_encode(\$retval));\n";
387                 }
388             }
389             // shall we exclude functions returning by ref?
390             // if($func->returnsReference())
391             //     return false;
392             $code = "function $xmlrpcfuncname(\$msg) {\n" . $innercode . "}\n}";
393             //print_r($code);
394             if ($buildit) {
395                 $allOK = 0;
396                 eval($code . '$allOK=1;');
397                 // alternative
398                 //$xmlrpcfuncname = create_function('$m', $innercode);
399
400                 if (!$allOK) {
401                     error_log('XML-RPC: could not create function ' . $xmlrpcfuncname . ' to wrap php function ' . $plainfuncname);
402
403                     return false;
404                 }
405             }
406
407             /// @todo examine if $paramDocs matches $parsvariations and build array for
408             /// usage as method signature, plus put together a nice string for docs
409
410             $ret = array('function' => $xmlrpcfuncname, 'signature' => $sigs, 'docstring' => $desc, 'signature_docs' => $psigs, 'source' => $code);
411
412             return $ret;
413         }
414     }
415
416     /**
417      * Given a user-defined PHP class or php object, map its methods onto a list of
418      * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc_server
419      * object and called from remote clients (as well as their corresponding signature info).
420      *
421      * @param mixed $classname the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class
422      * @param array $extra_options see the docs for wrap_php_method for more options
423      *                             string method_type 'static', 'nonstatic', 'all' and 'auto' (default); the latter will switch between static and non-static depending on wheter $classname is a class name or object instance
424      *
425      * @return array or false on failure
426      *
427      * @todo get_class_methods will return both static and non-static methods.
428      *       we have to differentiate the action, depending on wheter we recived a class name or object
429      */
430     public function wrap_php_class($classname, $extra_options = array())
431     {
432         $methodfilter = isset($extra_options['method_filter']) ? $extra_options['method_filter'] : '';
433         $methodtype = isset($extra_options['method_type']) ? $extra_options['method_type'] : 'auto';
434
435         $result = array();
436         $mlist = get_class_methods($classname);
437         foreach ($mlist as $mname) {
438             if ($methodfilter == '' || preg_match($methodfilter, $mname)) {
439                 // echo $mlist."\n";
440                 $func = new \ReflectionMethod($classname, $mname);
441                 if (!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract()) {
442                     if (($func->isStatic && ($methodtype == 'all' || $methodtype == 'static' || ($methodtype == 'auto' && is_string($classname)))) ||
443                         (!$func->isStatic && ($methodtype == 'all' || $methodtype == 'nonstatic' || ($methodtype == 'auto' && is_object($classname))))
444                     ) {
445                         $methodwrap = wrap_php_function(array($classname, $mname), '', $extra_options);
446                         if ($methodwrap) {
447                             $result[$methodwrap['function']] = $methodwrap['function'];
448                         }
449                     }
450                 }
451             }
452         }
453
454         return $result;
455     }
456
457     /**
458      * Given an xmlrpc client and a method name, register a php wrapper function
459      * that will call it and return results using native php types for both
460      * params and results. The generated php function will return a Response
461      * object for failed xmlrpc calls.
462      *
463      * Known limitations:
464      * - server must support system.methodsignature for the wanted xmlrpc method
465      * - for methods that expose many signatures, only one can be picked (we
466      *   could in principle check if signatures differ only by number of params
467      *   and not by type, but it would be more complication than we can spare time)
468      * - nested xmlrpc params: the caller of the generated php function has to
469      *   encode on its own the params passed to the php function if these are structs
470      *   or arrays whose (sub)members include values of type datetime or base64
471      *
472      * Notes: the connection properties of the given client will be copied
473      * and reused for the connection used during the call to the generated
474      * php function.
475      * Calling the generated php function 'might' be slow: a new xmlrpc client
476      * is created on every invocation and an xmlrpc-connection opened+closed.
477      * An extra 'debug' param is appended to param list of xmlrpc method, useful
478      * for debugging purposes.
479      *
480      * @param Client $client an xmlrpc client set up correctly to communicate with target server
481      * @param string $methodname the xmlrpc method to be mapped to a php function
482      * @param array $extra_options array of options that specify conversion details. valid options include
483      *                              integer       signum      the index of the method signature to use in mapping (if method exposes many sigs)
484      *                              integer       timeout     timeout (in secs) to be used when executing function/calling remote method
485      *                              string        protocol    'http' (default), 'http11' or 'https'
486      *                              string        new_function_name the name of php function to create. If unspecified, lib will pick an appropriate name
487      *                              string        return_source if true return php code w. function definition instead fo function name
488      *                              bool          encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
489      *                              bool          decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---
490      *                              mixed         return_on_fault a php value to be returned when the xmlrpc call fails/returns a fault response (by default the Response object is returned in this case). If a string is used, '%faultCode%' and '%faultString%' tokens will be substituted with actual error values
491      *                              bool          debug        set it to 1 or 2 to see debug results of querying server for method synopsis
492      *
493      * @return string the name of the generated php function (or false) - OR AN ARRAY...
494      */
495     public function wrap_xmlrpc_method($client, $methodname, $extra_options = 0, $timeout = 0, $protocol = '', $newfuncname = '')
496     {
497         // mind numbing: let caller use sane calling convention (as per javadoc, 3 params),
498         // OR the 2.0 calling convention (no options) - we really love backward compat, don't we?
499         if (!is_array($extra_options)) {
500             $signum = $extra_options;
501             $extra_options = array();
502         } else {
503             $signum = isset($extra_options['signum']) ? (int)$extra_options['signum'] : 0;
504             $timeout = isset($extra_options['timeout']) ? (int)$extra_options['timeout'] : 0;
505             $protocol = isset($extra_options['protocol']) ? $extra_options['protocol'] : '';
506             $newfuncname = isset($extra_options['new_function_name']) ? $extra_options['new_function_name'] : '';
507         }
508         //$encode_php_objects = in_array('encode_php_objects', $extra_options);
509         //$verbatim_client_copy = in_array('simple_client_copy', $extra_options) ? 1 :
510         //      in_array('build_class_code', $extra_options) ? 2 : 0;
511
512         $encode_php_objects = isset($extra_options['encode_php_objs']) ? (bool)$extra_options['encode_php_objs'] : false;
513         $decode_php_objects = isset($extra_options['decode_php_objs']) ? (bool)$extra_options['decode_php_objs'] : false;
514         // it seems like the meaning of 'simple_client_copy' here is swapped wrt client_copy_mode later on...
515         $simple_client_copy = isset($extra_options['simple_client_copy']) ? (int)($extra_options['simple_client_copy']) : 0;
516         $buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true;
517         $prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc';
518         if (isset($extra_options['return_on_fault'])) {
519             $decode_fault = true;
520             $fault_response = $extra_options['return_on_fault'];
521         } else {
522             $decode_fault = false;
523             $fault_response = '';
524         }
525         $debug = isset($extra_options['debug']) ? ($extra_options['debug']) : 0;
526
527         $msgclass = $prefix . 'msg';
528         $valclass = $prefix . 'val';
529         $decodefunc = 'php_' . $prefix . '_decode';
530
531         $msg = new $msgclass('system.methodSignature');
532         $msg->addparam(new $valclass($methodname));
533         $client->setDebug($debug);
534         $response = $client->send($msg, $timeout, $protocol);
535         if ($response->faultCode()) {
536             error_log('XML-RPC: could not retrieve method signature from remote server for method ' . $methodname);
537
538             return false;
539         } else {
540             $msig = $response->value();
541             if ($client->return_type != 'phpvals') {
542                 $msig = $decodefunc($msig);
543             }
544             if (!is_array($msig) || count($msig) <= $signum) {
545                 error_log('XML-RPC: could not retrieve method signature nr.' . $signum . ' from remote server for method ' . $methodname);
546
547                 return false;
548             } else {
549                 // pick a suitable name for the new function, avoiding collisions
550                 if ($newfuncname != '') {
551                     $xmlrpcfuncname = $newfuncname;
552                 } else {
553                     // take care to insure that methodname is translated to valid
554                     // php function name
555                     $xmlrpcfuncname = $prefix . '_' . preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
556                             array('_', ''), $methodname);
557                 }
558                 while ($buildit && function_exists($xmlrpcfuncname)) {
559                     $xmlrpcfuncname .= 'x';
560                 }
561
562                 $msig = $msig[$signum];
563                 $mdesc = '';
564                 // if in 'offline' mode, get method description too.
565                 // in online mode, favour speed of operation
566                 if (!$buildit) {
567                     $msg = new $msgclass('system.methodHelp');
568                     $msg->addparam(new $valclass($methodname));
569                     $response = $client->send($msg, $timeout, $protocol);
570                     if (!$response->faultCode()) {
571                         $mdesc = $response->value();
572                         if ($client->return_type != 'phpvals') {
573                             $mdesc = $mdesc->scalarval();
574                         }
575                     }
576                 }
577
578                 $results = $this->build_remote_method_wrapper_code($client, $methodname,
579                     $xmlrpcfuncname, $msig, $mdesc, $timeout, $protocol, $simple_client_copy,
580                     $prefix, $decode_php_objects, $encode_php_objects, $decode_fault,
581                     $fault_response);
582
583                 //print_r($code);
584                 if ($buildit) {
585                     $allOK = 0;
586                     eval($results['source'] . '$allOK=1;');
587                     // alternative
588                     //$xmlrpcfuncname = create_function('$m', $innercode);
589                     if ($allOK) {
590                         return $xmlrpcfuncname;
591                     } else {
592                         error_log('XML-RPC: could not create function ' . $xmlrpcfuncname . ' to wrap remote method ' . $methodname);
593
594                         return false;
595                     }
596                 } else {
597                     $results['function'] = $xmlrpcfuncname;
598
599                     return $results;
600                 }
601             }
602         }
603     }
604
605     /**
606      * Similar to wrap_xmlrpc_method, but will generate a php class that wraps
607      * all xmlrpc methods exposed by the remote server as own methods.
608      * For more details see wrap_xmlrpc_method.
609      *
610      * @param Client $client the client obj all set to query the desired server
611      * @param array $extra_options list of options for wrapped code
612      *
613      * @return mixed false on error, the name of the created class if all ok or an array with code, class name and comments (if the appropriatevoption is set in extra_options)
614      */
615     public function wrap_xmlrpc_server($client, $extra_options = array())
616     {
617         $methodfilter = isset($extra_options['method_filter']) ? $extra_options['method_filter'] : '';
618         //$signum = isset($extra_options['signum']) ? (int)$extra_options['signum'] : 0;
619         $timeout = isset($extra_options['timeout']) ? (int)$extra_options['timeout'] : 0;
620         $protocol = isset($extra_options['protocol']) ? $extra_options['protocol'] : '';
621         $newclassname = isset($extra_options['new_class_name']) ? $extra_options['new_class_name'] : '';
622         $encode_php_objects = isset($extra_options['encode_php_objs']) ? (bool)$extra_options['encode_php_objs'] : false;
623         $decode_php_objects = isset($extra_options['decode_php_objs']) ? (bool)$extra_options['decode_php_objs'] : false;
624         $verbatim_client_copy = isset($extra_options['simple_client_copy']) ? !($extra_options['simple_client_copy']) : true;
625         $buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true;
626         $prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc';
627
628         $msgclass = $prefix . 'msg';
629         //$valclass = $prefix.'val';
630         $decodefunc = 'php_' . $prefix . '_decode';
631
632         $msg = new $msgclass('system.listMethods');
633         $response = $client->send($msg, $timeout, $protocol);
634         if ($response->faultCode()) {
635             error_log('XML-RPC: could not retrieve method list from remote server');
636
637             return false;
638         } else {
639             $mlist = $response->value();
640             if ($client->return_type != 'phpvals') {
641                 $mlist = $decodefunc($mlist);
642             }
643             if (!is_array($mlist) || !count($mlist)) {
644                 error_log('XML-RPC: could not retrieve meaningful method list from remote server');
645
646                 return false;
647             } else {
648                 // pick a suitable name for the new function, avoiding collisions
649                 if ($newclassname != '') {
650                     $xmlrpcclassname = $newclassname;
651                 } else {
652                     $xmlrpcclassname = $prefix . '_' . preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
653                             array('_', ''), $client->server) . '_client';
654                 }
655                 while ($buildit && class_exists($xmlrpcclassname)) {
656                     $xmlrpcclassname .= 'x';
657                 }
658
659                 /// @todo add function setdebug() to new class, to enable/disable debugging
660                 $source = "class $xmlrpcclassname\n{\nvar \$client;\n\n";
661                 $source .= "function $xmlrpcclassname()\n{\n";
662                 $source .= $this->build_client_wrapper_code($client, $verbatim_client_copy, $prefix);
663                 $source .= "\$this->client =& \$client;\n}\n\n";
664                 $opts = array('simple_client_copy' => 2, 'return_source' => true,
665                     'timeout' => $timeout, 'protocol' => $protocol,
666                     'encode_php_objs' => $encode_php_objects, 'prefix' => $prefix,
667                     'decode_php_objs' => $decode_php_objects,
668                 );
669                 /// @todo build javadoc for class definition, too
670                 foreach ($mlist as $mname) {
671                     if ($methodfilter == '' || preg_match($methodfilter, $mname)) {
672                         $opts['new_function_name'] = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
673                             array('_', ''), $mname);
674                         $methodwrap = wrap_xmlrpc_method($client, $mname, $opts);
675                         if ($methodwrap) {
676                             if (!$buildit) {
677                                 $source .= $methodwrap['docstring'];
678                             }
679                             $source .= $methodwrap['source'] . "\n";
680                         } else {
681                             error_log('XML-RPC: will not create class method to wrap remote method ' . $mname);
682                         }
683                     }
684                 }
685                 $source .= "}\n";
686                 if ($buildit) {
687                     $allOK = 0;
688                     eval($source . '$allOK=1;');
689                     // alternative
690                     //$xmlrpcfuncname = create_function('$m', $innercode);
691                     if ($allOK) {
692                         return $xmlrpcclassname;
693                     } else {
694                         error_log('XML-RPC: could not create class ' . $xmlrpcclassname . ' to wrap remote server ' . $client->server);
695
696                         return false;
697                     }
698                 } else {
699                     return array('class' => $xmlrpcclassname, 'code' => $source, 'docstring' => '');
700                 }
701             }
702         }
703     }
704
705     /**
706      * Given the necessary info, build php code that creates a new function to
707      * invoke a remote xmlrpc method.
708      * Take care that no full checking of input parameters is done to ensure that
709      * valid php code is emitted.
710      * Note: real spaghetti code follows...
711      */
712     protected function build_remote_method_wrapper_code($client, $methodname, $xmlrpcfuncname,
713                                                         $msig, $mdesc = '', $timeout = 0, $protocol = '', $client_copy_mode = 0, $prefix = 'xmlrpc',
714                                                         $decode_php_objects = false, $encode_php_objects = false, $decode_fault = false,
715                                                         $fault_response = '')
716     {
717         $code = "function $xmlrpcfuncname (";
718         if ($client_copy_mode < 2) {
719             // client copy mode 0 or 1 == partial / full client copy in emitted code
720             $innercode = $this->build_client_wrapper_code($client, $client_copy_mode, $prefix);
721             $innercode .= "\$client->setDebug(\$debug);\n";
722             $this_ = '';
723         } else {
724             // client copy mode 2 == no client copy in emitted code
725             $innercode = '';
726             $this_ = 'this->';
727         }
728         $innercode .= "\$msg = new {$prefix}msg('$methodname');\n";
729
730         if ($mdesc != '') {
731             // take care that PHP comment is not terminated unwillingly by method description
732             $mdesc = "/**\n* " . str_replace('*/', '* /', $mdesc) . "\n";
733         } else {
734             $mdesc = "/**\nFunction $xmlrpcfuncname\n";
735         }
736
737         // param parsing
738         $plist = array();
739         $pcount = count($msig);
740         for ($i = 1; $i < $pcount; $i++) {
741             $plist[] = "\$p$i";
742             $ptype = $msig[$i];
743             if ($ptype == 'i4' || $ptype == 'int' || $ptype == 'boolean' || $ptype == 'double' ||
744                 $ptype == 'string' || $ptype == 'dateTime.iso8601' || $ptype == 'base64' || $ptype == 'null'
745             ) {
746                 // only build directly xmlrpcvals when type is known and scalar
747                 $innercode .= "\$p$i = new {$prefix}val(\$p$i, '$ptype');\n";
748             } else {
749                 if ($encode_php_objects) {
750                     $innercode .= "\$p$i = php_{$prefix}_encode(\$p$i, array('encode_php_objs'));\n";
751                 } else {
752                     $innercode .= "\$p$i = php_{$prefix}_encode(\$p$i);\n";
753                 }
754             }
755             $innercode .= "\$msg->addparam(\$p$i);\n";
756             $mdesc .= '* @param ' . $this->xmlrpc_2_php_type($ptype) . " \$p$i\n";
757         }
758         if ($client_copy_mode < 2) {
759             $plist[] = '$debug=0';
760             $mdesc .= "* @param int \$debug when 1 (or 2) will enable debugging of the underlying {$prefix} call (defaults to 0)\n";
761         }
762         $plist = implode(', ', $plist);
763         $mdesc .= '* @return ' . $this->xmlrpc_2_php_type($msig[0]) . " (or an {$prefix}resp obj instance if call fails)\n*/\n";
764
765         $innercode .= "\$res = \${$this_}client->send(\$msg, $timeout, '$protocol');\n";
766         if ($decode_fault) {
767             if (is_string($fault_response) && ((strpos($fault_response, '%faultCode%') !== false) || (strpos($fault_response, '%faultString%') !== false))) {
768                 $respcode = "str_replace(array('%faultCode%', '%faultString%'), array(\$res->faultCode(), \$res->faultString()), '" . str_replace("'", "''", $fault_response) . "')";
769             } else {
770                 $respcode = var_export($fault_response, true);
771             }
772         } else {
773             $respcode = '$res';
774         }
775         if ($decode_php_objects) {
776             $innercode .= "if (\$res->faultcode()) return $respcode; else return php_{$prefix}_decode(\$res->value(), array('decode_php_objs'));";
777         } else {
778             $innercode .= "if (\$res->faultcode()) return $respcode; else return php_{$prefix}_decode(\$res->value());";
779         }
780
781         $code = $code . $plist . ") {\n" . $innercode . "\n}\n";
782
783         return array('source' => $code, 'docstring' => $mdesc);
784     }
785
786     /**
787      * Given necessary info, generate php code that will rebuild a client object
788      * Take care that no full checking of input parameters is done to ensure that
789      * valid php code is emitted.
790      */
791     protected function build_client_wrapper_code($client, $verbatim_client_copy, $prefix = 'xmlrpc')
792     {
793         $code = "\$client = new {$prefix}_client('" . str_replace("'", "\'", $client->path) .
794             "', '" . str_replace("'", "\'", $client->server) . "', $client->port);\n";
795
796         // copy all client fields to the client that will be generated runtime
797         // (this provides for future expansion or subclassing of client obj)
798         if ($verbatim_client_copy) {
799             foreach ($client as $fld => $val) {
800                 if ($fld != 'debug' && $fld != 'return_type') {
801                     $val = var_export($val, true);
802                     $code .= "\$client->$fld = $val;\n";
803                 }
804             }
805         }
806         // only make sure that client always returns the correct data type
807         $code .= "\$client->return_type = '{$prefix}vals';\n";
808         //$code .= "\$client->setDebug(\$debug);\n";
809         return $code;
810     }
811 }