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