X-Git-Url: http://git.onelab.eu/?a=blobdiff_plain;f=src%2FWrapper.php;h=10aae52eaf6d4842bd6fb433938f597e30e33dd4;hb=fc4f17849d8bb022c3b8ff38a2bed1d1c188ac7f;hp=4b70dc18ec81fc15411a5d31a6c9796305df2655;hpb=fad2b474319b54adea5d1b16c135b7fde389c8dc;p=plcapi.git diff --git a/src/Wrapper.php b/src/Wrapper.php index 4b70dc1..10aae52 100644 --- a/src/Wrapper.php +++ b/src/Wrapper.php @@ -18,7 +18,7 @@ namespace PhpXmlRpc; */ class Wrapper { - /// used to hold a reference to object instances whose methods get wrapped by wrap_php_function(), in 'create source' mode + /// used to hold a reference to object instances whose methods get wrapped by wrapPhpFunction(), in 'create source' mode public static $objHolder = array(); /** @@ -34,7 +34,7 @@ class Wrapper * * @return string */ - public function php_2_xmlrpc_type($phpType) + public function php2XmlrpcType($phpType) { switch (strtolower($phpType)) { case 'string': @@ -76,7 +76,7 @@ class Wrapper * * @return string */ - public function xmlrpc_2_php_type($xmlrpcType) + public function xmlrpc2PhpType($xmlrpcType) { switch (strtolower($xmlrpcType)) { case 'base64': @@ -128,7 +128,7 @@ class Wrapper * php functions (ie. functions not expecting a single Request obj as parameter) * is by making use of the functions_parameters_type class member. * - * @param string|array $callable the name of the PHP user function to be exposed as xmlrpc method; array($obj, 'methodname') and array('class', 'methodname') are ok too + * @param callable $callable the PHP user function to be exposed as xmlrpc method/ a closure, function name, array($obj, 'methodname') or array('class', 'methodname') are ok * @param string $newFuncName (optional) name for function to be created. Used only when return_source in $extraOptions is true * @param array $extraOptions (optional) array of options for conversion. valid values include: * - bool return_source when true, php code w. function definition will be returned, instead of a closure @@ -146,8 +146,9 @@ class Wrapper * @todo what to do when the PHP function returns NULL? We are currently returning an empty string value... * @todo add an option to suppress php warnings in invocation of user function, similar to server debug level 3? * @todo add a verbatim_object_copy parameter to allow avoiding usage the same obj instance? + * @todo add an option to allow generated function to skip validation of number of parameters, as that is done by the server anyway */ - public function wrap_php_function($callable, $newFuncName = '', $extraOptions = array()) + public function wrapPhpFunction($callable, $newFuncName = '', $extraOptions = array()) { $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true; @@ -156,7 +157,7 @@ class Wrapper } if (is_array($callable)) { if (count($callable) < 2 || (!is_string($callable[0]) && !is_object($callable[0]))) { - error_log('XML-RPC: syntax for function to be wrapped is wrong'); + error_log('XML-RPC: ' . __METHOD__ . ': syntax for function to be wrapped is wrong'); return false; } if (is_string($callable[0])) { @@ -166,6 +167,12 @@ class Wrapper } $exists = method_exists($callable[0], $callable[1]); } else if ($callable instanceof \Closure) { + // we do not support creating code which wraps closures, as php does not allow to serialize them + if (!$buildIt) { + error_log('XML-RPC: ' . __METHOD__ . ': a closure can not be wrapped in generated source code'); + return false; + } + $plainFuncName = 'Closure'; $exists = true; } @@ -175,7 +182,7 @@ class Wrapper } if (!$exists) { - error_log('XML-RPC: function to be wrapped is not defined: ' . $plainFuncName); + error_log('XML-RPC: ' . __METHOD__ . ': function to be wrapped is not defined: ' . $plainFuncName); return false; } @@ -187,15 +194,12 @@ class Wrapper $funcSigs = $this->buildMethodSignatures($funcDesc); if ($buildIt) { - $callable = $this->buildWrapFunctionClosure($callable, $extraOptions, null, null); + $callable = $this->buildWrapFunctionClosure($callable, $extraOptions, $plainFuncName, $funcDesc); } else { $newFuncName = $this->newFunctionName($callable, $newFuncName, $extraOptions); $code = $this->buildWrapFunctionSource($callable, $newFuncName, $extraOptions, $plainFuncName, $funcDesc); } - /// @todo examine if $paramDocs matches $parsVariations and build array for - /// usage as method signature, plus put together a nice string for docs - $ret = array( 'function' => $callable, 'signature' => $funcSigs['sigs'], @@ -222,23 +226,23 @@ class Wrapper if (is_array($callable)) { $func = new \ReflectionMethod($callable[0], $callable[1]); if ($func->isPrivate()) { - error_log('XML-RPC: method to be wrapped is private: ' . $plainFuncName); + error_log('XML-RPC: ' . __METHOD__ . ': method to be wrapped is private: ' . $plainFuncName); return false; } if ($func->isProtected()) { - error_log('XML-RPC: method to be wrapped is protected: ' . $plainFuncName); + error_log('XML-RPC: ' . __METHOD__ . ': method to be wrapped is protected: ' . $plainFuncName); return false; } if ($func->isConstructor()) { - error_log('XML-RPC: method to be wrapped is the constructor: ' . $plainFuncName); + error_log('XML-RPC: ' . __METHOD__ . ': method to be wrapped is the constructor: ' . $plainFuncName); return false; } if ($func->isDestructor()) { - error_log('XML-RPC: method to be wrapped is the destructor: ' . $plainFuncName); + error_log('XML-RPC: ' . __METHOD__ . ': method to be wrapped is the destructor: ' . $plainFuncName); return false; } if ($func->isAbstract()) { - error_log('XML-RPC: method to be wrapped is abstract: ' . $plainFuncName); + error_log('XML-RPC: ' . __METHOD__ . ': method to be wrapped is abstract: ' . $plainFuncName); return false; } /// @todo add more checks for static vs. nonstatic? @@ -248,7 +252,7 @@ class Wrapper if ($func->isInternal()) { // Note: from PHP 5.1.0 onward, we will possibly be able to use invokeargs // instead of getparameters to fully reflect internal php functions ? - error_log('XML-RPC: function to be wrapped is internal: ' . $plainFuncName); + error_log('XML-RPC: ' . __METHOD__ . ': function to be wrapped is internal: ' . $plainFuncName); return false; } @@ -276,10 +280,10 @@ class Wrapper $desc .= $doc; } elseif (strpos($doc, '@param') === 0) { // syntax: @param type $name [desc] - if (preg_match('/@param\s+(\S+)\s+(\$\S+)\s+(.+)?/', $doc, $matches)) { + if (preg_match('/@param\s+(\S+)\s+(\$\S+)\s*(.+)?/', $doc, $matches)) { $name = strtolower(trim($matches[2])); //$paramDocs[$name]['name'] = trim($matches[2]); - $paramDocs[$name]['doc'] = $matches[3]; + $paramDocs[$name]['doc'] = isset($matches[3]) ? $matches[3] : ''; $paramDocs[$name]['type'] = $matches[1]; } $i++; @@ -363,12 +367,12 @@ class Wrapper $sigsDocs = array(); foreach ($parsVariations as $pars) { // build a signature - $sig = array($this->php_2_xmlrpc_type($funcDesc['returns'])); + $sig = array($this->php2XmlrpcType($funcDesc['returns'])); $pSig = array($funcDesc['returnsDocs']); for ($i = 0; $i < count($pars); $i++) { $name = strtolower($funcDesc['params'][$i]['name']); if (isset($funcDesc['paramDocs'][$name]['type'])) { - $sig[] = $this->php_2_xmlrpc_type($funcDesc['paramDocs'][$name]['type']); + $sig[] = $this->php2XmlrpcType($funcDesc['paramDocs'][$name]['type']); } else { $sig[] = Value::$xmlrpcValue; } @@ -404,6 +408,22 @@ class Wrapper $responseClass = $nameSpace.'Response'; $valueClass = $nameSpace.'Value'; + // validate number of parameters received + // this should be optional really, as we assume the server does the validation + $minPars = count($funcDesc['params']); + $maxPars = $minPars; + foreach ($funcDesc['params'] as $i => $param) { + if ($param['isoptional']) { + // this particular parameter is optional. We assume later ones are as well + $minPars = $i; + break; + } + } + $numPars = $req->getNumParams(); + if ($numPars < $minPars || $numPars > $maxPars) { + return new $responseClass(0, 3, 'Incorrect parameters passed to method'); + } + $encoder = new $encoderClass(); $options = array(); if (isset($extraOptions['decode_php_objs']) && $extraOptions['decode_php_objs']) { @@ -479,6 +499,8 @@ class Wrapper * @param string $plainFuncName * @param array $funcDesc * @return array + * + * @todo add a nice phpdoc block in the generated source */ protected function buildWrapFunctionSource($callable, $newFuncName, $extraOptions, $plainFuncName, $funcDesc) { @@ -488,37 +510,19 @@ class Wrapper $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false; $catchWarnings = isset($extraOptions['suppress_warnings']) && $extraOptions['suppress_warnings'] ? '@' : ''; - // build body of new function - - $innerCode = "\$encoder = new {$namespace}Encoder();\n"; $i = 0; $parsVariations = array(); $pars = array(); $pNum = count($funcDesc['params']); foreach ($funcDesc['params'] as $param) { - /*$name = strtolower($funcDesc['params'][$i]['name']); - if (!isset($funcDesc['paramDocs'][$name])) { - // no param found in phpdoc info matching param definition! - $funcDesc['paramDocs'][$name]['type'] = 'mixed'; - }*/ if ($param['isoptional']) { // this particular parameter is optional. save as valid previous list of parameters - $innerCode .= "if (\$paramcount > $i) {\n"; $parsVariations[] = $pars; } - $innerCode .= "\$p$i = \$req->getParam($i);\n"; - if ($decodePhpObjects) { - $innerCode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = \$encoder->decode(\$p$i, array('decode_php_objs'));\n"; - } else { - $innerCode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = \$encoder->decode(\$p$i);\n"; - } - $pars[] = "\$p$i"; + $pars[] = "\$p[$i]"; $i++; - if ($param['isoptional']) { - $innerCode .= "}\n"; - } if ($i == $pNum) { // last allowed parameters combination $parsVariations[] = $pars; @@ -529,20 +533,24 @@ class Wrapper // only known good synopsis = no parameters $parsVariations[] = array(); $minPars = 0; + $maxPars = 0; } else { $minPars = count($parsVariations[0]); + $maxPars = count($parsVariations[count($parsVariations)-1]); } - if ($minPars) { - // add to code the check for min params number - // NB: this check needs to be done BEFORE decoding param values - $innerCode = "\$paramcount = \$req->getNumParams();\n" . - "if (\$paramcount < $minPars) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcstr['incorrect_params'] . "');\n" . $innerCode; + // build body of new function + + $innerCode = "\$paramCount = \$req->getNumParams();\n"; + $innerCode .= "if (\$paramCount < $minPars || \$paramCount > $maxPars) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcstr['incorrect_params'] . "');\n"; + + $innerCode .= "\$encoder = new {$namespace}Encoder();\n"; + if ($decodePhpObjects) { + $innerCode .= "\$p = \$encoder->decode(\$req, array('decode_php_objs'));\n"; } else { - $innerCode = "\$paramcount = \$req->getNumParams();\n" . $innerCode; + $innerCode .= "\$p = \$encoder->decode(\$req);\n"; } - $innerCode .= "\$np = false;\n"; // since we are building source code for later use, if we are given an object instance, // we go out of our way and store a pointer to it in a static class var var... if (is_array($callable) && is_object($callable[0])) { @@ -552,12 +560,11 @@ class Wrapper } else { $realFuncName = $plainFuncName; } - foreach ($parsVariations as $pars) { - $innerCode .= "if (\$paramcount == " . count($pars) . ") \$retval = {$catchWarnings}$realFuncName(" . implode(',', $pars) . "); else\n"; + foreach ($parsVariations as $i => $pars) { + $innerCode .= "if (\$paramCount == " . count($pars) . ") \$retval = {$catchWarnings}$realFuncName(" . implode(',', $pars) . ");\n"; + if ($i < (count($parsVariations) - 1)) + $innerCode .= "else\n"; } - $innerCode .= "\$np = true;\n"; - $innerCode .= "if (\$np) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcstr['incorrect_params'] . "'); else {\n"; - //$innerCode .= "if (\$_xmlrpcs_error_occurred) return new Response(0, $GLOBALS['xmlrpcerr']user, \$_xmlrpcs_error_occurred); else\n"; $innerCode .= "if (is_a(\$retval, '{$namespace}Response')) return \$retval; else\n"; if ($funcDesc['returns'] == Value::$xmlrpcDateTime || $funcDesc['returns'] == Value::$xmlrpcBase64) { $innerCode .= "return new {$namespace}Response(new {$namespace}Value(\$retval, '{$funcDesc['returns']}'));"; @@ -572,7 +579,7 @@ class Wrapper // if($func->returnsReference()) // return false; - $code = "function $newFuncName(\$req) {\n" . $innerCode . "}\n}"; + $code = "function $newFuncName(\$req) {\n" . $innerCode . "\n}"; return $code; } @@ -582,15 +589,15 @@ class Wrapper * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc server * object and called from remote clients (as well as their corresponding signature info). * - * @param mixed $className the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class - * @param array $extraOptions see the docs for wrap_php_method for basic options, plus + * @param string|object $className the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class + * @param array $extraOptions see the docs for wrapPhpMethod for basic options, plus * - string method_type 'static', 'nonstatic', 'all' and 'auto' (default); the latter will switch between static and non-static depending on whether $className is a class name or object instance * - string method_filter a regexp used to filter methods to wrap based on their names * - string prefix used for the names of the xmlrpc methods created * * @return array|false false on failure */ - public function wrap_php_class($className, $extraOptions = array()) + public function wrapPhpClass($className, $extraOptions = array()) { $methodFilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : ''; $methodType = isset($extraOptions['method_type']) ? $extraOptions['method_type'] : 'auto'; @@ -605,7 +612,7 @@ class Wrapper if (($func->isStatic() && ($methodType == 'all' || $methodType == 'static' || ($methodType == 'auto' && is_string($className)))) || (!$func->isStatic() && ($methodType == 'all' || $methodType == 'nonstatic' || ($methodType == 'auto' && is_object($className)))) ) { - $methodWrap = $this->wrap_php_function(array($className, $mName), '', $extraOptions); + $methodWrap = $this->wrapPhpFunction(array($className, $mName), '', $extraOptions); if ($methodWrap) { if (is_object($className)) { $realClassName = get_class($className); @@ -667,7 +674,7 @@ class Wrapper * * @return \closure|array|false false on failure, closure by default and array for return_source = true */ - public function wrap_xmlrpc_method($client, $methodName, $extraOptions = array()) + public function wrapXmlrpcMethod($client, $methodName, $extraOptions = array()) { $newFuncName = isset($extraOptions['new_function_name']) ? $extraOptions['new_function_name'] : ''; @@ -724,7 +731,7 @@ class Wrapper $client->setDebug($debug); $response = $client->send($req, $timeout, $protocol); if ($response->faultCode()) { - error_log('XML-RPC: could not retrieve method signature from remote server for method ' . $methodName); + error_log('XML-RPC: ' . __METHOD__ . ': could not retrieve method signature from remote server for method ' . $methodName); return false; } @@ -735,7 +742,7 @@ class Wrapper } if (!is_array($mSig) || count($mSig) <= $sigNum) { - error_log('XML-RPC: could not retrieve method signature nr.' . $sigNum . ' from remote server for method ' . $methodName); + error_log('XML-RPC: ' . __METHOD__ . ': could not retrieve method signature nr.' . $sigNum . ' from remote server for method ' . $methodName); return false; } @@ -815,7 +822,7 @@ class Wrapper $decodeOptions[] = 'decode_php_objs'; } - /// @todo check for insufficient nr. of args besides excess ones + /// @todo check for insufficient nr. of args besides excess ones? note that 'source' version does not... // support one extra parameter: debug $maxArgs = count($mSig)-1; // 1st element is the return type @@ -828,7 +835,6 @@ class Wrapper $xmlrpcArgs = array(); foreach($currentArgs as $i => $arg) { if ($i == $maxArgs) { - /// @todo log warning? check what happens with the 'source' version break; } $pType = $mSig[$i+1]; @@ -866,7 +872,16 @@ class Wrapper return $function; } - protected function buildWrapMethodSource($client, $methodName, array $extraOptions, $newFuncName, $mSig, $mDesc='') + /** + * @param Client $client + * @param string $methodName + * @param array $extraOptions + * @param string $newFuncName + * @param array $mSig + * @param string $mDesc + * @return array + */ + public function buildWrapMethodSource($client, $methodName, array $extraOptions, $newFuncName, $mSig, $mDesc='') { $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0; $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : ''; @@ -888,7 +903,7 @@ class Wrapper if ($clientCopyMode < 2) { // client copy mode 0 or 1 == full / partial client copy in emitted code $verbatimClientCopy = !$clientCopyMode; - $innerCode = $this->build_client_wrapper_code($client, $verbatimClientCopy, $prefix, $namespace); + $innerCode = $this->buildClientWrapperCode($client, $verbatimClientCopy, $prefix, $namespace); $innerCode .= "\$client->setDebug(\$debug);\n"; $this_ = ''; } else { @@ -925,14 +940,14 @@ class Wrapper } } $innerCode .= "\$req->addparam(\$p$i);\n"; - $mDesc .= '* @param ' . $this->xmlrpc_2_php_type($pType) . " \$p$i\n"; + $mDesc .= '* @param ' . $this->xmlrpc2PhpType($pType) . " \$p$i\n"; } if ($clientCopyMode < 2) { $plist[] = '$debug=0'; $mDesc .= "* @param int \$debug when 1 (or 2) will enable debugging of the underlying {$prefix} call (defaults to 0)\n"; } $plist = implode(', ', $plist); - $mDesc .= '* @return ' . $this->xmlrpc_2_php_type($mSig[0]) . " (or an {$namespace}Response obj instance if call fails)\n*/\n"; + $mDesc .= '* @return ' . $this->xmlrpc2PhpType($mSig[0]) . " (or an {$namespace}Response obj instance if call fails)\n*/\n"; $innerCode .= "\$res = \${$this_}client->send(\$req, $timeout, '$protocol');\n"; if ($decodeFault) { @@ -956,24 +971,24 @@ class Wrapper } /** - * Similar to wrap_xmlrpc_method, but will generate a php class that wraps + * Similar to wrapXmlrpcMethod, 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. + * For more details see wrapXmlrpcMethod. * * For a slimmer alternative, see the code in demo/client/proxy.php * - * Note that unlike wrap_xmlrpc_method, we always have to generate php code here. It seems that php 7 will have anon classes... + * Note that unlike wrapXmlrpcMethod, we always have to generate php code here. It seems that php 7 will have anon classes... * * @param Client $client the client obj all set to query the desired server - * @param array $extraOptions list of options for wrapped code. See the ones from wrap_xmlrpc_method plus - * - string method_filter + * @param array $extraOptions list of options for wrapped code. See the ones from wrapXmlrpcMethod plus + * - string method_filter regular expression * - string new_class_name * - string prefix * - bool simple_client_copy set it to true to avoid copying all properties of $client into the copy made in the new class * * @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) */ - public function wrap_xmlrpc_server($client, $extraOptions = array()) + public function wrapXmlrpcServer($client, $extraOptions = array()) { $methodFilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : ''; $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0; @@ -992,7 +1007,7 @@ class Wrapper $req = new $reqClass('system.listMethods'); $response = $client->send($req, $timeout, $protocol); if ($response->faultCode()) { - error_log('XML-RPC: could not retrieve method list from remote server'); + error_log('XML-RPC: ' . __METHOD__ . ': could not retrieve method list from remote server'); return false; } else { @@ -1002,7 +1017,7 @@ class Wrapper $mList = $decoder->decode($mList); } if (!is_array($mList) || !count($mList)) { - error_log('XML-RPC: could not retrieve meaningful method list from remote server'); + error_log('XML-RPC: ' . __METHOD__ . ': could not retrieve meaningful method list from remote server'); return false; } else { @@ -1020,7 +1035,7 @@ class Wrapper /// @todo add function setdebug() to new class, to enable/disable debugging $source = "class $xmlrpcClassName\n{\npublic \$client;\n\n"; $source .= "function __construct()\n{\n"; - $source .= $this->build_client_wrapper_code($client, $verbatimClientCopy, $prefix, $namespace); + $source .= $this->buildClientWrapperCode($client, $verbatimClientCopy, $prefix, $namespace); $source .= "\$this->client = \$client;\n}\n\n"; $opts = array( 'return_source' => true, @@ -1037,14 +1052,14 @@ class Wrapper // note: this will fail if server exposes 2 methods called f.e. do.something and do_something $opts['new_function_name'] = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'), array('_', ''), $mName); - $methodWrap = $this->wrap_xmlrpc_method($client, $mName, $opts); + $methodWrap = $this->wrapXmlrpcMethod($client, $mName, $opts); if ($methodWrap) { if (!$buildIt) { $source .= $methodWrap['docstring']; } $source .= $methodWrap['source'] . "\n"; } else { - error_log('XML-RPC: will not create class method to wrap remote method ' . $mName); + error_log('XML-RPC: ' . __METHOD__ . ': will not create class method to wrap remote method ' . $mName); } } } @@ -1055,7 +1070,7 @@ class Wrapper if ($allOK) { return $xmlrpcClassName; } else { - error_log('XML-RPC: could not create class ' . $xmlrpcClassName . ' to wrap remote server ' . $client->server); + error_log('XML-RPC: ' . __METHOD__ . ': could not create class ' . $xmlrpcClassName . ' to wrap remote server ' . $client->server); return false; } } else { @@ -1076,7 +1091,7 @@ class Wrapper * * @return string */ - protected function build_client_wrapper_code($client, $verbatimClientCopy, $prefix = 'xmlrpc', $namespace = '\\PhpXmlRpc\\' ) + protected function buildClientWrapperCode($client, $verbatimClientCopy, $prefix = 'xmlrpc', $namespace = '\\PhpXmlRpc\\' ) { $code = "\$client = new {$namespace}Client('" . str_replace("'", "\'", $client->path) . "', '" . str_replace("'", "\'", $client->server) . "', $client->port);\n";