5 use PhpXmlRpc\Helper\XMLParser;
6 use PhpXmlRpc\Helper\Charset;
7 use PhpXmlRpc\Helper\Encoder;
10 * Error handler used to track errors that occur during server-side execution of PHP code.
11 * This allows to report back to the client whether an internal error has occurred or not
12 * using an xmlrpc response object, instead of letting the client deal with the html junk
13 * that a PHP execution error on the server generally entails.
15 * NB: in fact a user defined error handler can only handle WARNING, NOTICE and USER_* errors.
18 function _xmlrpcs_errorHandler($errcode, $errstring, $filename=null, $lineno=null, $context=null)
20 // obey the @ protocol
21 if (error_reporting() == 0)
24 //if($errcode != E_NOTICE && $errcode != E_WARNING && $errcode != E_USER_NOTICE && $errcode != E_USER_WARNING)
25 if($errcode != E_STRICT)
27 \PhpXmlRpc\Server::error_occurred($errstring);
29 // Try to avoid as much as possible disruption to the previous error handling
31 if($GLOBALS['_xmlrpcs_prev_ehandler'] == '')
33 // The previous error handler was the default: all we should do is log error
34 // to the default error log (if level high enough)
35 if(ini_get('log_errors') && (intval(ini_get('error_reporting')) & $errcode))
37 error_log($errstring);
42 // Pass control on to previous error handler, trying to avoid loops...
43 if($GLOBALS['_xmlrpcs_prev_ehandler'] != '_xmlrpcs_errorHandler')
45 // NB: this code will NOT work on php < 4.0.2: only 2 params were used for error handlers
46 if(is_array($GLOBALS['_xmlrpcs_prev_ehandler']))
48 // the following works both with static class methods and plain object methods as error handler
49 call_user_func_array($GLOBALS['_xmlrpcs_prev_ehandler'], array($errcode, $errstring, $filename, $lineno, $context));
53 $GLOBALS['_xmlrpcs_prev_ehandler']($errcode, $errstring, $filename, $lineno, $context);
63 * Array defining php functions exposed as xmlrpc methods by this server
65 protected $dmap=array();
67 * Defines how functions in dmap will be invoked: either using an xmlrpc msg object
68 * or plain php values.
69 * valid strings are 'xmlrpcvals', 'phpvals' or 'epivals'
71 var $functions_parameters_type='xmlrpcvals';
73 * Option used for fine-tuning the encoding the php values returned from
74 * functions registered in the dispatch map when the functions_parameters_types
75 * member is set to 'phpvals'
76 * @see php_xmlrpc_encode for a list of values
78 var $phpvals_encoding_options = array( 'auto_dates' );
79 /// controls whether the server is going to echo debugging messages back to the client as comments in response body. valid values: 0,1,2,3
82 * Controls behaviour of server when invoked user function throws an exception:
83 * 0 = catch it and return an 'internal error' xmlrpc response (default)
84 * 1 = catch it and return an xmlrpc response with the error corresponding to the exception
85 * 2 = allow the exception to float to the upper layers
87 var $exception_handling = 0;
89 * When set to true, it will enable HTTP compression of the response, in case
90 * the client has declared its support for compression in the request.
92 var $compress_response = false;
94 * List of http compression methods accepted by the server for requests.
95 * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib
97 var $accepted_compression = array();
98 /// shall we serve calls to system.* methods?
99 var $allow_system_funcs = true;
100 /// list of charset encodings natively accepted for requests
101 var $accepted_charset_encodings = array();
103 * charset encoding to be used for response.
104 * NB: if we can, we will convert the generated response from internal_encoding to the intended one.
105 * can be: a supported xml encoding (only UTF-8 and ISO-8859-1 at present, unless mbstring is enabled),
106 * null (leave unspecified in response, convert output stream to US_ASCII),
107 * 'default' (use xmlrpc library default as specified in xmlrpc.inc, convert output stream if needed),
108 * 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).
109 * NB: pretty dangerous if you accept every charset and do not have mbstring enabled)
111 var $response_charset_encoding = '';
113 * Storage for internal debug info
115 protected $debug_info = '';
117 * Extra data passed at runtime to method handling functions. Used only by EPI layer
119 var $user_data = null;
121 static protected $_xmlrpc_debuginfo = '';
122 static protected $_xmlrpcs_occurred_errors = '';
123 static $_xmlrpcs_prev_ehandler = '';
126 * @param array $dispmap the dispatch map with definition of exposed services
127 * @param boolean $servicenow set to false to prevent the server from running upon construction
129 function __construct($dispMap=null, $serviceNow=true)
131 // if ZLIB is enabled, let the server by default accept compressed requests,
132 // and compress responses sent to clients that support them
133 if(function_exists('gzinflate'))
135 $this->accepted_compression = array('gzip', 'deflate');
136 $this->compress_response = true;
139 // by default the xml parser can support these 3 charset encodings
140 $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII');
142 // dispMap is a dispatch array of methods
143 // mapped to function names and signatures
145 // doesn't appear in the map then an unknown
146 // method error is generated
147 /* milosch - changed to make passing dispMap optional.
148 * instead, you can use the class add_to_map() function
149 * to add functions manually (borrowed from SOAPX4)
153 $this->dmap = $dispMap;
162 * Set debug level of server.
163 * @param integer $in debug lvl: determines info added to xmlrpc responses (as xml comments)
165 * 1 = msgs set from user with debugmsg(),
166 * 2 = add complete xmlrpc request (headers and body),
167 * 3 = add also all processing warnings happened during method processing
168 * (NB: this involves setting a custom error handler, and might interfere
169 * with the standard processing of the php function exposed as method. In
170 * particular, triggering an USER_ERROR level error will not halt script
171 * execution anymore, but just end up logged in the xmlrpc response)
172 * Note that info added at level 2 and 3 will be base64 encoded
174 function setDebug($in)
180 * Add a string to the debug info that can be later serialized by the server
181 * as part of the response message.
182 * Note that for best compatibility, the debug string should be encoded using
183 * the PhpXmlRpc::$xmlrpc_internalencoding character set.
187 public static function xmlrpc_debugmsg($m)
189 static::$_xmlrpc_debuginfo .= $m . "\n";
192 public static function error_occurred($m)
194 static::$_xmlrpcs_occurred_errors .= $m . "\n";
198 * Return a string with the serialized representation of all debug info
199 * @param string $charset_encoding the target charset encoding for the serialization
200 * @return string an XML comment (or two)
202 function serializeDebug($charset_encoding='')
204 // Tough encoding problem: which internal charset should we assume for debug info?
205 // It might contain a copy of raw data received from client, ie with unknown encoding,
206 // intermixed with php generated data and user generated data...
207 // so we split it: system debug is base 64 encoded,
208 // user debug info should be encoded by the end user using the INTERNAL_ENCODING
210 if ($this->debug_info != '')
212 $out .= "<!-- SERVER DEBUG INFO (BASE64 ENCODED):\n".base64_encode($this->debug_info)."\n-->\n";
214 if( static::$_xmlrpc_debuginfo!='')
217 $out .= "<!-- DEBUG INFO:\n" . Charset::instance()->encode_entities(str_replace('--', '_-', static::$_xmlrpc_debuginfo), PhpXmlRpc::$xmlrpc_internalencoding, $charset_encoding) . "\n-->\n";
218 // NB: a better solution MIGHT be to use CDATA, but we need to insert it
219 // into return payload AFTER the beginning tag
220 //$out .= "<![CDATA[ DEBUG INFO:\n\n" . str_replace(']]>', ']_]_>', static::$_xmlrpc_debuginfo) . "\n]]>\n";
226 * Execute the xmlrpc request, printing the response
227 * @param string $data the request body. If null, the http POST request will be examined
228 * @param bool $return_payload When true, return the response but do not echo it or any http header
229 * @return Response the response object (usually not used by caller...)
231 function service($data=null, $return_payload=false)
235 // workaround for a known bug in php ver. 5.2.2 that broke $HTTP_RAW_POST_DATA
236 $data = file_get_contents('php://input');
240 // reset internal debug info
241 $this->debug_info = '';
243 // Echo back what we received, before parsing it
246 $this->debugmsg("+++GOT+++\n" . $data . "\n+++END+++");
249 $r = $this->parseRequestHeaders($data, $req_charset, $resp_charset, $resp_encoding);
252 $r=$this->parseRequest($data, $req_charset);
255 // save full body of request into response, for more debugging usages
256 $r->raw_data = $raw_data;
258 if($this->debug > 2 && static::$_xmlrpcs_occurred_errors)
260 $this->debugmsg("+++PROCESSING ERRORS AND WARNINGS+++\n" .
261 static::$_xmlrpcs_occurred_errors . "+++END+++");
264 $payload=$this->xml_header($resp_charset);
267 $payload = $payload . $this->serializeDebug($resp_charset);
270 // G. Giunta 2006-01-27: do not create response serialization if it has
271 // already happened. Helps building json magic
272 if (empty($r->payload))
274 $r->serialize($resp_charset);
276 $payload = $payload . $r->payload;
283 // if we get a warning/error that has output some text before here, then we cannot
284 // add a new header. We cannot say we are sending xml, either...
287 header('Content-Type: '.$r->content_type);
288 // we do not know if client actually told us an accepted charset, but if he did
289 // we have to tell him what we did
290 header("Vary: Accept-Charset");
292 // http compression of output: only
293 // if we can do it, and we want to do it, and client asked us to,
294 // and php ini settings do not force it already
295 $php_no_self_compress = !ini_get('zlib.output_compression') && (ini_get('output_handler') != 'ob_gzhandler');
296 if($this->compress_response && function_exists('gzencode') && $resp_encoding != ''
297 && $php_no_self_compress)
299 if(strpos($resp_encoding, 'gzip') !== false)
301 $payload = gzencode($payload);
302 header("Content-Encoding: gzip");
303 header("Vary: Accept-Encoding");
305 elseif (strpos($resp_encoding, 'deflate') !== false)
307 $payload = gzcompress($payload);
308 header("Content-Encoding: deflate");
309 header("Vary: Accept-Encoding");
313 // do not output content-length header if php is compressing output for us:
314 // it will mess up measurements
315 if($php_no_self_compress)
317 header('Content-Length: ' . (int)strlen($payload));
322 error_log('XML-RPC: '.__METHOD__.': http headers already sent before response is fully generated. Check for php warning or error messages');
327 // return request, in case subclasses want it
332 * Add a method to the dispatch map
333 * @param string $methodname the name with which the method will be made available
334 * @param string $function the php function that will get invoked
335 * @param array $sig the array of valid method signatures
336 * @param string $doc method documentation
337 * @param array $sigdoc the array of valid method signatures docs (one string per param, one for return type)
339 function add_to_map($methodname,$function,$sig=null,$doc=false,$sigdoc=false)
341 $this->dmap[$methodname] = array(
342 'function' => $function,
347 $this->dmap[$methodname]['signature'] = $sig;
351 $this->dmap[$methodname]['signature_docs'] = $sigdoc;
356 * Verify type and number of parameters received against a list of known signatures
357 * @param array $in array of either xmlrpcval objects or xmlrpc type definitions
358 * @param array $sig array of known signatures to match against
361 protected function verifySignature($in, $sig)
363 // check each possible signature in turn
366 $numParams = $in->getNumParams();
370 $numParams = count($in);
372 foreach($sig as $cursig)
374 if(count($cursig)==$numParams+1)
377 for($n=0; $n<$numParams; $n++)
381 $p=$in->getParam($n);
382 if($p->kindOf() == 'scalar')
393 $pt= $in[$n] == 'i4' ? 'int' : strtolower($in[$n]); // dispatch maps never use i4...
396 // param index is $n+1, as first member of sig is return type
397 if($pt != $cursig[$n+1] && $cursig[$n+1] != Value::$xmlrpcValue)
401 $wanted=$cursig[$n+1];
414 return array(0, "Wanted ${wanted}, got ${got} at param ${pno}");
418 return array(0, "No method signature matches number of parameters");
423 * Parse http headers received along with xmlrpc request. If needed, inflate request
424 * @return mixed null on success or an xmlrpcresp
426 protected function parseRequestHeaders(&$data, &$req_encoding, &$resp_encoding, &$resp_compression)
428 // check if $_SERVER is populated: it might have been disabled via ini file
429 // (this is true even when in CLI mode)
430 if (count($_SERVER) == 0)
432 error_log('XML-RPC: '.__METHOD__.': cannot parse request headers as $_SERVER is not populated');
437 if(function_exists('getallheaders'))
439 $this->debugmsg(''); // empty line
440 foreach(getallheaders() as $name => $val)
442 $this->debugmsg("HEADER: $name: $val");
448 if(isset($_SERVER['HTTP_CONTENT_ENCODING']))
450 $content_encoding = str_replace('x-', '', $_SERVER['HTTP_CONTENT_ENCODING']);
454 $content_encoding = '';
457 // check if request body has been compressed and decompress it
458 if($content_encoding != '' && strlen($data))
460 if($content_encoding == 'deflate' || $content_encoding == 'gzip')
462 // if decoding works, use it. else assume data wasn't gzencoded
463 if(function_exists('gzinflate') && in_array($content_encoding, $this->accepted_compression))
465 if($content_encoding == 'deflate' && $degzdata = @gzuncompress($data))
470 $this->debugmsg("\n+++INFLATED REQUEST+++[".strlen($data)." chars]+++\n" . $data . "\n+++END+++");
473 elseif($content_encoding == 'gzip' && $degzdata = @gzinflate(substr($data, 10)))
477 $this->debugmsg("+++INFLATED REQUEST+++[".strlen($data)." chars]+++\n" . $data . "\n+++END+++");
481 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['server_decompress_fail'], PhpXmlRpc::$xmlrpcstr['server_decompress_fail']);
487 //error_log('The server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
488 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['server_cannot_decompress'], PhpXmlRpc::$xmlrpcstr['server_cannot_decompress']);
494 // check if client specified accepted charsets, and if we know how to fulfill
496 if ($this->response_charset_encoding == 'auto')
499 if (isset($_SERVER['HTTP_ACCEPT_CHARSET']))
501 // here we should check if we can match the client-requested encoding
502 // with the encodings we know we can generate.
503 /// @todo we should parse q=0.x preferences instead of getting first charset specified...
504 $client_accepted_charsets = explode(',', strtoupper($_SERVER['HTTP_ACCEPT_CHARSET']));
505 // Give preference to internal encoding
506 $known_charsets = array(PhpXmlRpc::$xmlrpc_internalencoding, 'UTF-8', 'ISO-8859-1', 'US-ASCII');
507 foreach ($known_charsets as $charset)
509 foreach ($client_accepted_charsets as $accepted)
510 if (strpos($accepted, $charset) === 0)
512 $resp_encoding = $charset;
522 $resp_encoding = $this->response_charset_encoding;
525 if (isset($_SERVER['HTTP_ACCEPT_ENCODING']))
527 $resp_compression = $_SERVER['HTTP_ACCEPT_ENCODING'];
531 $resp_compression = '';
534 // 'guestimate' request encoding
535 /// @todo check if mbstring is enabled and automagic input conversion is on: it might mingle with this check???
536 $req_encoding = Encoder::guess_encoding(isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '',
543 * Parse an xml chunk containing an xmlrpc request and execute the corresponding
544 * php function registered with the server
545 * @param string $data the xml request
546 * @param string $req_encoding (optional) the charset encoding of the xml request
549 public function parseRequest($data, $req_encoding='')
551 // 2005/05/07 commented and moved into caller function code
554 // $data=$GLOBALS['HTTP_RAW_POST_DATA'];
557 // G. Giunta 2005/02/13: we do NOT expect to receive html entities
558 // so we do not try to convert them into xml character entities
559 //$data = xmlrpc_html_entity_xlate($data);
561 // decompose incoming XML into request structure
562 if ($req_encoding != '')
564 if (!in_array($req_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
565 // the following code might be better for mb_string enabled installs, but
566 // makes the lib about 200% slower...
567 //if (!is_valid_charset($req_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
569 error_log('XML-RPC: '.__METHOD__.': invalid charset encoding of received request: '.$req_encoding);
570 $req_encoding = PhpXmlRpc::$xmlrpc_defencoding;
572 /// @BUG this will fail on PHP 5 if charset is not specified in the xml prologue,
573 // the encoding is not UTF8 and there are non-ascii chars in the text...
574 /// @todo use an empty string for php 5 ???
575 $parser = xml_parser_create($req_encoding);
579 $parser = xml_parser_create();
582 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
583 // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell
584 // the xml parser to give us back data in the expected charset
585 // What if internal encoding is not in one of the 3 allowed?
586 // we use the broadest one, ie. utf8
587 // This allows to send data which is native in various charset,
588 // by extending xmlrpc_encode_entities() and setting xmlrpc_internalencoding
589 if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
591 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
595 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding);
598 $xmlRpcParser = new XMLParser();
599 xml_set_object($parser, $xmlRpcParser);
601 if ($this->functions_parameters_type != 'xmlrpcvals')
602 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
604 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');
605 xml_set_character_data_handler($parser, 'xmlrpc_cd');
606 xml_set_default_handler($parser, 'xmlrpc_dh');
607 if(!xml_parse($parser, $data, 1))
609 // return XML error as a faultCode
611 PhpXmlRpc::$xmlrpcerrxml+xml_get_error_code($parser),
612 sprintf('XML error: %s at line %d, column %d',
613 xml_error_string(xml_get_error_code($parser)),
614 xml_get_current_line_number($parser), xml_get_current_column_number($parser)));
615 xml_parser_free($parser);
617 elseif ($xmlRpcParser->_xh['isf'])
619 xml_parser_free($parser);
621 PhpXmlRpc::$xmlrpcerr['invalid_request'],
622 PhpXmlRpc::$xmlrpcstr['invalid_request'] . ' ' . $xmlRpcParser->_xh['isf_reason']);
626 xml_parser_free($parser);
627 // small layering violation in favor of speed and memory usage:
628 // we should allow the 'execute' method handle this, but in the
629 // most common scenario (xmlrpcvals type server with some methods
630 // registered as phpvals) that would mean a useless encode+decode pass
631 if ($this->functions_parameters_type != 'xmlrpcvals' || (isset($this->dmap[$xmlRpcParser->_xh['method']]['parameters_type']) && ($this->dmap[$xmlRpcParser->_xh['method']]['parameters_type'] == 'phpvals')))
635 $this->debugmsg("\n+++PARSED+++\n".var_export($xmlRpcParser->_xh['params'], true)."\n+++END+++");
637 $r = $this->execute($xmlRpcParser->_xh['method'], $xmlRpcParser->_xh['params'], $xmlRpcParser->_xh['pt']);
641 // build a Request object with data parsed from xml
642 $m=new Request($xmlRpcParser->_xh['method']);
643 // now add parameters in
644 for($i=0; $i<count($xmlRpcParser->_xh['params']); $i++)
646 $m->addParam($xmlRpcParser->_xh['params'][$i]);
651 $this->debugmsg("\n+++PARSED+++\n".var_export($m, true)."\n+++END+++");
653 $r = $this->execute($m);
660 * Execute a method invoked by the client, checking parameters used
661 * @param mixed $m either an xmlrpcmsg obj or a method name
662 * @param array $params array with method parameters as php types (if m is method name only)
663 * @param array $paramtypes array with xmlrpc types of method parameters (if m is method name only)
666 protected function execute($m, $params=null, $paramtypes=null)
670 $methName = $m->method();
676 $sysCall = $this->allow_system_funcs && (strpos($methName, "system.") === 0);
677 $dmap = $sysCall ? $this->getSystemDispatchMap() : $this->dmap;
679 if(!isset($dmap[$methName]['function']))
682 return new Response(0,
683 PhpXmlRpc::$xmlrpcerr['unknown_method'],
684 PhpXmlRpc::$xmlrpcstr['unknown_method']);
688 if(isset($dmap[$methName]['signature']))
690 $sig = $dmap[$methName]['signature'];
693 list($ok, $errstr) = $this->verifySignature($m, $sig);
697 list($ok, $errstr) = $this->verifySignature($paramtypes, $sig);
704 PhpXmlRpc::$xmlrpcerr['incorrect_params'],
705 PhpXmlRpc::$xmlrpcstr['incorrect_params'] . ": ${errstr}"
710 $func = $dmap[$methName]['function'];
711 // let the 'class::function' syntax be accepted in dispatch maps
712 if(is_string($func) && strpos($func, '::'))
714 $func = explode('::', $func);
716 // verify that function to be invoked is in fact callable
717 if(!is_callable($func))
719 error_log("XML-RPC: ".__METHOD__.": function $func registered as method handler is not callable");
722 PhpXmlRpc::$xmlrpcerr['server_error'],
723 PhpXmlRpc::$xmlrpcstr['server_error'] . ": no function matches method"
727 // If debug level is 3, we should catch all errors generated during
728 // processing of user function, and log them as part of response
731 $GLOBALS['_xmlrpcs_prev_ehandler'] = set_error_handler('_xmlrpcs_errorHandler');
735 // Allow mixed-convention servers
740 $r = call_user_func($func, $this, $m);
744 $r = call_user_func($func, $m);
746 if (!is_a($r, 'xmlrpcresp'))
748 error_log("XML-RPC: ".__METHOD__.": function $func registered as method handler does not return an xmlrpcresp object");
749 if (is_a($r, 'PhpXmlRpc\Value'))
751 $r = new Response($r);
757 PhpXmlRpc::$xmlrpcerr['server_error'],
758 PhpXmlRpc::$xmlrpcstr['server_error'] . ": function does not return xmlrpcresp object"
765 // call a 'plain php' function
768 array_unshift($params, $this);
769 $r = call_user_func_array($func, $params);
773 // 3rd API convention for method-handling functions: EPI-style
774 if ($this->functions_parameters_type == 'epivals')
776 $r = call_user_func_array($func, array($methName, $params, $this->user_data));
777 // mimic EPI behaviour: if we get an array that looks like an error, make it
779 if (is_array($r) && array_key_exists('faultCode', $r) && array_key_exists('faultString', $r))
781 $r = new Response(0, (integer)$r['faultCode'], (string)$r['faultString']);
785 // functions using EPI api should NOT return resp objects,
786 // so make sure we encode the return type correctly
787 $r = new Response(php_xmlrpc_encode($r, array('extension_api')));
792 $r = call_user_func_array($func, $params);
795 // the return type can be either an xmlrpcresp object or a plain php value...
796 if (!is_a($r, 'xmlrpcresp'))
798 // what should we assume here about automatic encoding of datetimes
799 // and php classes instances???
800 $r = new Response(php_xmlrpc_encode($r, $this->phpvals_encoding_options));
806 // (barring errors in the lib) an uncatched exception happened
807 // in the called function, we wrap it in a proper error-response
808 switch($this->exception_handling)
814 $r = new Response(0, $e->getCode(), $e->getMessage());
817 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['server_error'], PhpXmlRpc::$xmlrpcstr['server_error']);
822 // note: restore the error handler we found before calling the
823 // user func, even if it has been changed inside the func itself
824 if($GLOBALS['_xmlrpcs_prev_ehandler'])
826 set_error_handler($GLOBALS['_xmlrpcs_prev_ehandler']);
830 restore_error_handler();
837 * add a string to the 'internal debug message' (separate from 'user debug message')
838 * @param string $string
840 protected function debugmsg($string)
842 $this->debug_info .= $string."\n";
845 protected function xml_header($charset_encoding='')
847 if ($charset_encoding != '')
849 return "<?xml version=\"1.0\" encoding=\"$charset_encoding\"?" . ">\n";
853 return "<?xml version=\"1.0\"?" . ">\n";
858 * A debugging routine: just echoes back the input packet as a string value
863 $r=new Response(new Value( "'Aha said I: '" . $GLOBALS['HTTP_RAW_POST_DATA'], 'string'));
864 print $r->serialize();
867 /* Functions that implement system.XXX methods of xmlrpc servers */
869 public function getSystemDispatchMap()
872 'system.listMethods' => array(
873 'function' => 'PhpXmlRpc\Server::_xmlrpcs_listMethods',
874 // listMethods: signature was either a string, or nothing.
875 // The useless string variant has been removed
876 'signature' => array(array(Value::$xmlrpcArray)),
877 'docstring' => 'This method lists all the methods that the XML-RPC server knows how to dispatch',
878 'signature_docs' => array(array('list of method names')),
880 'system.methodHelp' => array(
881 'function' => 'PhpXmlRpc\Server::_xmlrpcs_methodHelp',
882 'signature' => array(array(Value::$xmlrpcString, Value::$xmlrpcString)),
883 'docstring' => 'Returns help text if defined for the method passed, otherwise returns an empty string',
884 'signature_docs' => array(array('method description', 'name of the method to be described')),
886 'system.methodSignature' => array(
887 'function' => 'PhpXmlRpc\Server::_xmlrpcs_methodSignature',
888 'signature' => array(array(Value::$xmlrpcArray, Value::$xmlrpcString)),
889 '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)',
890 'signature_docs' => array(array('list of known signatures, each sig being an array of xmlrpc type names', 'name of method to be described')),
892 'system.multicall' => array(
893 'function' => 'PhpXmlRpc\Server::_xmlrpcs_multicall',
894 'signature' => array(array(Value::$xmlrpcArray, Value::$xmlrpcArray)),
895 'docstring' => 'Boxcar multiple RPC calls in one request. See http://www.xmlrpc.com/discuss/msgReader$1208 for details',
896 '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"')),
898 'system.getCapabilities' => array(
899 'function' => 'PhpXmlRpc\Server::_xmlrpcs_getCapabilities',
900 'signature' => array(array(Value::$xmlrpcStruct)),
901 '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',
902 'signature_docs' => array(array('list of capabilities, described as structs with a version number and url for the spec'))
907 public static function _xmlrpcs_getCapabilities($server, $m=null)
910 // xmlrpc spec: always supported
911 'xmlrpc' => new Value(array(
912 'specUrl' => new Value('http://www.xmlrpc.com/spec', 'string'),
913 'specVersion' => new Value(1, 'int')
915 // if we support system.xxx functions, we always support multicall, too...
916 // Note that, as of 2006/09/17, the following URL does not respond anymore
917 'system.multicall' => new Value(array(
918 'specUrl' => new Value('http://www.xmlrpc.com/discuss/msgReader$1208', 'string'),
919 'specVersion' => new Value(1, 'int')
921 // introspection: version 2! we support 'mixed', too
922 'introspection' => new Value(array(
923 'specUrl' => new Value('http://phpxmlrpc.sourceforge.net/doc-2/ch10.html', 'string'),
924 'specVersion' => new Value(2, 'int')
929 if (PhpXmlRpc::$xmlrpc_null_extension) {
930 $outAr['nil'] = new Value(array(
931 'specUrl' => new Value('http://www.ontosys.com/xml-rpc/extensions.php', 'string'),
932 'specVersion' => new Value(1, 'int')
935 return new Response(new Value($outAr, 'struct'));
938 public static function _xmlrpcs_listMethods($server, $m=null) // if called in plain php values mode, second param is missing
942 foreach($server->dmap as $key => $val)
944 $outAr[]=new Value($key, 'string');
946 if($server->allow_system_funcs)
948 foreach($server->getSystemDispatchMap() as $key => $val)
950 $outAr[]=new Value($key, 'string');
953 return new Response(new Value($outAr, 'array'));
956 public static function _xmlrpcs_methodSignature($server, $m)
958 // let accept as parameter both an xmlrpcval or string
961 $methName=$m->getParam(0);
962 $methName=$methName->scalarval();
968 if(strpos($methName, "system.") === 0)
970 $dmap=$server->getSystemDispatchMap();
976 if(isset($dmap[$methName]))
978 if(isset($dmap[$methName]['signature']))
981 foreach($dmap[$methName]['signature'] as $inSig)
984 foreach($inSig as $sig)
986 $cursig[]=new Value($sig, 'string');
988 $sigs[]=new Value($cursig, 'array');
990 $r=new Response(new Value($sigs, 'array'));
994 // NB: according to the official docs, we should be returning a
995 // "none-array" here, which means not-an-array
996 $r=new Response(new Value('undef', 'string'));
1001 $r=new Response(0,PhpXmlRpc::$xmlrpcerr['introspect_unknown'], PhpXmlRpc::$xmlrpcstr['introspect_unknown']);
1006 public static function _xmlrpcs_methodHelp($server, $m)
1008 // let accept as parameter both an xmlrpcval or string
1011 $methName=$m->getParam(0);
1012 $methName=$methName->scalarval();
1018 if(strpos($methName, "system.") === 0)
1020 $dmap=$server->getSystemDispatchMap();
1024 $dmap=$server->dmap;
1026 if(isset($dmap[$methName]))
1028 if(isset($dmap[$methName]['docstring']))
1030 $r=new Response(new Value($dmap[$methName]['docstring']), 'string');
1034 $r=new Response(new Value('', 'string'));
1039 $r=new Response(0, PhpXmlRpc::$xmlrpcerr['introspect_unknown'], PhpXmlRpc::$xmlrpcstr['introspect_unknown']);
1044 public static function _xmlrpcs_multicall_error($err)
1048 $str = PhpXmlRpc::$xmlrpcstr["multicall_${err}"];
1049 $code = PhpXmlRpc::$xmlrpcerr["multicall_${err}"];
1053 $code = $err->faultCode();
1054 $str = $err->faultString();
1057 $struct['faultCode'] = new Value($code, 'int');
1058 $struct['faultString'] = new Value($str, 'string');
1059 return new Value($struct, 'struct');
1062 public static function _xmlrpcs_multicall_do_call($server, $call)
1064 if($call->kindOf() != 'struct')
1066 return _xmlrpcs_multicall_error('notstruct');
1068 $methName = @$call->structmem('methodName');
1071 return _xmlrpcs_multicall_error('nomethod');
1073 if($methName->kindOf() != 'scalar' || $methName->scalartyp() != 'string')
1075 return _xmlrpcs_multicall_error('notstring');
1077 if($methName->scalarval() == 'system.multicall')
1079 return _xmlrpcs_multicall_error('recursion');
1082 $params = @$call->structmem('params');
1085 return _xmlrpcs_multicall_error('noparams');
1087 if($params->kindOf() != 'array')
1089 return _xmlrpcs_multicall_error('notarray');
1091 $numParams = $params->arraysize();
1093 $msg = new Request($methName->scalarval());
1094 for($i = 0; $i < $numParams; $i++)
1096 if(!$msg->addParam($params->arraymem($i)))
1099 return _xmlrpcs_multicall_error(new Response(0,
1100 PhpXmlRpc::$xmlrpcerr['incorrect_params'],
1101 PhpXmlRpc::$xmlrpcstr['incorrect_params'] . ": probable xml error in param " . $i));
1105 $result = $server->execute($msg);
1107 if($result->faultCode() != 0)
1109 return _xmlrpcs_multicall_error($result); // Method returned fault.
1112 return new Value(array($result->value()), 'array');
1115 public static function _xmlrpcs_multicall_do_call_phpvals($server, $call)
1117 if(!is_array($call))
1119 return _xmlrpcs_multicall_error('notstruct');
1121 if(!array_key_exists('methodName', $call))
1123 return _xmlrpcs_multicall_error('nomethod');
1125 if (!is_string($call['methodName']))
1127 return _xmlrpcs_multicall_error('notstring');
1129 if($call['methodName'] == 'system.multicall')
1131 return _xmlrpcs_multicall_error('recursion');
1133 if(!array_key_exists('params', $call))
1135 return _xmlrpcs_multicall_error('noparams');
1137 if(!is_array($call['params']))
1139 return _xmlrpcs_multicall_error('notarray');
1142 // this is a real dirty and simplistic hack, since we might have received a
1143 // base64 or datetime values, but they will be listed as strings here...
1144 $numParams = count($call['params']);
1146 foreach($call['params'] as $val)
1147 $pt[] = php_2_xmlrpc_type(gettype($val));
1149 $result = $server->execute($call['methodName'], $call['params'], $pt);
1151 if($result->faultCode() != 0)
1153 return _xmlrpcs_multicall_error($result); // Method returned fault.
1156 return new Value(array($result->value()), 'array');
1159 public static function _xmlrpcs_multicall($server, $m)
1162 // let accept a plain list of php parameters, beside a single xmlrpc msg object
1165 $calls = $m->getParam(0);
1166 $numCalls = $calls->arraysize();
1167 for($i = 0; $i < $numCalls; $i++)
1169 $call = $calls->arraymem($i);
1170 $result[$i] = _xmlrpcs_multicall_do_call($server, $call);
1175 $numCalls=count($m);
1176 for($i = 0; $i < $numCalls; $i++)
1178 $result[$i] = _xmlrpcs_multicall_do_call_phpvals($server, $m[$i]);
1182 return new Response(new Value($result, 'array'));