3 * IXR - The Incutio XML-RPC Library
5 * Copyright (c) 2010, Incutio Ltd.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are met:
11 * - Redistributions of source code must retain the above copyright notice,
12 * this list of conditions and the following disclaimer.
13 * - Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * - Neither the name of Incutio Ltd. nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
21 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
22 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
24 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
25 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
26 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
27 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
28 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
30 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35 * @copyright Incutio Ltd 2010 (http://www.incutio.com)
36 * @version 1.7.4 7th September 2010
37 * @author Simon Willison
38 * @link http://scripts.incutio.com/xmlrpc/ Site/manual
39 * @license http://www.opensource.org/licenses/bsd-license.php BSD
55 function __construct( $data, $type = false )
59 $type = $this->calculateType();
62 if ($type == 'struct') {
63 // Turn all the values in the array in to new IXR_Value objects
64 foreach ($this->data as $key => $value) {
65 $this->data[$key] = new IXR_Value($value);
68 if ($type == 'array') {
69 for ($i = 0, $j = count($this->data); $i < $j; $i++) {
70 $this->data[$i] = new IXR_Value($this->data[$i]);
78 public function IXR_Value( $data, $type = false ) {
79 self::__construct( $data, $type );
82 function calculateType()
84 if ($this->data === true || $this->data === false) {
87 if (is_integer($this->data)) {
90 if (is_double($this->data)) {
94 // Deal with IXR object types base64 and date
95 if (is_object($this->data) && is_a($this->data, 'IXR_Date')) {
98 if (is_object($this->data) && is_a($this->data, 'IXR_Base64')) {
102 // If it is a normal PHP object convert it in to a struct
103 if (is_object($this->data)) {
104 $this->data = get_object_vars($this->data);
107 if (!is_array($this->data)) {
111 // We have an array - is it an array or a struct?
112 if ($this->isStruct($this->data)) {
121 // Return XML for this value
122 switch ($this->type) {
124 return '<boolean>'.(($this->data) ? '1' : '0').'</boolean>';
127 return '<int>'.$this->data.'</int>';
130 return '<double>'.$this->data.'</double>';
133 return '<string>'.htmlspecialchars($this->data).'</string>';
136 $return = '<array><data>'."\n";
137 foreach ($this->data as $item) {
138 $return .= ' <value>'.$item->getXml()."</value>\n";
140 $return .= '</data></array>';
144 $return = '<struct>'."\n";
145 foreach ($this->data as $name => $value) {
146 $name = htmlspecialchars($name);
147 $return .= " <member><name>$name</name><value>";
148 $return .= $value->getXml()."</value></member>\n";
150 $return .= '</struct>';
155 return $this->data->getXml();
162 * Checks whether or not the supplied array is a struct or not
164 * @param array $array
167 function isStruct($array)
170 foreach ($array as $key => $value) {
171 if ((string)$key != (string)$expected) {
190 var $messageType; // methodCall / methodResponse / fault
196 // Current variable stacks
197 var $_arraystructs = array(); // The stack used to keep track of the current array/struct
198 var $_arraystructstypes = array(); // Stack keeping track of if things are structs or array
199 var $_currentStructName = array(); // A stack as well
203 var $_currentTagContents;
204 var $_valueHasType = false;
211 function __construct( $message )
213 $this->message =& $message;
219 public function IXR_Message( $message ) {
220 self::__construct( $message );
225 // first remove the XML declaration
226 // merged from WP #10698 - this method avoids the RAM usage of preg_replace on very large messages
227 $header = preg_replace( '/<\?xml.*?\?'.'>/s', '', substr( $this->message, 0, 100 ), 1 );
228 $this->message = trim( substr_replace( $this->message, $header, 0, 100 ) );
229 if ( '' == $this->message ) {
233 // Then remove the DOCTYPE
234 $header = preg_replace( '/^<!DOCTYPE[^>]*+>/i', '', substr( $this->message, 0, 200 ), 1 );
235 $this->message = trim( substr_replace( $this->message, $header, 0, 200 ) );
236 if ( '' == $this->message ) {
240 // Check that the root tag is valid
241 $root_tag = substr( $this->message, 0, strcspn( substr( $this->message, 0, 20 ), "> \t\r\n" ) );
242 if ( '<!DOCTYPE' === strtoupper( $root_tag ) ) {
245 if ( ! in_array( $root_tag, array( '<methodCall', '<methodResponse', '<fault' ) ) ) {
249 // Bail if there are too many elements to parse
250 $element_limit = 30000;
251 if ( function_exists( 'apply_filters' ) ) {
253 * Filter the number of elements to parse in an XML-RPC response.
257 * @param int $element_limit Default elements limit.
259 $element_limit = apply_filters( 'xmlrpc_element_limit', $element_limit );
261 if ( $element_limit && 2 * $element_limit < substr_count( $this->message, '<' ) ) {
265 $this->_parser = xml_parser_create();
266 // Set XML parser to take the case of tags in to account
267 xml_parser_set_option($this->_parser, XML_OPTION_CASE_FOLDING, false);
268 // Set XML parser callback functions
269 xml_set_object($this->_parser, $this);
270 xml_set_element_handler($this->_parser, 'tag_open', 'tag_close');
271 xml_set_character_data_handler($this->_parser, 'cdata');
273 // 256Kb, parse in chunks to avoid the RAM usage on very large messages
274 $chunk_size = 262144;
277 * Filter the chunk size that can be used to parse an XML-RPC reponse message.
281 * @param int $chunk_size Chunk size to parse in bytes.
283 $chunk_size = apply_filters( 'xmlrpc_chunk_parsing_size', $chunk_size );
287 if (strlen($this->message) <= $chunk_size) {
290 $part = substr($this->message, 0, $chunk_size);
291 $this->message = substr($this->message, $chunk_size);
292 if (!xml_parse($this->_parser, $part, $final)) {
299 xml_parser_free($this->_parser);
301 // Grab the error messages, if any
302 if ($this->messageType == 'fault') {
303 $this->faultCode = $this->params[0]['faultCode'];
304 $this->faultString = $this->params[0]['faultString'];
309 function tag_open($parser, $tag, $attr)
311 $this->_currentTagContents = '';
312 $this->currentTag = $tag;
315 case 'methodResponse':
317 $this->messageType = $tag;
319 /* Deal with stacks of arrays and structs */
320 case 'data': // data is to all intents and puposes more interesting than array
321 $this->_arraystructstypes[] = 'array';
322 $this->_arraystructs[] = array();
325 $this->_arraystructstypes[] = 'struct';
326 $this->_arraystructs[] = array();
329 $this->_valueHasType = false;
333 function cdata($parser, $cdata)
335 $this->_currentTagContents .= $cdata;
338 function tag_close($parser, $tag)
344 $value = (int)trim($this->_currentTagContents);
348 $value = (double)trim($this->_currentTagContents);
352 $value = (string)trim($this->_currentTagContents);
355 case 'dateTime.iso8601':
356 $value = new IXR_Date(trim($this->_currentTagContents));
360 // "If no type is indicated, the type is string."
361 if ( !$this->_valueHasType ) {
362 $value = trim( $this->_currentTagContents );
367 $value = (boolean)trim($this->_currentTagContents);
371 $value = base64_decode($this->_currentTagContents);
374 /* Deal with stacks of arrays and structs */
377 $value = array_pop($this->_arraystructs);
378 array_pop($this->_arraystructstypes);
382 array_pop($this->_currentStructName);
385 $this->_currentStructName[] = trim($this->_currentTagContents);
388 $this->methodName = trim($this->_currentTagContents);
393 $this->_valueHasType = true;
395 if (count($this->_arraystructs) > 0) {
396 // Add value to struct or array
397 if ($this->_arraystructstypes[count($this->_arraystructstypes)-1] == 'struct') {
399 $this->_arraystructs[count($this->_arraystructs)-1][$this->_currentStructName[count($this->_currentStructName)-1]] = $value;
402 $this->_arraystructs[count($this->_arraystructs)-1][] = $value;
405 // Just add as a parameter
406 $this->params[] = $value;
409 $this->_currentTagContents = '';
422 var $callbacks = array();
429 function __construct( $callbacks = false, $data = false, $wait = false )
431 $this->setCapabilities();
433 $this->callbacks = $callbacks;
435 $this->setCallbacks();
444 public function IXR_Server( $callbacks = false, $data = false, $wait = false ) {
445 self::__construct( $callbacks, $data, $wait );
448 function serve($data = false)
451 if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] !== 'POST') {
452 if ( function_exists( 'status_header' ) ) {
453 status_header( 405 ); // WP #20986
454 header( 'Allow: POST' );
456 header('Content-Type: text/plain'); // merged from WP #9093
457 die('XML-RPC server accepts POST requests only.');
460 global $HTTP_RAW_POST_DATA;
461 if (empty($HTTP_RAW_POST_DATA)) {
462 // workaround for a bug in PHP 5.2.2 - http://bugs.php.net/bug.php?id=41293
463 $data = file_get_contents('php://input');
465 $data =& $HTTP_RAW_POST_DATA;
468 $this->message = new IXR_Message($data);
469 if (!$this->message->parse()) {
470 $this->error(-32700, 'parse error. not well formed');
472 if ($this->message->messageType != 'methodCall') {
473 $this->error(-32600, 'server error. invalid xml-rpc. not conforming to spec. Request must be a methodCall');
475 $result = $this->call($this->message->methodName, $this->message->params);
477 // Is the result an error?
478 if (is_a($result, 'IXR_Error')) {
479 $this->error($result);
483 $r = new IXR_Value($result);
484 $resultxml = $r->getXml();
503 function call($methodname, $args)
505 if (!$this->hasMethod($methodname)) {
506 return new IXR_Error(-32601, 'server error. requested method '.$methodname.' does not exist.');
508 $method = $this->callbacks[$methodname];
510 // Perform the callback and send the response
511 if (count($args) == 1) {
512 // If only one parameter just send that instead of the whole array
516 // Are we dealing with a function or a method?
517 if (is_string($method) && substr($method, 0, 5) == 'this:') {
518 // It's a class method - check it exists
519 $method = substr($method, 5);
520 if (!method_exists($this, $method)) {
521 return new IXR_Error(-32601, 'server error. requested class method "'.$method.'" does not exist.');
525 $result = $this->$method($args);
527 // It's a function - does it exist?
528 if (is_array($method)) {
529 if (!is_callable(array($method[0], $method[1]))) {
530 return new IXR_Error(-32601, 'server error. requested object method "'.$method[1].'" does not exist.');
532 } else if (!function_exists($method)) {
533 return new IXR_Error(-32601, 'server error. requested function "'.$method.'" does not exist.');
537 $result = call_user_func($method, $args);
542 function error($error, $message = false)
544 // Accepts either an error object or an error code and message
545 if ($message && !is_object($error)) {
546 $error = new IXR_Error($error, $message);
548 $this->output($error->getXml());
551 function output($xml)
553 $charset = function_exists('get_option') ? get_option('blog_charset') : '';
555 $xml = '<?xml version="1.0" encoding="'.$charset.'"?>'."\n".$xml;
557 $xml = '<?xml version="1.0"?>'."\n".$xml;
558 $length = strlen($xml);
559 header('Connection: close');
561 header('Content-Type: text/xml; charset='.$charset);
563 header('Content-Type: text/xml');
564 header('Date: '.date('r'));
569 function hasMethod($method)
571 return in_array($method, array_keys($this->callbacks));
574 function setCapabilities()
576 // Initialises capabilities array
577 $this->capabilities = array(
579 'specUrl' => 'http://www.xmlrpc.com/spec',
582 'faults_interop' => array(
583 'specUrl' => 'http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php',
584 'specVersion' => 20010516
586 'system.multicall' => array(
587 'specUrl' => 'http://www.xmlrpc.com/discuss/msgReader$1208',
593 function getCapabilities($args)
595 return $this->capabilities;
598 function setCallbacks()
600 $this->callbacks['system.getCapabilities'] = 'this:getCapabilities';
601 $this->callbacks['system.listMethods'] = 'this:listMethods';
602 $this->callbacks['system.multicall'] = 'this:multiCall';
605 function listMethods($args)
607 // Returns a list of methods - uses array_reverse to ensure user defined
608 // methods are listed before server defined methods
609 return array_reverse(array_keys($this->callbacks));
612 function multiCall($methodcalls)
614 // See http://www.xmlrpc.com/discuss/msgReader$1208
616 foreach ($methodcalls as $call) {
617 $method = $call['methodName'];
618 $params = $call['params'];
619 if ($method == 'system.multicall') {
620 $result = new IXR_Error(-32600, 'Recursive calls to system.multicall are forbidden');
622 $result = $this->call($method, $params);
624 if (is_a($result, 'IXR_Error')) {
626 'faultCode' => $result->code,
627 'faultString' => $result->message
630 $return[] = array($result);
652 function __construct($method, $args)
654 $this->method = $method;
657 <?xml version="1.0"?>
659 <methodName>{$this->method}</methodName>
663 foreach ($this->args as $arg) {
664 $this->xml .= '<param><value>';
665 $v = new IXR_Value($arg);
666 $this->xml .= $v->getXml();
667 $this->xml .= "</value></param>\n";
669 $this->xml .= '</params></methodCall>';
675 public function IXR_Request( $method, $args ) {
676 self::__construct( $method, $args );
681 return strlen($this->xml);
704 var $message = false;
707 var $headers = array();
709 // Storage place for an error message
715 function __construct( $server, $path = false, $port = 80, $timeout = 15 )
718 // Assume we have been given a URL instead
719 $bits = parse_url($server);
720 $this->server = $bits['host'];
721 $this->port = isset($bits['port']) ? $bits['port'] : 80;
722 $this->path = isset($bits['path']) ? $bits['path'] : '/';
724 // Make absolutely sure we have a path
729 if ( ! empty( $bits['query'] ) ) {
730 $this->path .= '?' . $bits['query'];
733 $this->server = $server;
737 $this->useragent = 'The Incutio XML-RPC PHP Library';
738 $this->timeout = $timeout;
744 public function IXR_Client( $server, $path = false, $port = 80, $timeout = 15 ) {
745 self::__construct( $server, $path, $port, $timeout );
750 $args = func_get_args();
751 $method = array_shift($args);
752 $request = new IXR_Request($method, $args);
753 $length = $request->getLength();
754 $xml = $request->getXml();
756 $request = "POST {$this->path} HTTP/1.0$r";
758 // Merged from WP #8145 - allow custom headers
759 $this->headers['Host'] = $this->server;
760 $this->headers['Content-Type'] = 'text/xml';
761 $this->headers['User-Agent'] = $this->useragent;
762 $this->headers['Content-Length']= $length;
764 foreach( $this->headers as $header => $value ) {
765 $request .= "{$header}: {$value}{$r}";
771 // Now send the request
773 echo '<pre class="ixr_request">'.htmlspecialchars($request)."\n</pre>\n\n";
776 if ($this->timeout) {
777 $fp = @fsockopen($this->server, $this->port, $errno, $errstr, $this->timeout);
779 $fp = @fsockopen($this->server, $this->port, $errno, $errstr);
782 $this->error = new IXR_Error(-32300, 'transport error - could not open socket');
785 fputs($fp, $request);
788 $gotFirstLine = false;
789 $gettingHeaders = true;
791 $line = fgets($fp, 4096);
792 if (!$gotFirstLine) {
793 // Check line for '200'
794 if (strstr($line, '200') === false) {
795 $this->error = new IXR_Error(-32300, 'transport error - HTTP status code was not 200');
798 $gotFirstLine = true;
800 if (trim($line) == '') {
801 $gettingHeaders = false;
803 if (!$gettingHeaders) {
804 // merged from WP #12559 - remove trim
808 $debugContents .= $line;
812 echo '<pre class="ixr_response">'.htmlspecialchars($debugContents)."\n</pre>\n\n";
815 // Now parse what we've got back
816 $this->message = new IXR_Message($contents);
817 if (!$this->message->parse()) {
819 $this->error = new IXR_Error(-32700, 'parse error. not well formed');
823 // Is the message a fault?
824 if ($this->message->messageType == 'fault') {
825 $this->error = new IXR_Error($this->message->faultCode, $this->message->faultString);
829 // Message must be OK
833 function getResponse()
835 // methodResponses can only have one param - return that
836 return $this->message->params[0];
841 return (is_object($this->error));
844 function getErrorCode()
846 return $this->error->code;
849 function getErrorMessage()
851 return $this->error->message;
870 function __construct( $code, $message )
873 $this->message = htmlspecialchars($message);
879 public function IXR_Error( $code, $message ) {
880 self::__construct( $code, $message );
891 <name>faultCode</name>
892 <value><int>{$this->code}</int></value>
895 <name>faultString</name>
896 <value><string>{$this->message}</string></value>
926 function __construct( $time )
928 // $time can be a PHP timestamp or an ISO one
929 if (is_numeric($time)) {
930 $this->parseTimestamp($time);
932 $this->parseIso($time);
939 public function IXR_Date( $time ) {
940 self::__construct( $time );
943 function parseTimestamp($timestamp)
945 $this->year = date('Y', $timestamp);
946 $this->month = date('m', $timestamp);
947 $this->day = date('d', $timestamp);
948 $this->hour = date('H', $timestamp);
949 $this->minute = date('i', $timestamp);
950 $this->second = date('s', $timestamp);
951 $this->timezone = '';
954 function parseIso($iso)
956 $this->year = substr($iso, 0, 4);
957 $this->month = substr($iso, 4, 2);
958 $this->day = substr($iso, 6, 2);
959 $this->hour = substr($iso, 9, 2);
960 $this->minute = substr($iso, 12, 2);
961 $this->second = substr($iso, 15, 2);
962 $this->timezone = substr($iso, 17);
967 return $this->year.$this->month.$this->day.'T'.$this->hour.':'.$this->minute.':'.$this->second.$this->timezone;
972 return '<dateTime.iso8601>'.$this->getIso().'</dateTime.iso8601>';
975 function getTimestamp()
977 return mktime($this->hour, $this->minute, $this->second, $this->month, $this->day, $this->year);
994 function __construct( $data )
1002 public function IXR_Base64( $data ) {
1003 self::__construct( $data );
1008 return '<base64>'.base64_encode($this->data).'</base64>';
1013 * IXR_IntrospectionServer
1018 class IXR_IntrospectionServer extends IXR_Server
1026 function __construct()
1028 $this->setCallbacks();
1029 $this->setCapabilities();
1030 $this->capabilities['introspection'] = array(
1031 'specUrl' => 'http://xmlrpc.usefulinc.com/doc/reserved.html',
1035 'system.methodSignature',
1036 'this:methodSignature',
1037 array('array', 'string'),
1038 'Returns an array describing the return type and required parameters of a method'
1041 'system.getCapabilities',
1042 'this:getCapabilities',
1044 'Returns a struct describing the XML-RPC specifications supported by this server'
1047 'system.listMethods',
1050 'Returns an array of available methods on this server'
1053 'system.methodHelp',
1055 array('string', 'string'),
1056 'Returns a documentation string for the specified method'
1063 public function IXR_IntrospectionServer() {
1064 self::__construct();
1067 function addCallback($method, $callback, $args, $help)
1069 $this->callbacks[$method] = $callback;
1070 $this->signatures[$method] = $args;
1071 $this->help[$method] = $help;
1074 function call($methodname, $args)
1076 // Make sure it's in an array
1077 if ($args && !is_array($args)) {
1078 $args = array($args);
1081 // Over-rides default call method, adds signature check
1082 if (!$this->hasMethod($methodname)) {
1083 return new IXR_Error(-32601, 'server error. requested method "'.$this->message->methodName.'" not specified.');
1085 $method = $this->callbacks[$methodname];
1086 $signature = $this->signatures[$methodname];
1087 $returnType = array_shift($signature);
1089 // Check the number of arguments
1090 if (count($args) != count($signature)) {
1091 return new IXR_Error(-32602, 'server error. wrong number of method parameters');
1094 // Check the argument types
1096 $argsbackup = $args;
1097 for ($i = 0, $j = count($args); $i < $j; $i++) {
1098 $arg = array_shift($args);
1099 $type = array_shift($signature);
1103 if (is_array($arg) || !is_int($arg)) {
1109 if (!is_string($arg)) {
1114 if ($arg !== false && $arg !== true) {
1120 if (!is_float($arg)) {
1125 case 'dateTime.iso8601':
1126 if (!is_a($arg, 'IXR_Date')) {
1132 return new IXR_Error(-32602, 'server error. invalid method parameters');
1135 // It passed the test - run the "real" method call
1136 return parent::call($methodname, $argsbackup);
1139 function methodSignature($method)
1141 if (!$this->hasMethod($method)) {
1142 return new IXR_Error(-32601, 'server error. requested method "'.$method.'" not specified.');
1144 // We should be returning an array of types
1145 $types = $this->signatures[$method];
1147 foreach ($types as $type) {
1150 $return[] = 'string';
1159 case 'dateTime.iso8601':
1160 $return[] = new IXR_Date(time());
1166 $return[] = new IXR_Base64('base64');
1169 $return[] = array('array');
1172 $return[] = array('struct' => 'struct');
1179 function methodHelp($method)
1181 return $this->help[$method];
1186 * IXR_ClientMulticall
1191 class IXR_ClientMulticall extends IXR_Client
1193 var $calls = array();
1198 function __construct( $server, $path = false, $port = 80 )
1200 parent::IXR_Client($server, $path, $port);
1201 $this->useragent = 'The Incutio XML-RPC PHP Library (multicall client)';
1207 public function IXR_ClientMulticall( $server, $path = false, $port = 80 ) {
1208 self::__construct( $server, $path, $port );
1213 $args = func_get_args();
1214 $methodName = array_shift($args);
1216 'methodName' => $methodName,
1219 $this->calls[] = $struct;
1224 // Prepare multicall, then call the parent::query() method
1225 return parent::query('system.multicall', $this->calls);