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