topical media & game development
mashup-delicious-06-example6-9-lib-xmlrpc-wrappers.inc / inc
<?php
PHP-XMLRPC "wrapper" functions
Generate stubs to transparently access xmlrpc methods as php functions and viceversa
version:
@copyright G. Giunta (C) 2006
author: Gaetano Giunta
@todo separate introspection from code generation for func-2-method wrapping
@todo use some better templating system from code generation?
@todo implement method wrapping with preservation of php objs in calls
@todo when wrapping methods without obj rebuilding, use return_type = 'phpvals' (faster)
@todo implement self-parsing of php code for PHP <= 4
// requires: xmlrpc.inc
Given a string defining a php type or phpxmlrpc type (loosely defined: strings
accepted come from javadoc blocks), return corresponding phpxmlrpc type.
NB: for php 'resource' types returns empty string, since resources cannot be serialized;
for php class names returns 'struct', since php objects can be serialized as xmlrpc structs
parameter: string
function php_2_xmlrpc_type(phptype)
{
switch(strtolower(GLOBALS['xmlrpcString'];
case 'integer':
case GLOBALS['xmlrpcI4']:
return GLOBALS['xmlrpcDouble'];
case 'boolean':
return GLOBALS['xmlrpcArray'];
case 'object':
return GLOBALS['xmlrpcBase64']:
case phptype);
case 'resource':
return '';
default:
if(class_exists(GLOBALS['xmlrpcStruct'];
}
else
{
// unknown: might be any 'extended' xmlrpc type
return
Given a string defining a phpxmlrpc type return corresponding php type.
parameter: string xmlrpctype
returns: string
function xmlrpc_2_php_type(xmlrpctype))
{
case 'base64':
case 'datetime.iso8601':
case 'string':
return xmlrpctype);
}
}
Given a user-defined PHP function, create a PHP 'wrapper' function that can
be exposed as xmlrpc method from an xmlrpc_server object and called from remote
clients (as well as its corresponding signature info).
Since php is a typeless language, to infer types of input and output parameters,
it relies on parsing the javadoc-style comment block associated with the given
function. Usage of xmlrpc native types (such as datetime.dateTime.iso8601 and base64)
in the
parameter: tag is also allowed, if you need the php function to receive/send
data in that particular format (note that base64 encoding/decoding is transparently
carried out by the lib, while datetime vals are passed around as strings)
Known limitations:
- requires PHP 5.0.3 +
- only works for user-defined functions, not for PHP internal functions
(reflection does not support retrieving number/type of params for those)
- functions returning php objects will generate special xmlrpc responses:
when the xmlrpc decoding of those responses is carried out by this same lib, using
the appropriate param in php_xmlrpc_decode, the php objects will be rebuilt.
In short: php objects can be serialized, too (except for their resource members),
using this function.
Other libs might choke on the very same xml that will be generated in this case
(i.e. it has a nonstandard attribute on struct element tags)
- usage of javadoc
parameter: tags using param names in a different order from the
function prototype is not considered valid (to be fixed?)
Note that since rel. 2.0RC3 the preferred method to have the server call 'standard'
php functions (ie. functions not expecting a single xmlrpcmsg obj as parameter)
is by making use of the functions_parameters_type class member.
parameter: string obj, 'methodname') might be ok too, in the future...
parameter: string extra_options (optional) array of options for conversion. valid values include:
bool return_source when true, php code w. function definition will be returned, not evaluated
bool encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
bool decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---
bool suppress_warnings remove from produced xml any runtime warnings due to the php function being invoked
returns: false on error, or an array containing the name of the new php function,
its signature and docs, to be used in the server dispatch map
@todo decide how to deal with params passed by ref: bomb out or allow?
@todo finish using javadoc info to build method sig if all params are named but out of order
@todo add a check for params of 'resource' type
@todo add some trigger_errors / error_log when returning false?
@todo what to do when the PHP function returns NULL? we are currently an empty string value...
@todo add an option to suppress php warnings in invocation of user function, similar to server debug level 3?
function wrap_php_function(newfuncname='', buildit = isset(extra_options['return_source']) : true;
extra_options['prefix']) ? encode_php_objects = isset(extra_options['encode_php_objs'] : false;
extra_options['decode_php_objs']) ? (bool)catch_warnings = isset(extra_options['suppress_warnings'] ? '@' : '';
if(version_compare(phpversion(), '5.0.3') == -1)
{
// up to php 5.0.3 some useful reflection methods were missing
error_log('XML-RPC: cannot not wrap php functions unless running php version bigger than 5.0.3');
return false;
}
if((is_array(funcname[0], funcname))
{
error_log('XML-RPC: function to be wrapped is not defined: '.newfuncname == '')
{
if(is_array(xmlrpcfuncname = "{funcname);
}
else
{
prefix}_xmlrpcfuncname = buildit && function_exists(xmlrpcfuncname .= 'x';
}
// start to introspect PHP code
funcname);
if(funcname);
return false;
}
// retrieve parameter names, types and description from javadoc comments
// function description
returns = returnsDocs = '';
// type + name of function parameters
docs = docs != '')
{
docs);
docs as doc = trim(doc) && strpos(i)
{
if(desc .= "\n";
}
doc;
}
elseif(strpos(name] desc
if(preg_match('/@param\s+(\S+)(\s+$\S+)?\s+(.+)/', matches))
{
if(strpos(paramDocs[matches[1]);
i]['type'] = 'mixed';
}
else
{
i]['type'] = paramDocs[matches[2]);
i]['doc'] = i++;
}
elseif(strpos(returns = preg_split('/\s+/', doc, returns = php_2_xmlrpc_type(matches[2]))
{
matches[2];
}
}
}
}
}
// execute introspection of actual function prototype
i = 0;
foreach(paramobj)
{
i] = array();
i]['name'] = 'paramobj->getName();
i]['isoptional'] = i++;
}
// start building of PHP code to be eval'd
i = 0;
pars = array();
params);
foreach(param)
{
if (isset(i]['name']) && i]['name'] && strtolower(i]['name']) != strtolower(paramDocs[param['isoptional'])
{
// this particular parameter is optional. save as valid previous list of parameters
i) {\n";
pars;
}
i = $msg->getParam(decode_php_objects)
{
i}->kindOf() == 'scalar') $pi}->scalarval(); else $pprefix}_decode($pinnercode .= "if ($p{i = $p{i = php_{i);\n";
}
i";
param['isoptional'])
{
i == parsvariations[] = sigs = array();
parsvariations) == 0)
{
// only known good synopsis = no parameters
minpars = 0;
}
else
{
parsvariations[0]);
}
if(innercode = "$paramcount = $msg->getNumParams();\n" .
"if ($paramcount < prefix}resp(0, {GLOBALS['xmlrpcstr']['incorrect_params']}');\n" . innercode = "$paramcount = $msg->getNumParams();\n" . innercode .= "$np = false;\n";
foreach(pars)
{
pars) . ") $retval = {funcname(" . implode(',', sig = array(psig = array(i=0; pars); paramDocs[sig[] = php_2_xmlrpc_type(i]['type']);
}
else
{
GLOBALS['xmlrpcValue'];
}
paramDocs[paramDocs[sigs[] = psigs[] = innercode .= "$np = true;\n";
prefix}resp(0, {GLOBALS['xmlrpcstr']['incorrect_params']}'); else {\n";
//GLOBALS['xmlrpcerr']user, $_xmlrpcs_error_occurred); else\n";
prefix}resp')) return $retval; else\n";
if(GLOBALS['xmlrpcDateTime'] || GLOBALS['xmlrpcBase64'])
{
prefix}resp(new {returns'));";
}
else
{
if (innercode .= "return new {prefix}_encode($retval, array('encode_php_objs')));\n";
else
prefix}resp(php_{func->returnsReference())
// return false;
xmlrpcfuncname($msg) {\n" . code);
if (allOK = 0;
eval(allOK=1;');
// alternative
//m', allOK)
{
error_log('XML-RPC: could not create function '.funcname);
return false;
}
}
@todo examine if
parsvariations and build array for
usage as method signature, plus put together a nice string for docs
xmlrpcfuncname, 'signature' => desc, 'signature_docs' => code);
return
Given an xmlrpc client and a method name, register a php wrapper function
that will call it and return results using native php types for both
params and results. The generated php function will return an xmlrpcresp
oject for failed xmlrpc calls
Known limitations:
9 * - server must support system.methodsignature for the wanted xmlrpc method
- for methods that expose many signatures, only one can be picked (we
could in priciple check if signatures differ only by number of params
and not by type, but it would be more complication than we can spare time)
- nested xmlrpc params: the caller of the generated php function has to
encode on its own the params passed to the php function if these are structs
or arrays whose (sub)members include values of type datetime or base64
Notes: the connection properties of the given client will be copied
and reused for the connection used during the call to the generated
php function.
Calling the generated php function 'might' be slow: a new xmlrpc client
is created on every invocation and an xmlrpc-connection opened+closed.
An extra 'debug' param is appended to param list of xmlrpc method, useful
for debugging purposes.
parameter: xmlrpc_client client an xmlrpc client set up correctly to communicate with target server
parameter: string extra_options array of options that specify conversion details. valid ptions include
integer signum the index of the method signature to use in mapping (if method exposes many sigs)
integer timeout timeout (in secs) to be used when executing function/calling remote method
string protocol 'http' (default), 'http11' or 'https'
string new_function_name the name of php function to create. If unsepcified, lib will pick an appropriate name
string return_source if true return php code w. function definition instead fo function name
bool encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
bool decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---
returns: string the name of the generated php function (or false) - OR AN ARRAY...
function wrap_xmlrpc_method(methodname, timeout=0, newfuncname='')
{
// mind numbing: let caller use sane calling convention (as per javadoc, 3 params),
// OR the 2.0 calling convention (no ptions) - we really love backward compat, don't we?
if (!is_array(signum = extra_options = array();
}
else
{
extra_options['signum']) ? (int)timeout = isset(extra_options['timeout'] : 0;
extra_options['protocol']) ? newfuncname = isset(extra_options['new_function_name'] : '';
}
//extra_options);
//extra_options) ? 1 :
// in_array('build_class_code', encode_php_objects = isset(extra_options['encode_php_objs'] : false;
extra_options['decode_php_objs']) ? (bool)simple_client_copy = isset(extra_options['simple_client_copy']) : 0;
extra_options['return_source']) ? !(prefix = isset(extra_options['prefix'] : 'xmlrpc';
prefix.'msg';
prefix.'val';
prefix.'_decode';
msgclass('system.methodSignature');
valclass(response =& msg, protocol);
if(methodname);
return false;
}
else
{
response->value();
if (msig = msig);
}
if(!is_array(msig) <= signum.' from remote server for method '.newfuncname != '')
{
newfuncname;
}
else
{
// take care to insure that methodname is translated to valid
// php function name
prefix.'_'.preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
array('_', ''), buildit && function_exists(xmlrpcfuncname .= 'x';
}
msig[mdesc = '';
// if in 'offline' mode, get method description too.
// in online mode, favour speed of operation
if(!msg =& new msg->addparam(new methodname));
client->send(timeout, response->faultCode())
{
response->value();
if (mdesc = results = build_remote_method_wrapper_code(methodname,
msig, timeout, simple_client_copy,
decode_php_objects, code);
if (allOK = 0;
eval(allOK=1;');
// alternative
//m', allOK)
{
return xmlrpcfuncname.' to wrap remote method '.results['function'] = results;
}
}
}
}
Similar to wrap_xmlrpc_method, but will generate a php class that wraps
all xmlrpc methods exposed by the remote server as own methods.
For more details see wrap_xmlrpc_method.
parameter: xmlrpc_client extra_options list of options for wrapped code
returns: 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)
function wrap_xmlrpc_server(extra_options=array())
{
extra_options['method_filter']) ? signum = isset(extra_options['signum'] : 0;
extra_options['timeout']) ? (int)protocol = isset(extra_options['protocol'] : '';
extra_options['new_class_name']) ? encode_php_objects = isset(extra_options['encode_php_objs'] : false;
extra_options['decode_php_objs']) ? (bool)verbatim_client_copy = isset(extra_options['simple_client_copy']) : true;
extra_options['return_source']) ? !(prefix = isset(extra_options['prefix'] : 'xmlrpc';
prefix.'msg';
//prefix.'val';
prefix.'_decode';
msgclass('system.listMethods');
client->send(timeout, response->faultCode())
{
error_log('XML-RPC: could not retrieve method list from remote server');
return false;
}
else
{
response->value();
if (mlist = mlist);
}
if(!is_array(mlist))
{
error_log('XML-RPC: could not retrieve meaningful method list from remote server');
return false;
}
else
{
// pick a suitable name for the new function, avoiding collisions
if(xmlrpcclassname = xmlrpcclassname = client->server).'_client';
}
while(xmlrpcclassname))
{
@todo add function setdebug() to new class, to enable/disable debugging
source = "class
source .= "function
source .= build_client_wrapper_code(
verbatim_client_copy,
source .= "$this->client =& $client;\n}\n\n";
timeout, 'protocol' =>
encode_php_objects, 'prefix' =>
decode_php_objects
);
@todo build javadoc for class definition, too
foreach(
mname)
{
if (
methodfilter,
opts['new_function_name'] = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
array('_', ''),
methodwrap = wrap_xmlrpc_method(
mname,
methodwrap)
{
if (!
source .=
source .=
mname);
}
}
}
buildit)
{
source.'
xmlrpcfuncname = create_function('
innercode);
if(
xmlrpcclassname;
}
else
{
error_log('XML-RPC: could not create class '.
client->server);
return false;
}
}
else
{
return array('class' =>
source, 'docstring' => '');
}
}
}
}
Given the necessary info, build php code that creates a new function to
invoke a remote xmlrpc method.
Take care that no full checking of input parameters is done to ensure that
valid php code is emitted.
Note: real spaghetti code follows...
@access private
function build_remote_method_wrapper_code(methodname, msig, timeout=0, client_copy_mode=0, decode_php_objects=false, code = "function client_copy_mode < 2)
{
// client copy mode 0 or 1 == partial / full client copy in emitted code
client, prefix);
this_ = '';
}
else
{
// client copy mode 2 == no client copy in emitted code
this_ = 'this->';
}
prefix}msg('mdesc != '')
{
// take care that PHP comment is not terminated unwillingly by method description
\n* ".str_replace('
', '* /', mdesc)."\n";
}
else
{
\nFunction xmlrpcfuncname\n";
}
// param parsing
pcount = count(i = 1; pcount; plist[] = "$pptype = i];
if(ptype == 'int' || ptype == 'double' ||
ptype == 'dateTime.iso8601' || ptype == 'null')
{
// only build directly xmlrpcvals when type is known and scalar
i =& new {i, 'encode_php_objects)
{
i =& php_{i, array('encode_php_obs'));\n";
}
else
{
i =& php_{i);\n";
}
}
i);\n";
ptype)." $pclient_copy_mode < 2)
{
debug=0';
prefix} call (defaults to 0)\n";
}
plist);
msig[0])." (or an {innercode .= "$res =& ${timeout, 'decode_php_objects)
{
prefix}_decode($res->value(), array('decode_php_objs'));";
}
else
{
prefix}_decode($res->value());";
}
code . innercode . "\n}\n";
return array('source' => mdesc);
}
Given necessary info, generate php code that will rebuild a client object
Take care that no full checking of input parameters is done to ensure that
valid php code is emitted.
@access private
function build_client_wrapper_code(verbatim_client_copy, code = "$client =& new {client->path).
"', '" . str_replace("'", "\'", client->port);\n";
// copy all client fields to the client that will be generated runtime
// (this provides for future expansion or subclassing of client obj)
if (client as val)
{
if(fld != 'return_type')
{
val, true);
fld = code .= "$client->return_type = '{code .= "$client->setDebug($debug);\n";
return
(C) Æliens
20/2/2008
You may not copy or print any of this material without explicit permission of the author or the publisher.
In case of other copyright issues, contact the author.