xmlrpc_wrappers.inc

来自「PHP 知识管理系统(基于树结构的知识管理系统), 英文原版的PHP源码。」· INC 代码 · 共 818 行 · 第 1/2 页

INC
818
字号
	* - 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.
	*
	* @param xmlrpc_client $client     an xmlrpc client set up correctly to communicate with target server
	* @param string        $methodname the xmlrpc method to be mapped to a php function
	* @param array         $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 ---
	*        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
	*        bool          debug        set it to 1 or 2 to see debug results of querying server for method synopsis
	* @return string                   the name of the generated php function (or false) - OR AN ARRAY...
	*/
	function wrap_xmlrpc_method($client, $methodname, $extra_options=0, $timeout=0, $protocol='', $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($extra_options))
		{
			$signum = $extra_options;
			$extra_options = array();
		}
		else
		{
			$signum = isset($extra_options['signum']) ? (int)$extra_options['signum'] : 0;
			$timeout = isset($extra_options['timeout']) ? (int)$extra_options['timeout'] : 0;
			$protocol = isset($extra_options['protocol']) ? $extra_options['protocol'] : '';
			$newfuncname = isset($extra_options['new_function_name']) ? $extra_options['new_function_name'] : '';
		}
		//$encode_php_objects = in_array('encode_php_objects', $extra_options);
		//$verbatim_client_copy = in_array('simple_client_copy', $extra_options) ? 1 :
		//	in_array('build_class_code', $extra_options) ? 2 : 0;

		$encode_php_objects = isset($extra_options['encode_php_objs']) ? (bool)$extra_options['encode_php_objs'] : false;
		$decode_php_objects = isset($extra_options['decode_php_objs']) ? (bool)$extra_options['decode_php_objs'] : false;
		$simple_client_copy = isset($extra_options['simple_client_copy']) ? (int)($extra_options['simple_client_copy']) : 0;
		$buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true;
		$prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc';
		if (isset($extra_options['return_on_fault']))
		{
			$decode_fault = true;
			$fault_response = $extra_options['return_on_fault'];
		}
		else
		{
			$decode_fault = false;
			$fault_response = '';
		}
		$debug = isset($extra_options['debug']) ? ($extra_options['debug']) : 0;

		$msgclass = $prefix.'msg';
		$valclass = $prefix.'val';
		$decodefunc = 'php_'.$prefix.'_decode';

		$msg =& new $msgclass('system.methodSignature');
		$msg->addparam(new $valclass($methodname));
		$client->setDebug($debug);
		$response =& $client->send($msg, $timeout, $protocol);
		if($response->faultCode())
		{
			error_log('XML-RPC: could not retrieve method signature from remote server for method '.$methodname);
			return false;
		}
		else
		{
			$msig = $response->value();
			if ($client->return_type != 'phpvals')
			{
				$msig = $decodefunc($msig);
			}
			if(!is_array($msig) || count($msig) <= $signum)
			{
				error_log('XML-RPC: could not retrieve method signature nr.'.$signum.' from remote server for method '.$methodname);
				return false;
			}
			else
			{
				// pick a suitable name for the new function, avoiding collisions
				if($newfuncname != '')
				{
					$xmlrpcfuncname = $newfuncname;
				}
				else
				{
					// take care to insure that methodname is translated to valid
					// php function name
					$xmlrpcfuncname = $prefix.'_'.preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
						array('_', ''), $methodname);
				}
				while($buildit && function_exists($xmlrpcfuncname))
				{
					$xmlrpcfuncname .= 'x';
				}

				$msig = $msig[$signum];
				$mdesc = '';
				// if in 'offline' mode, get method description too.
				// in online mode, favour speed of operation
				if(!$buildit)
				{
					$msg =& new $msgclass('system.methodHelp');
					$msg->addparam(new $valclass($methodname));
					$response =& $client->send($msg, $timeout, $protocol);
					if (!$response->faultCode())
					{
						$mdesc = $response->value();
						if ($client->return_type != 'phpvals')
						{
							$mdesc = $mdesc->scalarval();
						}
					}
				}

				$results = build_remote_method_wrapper_code($client, $methodname,
					$xmlrpcfuncname, $msig, $mdesc, $timeout, $protocol, $simple_client_copy,
					$prefix, $decode_php_objects, $encode_php_objects, $decode_fault,
					$fault_response);

				//print_r($code);
				if ($buildit)
				{
					$allOK = 0;
					eval($results['source'].'$allOK=1;');
					// alternative
					//$xmlrpcfuncname = create_function('$m', $innercode);
					if($allOK)
					{
						return $xmlrpcfuncname;
					}
					else
					{
						error_log('XML-RPC: could not create function '.$xmlrpcfuncname.' to wrap remote method '.$methodname);
						return false;
					}
				}
				else
				{
					$results['function'] = $xmlrpcfuncname;
					return $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.
	* @param xmlrpc_client $client the client obj all set to query the desired server
	* @param array $extra_options list of options for wrapped code
	* @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)
	*/
	function wrap_xmlrpc_server($client, $extra_options=array())
	{
		$methodfilter = isset($extra_options['method_filter']) ? $extra_options['method_filter'] : '';
		$signum = isset($extra_options['signum']) ? (int)$extra_options['signum'] : 0;
		$timeout = isset($extra_options['timeout']) ? (int)$extra_options['timeout'] : 0;
		$protocol = isset($extra_options['protocol']) ? $extra_options['protocol'] : '';
		$newclassname = isset($extra_options['new_class_name']) ? $extra_options['new_class_name'] : '';
		$encode_php_objects = isset($extra_options['encode_php_objs']) ? (bool)$extra_options['encode_php_objs'] : false;
		$decode_php_objects = isset($extra_options['decode_php_objs']) ? (bool)$extra_options['decode_php_objs'] : false;
		$verbatim_client_copy = isset($extra_options['simple_client_copy']) ? !($extra_options['simple_client_copy']) : true;
		$buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true;
		$prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc';

		$msgclass = $prefix.'msg';
		//$valclass = $prefix.'val';
		$decodefunc = 'php_'.$prefix.'_decode';

		$msg =& new $msgclass('system.listMethods');
		$response =& $client->send($msg, $timeout, $protocol);
		if($response->faultCode())
		{
			error_log('XML-RPC: could not retrieve method list from remote server');
			return false;
		}
		else
		{
			$mlist = $response->value();
			if ($client->return_type != 'phpvals')
			{
				$mlist = $decodefunc($mlist);
			}
			if(!is_array($mlist) || !count($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($newclassname != '')
				{
					$xmlrpcclassname = $newclassname;
				}
				else
				{
					$xmlrpcclassname = $prefix.'_'.preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
						array('_', ''), $client->server).'_client';
				}
				while($buildit && class_exists($xmlrpcclassname))
				{
					$xmlrpcclassname .= 'x';
				}

				/// @todo add function setdebug() to new class, to enable/disable debugging
				$source = "class $xmlrpcclassname\n{\nvar \$client;\n\n";
				$source .= "function $xmlrpcclassname()\n{\n";
				$source .= build_client_wrapper_code($client, $verbatim_client_copy, $prefix);
				$source .= "\$this->client =& \$client;\n}\n\n";
				$opts = array('simple_client_copy' => 2, 'return_source' => true,
					'timeout' => $timeout, 'protocol' => $protocol,
					'encode_php_objs' => $encode_php_objects, 'prefix' => $prefix,
					'decode_php_objs' => $decode_php_objects
					);
				/// @todo build javadoc for class definition, too
				foreach($mlist as $mname)
				{
					if ($methodfilter == '' || preg_match($methodfilter, $mname))
					{
						$opts['new_function_name'] = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
							array('_', ''), $mname);
						$methodwrap = wrap_xmlrpc_method($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);
						}
					}
				}
				$source .= "}\n";
				if ($buildit)
				{
					$allOK = 0;
					eval($source.'$allOK=1;');
					// alternative
					//$xmlrpcfuncname = create_function('$m', $innercode);
					if($allOK)
					{
						return $xmlrpcclassname;
					}
					else
					{
						error_log('XML-RPC: could not create class '.$xmlrpcclassname.' to wrap remote server '.$client->server);
						return false;
					}
				}
				else
				{
					return array('class' => $xmlrpcclassname, 'code' => $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($client, $methodname, $xmlrpcfuncname,
		$msig, $mdesc='', $timeout=0, $protocol='', $client_copy_mode=0, $prefix='xmlrpc',
		$decode_php_objects=false, $encode_php_objects=false, $decode_fault=false,
		$fault_response='')
	{
		$code = "function $xmlrpcfuncname (";
		if ($client_copy_mode < 2)
		{
			// client copy mode 0 or 1 == partial / full client copy in emitted code
			$innercode = build_client_wrapper_code($client, $client_copy_mode, $prefix);
			$innercode .= "\$client->setDebug(\$debug);\n";
			$this_ = '';
		}
		else
		{
			// client copy mode 2 == no client copy in emitted code
			$innercode = '';
			$this_ = 'this->';
		}
		$innercode .= "\$msg =& new {$prefix}msg('$methodname');\n";

		if ($mdesc != '')
		{
			// take care that PHP comment is not terminated unwillingly by method description
			$mdesc = "/**\n* ".str_replace('*/', '* /', $mdesc)."\n";
		}
		else
		{
			$mdesc = "/**\nFunction $xmlrpcfuncname\n";
		}

		// param parsing
		$plist = array();
		$pcount = count($msig);
		for($i = 1; $i < $pcount; $i++)
		{
			$plist[] = "\$p$i";
			$ptype = $msig[$i];
			if($ptype == 'i4' || $ptype == 'int' || $ptype == 'boolean' || $ptype == 'double' ||
				$ptype == 'string' || $ptype == 'dateTime.iso8601' || $ptype == 'base64' || $ptype == 'null')
			{
				// only build directly xmlrpcvals when type is known and scalar
				$innercode .= "\$p$i =& new {$prefix}val(\$p$i, '$ptype');\n";
			}
			else
			{
				if ($encode_php_objects)
				{
					$innercode .= "\$p$i =& php_{$prefix}_encode(\$p$i, array('encode_php_objs'));\n";
				}
				else
				{
					$innercode .= "\$p$i =& php_{$prefix}_encode(\$p$i);\n";
				}
			}
			$innercode .= "\$msg->addparam(\$p$i);\n";
			$mdesc .= '* @param '.xmlrpc_2_php_type($ptype)." \$p$i\n";
		}
		if ($client_copy_mode < 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 '.xmlrpc_2_php_type($msig[0])." (or an {$prefix}resp obj instance if call fails)\n*/\n";

		$innercode .= "\$res =& \${$this_}client->send(\$msg, $timeout, '$protocol');\n";
		if ($decode_fault)
		{
			if (is_string($fault_response) && ((strpos($fault_response, '%faultCode%') !== false) || (strpos($fault_response, '%faultString%') !== false)))
			{
				$respcode = "str_replace(array('%faultCode%', '%faultString%'), array(\$res->faultCode(), \$res->faultString()), '".str_replace("'", "''", $fault_response)."')";
			}
			else
			{
				$respcode = var_export($fault_response, true);
			}
		}
		else
		{
			$respcode = '$res';
		}
		if ($decode_php_objects)
		{
			$innercode .= "if (\$res->faultcode()) return $respcode; else return php_{$prefix}_decode(\$res->value(), array('decode_php_objs'));";
		}
		else
		{
			$innercode .= "if (\$res->faultcode()) return $respcode; else return php_{$prefix}_decode(\$res->value());";
		}

		$code = $code . $plist. ") {\n" . $innercode . "\n}\n";

		return array('source' => $code, 'docstring' => $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($client, $verbatim_client_copy, $prefix='xmlrpc')
	{
		$code = "\$client =& new {$prefix}_client('".str_replace("'", "\'", $client->path).
			"', '" . str_replace("'", "\'", $client->server) . "', $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 ($verbatim_client_copy)
		{
			foreach($client as $fld => $val)
			{
				if($fld != 'debug' && $fld != 'return_type')
				{
					$val = var_export($val, true);
					$code .= "\$client->$fld = $val;\n";
				}
			}
		}
		// only make sure that client always returns the correct data type
		$code .= "\$client->return_type = '{$prefix}vals';\n";
		//$code .= "\$client->setDebug(\$debug);\n";
		return $code;
	}
?>

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?