4 * IXR - The Incutio XML-RPC Library
6 * Copyright (c) 2010, Incutio Ltd.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions are met:
12 * - Redistributions of source code must retain the above copyright notice,
13 * this list of conditions and the following disclaimer.
14 * - Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * - Neither the name of Incutio Ltd. nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
22 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
23 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
25 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
26 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
27 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
29 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
31 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 * @copyright Incutio Ltd 2010 (http://www.incutio.com)
37 * @version 1.7.4 7th September 2010
38 * @author Simon Willison
39 * @link http://scripts.incutio.com/xmlrpc/ Site/manual
41 * Modified for DokuWiki
42 * @author Andreas Gohr <andi@splitbrain.org>
46 /** @var IXR_Value[]|IXR_Date|IXR_Base64|int|bool|double|string */
55 function __construct($data, $type = false) {
58 $type = $this->calculateType();
61 if($type == 'struct') {
62 // Turn all the values in the array in to new IXR_Value objects
63 foreach($this->data
as $key => $value) {
64 $this->data
[$key] = new IXR_Value($value);
67 if($type == 'array') {
68 for($i = 0, $j = count($this->data
); $i < $j; $i++
) {
69 $this->data
[$i] = new IXR_Value($this->data
[$i]);
77 function calculateType() {
78 if($this->data
=== true ||
$this->data
=== false) {
81 if(is_integer($this->data
)) {
84 if(is_double($this->data
)) {
88 // Deal with IXR object types base64 and date
89 if(is_object($this->data
) && is_a($this->data
, 'IXR_Date')) {
92 if(is_object($this->data
) && is_a($this->data
, 'IXR_Base64')) {
96 // If it is a normal PHP object convert it in to a struct
97 if(is_object($this->data
)) {
98 $this->data
= get_object_vars($this->data
);
101 if(!is_array($this->data
)) {
105 // We have an array - is it an array or a struct?
106 if($this->isStruct($this->data
)) {
114 * @return bool|string
117 // Return XML for this value
118 switch($this->type
) {
120 return '<boolean>' . (($this->data
) ?
'1' : '0') . '</boolean>';
123 return '<int>' . $this->data
. '</int>';
126 return '<double>' . $this->data
. '</double>';
129 return '<string>' . htmlspecialchars($this->data
) . '</string>';
132 $return = '<array><data>' . "\n";
133 foreach($this->data
as $item) {
134 $return .= ' <value>' . $item->getXml() . "</value>\n";
136 $return .= '</data></array>';
140 $return = '<struct>' . "\n";
141 foreach($this->data
as $name => $value) {
142 $return .= " <member><name>$name</name><value>";
143 $return .= $value->getXml() . "</value></member>\n";
145 $return .= '</struct>';
150 return $this->data
->getXml();
157 * Checks whether or not the supplied array is a struct or not
159 * @param array $array
162 function isStruct($array) {
164 foreach($array as $key => $value) {
165 if((string) $key != (string) $expected) {
183 var $messageType; // methodCall / methodResponse / fault
189 // Current variable stacks
190 var $_arraystructs = array(); // The stack used to keep track of the current array/struct
191 var $_arraystructstypes = array(); // Stack keeping track of if things are structs or array
192 var $_currentStructName = array(); // A stack as well
196 var $_currentTagContents;
202 * @param string $message
204 function __construct($message) {
205 $this->message
=& $message;
212 // first remove the XML declaration
213 // merged from WP #10698 - this method avoids the RAM usage of preg_replace on very large messages
214 $header = preg_replace('/<\?xml.*?\?' . '>/', '', substr($this->message
, 0, 100), 1);
215 $this->message
= substr_replace($this->message
, $header, 0, 100);
217 // workaround for a bug in PHP/libxml2, see http://bugs.php.net/bug.php?id=45996
218 $this->message
= str_replace('<', '<', $this->message
);
219 $this->message
= str_replace('>', '>', $this->message
);
220 $this->message
= str_replace('&', '&', $this->message
);
221 $this->message
= str_replace(''', ''', $this->message
);
222 $this->message
= str_replace('"', '"', $this->message
);
223 $this->message
= str_replace("\x0b", ' ', $this->message
); //vertical tab
224 if(trim($this->message
) == '') {
227 $this->_parser
= xml_parser_create();
228 // Set XML parser to take the case of tags in to account
229 xml_parser_set_option($this->_parser
, XML_OPTION_CASE_FOLDING
, false);
230 // Set XML parser callback functions
231 xml_set_object($this->_parser
, $this);
232 xml_set_element_handler($this->_parser
, 'tag_open', 'tag_close');
233 xml_set_character_data_handler($this->_parser
, 'cdata');
234 $chunk_size = 262144; // 256Kb, parse in chunks to avoid the RAM usage on very large messages
237 if(strlen($this->message
) <= $chunk_size) {
240 $part = substr($this->message
, 0, $chunk_size);
241 $this->message
= substr($this->message
, $chunk_size);
242 if(!xml_parse($this->_parser
, $part, $final)) {
249 xml_parser_free($this->_parser
);
251 // Grab the error messages, if any
252 if($this->messageType
== 'fault') {
253 $this->faultCode
= $this->params
[0]['faultCode'];
254 $this->faultString
= $this->params
[0]['faultString'];
264 function tag_open($parser, $tag, $attr) {
265 $this->_currentTagContents
= '';
266 $this->_currentTag
= $tag;
270 case 'methodResponse':
272 $this->messageType
= $tag;
274 /* Deal with stacks of arrays and structs */
275 case 'data': // data is to all intents and purposes more interesting than array
276 $this->_arraystructstypes
[] = 'array';
277 $this->_arraystructs
[] = array();
280 $this->_arraystructstypes
[] = 'struct';
281 $this->_arraystructs
[] = array();
284 $this->_lastseen
= $tag;
289 * @param string $cdata
291 function cdata($parser, $cdata) {
292 $this->_currentTagContents
.= $cdata;
299 function tag_close($parser, $tag) {
305 $value = (int) trim($this->_currentTagContents
);
309 $value = (double) trim($this->_currentTagContents
);
313 $value = (string) $this->_currentTagContents
;
316 case 'dateTime.iso8601':
317 $value = new IXR_Date(trim($this->_currentTagContents
));
321 // "If no type is indicated, the type is string."
322 if($this->_lastseen
== 'value') {
323 $value = (string) $this->_currentTagContents
;
328 $value = (boolean
) trim($this->_currentTagContents
);
332 $value = base64_decode($this->_currentTagContents
);
335 /* Deal with stacks of arrays and structs */
338 $value = array_pop($this->_arraystructs
);
339 array_pop($this->_arraystructstypes
);
343 array_pop($this->_currentStructName
);
346 $this->_currentStructName
[] = trim($this->_currentTagContents
);
349 $this->methodName
= trim($this->_currentTagContents
);
354 if(count($this->_arraystructs
) > 0) {
355 // Add value to struct or array
356 if($this->_arraystructstypes
[count($this->_arraystructstypes
) - 1] == 'struct') {
358 $this->_arraystructs
[count($this->_arraystructs
) - 1][$this->_currentStructName
[count($this->_currentStructName
) - 1]] = $value;
361 $this->_arraystructs
[count($this->_arraystructs
) - 1][] = $value;
364 // Just add as a parameter
365 $this->params
[] = $value;
368 $this->_currentTagContents
= '';
369 $this->_lastseen
= $tag;
382 var $callbacks = array();
388 * @param array|bool $callbacks
392 function __construct($callbacks = false, $data = false, $wait = false) {
393 $this->setCapabilities();
395 $this->callbacks
= $callbacks;
397 $this->setCallbacks();
405 * @param bool|string $data
407 function serve($data = false) {
410 $postData = trim(http_get_raw_post_data());
412 header('Content-Type: text/plain'); // merged from WP #9093
413 die('XML-RPC server accepts POST requests only.');
417 $this->message
= new IXR_Message($data);
418 if(!$this->message
->parse()) {
419 $this->error(-32700, 'parse error. not well formed');
421 if($this->message
->messageType
!= 'methodCall') {
422 $this->error(-32600, 'server error. invalid xml-rpc. not conforming to spec. Request must be a methodCall');
424 $result = $this->call($this->message
->methodName
, $this->message
->params
);
426 // Is the result an error?
427 if(is_a($result, 'IXR_Error')) {
428 $this->error($result);
432 $r = new IXR_Value($result);
433 $resultxml = $r->getXml();
453 * @param string $methodname
455 * @return IXR_Error|mixed
457 function call($methodname, $args) {
458 if(!$this->hasMethod($methodname)) {
459 return new IXR_Error(-32601, 'server error. requested method ' . $methodname . ' does not exist.');
461 $method = $this->callbacks
[$methodname];
463 // Perform the callback and send the response
465 # Removed for DokuWiki to have a more consistent interface
466 # if (count($args) == 1) {
467 # // If only one parameter just send that instead of the whole array
471 # Adjusted for DokuWiki to use call_user_func_array
473 // args need to be an array
474 $args = (array) $args;
476 // Are we dealing with a function or a method?
477 if(is_string($method) && substr($method, 0, 5) == 'this:') {
478 // It's a class method - check it exists
479 $method = substr($method, 5);
480 if(!method_exists($this, $method)) {
481 return new IXR_Error(-32601, 'server error. requested class method "' . $method . '" does not exist.');
484 #$result = $this->$method($args);
485 $result = call_user_func_array(array(&$this, $method), $args);
486 } elseif(substr($method, 0, 7) == 'plugin:') {
487 list($pluginname, $callback) = explode(':', substr($method, 7), 2);
488 if(!plugin_isdisabled($pluginname)) {
489 $plugin = plugin_load('action', $pluginname);
490 return call_user_func_array(array($plugin, $callback), $args);
492 return new IXR_Error(-99999, 'server error');
495 // It's a function - does it exist?
496 if(is_array($method)) {
497 if(!is_callable(array($method[0], $method[1]))) {
498 return new IXR_Error(-32601, 'server error. requested object method "' . $method[1] . '" does not exist.');
500 } else if(!function_exists($method)) {
501 return new IXR_Error(-32601, 'server error. requested function "' . $method . '" does not exist.');
505 $result = call_user_func($method, $args);
512 * @param string|bool $message
514 function error($error, $message = false) {
515 // Accepts either an error object or an error code and message
516 if($message && !is_object($error)) {
517 $error = new IXR_Error($error, $message);
519 $this->output($error->getXml());
525 function output($xml) {
526 header('Content-Type: text/xml; charset=utf-8');
527 echo '<?xml version="1.0"?>', "\n", $xml;
532 * @param string $method
535 function hasMethod($method) {
536 return in_array($method, array_keys($this->callbacks
));
539 function setCapabilities() {
540 // Initialises capabilities array
541 $this->capabilities
= array(
543 'specUrl' => 'http://www.xmlrpc.com/spec',
546 'faults_interop' => array(
547 'specUrl' => 'http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php',
548 'specVersion' => 20010516
550 'system.multicall' => array(
551 'specUrl' => 'http://www.xmlrpc.com/discuss/msgReader$1208',
560 function getCapabilities() {
561 return $this->capabilities
;
564 function setCallbacks() {
565 $this->callbacks
['system.getCapabilities'] = 'this:getCapabilities';
566 $this->callbacks
['system.listMethods'] = 'this:listMethods';
567 $this->callbacks
['system.multicall'] = 'this:multiCall';
573 function listMethods() {
574 // Returns a list of methods - uses array_reverse to ensure user defined
575 // methods are listed before server defined methods
576 return array_reverse(array_keys($this->callbacks
));
580 * @param array $methodcalls
583 function multiCall($methodcalls) {
584 // See http://www.xmlrpc.com/discuss/msgReader$1208
586 foreach($methodcalls as $call) {
587 $method = $call['methodName'];
588 $params = $call['params'];
589 if($method == 'system.multicall') {
590 $result = new IXR_Error(-32800, 'Recursive calls to system.multicall are forbidden');
592 $result = $this->call($method, $params);
594 if(is_a($result, 'IXR_Error')) {
596 'faultCode' => $result->code
,
597 'faultString' => $result->message
600 $return[] = array($result);
622 * @param string $method
625 function __construct($method, $args) {
626 $this->method
= $method;
629 <?xml version="1.0"?>
631 <methodName>{$this->method}</methodName>
635 foreach($this->args
as $arg) {
636 $this->xml
.= '<param><value>';
637 $v = new IXR_Value($arg);
638 $this->xml
.= $v->getXml();
639 $this->xml
.= "</value></param>\n";
641 $this->xml
.= '</params></methodCall>';
647 function getLength() {
648 return strlen($this->xml
);
665 * Changed for DokuWiki to use DokuHTTPClient
667 * This should be compatible to the original class, but uses DokuWiki's
668 * HTTP client library which will respect proxy settings
670 * Because the XMLRPC client is not used in DokuWiki currently this is completely
673 class IXR_Client
extends DokuHTTPClient
{
675 /** @var IXR_Message|bool */
676 var $message = false;
678 // Storage place for an error message
679 /** @var IXR_Error|bool */
680 var $xmlerror = false;
683 * @param string $server
684 * @param string|bool $path
686 * @param int $timeout
688 function __construct($server, $path = false, $port = 80, $timeout = 15) {
689 parent
::__construct();
691 // Assume we have been given a URL instead
692 $this->posturl
= $server;
694 $this->posturl
= 'http://' . $server . ':' . $port . $path;
696 $this->timeout
= $timeout;
700 * parameters: method and arguments
701 * @return bool success or error
704 $args = func_get_args();
705 $method = array_shift($args);
706 $request = new IXR_Request($method, $args);
707 $xml = $request->getXml();
709 $this->headers
['Content-Type'] = 'text/xml';
710 if(!$this->sendRequest($this->posturl
, $xml, 'POST')) {
711 $this->xmlerror
= new IXR_Error(-32300, 'transport error - ' . $this->error
);
715 // Check HTTP Response code
716 if($this->status
< 200 ||
$this->status
> 206) {
717 $this->xmlerror
= new IXR_Error(-32300, 'transport error - HTTP status ' . $this->status
);
721 // Now parse what we've got back
722 $this->message
= new IXR_Message($this->resp_body
);
723 if(!$this->message
->parse()) {
725 $this->xmlerror
= new IXR_Error(-32700, 'parse error. not well formed');
729 // Is the message a fault?
730 if($this->message
->messageType
== 'fault') {
731 $this->xmlerror
= new IXR_Error($this->message
->faultCode
, $this->message
->faultString
);
735 // Message must be OK
742 function getResponse() {
743 // methodResponses can only have one param - return that
744 return $this->message
->params
[0];
751 return (is_object($this->xmlerror
));
757 function getErrorCode() {
758 return $this->xmlerror
->code
;
764 function getErrorMessage() {
765 return $this->xmlerror
->message
;
781 * @param string $message
783 function __construct($code, $message) {
785 $this->message
= htmlspecialchars($message);
798 <name>faultCode</name>
799 <value><int>{$this->code}</int></value>
802 <name>faultString</name>
803 <value><string>{$this->message}</string></value>
827 * @param int|string $time
829 public function __construct($time) {
830 // $time can be a PHP timestamp or an ISO one
831 if(is_numeric($time)) {
832 $this->parseTimestamp($time);
834 $this->parseIso($time);
839 * Parse unix timestamp
841 * @param int $timestamp
843 protected function parseTimestamp($timestamp) {
844 $this->date
= new DateTime('@' . $timestamp);
848 * Parses less or more complete iso dates and much more, if no timezone given assumes UTC
852 protected function parseIso($iso) {
853 $this->date
= new DateTime($iso, new DateTimeZone("UTC"));
857 * Returns date in ISO 8601 format
861 public function getIso() {
862 return $this->date
->format(DateTime
::ISO8601
);
866 * Returns date in valid xml
870 public function getXml() {
871 return '<dateTime.iso8601>' . $this->getIso() . '</dateTime.iso8601>';
875 * Returns Unix timestamp
879 function getTimestamp() {
880 return $this->date
->getTimestamp();
894 * @param string $data
896 function __construct($data) {
904 return '<base64>' . base64_encode($this->data
) . '</base64>';
909 * IXR_IntrospectionServer
914 class IXR_IntrospectionServer
extends IXR_Server
{
923 function __construct() {
924 $this->setCallbacks();
925 $this->setCapabilities();
926 $this->capabilities
['introspection'] = array(
927 'specUrl' => 'http://xmlrpc.usefulinc.com/doc/reserved.html',
931 'system.methodSignature',
932 'this:methodSignature',
933 array('array', 'string'),
934 'Returns an array describing the return type and required parameters of a method'
937 'system.getCapabilities',
938 'this:getCapabilities',
940 'Returns a struct describing the XML-RPC specifications supported by this server'
943 'system.listMethods',
946 'Returns an array of available methods on this server'
951 array('string', 'string'),
952 'Returns a documentation string for the specified method'
957 * @param string $method
958 * @param string $callback
959 * @param string[] $args
960 * @param string $help
962 function addCallback($method, $callback, $args, $help) {
963 $this->callbacks
[$method] = $callback;
964 $this->signatures
[$method] = $args;
965 $this->help
[$method] = $help;
969 * @param string $methodname
971 * @return IXR_Error|mixed
973 function call($methodname, $args) {
974 // Make sure it's in an array
975 if($args && !is_array($args)) {
976 $args = array($args);
979 // Over-rides default call method, adds signature check
980 if(!$this->hasMethod($methodname)) {
981 return new IXR_Error(-32601, 'server error. requested method "' . $this->message
->methodName
. '" not specified.');
983 $method = $this->callbacks
[$methodname];
984 $signature = $this->signatures
[$methodname];
985 $returnType = array_shift($signature);
986 // Check the number of arguments. Check only, if the minimum count of parameters is specified. More parameters are possible.
987 // This is a hack to allow optional parameters...
988 if(count($args) < count($signature)) {
989 // print 'Num of args: '.count($args).' Num in signature: '.count($signature);
990 return new IXR_Error(-32602, 'server error. wrong number of method parameters');
993 // Check the argument types
996 for($i = 0, $j = count($args); $i < $j; $i++
) {
997 $arg = array_shift($args);
998 $type = array_shift($signature);
1002 if(is_array($arg) ||
!is_int($arg)) {
1008 if(!is_string($arg)) {
1013 if($arg !== false && $arg !== true) {
1019 if(!is_float($arg)) {
1024 case 'dateTime.iso8601':
1025 if(!is_a($arg, 'IXR_Date')) {
1031 return new IXR_Error(-32602, 'server error. invalid method parameters');
1034 // It passed the test - run the "real" method call
1035 return parent
::call($methodname, $argsbackup);
1039 * @param string $method
1040 * @return array|IXR_Error
1042 function methodSignature($method) {
1043 if(!$this->hasMethod($method)) {
1044 return new IXR_Error(-32601, 'server error. requested method "' . $method . '" not specified.');
1046 // We should be returning an array of types
1047 $types = $this->signatures
[$method];
1049 foreach($types as $type) {
1052 $return[] = 'string';
1061 case 'dateTime.iso8601':
1062 $return[] = new IXR_Date(time());
1068 $return[] = new IXR_Base64('base64');
1071 $return[] = array('array');
1074 $return[] = array('struct' => 'struct');
1082 * @param string $method
1085 function methodHelp($method) {
1086 return $this->help
[$method];
1091 * IXR_ClientMulticall
1096 class IXR_ClientMulticall
extends IXR_Client
{
1099 var $calls = array();
1102 * @param string $server
1103 * @param string|bool $path
1106 function __construct($server, $path = false, $port = 80) {
1107 parent
::__construct($server, $path, $port);
1108 //$this->useragent = 'The Incutio XML-RPC PHP Library (multicall client)';
1114 function addCall() {
1115 $args = func_get_args();
1116 $methodName = array_shift($args);
1118 'methodName' => $methodName,
1121 $this->calls
[] = $struct;
1128 // Prepare multicall, then call the parent::query() method
1129 return parent
::query('system.multicall', $this->calls
);