5 use PhpXmlRpc\Helper\XMLParser;
6 use PhpXmlRpc\Helper\Charset;
11 * Array defining php functions exposed as xmlrpc methods by this server.
13 protected $dmap = array();
15 * Defines how functions in dmap will be invoked: either using an xmlrpc request object
16 * or plain php values.
17 * Valid strings are 'xmlrpcvals', 'phpvals' or 'epivals'
19 public $functions_parameters_type = 'xmlrpcvals';
21 * Option used for fine-tuning the encoding the php values returned from
22 * functions registered in the dispatch map when the functions_parameters_types
23 * member is set to 'phpvals'
24 * @see Encoder::encode for a list of values
26 public $phpvals_encoding_options = array('auto_dates');
28 * Controls whether the server is going to echo debugging messages back to the client as comments in response body.
29 * Valid values: 0,1,2,3
33 * Controls behaviour of server when the invoked user function throws an exception:
34 * 0 = catch it and return an 'internal error' xmlrpc response (default)
35 * 1 = catch it and return an xmlrpc response with the error corresponding to the exception
36 * 2 = allow the exception to float to the upper layers
38 public $exception_handling = 0;
40 * When set to true, it will enable HTTP compression of the response, in case
41 * the client has declared its support for compression in the request.
42 * Set at constructor time.
44 public $compress_response = false;
46 * List of http compression methods accepted by the server for requests. Set at constructor time.
47 * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib
49 public $accepted_compression = array();
50 /// shall we serve calls to system.* methods?
51 public $allow_system_funcs = true;
53 * List of charset encodings natively accepted for requests.
54 * Set at constructor time.
56 public $accepted_charset_encodings = array();
58 * charset encoding to be used for response.
59 * NB: if we can, we will convert the generated response from internal_encoding to the intended one.
60 * Can be: a supported xml encoding (only UTF-8 and ISO-8859-1 at present, unless mbstring is enabled),
61 * null (leave unspecified in response, convert output stream to US_ASCII),
62 * 'default' (use xmlrpc library default as specified in xmlrpc.inc, convert output stream if needed),
63 * or 'auto' (use client-specified charset encoding or same as request if request headers do not specify it (unless request is US-ASCII: then use library default anyway).
64 * NB: pretty dangerous if you accept every charset and do not have mbstring enabled)
66 public $response_charset_encoding = '';
68 * Storage for internal debug info.
70 protected $debug_info = '';
72 * Extra data passed at runtime to method handling functions. Used only by EPI layer
74 public $user_data = null;
76 protected static $_xmlrpc_debuginfo = '';
77 protected static $_xmlrpcs_occurred_errors = '';
78 protected static $_xmlrpcs_prev_ehandler = '';
81 * @param array $dispatchMap the dispatch map with definition of exposed services
82 * @param boolean $serviceNow set to false to prevent the server from running upon construction
84 public function __construct($dispatchMap = null, $serviceNow = true)
86 // if ZLIB is enabled, let the server by default accept compressed requests,
87 // and compress responses sent to clients that support them
88 if (function_exists('gzinflate')) {
89 $this->accepted_compression = array('gzip', 'deflate');
90 $this->compress_response = true;
93 // by default the xml parser can support these 3 charset encodings
94 $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII');
96 // dispMap is a dispatch array of methods mapped to function names and signatures.
97 // If a method doesn't appear in the map then an unknown method error is generated
98 /* milosch - changed to make passing dispMap optional.
99 * instead, you can use the class add_to_map() function
100 * to add functions manually (borrowed from SOAPX4)
103 $this->dmap = $dispatchMap;
111 * Set debug level of server.
113 * @param integer $level debug lvl: determines info added to xmlrpc responses (as xml comments)
115 * 1 = msgs set from user with debugmsg(),
116 * 2 = add complete xmlrpc request (headers and body),
117 * 3 = add also all processing warnings happened during method processing
118 * (NB: this involves setting a custom error handler, and might interfere
119 * with the standard processing of the php function exposed as method. In
120 * particular, triggering an USER_ERROR level error will not halt script
121 * execution anymore, but just end up logged in the xmlrpc response)
122 * Note that info added at level 2 and 3 will be base64 encoded
124 public function setDebug($level)
126 $this->debug = $level;
130 * Add a string to the debug info that can be later serialized by the server
131 * as part of the response message.
132 * Note that for best compatibility, the debug string should be encoded using
133 * the PhpXmlRpc::$xmlrpc_internalencoding character set.
138 public static function xmlrpc_debugmsg($msg)
140 static::$_xmlrpc_debuginfo .= $msg . "\n";
143 public static function error_occurred($msg)
145 static::$_xmlrpcs_occurred_errors .= $msg . "\n";
149 * Return a string with the serialized representation of all debug info.
151 * @param string $charsetEncoding the target charset encoding for the serialization
153 * @return string an XML comment (or two)
155 public function serializeDebug($charsetEncoding = '')
157 // Tough encoding problem: which internal charset should we assume for debug info?
158 // It might contain a copy of raw data received from client, ie with unknown encoding,
159 // intermixed with php generated data and user generated data...
160 // so we split it: system debug is base 64 encoded,
161 // user debug info should be encoded by the end user using the INTERNAL_ENCODING
163 if ($this->debug_info != '') {
164 $out .= "<!-- SERVER DEBUG INFO (BASE64 ENCODED):\n" . base64_encode($this->debug_info) . "\n-->\n";
166 if (static::$_xmlrpc_debuginfo != '') {
167 $out .= "<!-- DEBUG INFO:\n" . Charset::instance()->encodeEntities(str_replace('--', '_-', static::$_xmlrpc_debuginfo), PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "\n-->\n";
168 // NB: a better solution MIGHT be to use CDATA, but we need to insert it
169 // into return payload AFTER the beginning tag
170 //$out .= "<![CDATA[ DEBUG INFO:\n\n" . str_replace(']]>', ']_]_>', static::$_xmlrpc_debuginfo) . "\n]]>\n";
177 * Execute the xmlrpc request, printing the response.
179 * @param string $data the request body. If null, the http POST request will be examined
180 * @param bool $returnPayload When true, return the response but do not echo it or any http header
182 * @return Response the response object (usually not used by caller...)
184 public function service($data = null, $returnPayload = false)
186 if ($data === null) {
187 $data = file_get_contents('php://input');
191 // reset internal debug info
192 $this->debug_info = '';
194 // Echo back what we received, before parsing it
195 if ($this->debug > 1) {
196 $this->debugmsg("+++GOT+++\n" . $data . "\n+++END+++");
199 $r = $this->parseRequestHeaders($data, $reqCharset, $respCharset, $respEncoding);
201 $r = $this->parseRequest($data, $reqCharset);
204 // save full body of request into response, for more debugging usages
205 $r->raw_data = $rawData;
207 if ($this->debug > 2 && static::$_xmlrpcs_occurred_errors) {
208 $this->debugmsg("+++PROCESSING ERRORS AND WARNINGS+++\n" .
209 static::$_xmlrpcs_occurred_errors . "+++END+++");
212 $payload = $this->xml_header($respCharset);
213 if ($this->debug > 0) {
214 $payload = $payload . $this->serializeDebug($respCharset);
217 // G. Giunta 2006-01-27: do not create response serialization if it has
218 // already happened. Helps building json magic
219 if (empty($r->payload)) {
220 $r->serialize($respCharset);
222 $payload = $payload . $r->payload;
224 if ($returnPayload) {
228 // if we get a warning/error that has output some text before here, then we cannot
229 // add a new header. We cannot say we are sending xml, either...
230 if (!headers_sent()) {
231 header('Content-Type: ' . $r->content_type);
232 // we do not know if client actually told us an accepted charset, but if he did
233 // we have to tell him what we did
234 header("Vary: Accept-Charset");
236 // http compression of output: only
237 // if we can do it, and we want to do it, and client asked us to,
238 // and php ini settings do not force it already
239 $phpNoSelfCompress = !ini_get('zlib.output_compression') && (ini_get('output_handler') != 'ob_gzhandler');
240 if ($this->compress_response && function_exists('gzencode') && $respEncoding != ''
241 && $phpNoSelfCompress
243 if (strpos($respEncoding, 'gzip') !== false) {
244 $payload = gzencode($payload);
245 header("Content-Encoding: gzip");
246 header("Vary: Accept-Encoding");
247 } elseif (strpos($respEncoding, 'deflate') !== false) {
248 $payload = gzcompress($payload);
249 header("Content-Encoding: deflate");
250 header("Vary: Accept-Encoding");
254 // do not output content-length header if php is compressing output for us:
255 // it will mess up measurements
256 if ($phpNoSelfCompress) {
257 header('Content-Length: ' . (int)strlen($payload));
260 error_log('XML-RPC: ' . __METHOD__ . ': http headers already sent before response is fully generated. Check for php warning or error messages');
265 // return request, in case subclasses want it
270 * Add a method to the dispatch map.
272 * @param string $methodName the name with which the method will be made available
273 * @param string $function the php function that will get invoked
274 * @param array $sig the array of valid method signatures
275 * @param string $doc method documentation
276 * @param array $sigDoc the array of valid method signatures docs (one string per param, one for return type)
278 public function add_to_map($methodName, $function, $sig = null, $doc = false, $sigDoc = false)
280 $this->dmap[$methodName] = array(
281 'function' => $function,
285 $this->dmap[$methodName]['signature'] = $sig;
288 $this->dmap[$methodName]['signature_docs'] = $sigDoc;
293 * Verify type and number of parameters received against a list of known signatures.
295 * @param array|Request $in array of either xmlrpc value objects or xmlrpc type definitions
296 * @param array $sigs array of known signatures to match against
300 protected function verifySignature($in, $sigs)
302 // check each possible signature in turn
303 if (is_object($in)) {
304 $numParams = $in->getNumParams();
306 $numParams = count($in);
308 foreach ($sigs as $curSig) {
309 if (count($curSig) == $numParams + 1) {
311 for ($n = 0; $n < $numParams; $n++) {
312 if (is_object($in)) {
313 $p = $in->getParam($n);
314 if ($p->kindOf() == 'scalar') {
315 $pt = $p->scalartyp();
320 $pt = $in[$n] == 'i4' ? 'int' : strtolower($in[$n]); // dispatch maps never use i4...
323 // param index is $n+1, as first member of sig is return type
324 if ($pt != $curSig[$n + 1] && $curSig[$n + 1] != Value::$xmlrpcValue) {
327 $wanted = $curSig[$n + 1];
337 if (isset($wanted)) {
338 return array(0, "Wanted ${wanted}, got ${got} at param ${pno}");
340 return array(0, "No method signature matches number of parameters");
345 * Parse http headers received along with xmlrpc request. If needed, inflate request.
347 * @return mixed null on success or a Response
349 protected function parseRequestHeaders(&$data, &$reqEncoding, &$respEncoding, &$respCompression)
351 // check if $_SERVER is populated: it might have been disabled via ini file
352 // (this is true even when in CLI mode)
353 if (count($_SERVER) == 0) {
354 error_log('XML-RPC: ' . __METHOD__ . ': cannot parse request headers as $_SERVER is not populated');
357 if ($this->debug > 1) {
358 if (function_exists('getallheaders')) {
359 $this->debugmsg(''); // empty line
360 foreach (getallheaders() as $name => $val) {
361 $this->debugmsg("HEADER: $name: $val");
366 if (isset($_SERVER['HTTP_CONTENT_ENCODING'])) {
367 $contentEncoding = str_replace('x-', '', $_SERVER['HTTP_CONTENT_ENCODING']);
369 $contentEncoding = '';
372 // check if request body has been compressed and decompress it
373 if ($contentEncoding != '' && strlen($data)) {
374 if ($contentEncoding == 'deflate' || $contentEncoding == 'gzip') {
375 // if decoding works, use it. else assume data wasn't gzencoded
376 if (function_exists('gzinflate') && in_array($contentEncoding, $this->accepted_compression)) {
377 if ($contentEncoding == 'deflate' && $degzdata = @gzuncompress($data)) {
379 if ($this->debug > 1) {
380 $this->debugmsg("\n+++INFLATED REQUEST+++[" . strlen($data) . " chars]+++\n" . $data . "\n+++END+++");
382 } elseif ($contentEncoding == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) {
384 if ($this->debug > 1) {
385 $this->debugmsg("+++INFLATED REQUEST+++[" . strlen($data) . " chars]+++\n" . $data . "\n+++END+++");
388 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['server_decompress_fail'], PhpXmlRpc::$xmlrpcstr['server_decompress_fail']);
393 //error_log('The server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
394 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['server_cannot_decompress'], PhpXmlRpc::$xmlrpcstr['server_cannot_decompress']);
401 // check if client specified accepted charsets, and if we know how to fulfill
403 if ($this->response_charset_encoding == 'auto') {
405 if (isset($_SERVER['HTTP_ACCEPT_CHARSET'])) {
406 // here we should check if we can match the client-requested encoding
407 // with the encodings we know we can generate.
408 /// @todo we should parse q=0.x preferences instead of getting first charset specified...
409 $clientAcceptedCharsets = explode(',', strtoupper($_SERVER['HTTP_ACCEPT_CHARSET']));
410 // Give preference to internal encoding
411 $knownCharsets = array(PhpXmlRpc::$xmlrpc_internalencoding, 'UTF-8', 'ISO-8859-1', 'US-ASCII');
412 foreach ($knownCharsets as $charset) {
413 foreach ($clientAcceptedCharsets as $accepted) {
414 if (strpos($accepted, $charset) === 0) {
415 $respEncoding = $charset;
425 $respEncoding = $this->response_charset_encoding;
428 if (isset($_SERVER['HTTP_ACCEPT_ENCODING'])) {
429 $respCompression = $_SERVER['HTTP_ACCEPT_ENCODING'];
431 $respCompression = '';
434 // 'guestimate' request encoding
435 /// @todo check if mbstring is enabled and automagic input conversion is on: it might mingle with this check???
436 $reqEncoding = XMLParser::guessEncoding(isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '',
443 * Parse an xml chunk containing an xmlrpc request and execute the corresponding
444 * php function registered with the server.
446 * @param string $data the xml request
447 * @param string $reqEncoding (optional) the charset encoding of the xml request
451 public function parseRequest($data, $reqEncoding = '')
453 // decompose incoming XML into request structure
455 if ($reqEncoding != '') {
456 // Since parsing will fail if charset is not specified in the xml prologue,
457 // the encoding is not UTF8 and there are non-ascii chars in the text, we try to work round that...
458 // The following code might be better for mb_string enabled installs, but
459 // makes the lib about 200% slower...
460 //if (!is_valid_charset($reqEncoding, array('UTF-8')))
461 if (!in_array($reqEncoding, array('UTF-8', 'US-ASCII')) && !XMLParser::hasEncoding($data)) {
462 if ($reqEncoding == 'ISO-8859-1') {
463 $data = utf8_encode($data);
465 if (extension_loaded('mbstring')) {
466 $data = mb_convert_encoding($data, 'UTF-8', $reqEncoding);
468 error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of received request: ' . $reqEncoding);
474 $parser = xml_parser_create();
475 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
476 // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell
477 // the xml parser to give us back data in the expected charset
478 // What if internal encoding is not in one of the 3 allowed?
479 // we use the broadest one, ie. utf8
480 // This allows to send data which is native in various charset,
481 // by extending xmlrpc_encode_entities() and setting xmlrpc_internalencoding
482 if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
483 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
485 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding);
488 $xmlRpcParser = new XMLParser();
489 xml_set_object($parser, $xmlRpcParser);
491 if ($this->functions_parameters_type != 'xmlrpcvals') {
492 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
494 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');
496 xml_set_character_data_handler($parser, 'xmlrpc_cd');
497 xml_set_default_handler($parser, 'xmlrpc_dh');
498 if (!xml_parse($parser, $data, 1)) {
499 // return XML error as a faultCode
501 PhpXmlRpc::$xmlrpcerrxml + xml_get_error_code($parser),
502 sprintf('XML error: %s at line %d, column %d',
503 xml_error_string(xml_get_error_code($parser)),
504 xml_get_current_line_number($parser), xml_get_current_column_number($parser)));
505 xml_parser_free($parser);
506 } elseif ($xmlRpcParser->_xh['isf']) {
507 xml_parser_free($parser);
509 PhpXmlRpc::$xmlrpcerr['invalid_request'],
510 PhpXmlRpc::$xmlrpcstr['invalid_request'] . ' ' . $xmlRpcParser->_xh['isf_reason']);
512 xml_parser_free($parser);
513 // small layering violation in favor of speed and memory usage:
514 // we should allow the 'execute' method handle this, but in the
515 // most common scenario (xmlrpc values type server with some methods
516 // registered as phpvals) that would mean a useless encode+decode pass
517 if ($this->functions_parameters_type != 'xmlrpcvals' || (isset($this->dmap[$xmlRpcParser->_xh['method']]['parameters_type']) && ($this->dmap[$xmlRpcParser->_xh['method']]['parameters_type'] == 'phpvals'))) {
518 if ($this->debug > 1) {
519 $this->debugmsg("\n+++PARSED+++\n" . var_export($xmlRpcParser->_xh['params'], true) . "\n+++END+++");
521 $r = $this->execute($xmlRpcParser->_xh['method'], $xmlRpcParser->_xh['params'], $xmlRpcParser->_xh['pt']);
523 // build a Request object with data parsed from xml
524 $req = new Request($xmlRpcParser->_xh['method']);
525 // now add parameters in
526 for ($i = 0; $i < count($xmlRpcParser->_xh['params']); $i++) {
527 $req->addParam($xmlRpcParser->_xh['params'][$i]);
530 if ($this->debug > 1) {
531 $this->debugmsg("\n+++PARSED+++\n" . var_export($req, true) . "\n+++END+++");
533 $r = $this->execute($req);
541 * Execute a method invoked by the client, checking parameters used.
543 * @param mixed $req either a Request obj or a method name
544 * @param array $params array with method parameters as php types (if m is method name only)
545 * @param array $paramTypes array with xmlrpc types of method parameters (if m is method name only)
549 * @throws \Exception in case the executed method does throw an exception (and depending on )
551 protected function execute($req, $params = null, $paramTypes = null)
553 if (is_object($req)) {
554 $methName = $req->method();
558 $sysCall = $this->allow_system_funcs && (strpos($methName, "system.") === 0);
559 $dmap = $sysCall ? $this->getSystemDispatchMap() : $this->dmap;
561 if (!isset($dmap[$methName]['function'])) {
563 return new Response(0,
564 PhpXmlRpc::$xmlrpcerr['unknown_method'],
565 PhpXmlRpc::$xmlrpcstr['unknown_method']);
569 if (isset($dmap[$methName]['signature'])) {
570 $sig = $dmap[$methName]['signature'];
571 if (is_object($req)) {
572 list($ok, $errStr) = $this->verifySignature($req, $sig);
574 list($ok, $errStr) = $this->verifySignature($paramTypes, $sig);
580 PhpXmlRpc::$xmlrpcerr['incorrect_params'],
581 PhpXmlRpc::$xmlrpcstr['incorrect_params'] . ": ${errStr}"
586 $func = $dmap[$methName]['function'];
587 // let the 'class::function' syntax be accepted in dispatch maps
588 if (is_string($func) && strpos($func, '::')) {
589 $func = explode('::', $func);
592 if (is_array($func)) {
593 if (is_object($func[0])) {
594 $funcName = get_class($func[0]) . '->' . $func[1];
596 $funcName = implode('::', $func);
598 } else if ($func instanceof \Closure) {
599 $funcName = 'Closure';
604 // verify that function to be invoked is in fact callable
605 if (!is_callable($func)) {
606 error_log("XML-RPC: " . __METHOD__ . ": function '$funcName' registered as method handler is not callable");
610 PhpXmlRpc::$xmlrpcerr['server_error'],
611 PhpXmlRpc::$xmlrpcstr['server_error'] . ": no function matches method"
615 // If debug level is 3, we should catch all errors generated during
616 // processing of user function, and log them as part of response
617 if ($this->debug > 2) {
618 self::$_xmlrpcs_prev_ehandler = set_error_handler(array('\PhpXmlRpc\Server', '_xmlrpcs_errorHandler'));
621 // Allow mixed-convention servers
622 if (is_object($req)) {
624 $r = call_user_func($func, $this, $req);
626 $r = call_user_func($func, $req);
628 if (!is_a($r, 'PhpXmlRpc\Response')) {
629 error_log("XML-RPC: " . __METHOD__ . ": function '$funcName' registered as method handler does not return an xmlrpc response object but a " . gettype($r));
630 if (is_a($r, 'PhpXmlRpc\Value')) {
631 $r = new Response($r);
635 PhpXmlRpc::$xmlrpcerr['server_error'],
636 PhpXmlRpc::$xmlrpcstr['server_error'] . ": function does not return xmlrpc response object"
641 // call a 'plain php' function
643 array_unshift($params, $this);
644 $r = call_user_func_array($func, $params);
646 // 3rd API convention for method-handling functions: EPI-style
647 if ($this->functions_parameters_type == 'epivals') {
648 $r = call_user_func_array($func, array($methName, $params, $this->user_data));
649 // mimic EPI behaviour: if we get an array that looks like an error, make it
651 if (is_array($r) && array_key_exists('faultCode', $r) && array_key_exists('faultString', $r)) {
652 $r = new Response(0, (integer)$r['faultCode'], (string)$r['faultString']);
654 // functions using EPI api should NOT return resp objects,
655 // so make sure we encode the return type correctly
656 $r = new Response(php_xmlrpc_encode($r, array('extension_api')));
659 $r = call_user_func_array($func, $params);
662 // the return type can be either a Response object or a plain php value...
663 if (!is_a($r, '\PhpXmlRpc\Response')) {
664 // what should we assume here about automatic encoding of datetimes
665 // and php classes instances???
666 $r = new Response(php_xmlrpc_encode($r, $this->phpvals_encoding_options));
669 } catch (\Exception $e) {
670 // (barring errors in the lib) an uncatched exception happened
671 // in the called function, we wrap it in a proper error-response
672 switch ($this->exception_handling) {
677 $r = new Response(0, $e->getCode(), $e->getMessage());
680 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['server_error'], PhpXmlRpc::$xmlrpcstr['server_error']);
683 if ($this->debug > 2) {
684 // note: restore the error handler we found before calling the
685 // user func, even if it has been changed inside the func itself
686 if (self::$_xmlrpcs_prev_ehandler) {
687 set_error_handler(self::$_xmlrpcs_prev_ehandler);
689 restore_error_handler();
697 * add a string to the 'internal debug message' (separate from 'user debug message').
699 * @param string $string
701 protected function debugmsg($string)
703 $this->debug_info .= $string . "\n";
706 protected function xml_header($charsetEncoding = '')
708 if ($charsetEncoding != '') {
709 return "<?xml version=\"1.0\" encoding=\"$charsetEncoding\"?" . ">\n";
711 return "<?xml version=\"1.0\"?" . ">\n";
715 /* Functions that implement system.XXX methods of xmlrpc servers */
717 public function getSystemDispatchMap()
720 'system.listMethods' => array(
721 'function' => 'PhpXmlRpc\Server::_xmlrpcs_listMethods',
722 // listMethods: signature was either a string, or nothing.
723 // The useless string variant has been removed
724 'signature' => array(array(Value::$xmlrpcArray)),
725 'docstring' => 'This method lists all the methods that the XML-RPC server knows how to dispatch',
726 'signature_docs' => array(array('list of method names')),
728 'system.methodHelp' => array(
729 'function' => 'PhpXmlRpc\Server::_xmlrpcs_methodHelp',
730 'signature' => array(array(Value::$xmlrpcString, Value::$xmlrpcString)),
731 'docstring' => 'Returns help text if defined for the method passed, otherwise returns an empty string',
732 'signature_docs' => array(array('method description', 'name of the method to be described')),
734 'system.methodSignature' => array(
735 'function' => 'PhpXmlRpc\Server::_xmlrpcs_methodSignature',
736 'signature' => array(array(Value::$xmlrpcArray, Value::$xmlrpcString)),
737 'docstring' => 'Returns an array of known signatures (an array of arrays) for the method name passed. If no signatures are known, returns a none-array (test for type != array to detect missing signature)',
738 'signature_docs' => array(array('list of known signatures, each sig being an array of xmlrpc type names', 'name of method to be described')),
740 'system.multicall' => array(
741 'function' => 'PhpXmlRpc\Server::_xmlrpcs_multicall',
742 'signature' => array(array(Value::$xmlrpcArray, Value::$xmlrpcArray)),
743 'docstring' => 'Boxcar multiple RPC calls in one request. See http://www.xmlrpc.com/discuss/msgReader$1208 for details',
744 'signature_docs' => array(array('list of response structs, where each struct has the usual members', 'list of calls, with each call being represented as a struct, with members "methodname" and "params"')),
746 'system.getCapabilities' => array(
747 'function' => 'PhpXmlRpc\Server::_xmlrpcs_getCapabilities',
748 'signature' => array(array(Value::$xmlrpcStruct)),
749 'docstring' => 'This method lists all the capabilites that the XML-RPC server has: the (more or less standard) extensions to the xmlrpc spec that it adheres to',
750 'signature_docs' => array(array('list of capabilities, described as structs with a version number and url for the spec')),
755 public static function _xmlrpcs_getCapabilities($server, $req = null)
758 // xmlrpc spec: always supported
759 'xmlrpc' => new Value(array(
760 'specUrl' => new Value('http://www.xmlrpc.com/spec', 'string'),
761 'specVersion' => new Value(1, 'int'),
763 // if we support system.xxx functions, we always support multicall, too...
764 // Note that, as of 2006/09/17, the following URL does not respond anymore
765 'system.multicall' => new Value(array(
766 'specUrl' => new Value('http://www.xmlrpc.com/discuss/msgReader$1208', 'string'),
767 'specVersion' => new Value(1, 'int'),
769 // introspection: version 2! we support 'mixed', too
770 'introspection' => new Value(array(
771 'specUrl' => new Value('http://phpxmlrpc.sourceforge.net/doc-2/ch10.html', 'string'),
772 'specVersion' => new Value(2, 'int'),
777 if (PhpXmlRpc::$xmlrpc_null_extension) {
778 $outAr['nil'] = new Value(array(
779 'specUrl' => new Value('http://www.ontosys.com/xml-rpc/extensions.php', 'string'),
780 'specVersion' => new Value(1, 'int'),
784 return new Response(new Value($outAr, 'struct'));
787 public static function _xmlrpcs_listMethods($server, $req = null) // if called in plain php values mode, second param is missing
790 foreach ($server->dmap as $key => $val) {
791 $outAr[] = new Value($key, 'string');
793 if ($server->allow_system_funcs) {
794 foreach ($server->getSystemDispatchMap() as $key => $val) {
795 $outAr[] = new Value($key, 'string');
799 return new Response(new Value($outAr, 'array'));
802 public static function _xmlrpcs_methodSignature($server, $req)
804 // let accept as parameter both an xmlrpc value or string
805 if (is_object($req)) {
806 $methName = $req->getParam(0);
807 $methName = $methName->scalarval();
811 if (strpos($methName, "system.") === 0) {
812 $dmap = $server->getSystemDispatchMap();
814 $dmap = $server->dmap;
816 if (isset($dmap[$methName])) {
817 if (isset($dmap[$methName]['signature'])) {
819 foreach ($dmap[$methName]['signature'] as $inSig) {
821 foreach ($inSig as $sig) {
822 $curSig[] = new Value($sig, 'string');
824 $sigs[] = new Value($curSig, 'array');
826 $r = new Response(new Value($sigs, 'array'));
828 // NB: according to the official docs, we should be returning a
829 // "none-array" here, which means not-an-array
830 $r = new Response(new Value('undef', 'string'));
833 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['introspect_unknown'], PhpXmlRpc::$xmlrpcstr['introspect_unknown']);
839 public static function _xmlrpcs_methodHelp($server, $req)
841 // let accept as parameter both an xmlrpc value or string
842 if (is_object($req)) {
843 $methName = $req->getParam(0);
844 $methName = $methName->scalarval();
848 if (strpos($methName, "system.") === 0) {
849 $dmap = $server->getSystemDispatchMap();
851 $dmap = $server->dmap;
853 if (isset($dmap[$methName])) {
854 if (isset($dmap[$methName]['docstring'])) {
855 $r = new Response(new Value($dmap[$methName]['docstring']), 'string');
857 $r = new Response(new Value('', 'string'));
860 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['introspect_unknown'], PhpXmlRpc::$xmlrpcstr['introspect_unknown']);
866 public static function _xmlrpcs_multicall_error($err)
868 if (is_string($err)) {
869 $str = PhpXmlRpc::$xmlrpcstr["multicall_${err}"];
870 $code = PhpXmlRpc::$xmlrpcerr["multicall_${err}"];
872 $code = $err->faultCode();
873 $str = $err->faultString();
876 $struct['faultCode'] = new Value($code, 'int');
877 $struct['faultString'] = new Value($str, 'string');
879 return new Value($struct, 'struct');
882 public static function _xmlrpcs_multicall_do_call($server, $call)
884 if ($call->kindOf() != 'struct') {
885 return static::_xmlrpcs_multicall_error('notstruct');
887 $methName = @$call->structmem('methodName');
889 return static::_xmlrpcs_multicall_error('nomethod');
891 if ($methName->kindOf() != 'scalar' || $methName->scalartyp() != 'string') {
892 return static::_xmlrpcs_multicall_error('notstring');
894 if ($methName->scalarval() == 'system.multicall') {
895 return static::_xmlrpcs_multicall_error('recursion');
898 $params = @$call->structmem('params');
900 return static::_xmlrpcs_multicall_error('noparams');
902 if ($params->kindOf() != 'array') {
903 return static::_xmlrpcs_multicall_error('notarray');
905 $numParams = $params->arraysize();
907 $req = new Request($methName->scalarval());
908 for ($i = 0; $i < $numParams; $i++) {
909 if (!$req->addParam($params->arraymem($i))) {
912 return static::_xmlrpcs_multicall_error(new Response(0,
913 PhpXmlRpc::$xmlrpcerr['incorrect_params'],
914 PhpXmlRpc::$xmlrpcstr['incorrect_params'] . ": probable xml error in param " . $i));
918 $result = $server->execute($req);
920 if ($result->faultCode() != 0) {
921 return static::_xmlrpcs_multicall_error($result); // Method returned fault.
924 return new Value(array($result->value()), 'array');
927 public static function _xmlrpcs_multicall_do_call_phpvals($server, $call)
929 if (!is_array($call)) {
930 return static::_xmlrpcs_multicall_error('notstruct');
932 if (!array_key_exists('methodName', $call)) {
933 return static::_xmlrpcs_multicall_error('nomethod');
935 if (!is_string($call['methodName'])) {
936 return static::_xmlrpcs_multicall_error('notstring');
938 if ($call['methodName'] == 'system.multicall') {
939 return static::_xmlrpcs_multicall_error('recursion');
941 if (!array_key_exists('params', $call)) {
942 return static::_xmlrpcs_multicall_error('noparams');
944 if (!is_array($call['params'])) {
945 return static::_xmlrpcs_multicall_error('notarray');
948 // this is a real dirty and simplistic hack, since we might have received a
949 // base64 or datetime values, but they will be listed as strings here...
950 $numParams = count($call['params']);
952 $wrapper = new Wrapper();
953 foreach ($call['params'] as $val) {
954 $pt[] = $wrapper->php_2_xmlrpc_type(gettype($val));
957 $result = $server->execute($call['methodName'], $call['params'], $pt);
959 if ($result->faultCode() != 0) {
960 return static::_xmlrpcs_multicall_error($result); // Method returned fault.
963 return new Value(array($result->value()), 'array');
966 public static function _xmlrpcs_multicall($server, $req)
969 // let accept a plain list of php parameters, beside a single xmlrpc msg object
970 if (is_object($req)) {
971 $calls = $req->getParam(0);
972 $numCalls = $calls->arraysize();
973 for ($i = 0; $i < $numCalls; $i++) {
974 $call = $calls->arraymem($i);
975 $result[$i] = static::_xmlrpcs_multicall_do_call($server, $call);
978 $numCalls = count($req);
979 for ($i = 0; $i < $numCalls; $i++) {
980 $result[$i] = static::_xmlrpcs_multicall_do_call_phpvals($server, $req[$i]);
984 return new Response(new Value($result, 'array'));
988 * Error handler used to track errors that occur during server-side execution of PHP code.
989 * This allows to report back to the client whether an internal error has occurred or not
990 * using an xmlrpc response object, instead of letting the client deal with the html junk
991 * that a PHP execution error on the server generally entails.
993 * NB: in fact a user defined error handler can only handle WARNING, NOTICE and USER_* errors.
995 public static function _xmlrpcs_errorHandler($errCode, $errString, $filename = null, $lineNo = null, $context = null)
997 // obey the @ protocol
998 if (error_reporting() == 0) {
1002 //if($errCode != E_NOTICE && $errCode != E_WARNING && $errCode != E_USER_NOTICE && $errCode != E_USER_WARNING)
1003 if ($errCode != E_STRICT) {
1004 \PhpXmlRpc\Server::error_occurred($errString);
1006 // Try to avoid as much as possible disruption to the previous error handling
1007 // mechanism in place
1008 if (self::$_xmlrpcs_prev_ehandler == '') {
1009 // The previous error handler was the default: all we should do is log error
1010 // to the default error log (if level high enough)
1011 if (ini_get('log_errors') && (intval(ini_get('error_reporting')) & $errCode)) {
1012 error_log($errString);
1015 // Pass control on to previous error handler, trying to avoid loops...
1016 if (self::$_xmlrpcs_prev_ehandler != array('\PhpXmlRpc\Server', '_xmlrpcs_errorHandler')) {
1017 if (is_array(self::$_xmlrpcs_prev_ehandler)) {
1018 // the following works both with static class methods and plain object methods as error handler
1019 call_user_func_array(self::$_xmlrpcs_prev_ehandler, array($errCode, $errString, $filename, $lineNo, $context));
1021 $method = self::$_xmlrpcs_prev_ehandler;
1022 $method($errCode, $errString, $filename, $lineNo, $context);