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