3 * IXR - The Inutio XML-RPC Library - (c) Incutio Ltd 2002
6 * @author Simon Willison
8 * @link http://scripts.incutio.com/xmlrpc/
9 * @link http://scripts.incutio.com/xmlrpc/manual.php
10 * @license Artistic License http://www.opensource.org/licenses/artistic-license.php
12 * Modified for DokuWiki
13 * @author Andreas Gohr <andi@splitbrain.org>
20 function IXR_Value ($data, $type = false) {
23 $type = $this->calculateType();
26 if ($type == 'struct') {
27 /* Turn all the values in the array in to new IXR_Value objects */
28 foreach ($this->data as $key => $value) {
29 $this->data[$key] = new IXR_Value($value);
32 if ($type == 'array') {
33 for ($i = 0, $j = count($this->data); $i < $j; $i++) {
34 $this->data[$i] = new IXR_Value($this->data[$i]);
38 function calculateType() {
39 if ($this->data === true || $this->data === false) {
42 if (is_integer($this->data)) {
45 if (is_double($this->data)) {
48 // Deal with IXR object types base64 and date
49 if (is_object($this->data) && is_a($this->data, 'IXR_Date')) {
52 if (is_object($this->data) && is_a($this->data, 'IXR_Base64')) {
55 // If it is a normal PHP object convert it in to a struct
56 if (is_object($this->data)) {
58 $this->data = get_object_vars($this->data);
61 if (!is_array($this->data)) {
64 /* We have an array - is it an array or a struct ? */
65 if ($this->isStruct($this->data)) {
72 /* Return XML for this value */
73 switch ($this->type) {
75 return '<boolean>'.(($this->data) ? '1' : '0').'</boolean>';
78 return '<int>'.$this->data.'</int>';
81 return '<double>'.$this->data.'</double>';
84 return '<string>'.htmlspecialchars($this->data).'</string>';
87 $return = '<array><data>'."\n";
88 foreach ($this->data as $item) {
89 $return .= ' <value>'.$item->getXml()."</value>\n";
91 $return .= '</data></array>';
95 $return = '<struct>'."\n";
96 foreach ($this->data as $name => $value) {
97 $return .= " <member><name>$name</name><value>";
98 $return .= $value->getXml()."</value></member>\n";
100 $return .= '</struct>';
105 return $this->data->getXml();
110 function isStruct($array) {
111 /* Nasty function to check if an array is a struct or not */
113 foreach ($array as $key => $value) {
114 if ((string)$key != (string)$expected) {
126 var $messageType; // methodCall / methodResponse / fault
131 // Current variable stacks
132 var $_arraystructs = array(); // The stack used to keep track of the current array/struct
133 var $_arraystructstypes = array(); // Stack keeping track of if things are structs or array
134 var $_currentStructName = array(); // A stack as well
138 var $_currentTagContents;
142 function IXR_Message ($message) {
143 $this->message = $message;
146 // first remove the XML declaration
147 $this->message = preg_replace('/<\?xml(.*)?\?'.'>/', '', $this->message);
148 // workaround for a bug in PHP/libxml2, see http://bugs.php.net/bug.php?id=45996
149 $this->message = str_replace('<', '<', $this->message);
150 $this->message = str_replace('>', '>', $this->message);
151 $this->message = str_replace('&', '&', $this->message);
152 $this->message = str_replace(''', ''', $this->message);
153 $this->message = str_replace('"', '"', $this->message);
154 $this->message = str_replace("\x0b", ' ', $this->message); //vertical tab
155 if (trim($this->message) == '') {
158 $this->_parser = xml_parser_create();
159 // Set XML parser to take the case of tags in to account
160 xml_parser_set_option($this->_parser, XML_OPTION_CASE_FOLDING, false);
161 // Set XML parser callback functions
162 xml_set_object($this->_parser, $this);
163 xml_set_element_handler($this->_parser, 'tag_open', 'tag_close');
164 xml_set_character_data_handler($this->_parser, 'cdata');
165 if (!xml_parse($this->_parser, $this->message)) {
166 /* die(sprintf('XML error: %s at line %d',
167 xml_error_string(xml_get_error_code($this->_parser)),
168 xml_get_current_line_number($this->_parser))); */
171 xml_parser_free($this->_parser);
172 // Grab the error messages, if any
173 if ($this->messageType == 'fault') {
174 $this->faultCode = $this->params[0]['faultCode'];
175 $this->faultString = $this->params[0]['faultString'];
179 function tag_open($parser, $tag, $attr) {
180 $this->currentTag = $tag;
181 $this->_currentTagContents = '';
184 case 'methodResponse':
186 $this->messageType = $tag;
188 /* Deal with stacks of arrays and structs */
189 case 'data': // data is to all intents and puposes more interesting than array
190 $this->_arraystructstypes[] = 'array';
191 $this->_arraystructs[] = array();
194 $this->_arraystructstypes[] = 'struct';
195 $this->_arraystructs[] = array();
198 $this->_lastseen = $tag;
200 function cdata($parser, $cdata) {
201 $this->_currentTagContents .= $cdata;
203 function tag_close($parser, $tag) {
208 $value = (int)trim($this->_currentTagContents);
209 $this->_currentTagContents = '';
213 $value = (double)trim($this->_currentTagContents);
214 $this->_currentTagContents = '';
218 $value = (string)$this->_currentTagContents;
219 $this->_currentTagContents = '';
222 case 'dateTime.iso8601':
223 $value = new IXR_Date(trim($this->_currentTagContents));
224 // $value = $iso->getTimestamp();
225 $this->_currentTagContents = '';
229 // "If no type is indicated, the type is string."
230 if($this->_lastseen == 'value'){
231 $value = (string)$this->_currentTagContents;
232 $this->_currentTagContents = '';
237 $value = (boolean)trim($this->_currentTagContents);
238 $this->_currentTagContents = '';
242 $value = base64_decode($this->_currentTagContents);
243 $this->_currentTagContents = '';
246 /* Deal with stacks of arrays and structs */
249 $value = array_pop($this->_arraystructs);
250 array_pop($this->_arraystructstypes);
254 array_pop($this->_currentStructName);
257 $this->_currentStructName[] = trim($this->_currentTagContents);
258 $this->_currentTagContents = '';
261 $this->methodName = trim($this->_currentTagContents);
262 $this->_currentTagContents = '';
267 if (!is_array($value) && !is_object($value)) {
268 $value = trim($value);
271 if (count($this->_arraystructs) > 0) {
272 // Add value to struct or array
273 if ($this->_arraystructstypes[count($this->_arraystructstypes)-1] == 'struct') {
275 $this->_arraystructs[count($this->_arraystructs)-1][$this->_currentStructName[count($this->_currentStructName)-1]] = $value;
278 $this->_arraystructs[count($this->_arraystructs)-1][] = $value;
281 // Just add as a paramater
282 $this->params[] = $value;
285 $this->_lastseen = $tag;
292 var $callbacks = array();
295 function IXR_Server($callbacks = false, $data = false) {
296 $this->setCapabilities();
298 $this->callbacks = $callbacks;
300 $this->setCallbacks();
303 function serve($data = false) {
305 global $HTTP_RAW_POST_DATA;
306 if (!$HTTP_RAW_POST_DATA) {
307 die('XML-RPC server accepts POST requests only.');
309 $data = $HTTP_RAW_POST_DATA;
311 $this->message = new IXR_Message($data);
312 if (!$this->message->parse()) {
313 $this->error(-32700, 'parse error. not well formed');
315 if ($this->message->messageType != 'methodCall') {
316 $this->error(-32600, 'server error. invalid xml-rpc. not conforming to spec. Request must be a methodCall');
318 $result = $this->call($this->message->methodName, $this->message->params);
319 // Is the result an error?
320 if (is_a($result, 'IXR_Error')) {
321 $this->error($result);
324 $r = new IXR_Value($result);
325 $resultxml = $r->getXml();
342 function call($methodname, $args) {
343 if (!$this->hasMethod($methodname)) {
344 return new IXR_Error(-32601, 'server error. requested method '.$methodname.' does not exist.');
346 $method = $this->callbacks[$methodname];
347 // Perform the callback and send the response
349 # Removed for DokuWiki to have a more consistent interface
350 # if (count($args) == 1) {
351 # // If only one paramater just send that instead of the whole array
355 # Adjusted for DokuWiki to use call_user_func_array
357 // args need to be an array
358 $args = (array) $args;
360 // Are we dealing with a function or a method?
361 if (substr($method, 0, 5) == 'this:') {
362 // It's a class method - check it exists
363 $method = substr($method, 5);
364 if (!method_exists($this, $method)) {
365 return new IXR_Error(-32601, 'server error. requested class method "'.$method.'" does not exist.');
368 #$result = $this->$method($args);
369 $result = call_user_func_array(array(&$this,$method),$args);
370 } elseif (substr($method, 0, 7) == 'plugin:') {
371 list($pluginname, $callback) = explode(':', substr($method, 7), 2);
372 if(!plugin_isdisabled($pluginname)) {
373 $plugin = plugin_load('action', $pluginname);
374 return call_user_func_array(array($plugin, $callback), $args);
376 return new IXR_Error(-99999, 'server error');
379 // It's a function - does it exist?
380 if (!function_exists($method)) {
381 return new IXR_Error(-32601, 'server error. requested function "'.$method.'" does not exist.');
384 #$result = $method($args);
385 $result = call_user_func_array($method,$args);
390 function error($error, $message = false) {
391 // Accepts either an error object or an error code and message
392 if ($message && !is_object($error)) {
393 $error = new IXR_Error($error, $message);
395 $this->output($error->getXml());
397 function output($xml) {
398 header('Content-Type: text/xml; charset=utf-8');
399 echo '<?xml version="1.0"?>', "\n", $xml;
402 function hasMethod($method) {
403 return in_array($method, array_keys($this->callbacks));
405 function setCapabilities() {
406 // Initialises capabilities array
407 $this->capabilities = array(
409 'specUrl' => 'http://www.xmlrpc.com/spec',
412 'faults_interop' => array(
413 'specUrl' => 'http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php',
414 'specVersion' => 20010516
416 'system.multicall' => array(
417 'specUrl' => 'http://www.xmlrpc.com/discuss/msgReader$1208',
422 function getCapabilities() {
423 return $this->capabilities;
425 function setCallbacks() {
426 $this->callbacks['system.getCapabilities'] = 'this:getCapabilities';
427 $this->callbacks['system.listMethods'] = 'this:listMethods';
428 $this->callbacks['system.multicall'] = 'this:multiCall';
430 function listMethods() {
431 // Returns a list of methods - uses array_reverse to ensure user defined
432 // methods are listed before server defined methods
433 return array_reverse(array_keys($this->callbacks));
435 function multiCall($methodcalls) {
436 // See http://www.xmlrpc.com/discuss/msgReader$1208
438 foreach ($methodcalls as $call) {
439 $method = $call['methodName'];
440 $params = $call['params'];
441 if ($method == 'system.multicall') {
442 $result = new IXR_Error(-32600, 'Recursive calls to system.multicall are forbidden');
444 $result = $this->call($method, $params);
446 if (is_a($result, 'IXR_Error')) {
448 'faultCode' => $result->code,
449 'faultString' => $result->message
452 $return[] = array($result);
463 function IXR_Request($method, $args) {
464 $this->method = $method;
467 <?xml version="1.0"?>
469 <methodName>{$this->method}</methodName>
473 foreach ($this->args as $arg) {
474 $this->xml .= '<param><value>';
475 $v = new IXR_Value($arg);
476 $this->xml .= $v->getXml();
477 $this->xml .= "</value></param>\n";
479 $this->xml .= '</params></methodCall>';
481 function getLength() {
482 return strlen($this->xml);
490 * Changed for DokuWiki to use DokuHTTPClient
492 * This should be compatible to the original class, but uses DokuWiki's
493 * HTTP client library which will respect proxy settings
495 * Because the XMLRPC client is not used in DokuWiki currently this is completely
498 class IXR_Client extends DokuHTTPClient {
500 var $message = false;
501 var $xmlerror = false;
503 function IXR_Client($server, $path = false, $port = 80) {
504 $this->DokuHTTPClient();
506 // Assume we have been given a URL instead
507 $this->posturl = $server;
509 $this->posturl = 'http://'.$server.':'.$port.$path;
514 $args = func_get_args();
515 $method = array_shift($args);
516 $request = new IXR_Request($method, $args);
517 $xml = $request->getXml();
519 $this->headers['Content-Type'] = 'text/xml';
520 if(!$this->sendRequest($this->posturl,$xml,'POST')){
521 $this->xmlerror = new IXR_Error(-32300, 'transport error - '.$this->error);
525 // Check HTTP Response code
526 if($this->status < 200 || $this->status > 206){
527 $this->xmlerror = new IXR_Error(-32300, 'transport error - HTTP status '.$this->status);
531 // Now parse what we've got back
532 $this->message = new IXR_Message($this->resp_body);
533 if (!$this->message->parse()) {
535 $this->xmlerror = new IXR_Error(-32700, 'parse error. not well formed');
538 // Is the message a fault?
539 if ($this->message->messageType == 'fault') {
540 $this->xmlerror = new IXR_Error($this->message->faultCode, $this->message->faultString);
543 // Message must be OK
546 function getResponse() {
547 // methodResponses can only have one param - return that
548 return $this->message->params[0];
551 return (is_object($this->xmlerror));
553 function getErrorCode() {
554 return $this->xmlerror->code;
556 function getErrorMessage() {
557 return $this->xmlerror->message;
565 function IXR_Error($code, $message) {
567 $this->message = $message;
576 <name>faultCode</name>
577 <value><int>{$this->code}</int></value>
580 <name>faultString</name>
581 <value><string>{$this->message}</string></value>
601 function IXR_Date($time) {
602 // $time can be a PHP timestamp or an ISO one
603 if (is_numeric($time)) {
604 $this->parseTimestamp($time);
606 $this->parseIso($time);
609 function parseTimestamp($timestamp) {
610 $this->year = gmdate('Y', $timestamp);
611 $this->month = gmdate('m', $timestamp);
612 $this->day = gmdate('d', $timestamp);
613 $this->hour = gmdate('H', $timestamp);
614 $this->minute = gmdate('i', $timestamp);
615 $this->second = gmdate('s', $timestamp);
617 function parseIso($iso) {
618 if(preg_match('/^(\d\d\d\d)-?(\d\d)-?(\d\d)([T ](\d\d):(\d\d)(:(\d\d))?)?/',$iso,$match)){
619 $this->year = (int) $match[1];
620 $this->month = (int) $match[2];
621 $this->day = (int) $match[3];
622 $this->hour = (int) $match[5];
623 $this->minute = (int) $match[6];
624 $this->second = (int) $match[8];
628 return $this->year.$this->month.$this->day.'T'.$this->hour.':'.$this->minute.':'.$this->second;
631 return '<dateTime.iso8601>'.$this->getIso().'</dateTime.iso8601>';
633 function getTimestamp() {
634 return gmmktime($this->hour, $this->minute, $this->second, $this->month, $this->day, $this->year);
641 function IXR_Base64($data) {
645 return '<base64>'.base64_encode($this->data).'</base64>';
650 class IXR_IntrospectionServer extends IXR_Server {
653 function IXR_IntrospectionServer() {
654 $this->setCallbacks();
655 $this->setCapabilities();
656 $this->capabilities['introspection'] = array(
657 'specUrl' => 'http://xmlrpc.usefulinc.com/doc/reserved.html',
661 'system.methodSignature',
662 'this:methodSignature',
663 array('array', 'string'),
664 'Returns an array describing the return type and required parameters of a method'
667 'system.getCapabilities',
668 'this:getCapabilities',
670 'Returns a struct describing the XML-RPC specifications supported by this server'
673 'system.listMethods',
676 'Returns an array of available methods on this server'
681 array('string', 'string'),
682 'Returns a documentation string for the specified method'
685 function addCallback($method, $callback, $args, $help) {
686 $this->callbacks[$method] = $callback;
687 $this->signatures[$method] = $args;
688 $this->help[$method] = $help;
690 function call($methodname, $args) {
691 // Make sure it's in an array
692 if ($args && !is_array($args)) {
693 $args = array($args);
695 // Over-rides default call method, adds signature check
696 if (!$this->hasMethod($methodname)) {
697 return new IXR_Error(-32601, 'server error. requested method "'.$this->message->methodName.'" not specified.');
699 $method = $this->callbacks[$methodname];
700 $signature = $this->signatures[$methodname];
701 $returnType = array_shift($signature);
702 // Check the number of arguments. Check only, if the minimum count of parameters is specified. More parameters are possible.
703 // This is a hack to allow optional parameters...
704 if (count($args) < count($signature)) {
705 // print 'Num of args: '.count($args).' Num in signature: '.count($signature);
706 return new IXR_Error(-32602, 'server error. wrong number of method parameters');
708 // Check the argument types
711 for ($i = 0, $j = count($args); $i < $j; $i++) {
712 $arg = array_shift($args);
713 $type = array_shift($signature);
717 if (is_array($arg) || !is_int($arg)) {
723 if (!is_string($arg)) {
728 if ($arg !== false && $arg !== true) {
734 if (!is_float($arg)) {
739 case 'dateTime.iso8601':
740 if (!is_a($arg, 'IXR_Date')) {
746 return new IXR_Error(-32602, 'server error. invalid method parameters');
749 // It passed the test - run the "real" method call
750 return parent::call($methodname, $argsbackup);
752 function methodSignature($method) {
753 if (!$this->hasMethod($method)) {
754 return new IXR_Error(-32601, 'server error. requested method "'.$method.'" not specified.');
756 // We should be returning an array of types
757 $types = $this->signatures[$method];
759 foreach ($types as $type) {
762 $return[] = 'string';
771 case 'dateTime.iso8601':
772 $return[] = new IXR_Date(time());
778 $return[] = new IXR_Base64('base64');
781 $return[] = array('array');
784 $return[] = array('struct' => 'struct');
790 function methodHelp($method) {
791 return $this->help[$method];
796 class IXR_ClientMulticall extends IXR_Client {
797 var $calls = array();
798 function IXR_ClientMulticall($server, $path = false, $port = 80) {
799 parent::IXR_Client($server, $path, $port);
800 //$this->useragent = 'The Incutio XML-RPC PHP Library (multicall client)';
803 $args = func_get_args();
804 $methodName = array_shift($args);
806 'methodName' => $methodName,
809 $this->calls[] = $struct;
812 // Prepare multicall, then call the parent::query() method
813 return parent::query('system.multicall', $this->calls);