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