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