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;
210 function __construct( $message )
212 $this->message =& $message;
218 public function IXR_Message( $message ) {
219 self::__construct( $message );
224 // first remove the XML declaration
225 // merged from WP #10698 - this method avoids the RAM usage of preg_replace on very large messages
226 $header = preg_replace( '/<\?xml.*?\?'.'>/s', '', substr( $this->message, 0, 100 ), 1 );
227 $this->message = trim( substr_replace( $this->message, $header, 0, 100 ) );
228 if ( '' == $this->message ) {
232 // Then remove the DOCTYPE
233 $header = preg_replace( '/^<!DOCTYPE[^>]*+>/i', '', substr( $this->message, 0, 200 ), 1 );
234 $this->message = trim( substr_replace( $this->message, $header, 0, 200 ) );
235 if ( '' == $this->message ) {
239 // Check that the root tag is valid
240 $root_tag = substr( $this->message, 0, strcspn( substr( $this->message, 0, 20 ), "> \t\r\n" ) );
241 if ( '<!DOCTYPE' === strtoupper( $root_tag ) ) {
244 if ( ! in_array( $root_tag, array( '<methodCall', '<methodResponse', '<fault' ) ) ) {
248 // Bail if there are too many elements to parse
249 $element_limit = 30000;
250 if ( function_exists( 'apply_filters' ) ) {
252 * Filter the number of elements to parse in an XML-RPC response.
256 * @param int $element_limit Default elements limit.
258 $element_limit = apply_filters( 'xmlrpc_element_limit', $element_limit );
260 if ( $element_limit && 2 * $element_limit < substr_count( $this->message, '<' ) ) {
264 $this->_parser = xml_parser_create();
265 // Set XML parser to take the case of tags in to account
266 xml_parser_set_option($this->_parser, XML_OPTION_CASE_FOLDING, false);
267 // Set XML parser callback functions
268 xml_set_object($this->_parser, $this);
269 xml_set_element_handler($this->_parser, 'tag_open', 'tag_close');
270 xml_set_character_data_handler($this->_parser, 'cdata');
271 $chunk_size = 262144; // 256Kb, parse in chunks to avoid the RAM usage on very large messages
274 if (strlen($this->message) <= $chunk_size) {
277 $part = substr($this->message, 0, $chunk_size);
278 $this->message = substr($this->message, $chunk_size);
279 if (!xml_parse($this->_parser, $part, $final)) {
286 xml_parser_free($this->_parser);
288 // Grab the error messages, if any
289 if ($this->messageType == 'fault') {
290 $this->faultCode = $this->params[0]['faultCode'];
291 $this->faultString = $this->params[0]['faultString'];
296 function tag_open($parser, $tag, $attr)
298 $this->_currentTagContents = '';
299 $this->currentTag = $tag;
302 case 'methodResponse':
304 $this->messageType = $tag;
306 /* Deal with stacks of arrays and structs */
307 case 'data': // data is to all intents and puposes more interesting than array
308 $this->_arraystructstypes[] = 'array';
309 $this->_arraystructs[] = array();
312 $this->_arraystructstypes[] = 'struct';
313 $this->_arraystructs[] = array();
318 function cdata($parser, $cdata)
320 $this->_currentTagContents .= $cdata;
323 function tag_close($parser, $tag)
329 $value = (int)trim($this->_currentTagContents);
333 $value = (double)trim($this->_currentTagContents);
337 $value = (string)trim($this->_currentTagContents);
340 case 'dateTime.iso8601':
341 $value = new IXR_Date(trim($this->_currentTagContents));
345 // "If no type is indicated, the type is string."
346 if (trim($this->_currentTagContents) != '') {
347 $value = (string)$this->_currentTagContents;
352 $value = (boolean)trim($this->_currentTagContents);
356 $value = base64_decode($this->_currentTagContents);
359 /* Deal with stacks of arrays and structs */
362 $value = array_pop($this->_arraystructs);
363 array_pop($this->_arraystructstypes);
367 array_pop($this->_currentStructName);
370 $this->_currentStructName[] = trim($this->_currentTagContents);
373 $this->methodName = trim($this->_currentTagContents);
378 if (count($this->_arraystructs) > 0) {
379 // Add value to struct or array
380 if ($this->_arraystructstypes[count($this->_arraystructstypes)-1] == 'struct') {
382 $this->_arraystructs[count($this->_arraystructs)-1][$this->_currentStructName[count($this->_currentStructName)-1]] = $value;
385 $this->_arraystructs[count($this->_arraystructs)-1][] = $value;
388 // Just add as a parameter
389 $this->params[] = $value;
392 $this->_currentTagContents = '';
405 var $callbacks = array();
412 function __construct( $callbacks = false, $data = false, $wait = false )
414 $this->setCapabilities();
416 $this->callbacks = $callbacks;
418 $this->setCallbacks();
427 public function IXR_Server( $callbacks = false, $data = false, $wait = false ) {
428 self::__construct( $callbacks, $data, $wait );
431 function serve($data = false)
434 if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] !== 'POST') {
435 if ( function_exists( 'status_header' ) ) {
436 status_header( 405 ); // WP #20986
437 header( 'Allow: POST' );
439 header('Content-Type: text/plain'); // merged from WP #9093
440 die('XML-RPC server accepts POST requests only.');
443 global $HTTP_RAW_POST_DATA;
444 if (empty($HTTP_RAW_POST_DATA)) {
445 // workaround for a bug in PHP 5.2.2 - http://bugs.php.net/bug.php?id=41293
446 $data = file_get_contents('php://input');
448 $data =& $HTTP_RAW_POST_DATA;
451 $this->message = new IXR_Message($data);
452 if (!$this->message->parse()) {
453 $this->error(-32700, 'parse error. not well formed');
455 if ($this->message->messageType != 'methodCall') {
456 $this->error(-32600, 'server error. invalid xml-rpc. not conforming to spec. Request must be a methodCall');
458 $result = $this->call($this->message->methodName, $this->message->params);
460 // Is the result an error?
461 if (is_a($result, 'IXR_Error')) {
462 $this->error($result);
466 $r = new IXR_Value($result);
467 $resultxml = $r->getXml();
486 function call($methodname, $args)
488 if (!$this->hasMethod($methodname)) {
489 return new IXR_Error(-32601, 'server error. requested method '.$methodname.' does not exist.');
491 $method = $this->callbacks[$methodname];
493 // Perform the callback and send the response
494 if (count($args) == 1) {
495 // If only one parameter just send that instead of the whole array
499 // Are we dealing with a function or a method?
500 if (is_string($method) && substr($method, 0, 5) == 'this:') {
501 // It's a class method - check it exists
502 $method = substr($method, 5);
503 if (!method_exists($this, $method)) {
504 return new IXR_Error(-32601, 'server error. requested class method "'.$method.'" does not exist.');
508 $result = $this->$method($args);
510 // It's a function - does it exist?
511 if (is_array($method)) {
512 if (!is_callable(array($method[0], $method[1]))) {
513 return new IXR_Error(-32601, 'server error. requested object method "'.$method[1].'" does not exist.');
515 } else if (!function_exists($method)) {
516 return new IXR_Error(-32601, 'server error. requested function "'.$method.'" does not exist.');
520 $result = call_user_func($method, $args);
525 function error($error, $message = false)
527 // Accepts either an error object or an error code and message
528 if ($message && !is_object($error)) {
529 $error = new IXR_Error($error, $message);
531 $this->output($error->getXml());
534 function output($xml)
536 $charset = function_exists('get_option') ? get_option('blog_charset') : '';
538 $xml = '<?xml version="1.0" encoding="'.$charset.'"?>'."\n".$xml;
540 $xml = '<?xml version="1.0"?>'."\n".$xml;
541 $length = strlen($xml);
542 header('Connection: close');
543 header('Content-Length: '.$length);
545 header('Content-Type: text/xml; charset='.$charset);
547 header('Content-Type: text/xml');
548 header('Date: '.date('r'));
553 function hasMethod($method)
555 return in_array($method, array_keys($this->callbacks));
558 function setCapabilities()
560 // Initialises capabilities array
561 $this->capabilities = array(
563 'specUrl' => 'http://www.xmlrpc.com/spec',
566 'faults_interop' => array(
567 'specUrl' => 'http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php',
568 'specVersion' => 20010516
570 'system.multicall' => array(
571 'specUrl' => 'http://www.xmlrpc.com/discuss/msgReader$1208',
577 function getCapabilities($args)
579 return $this->capabilities;
582 function setCallbacks()
584 $this->callbacks['system.getCapabilities'] = 'this:getCapabilities';
585 $this->callbacks['system.listMethods'] = 'this:listMethods';
586 $this->callbacks['system.multicall'] = 'this:multiCall';
589 function listMethods($args)
591 // Returns a list of methods - uses array_reverse to ensure user defined
592 // methods are listed before server defined methods
593 return array_reverse(array_keys($this->callbacks));
596 function multiCall($methodcalls)
598 // See http://www.xmlrpc.com/discuss/msgReader$1208
600 foreach ($methodcalls as $call) {
601 $method = $call['methodName'];
602 $params = $call['params'];
603 if ($method == 'system.multicall') {
604 $result = new IXR_Error(-32600, 'Recursive calls to system.multicall are forbidden');
606 $result = $this->call($method, $params);
608 if (is_a($result, 'IXR_Error')) {
610 'faultCode' => $result->code,
611 'faultString' => $result->message
614 $return[] = array($result);
636 function __construct($method, $args)
638 $this->method = $method;
641 <?xml version="1.0"?>
643 <methodName>{$this->method}</methodName>
647 foreach ($this->args as $arg) {
648 $this->xml .= '<param><value>';
649 $v = new IXR_Value($arg);
650 $this->xml .= $v->getXml();
651 $this->xml .= "</value></param>\n";
653 $this->xml .= '</params></methodCall>';
659 public function IXR_Request( $method, $args ) {
660 self::__construct( $method, $args );
665 return strlen($this->xml);
688 var $message = false;
691 var $headers = array();
693 // Storage place for an error message
699 function __construct( $server, $path = false, $port = 80, $timeout = 15 )
702 // Assume we have been given a URL instead
703 $bits = parse_url($server);
704 $this->server = $bits['host'];
705 $this->port = isset($bits['port']) ? $bits['port'] : 80;
706 $this->path = isset($bits['path']) ? $bits['path'] : '/';
708 // Make absolutely sure we have a path
713 if ( ! empty( $bits['query'] ) ) {
714 $this->path .= '?' . $bits['query'];
717 $this->server = $server;
721 $this->useragent = 'The Incutio XML-RPC PHP Library';
722 $this->timeout = $timeout;
728 public function IXR_Client( $server, $path = false, $port = 80, $timeout = 15 ) {
729 self::__construct( $server, $path, $port, $timeout );
734 $args = func_get_args();
735 $method = array_shift($args);
736 $request = new IXR_Request($method, $args);
737 $length = $request->getLength();
738 $xml = $request->getXml();
740 $request = "POST {$this->path} HTTP/1.0$r";
742 // Merged from WP #8145 - allow custom headers
743 $this->headers['Host'] = $this->server;
744 $this->headers['Content-Type'] = 'text/xml';
745 $this->headers['User-Agent'] = $this->useragent;
746 $this->headers['Content-Length']= $length;
748 foreach( $this->headers as $header => $value ) {
749 $request .= "{$header}: {$value}{$r}";
755 // Now send the request
757 echo '<pre class="ixr_request">'.htmlspecialchars($request)."\n</pre>\n\n";
760 if ($this->timeout) {
761 $fp = @fsockopen($this->server, $this->port, $errno, $errstr, $this->timeout);
763 $fp = @fsockopen($this->server, $this->port, $errno, $errstr);
766 $this->error = new IXR_Error(-32300, 'transport error - could not open socket');
769 fputs($fp, $request);
772 $gotFirstLine = false;
773 $gettingHeaders = true;
775 $line = fgets($fp, 4096);
776 if (!$gotFirstLine) {
777 // Check line for '200'
778 if (strstr($line, '200') === false) {
779 $this->error = new IXR_Error(-32300, 'transport error - HTTP status code was not 200');
782 $gotFirstLine = true;
784 if (trim($line) == '') {
785 $gettingHeaders = false;
787 if (!$gettingHeaders) {
788 // merged from WP #12559 - remove trim
792 $debugContents .= $line;
796 echo '<pre class="ixr_response">'.htmlspecialchars($debugContents)."\n</pre>\n\n";
799 // Now parse what we've got back
800 $this->message = new IXR_Message($contents);
801 if (!$this->message->parse()) {
803 $this->error = new IXR_Error(-32700, 'parse error. not well formed');
807 // Is the message a fault?
808 if ($this->message->messageType == 'fault') {
809 $this->error = new IXR_Error($this->message->faultCode, $this->message->faultString);
813 // Message must be OK
817 function getResponse()
819 // methodResponses can only have one param - return that
820 return $this->message->params[0];
825 return (is_object($this->error));
828 function getErrorCode()
830 return $this->error->code;
833 function getErrorMessage()
835 return $this->error->message;
854 function __construct( $code, $message )
857 $this->message = htmlspecialchars($message);
863 public function IXR_Error( $code, $message ) {
864 self::__construct( $code, $message );
875 <name>faultCode</name>
876 <value><int>{$this->code}</int></value>
879 <name>faultString</name>
880 <value><string>{$this->message}</string></value>
910 function __construct( $time )
912 // $time can be a PHP timestamp or an ISO one
913 if (is_numeric($time)) {
914 $this->parseTimestamp($time);
916 $this->parseIso($time);
923 public function IXR_Date( $time ) {
924 self::__construct( $time );
927 function parseTimestamp($timestamp)
929 $this->year = date('Y', $timestamp);
930 $this->month = date('m', $timestamp);
931 $this->day = date('d', $timestamp);
932 $this->hour = date('H', $timestamp);
933 $this->minute = date('i', $timestamp);
934 $this->second = date('s', $timestamp);
935 $this->timezone = '';
938 function parseIso($iso)
940 $this->year = substr($iso, 0, 4);
941 $this->month = substr($iso, 4, 2);
942 $this->day = substr($iso, 6, 2);
943 $this->hour = substr($iso, 9, 2);
944 $this->minute = substr($iso, 12, 2);
945 $this->second = substr($iso, 15, 2);
946 $this->timezone = substr($iso, 17);
951 return $this->year.$this->month.$this->day.'T'.$this->hour.':'.$this->minute.':'.$this->second.$this->timezone;
956 return '<dateTime.iso8601>'.$this->getIso().'</dateTime.iso8601>';
959 function getTimestamp()
961 return mktime($this->hour, $this->minute, $this->second, $this->month, $this->day, $this->year);
978 function __construct( $data )
986 public function IXR_Base64( $data ) {
987 self::__construct( $data );
992 return '<base64>'.base64_encode($this->data).'</base64>';
997 * IXR_IntrospectionServer
1002 class IXR_IntrospectionServer extends IXR_Server
1010 function __construct()
1012 $this->setCallbacks();
1013 $this->setCapabilities();
1014 $this->capabilities['introspection'] = array(
1015 'specUrl' => 'http://xmlrpc.usefulinc.com/doc/reserved.html',
1019 'system.methodSignature',
1020 'this:methodSignature',
1021 array('array', 'string'),
1022 'Returns an array describing the return type and required parameters of a method'
1025 'system.getCapabilities',
1026 'this:getCapabilities',
1028 'Returns a struct describing the XML-RPC specifications supported by this server'
1031 'system.listMethods',
1034 'Returns an array of available methods on this server'
1037 'system.methodHelp',
1039 array('string', 'string'),
1040 'Returns a documentation string for the specified method'
1047 public function IXR_IntrospectionServer() {
1048 self::__construct();
1051 function addCallback($method, $callback, $args, $help)
1053 $this->callbacks[$method] = $callback;
1054 $this->signatures[$method] = $args;
1055 $this->help[$method] = $help;
1058 function call($methodname, $args)
1060 // Make sure it's in an array
1061 if ($args && !is_array($args)) {
1062 $args = array($args);
1065 // Over-rides default call method, adds signature check
1066 if (!$this->hasMethod($methodname)) {
1067 return new IXR_Error(-32601, 'server error. requested method "'.$this->message->methodName.'" not specified.');
1069 $method = $this->callbacks[$methodname];
1070 $signature = $this->signatures[$methodname];
1071 $returnType = array_shift($signature);
1073 // Check the number of arguments
1074 if (count($args) != count($signature)) {
1075 return new IXR_Error(-32602, 'server error. wrong number of method parameters');
1078 // Check the argument types
1080 $argsbackup = $args;
1081 for ($i = 0, $j = count($args); $i < $j; $i++) {
1082 $arg = array_shift($args);
1083 $type = array_shift($signature);
1087 if (is_array($arg) || !is_int($arg)) {
1093 if (!is_string($arg)) {
1098 if ($arg !== false && $arg !== true) {
1104 if (!is_float($arg)) {
1109 case 'dateTime.iso8601':
1110 if (!is_a($arg, 'IXR_Date')) {
1116 return new IXR_Error(-32602, 'server error. invalid method parameters');
1119 // It passed the test - run the "real" method call
1120 return parent::call($methodname, $argsbackup);
1123 function methodSignature($method)
1125 if (!$this->hasMethod($method)) {
1126 return new IXR_Error(-32601, 'server error. requested method "'.$method.'" not specified.');
1128 // We should be returning an array of types
1129 $types = $this->signatures[$method];
1131 foreach ($types as $type) {
1134 $return[] = 'string';
1143 case 'dateTime.iso8601':
1144 $return[] = new IXR_Date(time());
1150 $return[] = new IXR_Base64('base64');
1153 $return[] = array('array');
1156 $return[] = array('struct' => 'struct');
1163 function methodHelp($method)
1165 return $this->help[$method];
1170 * IXR_ClientMulticall
1175 class IXR_ClientMulticall extends IXR_Client
1177 var $calls = array();
1182 function __construct( $server, $path = false, $port = 80 )
1184 parent::IXR_Client($server, $path, $port);
1185 $this->useragent = 'The Incutio XML-RPC PHP Library (multicall client)';
1191 public function IXR_ClientMulticall( $server, $path = false, $port = 80 ) {
1192 self::__construct( $server, $path, $port );
1197 $args = func_get_args();
1198 $methodName = array_shift($args);
1200 'methodName' => $methodName,
1203 $this->calls[] = $struct;
1208 // Prepare multicall, then call the parent::query() method
1209 return parent::query('system.multicall', $this->calls);