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 * Filters 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');
272 // 256Kb, parse in chunks to avoid the RAM usage on very large messages
273 $chunk_size = 262144;
276 * Filters the chunk size that can be used to parse an XML-RPC reponse message.
280 * @param int $chunk_size Chunk size to parse in bytes.
282 $chunk_size = apply_filters( 'xmlrpc_chunk_parsing_size', $chunk_size );
286 if (strlen($this->message) <= $chunk_size) {
289 $part = substr($this->message, 0, $chunk_size);
290 $this->message = substr($this->message, $chunk_size);
291 if (!xml_parse($this->_parser, $part, $final)) {
298 xml_parser_free($this->_parser);
300 // Grab the error messages, if any
301 if ($this->messageType == 'fault') {
302 $this->faultCode = $this->params[0]['faultCode'];
303 $this->faultString = $this->params[0]['faultString'];
308 function tag_open($parser, $tag, $attr)
310 $this->_currentTagContents = '';
311 $this->currentTag = $tag;
314 case 'methodResponse':
316 $this->messageType = $tag;
318 /* Deal with stacks of arrays and structs */
319 case 'data': // data is to all intents and puposes more interesting than array
320 $this->_arraystructstypes[] = 'array';
321 $this->_arraystructs[] = array();
324 $this->_arraystructstypes[] = 'struct';
325 $this->_arraystructs[] = array();
330 function cdata($parser, $cdata)
332 $this->_currentTagContents .= $cdata;
335 function tag_close($parser, $tag)
341 $value = (int)trim($this->_currentTagContents);
345 $value = (double)trim($this->_currentTagContents);
349 $value = (string)trim($this->_currentTagContents);
352 case 'dateTime.iso8601':
353 $value = new IXR_Date(trim($this->_currentTagContents));
357 // "If no type is indicated, the type is string."
358 if (trim($this->_currentTagContents) != '') {
359 $value = (string)$this->_currentTagContents;
364 $value = (boolean)trim($this->_currentTagContents);
368 $value = base64_decode($this->_currentTagContents);
371 /* Deal with stacks of arrays and structs */
374 $value = array_pop($this->_arraystructs);
375 array_pop($this->_arraystructstypes);
379 array_pop($this->_currentStructName);
382 $this->_currentStructName[] = trim($this->_currentTagContents);
385 $this->methodName = trim($this->_currentTagContents);
390 if (count($this->_arraystructs) > 0) {
391 // Add value to struct or array
392 if ($this->_arraystructstypes[count($this->_arraystructstypes)-1] == 'struct') {
394 $this->_arraystructs[count($this->_arraystructs)-1][$this->_currentStructName[count($this->_currentStructName)-1]] = $value;
397 $this->_arraystructs[count($this->_arraystructs)-1][] = $value;
400 // Just add as a parameter
401 $this->params[] = $value;
404 $this->_currentTagContents = '';
417 var $callbacks = array();
424 function __construct( $callbacks = false, $data = false, $wait = false )
426 $this->setCapabilities();
428 $this->callbacks = $callbacks;
430 $this->setCallbacks();
439 public function IXR_Server( $callbacks = false, $data = false, $wait = false ) {
440 self::__construct( $callbacks, $data, $wait );
443 function serve($data = false)
446 if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] !== 'POST') {
447 if ( function_exists( 'status_header' ) ) {
448 status_header( 405 ); // WP #20986
449 header( 'Allow: POST' );
451 header('Content-Type: text/plain'); // merged from WP #9093
452 die('XML-RPC server accepts POST requests only.');
455 global $HTTP_RAW_POST_DATA;
456 if (empty($HTTP_RAW_POST_DATA)) {
457 // workaround for a bug in PHP 5.2.2 - http://bugs.php.net/bug.php?id=41293
458 $data = file_get_contents('php://input');
460 $data =& $HTTP_RAW_POST_DATA;
463 $this->message = new IXR_Message($data);
464 if (!$this->message->parse()) {
465 $this->error(-32700, 'parse error. not well formed');
467 if ($this->message->messageType != 'methodCall') {
468 $this->error(-32600, 'server error. invalid xml-rpc. not conforming to spec. Request must be a methodCall');
470 $result = $this->call($this->message->methodName, $this->message->params);
472 // Is the result an error?
473 if (is_a($result, 'IXR_Error')) {
474 $this->error($result);
478 $r = new IXR_Value($result);
479 $resultxml = $r->getXml();
498 function call($methodname, $args)
500 if (!$this->hasMethod($methodname)) {
501 return new IXR_Error(-32601, 'server error. requested method '.$methodname.' does not exist.');
503 $method = $this->callbacks[$methodname];
505 // Perform the callback and send the response
506 if (count($args) == 1) {
507 // If only one parameter just send that instead of the whole array
511 // Are we dealing with a function or a method?
512 if (is_string($method) && substr($method, 0, 5) == 'this:') {
513 // It's a class method - check it exists
514 $method = substr($method, 5);
515 if (!method_exists($this, $method)) {
516 return new IXR_Error(-32601, 'server error. requested class method "'.$method.'" does not exist.');
520 $result = $this->$method($args);
522 // It's a function - does it exist?
523 if (is_array($method)) {
524 if (!is_callable(array($method[0], $method[1]))) {
525 return new IXR_Error(-32601, 'server error. requested object method "'.$method[1].'" does not exist.');
527 } else if (!function_exists($method)) {
528 return new IXR_Error(-32601, 'server error. requested function "'.$method.'" does not exist.');
532 $result = call_user_func($method, $args);
537 function error($error, $message = false)
539 // Accepts either an error object or an error code and message
540 if ($message && !is_object($error)) {
541 $error = new IXR_Error($error, $message);
543 $this->output($error->getXml());
546 function output($xml)
548 $charset = function_exists('get_option') ? get_option('blog_charset') : '';
550 $xml = '<?xml version="1.0" encoding="'.$charset.'"?>'."\n".$xml;
552 $xml = '<?xml version="1.0"?>'."\n".$xml;
553 $length = strlen($xml);
554 header('Connection: close');
556 header('Content-Type: text/xml; charset='.$charset);
558 header('Content-Type: text/xml');
559 header('Date: '.date('r'));
564 function hasMethod($method)
566 return in_array($method, array_keys($this->callbacks));
569 function setCapabilities()
571 // Initialises capabilities array
572 $this->capabilities = array(
574 'specUrl' => 'http://www.xmlrpc.com/spec',
577 'faults_interop' => array(
578 'specUrl' => 'http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php',
579 'specVersion' => 20010516
581 'system.multicall' => array(
582 'specUrl' => 'http://www.xmlrpc.com/discuss/msgReader$1208',
588 function getCapabilities($args)
590 return $this->capabilities;
593 function setCallbacks()
595 $this->callbacks['system.getCapabilities'] = 'this:getCapabilities';
596 $this->callbacks['system.listMethods'] = 'this:listMethods';
597 $this->callbacks['system.multicall'] = 'this:multiCall';
600 function listMethods($args)
602 // Returns a list of methods - uses array_reverse to ensure user defined
603 // methods are listed before server defined methods
604 return array_reverse(array_keys($this->callbacks));
607 function multiCall($methodcalls)
609 // See http://www.xmlrpc.com/discuss/msgReader$1208
611 foreach ($methodcalls as $call) {
612 $method = $call['methodName'];
613 $params = $call['params'];
614 if ($method == 'system.multicall') {
615 $result = new IXR_Error(-32600, 'Recursive calls to system.multicall are forbidden');
617 $result = $this->call($method, $params);
619 if (is_a($result, 'IXR_Error')) {
621 'faultCode' => $result->code,
622 'faultString' => $result->message
625 $return[] = array($result);
647 function __construct($method, $args)
649 $this->method = $method;
652 <?xml version="1.0"?>
654 <methodName>{$this->method}</methodName>
658 foreach ($this->args as $arg) {
659 $this->xml .= '<param><value>';
660 $v = new IXR_Value($arg);
661 $this->xml .= $v->getXml();
662 $this->xml .= "</value></param>\n";
664 $this->xml .= '</params></methodCall>';
670 public function IXR_Request( $method, $args ) {
671 self::__construct( $method, $args );
676 return strlen($this->xml);
699 var $message = false;
702 var $headers = array();
704 // Storage place for an error message
710 function __construct( $server, $path = false, $port = 80, $timeout = 15 )
713 // Assume we have been given a URL instead
714 $bits = parse_url($server);
715 $this->server = $bits['host'];
716 $this->port = isset($bits['port']) ? $bits['port'] : 80;
717 $this->path = isset($bits['path']) ? $bits['path'] : '/';
719 // Make absolutely sure we have a path
724 if ( ! empty( $bits['query'] ) ) {
725 $this->path .= '?' . $bits['query'];
728 $this->server = $server;
732 $this->useragent = 'The Incutio XML-RPC PHP Library';
733 $this->timeout = $timeout;
739 public function IXR_Client( $server, $path = false, $port = 80, $timeout = 15 ) {
740 self::__construct( $server, $path, $port, $timeout );
745 $args = func_get_args();
746 $method = array_shift($args);
747 $request = new IXR_Request($method, $args);
748 $length = $request->getLength();
749 $xml = $request->getXml();
751 $request = "POST {$this->path} HTTP/1.0$r";
753 // Merged from WP #8145 - allow custom headers
754 $this->headers['Host'] = $this->server;
755 $this->headers['Content-Type'] = 'text/xml';
756 $this->headers['User-Agent'] = $this->useragent;
757 $this->headers['Content-Length']= $length;
759 foreach( $this->headers as $header => $value ) {
760 $request .= "{$header}: {$value}{$r}";
766 // Now send the request
768 echo '<pre class="ixr_request">'.htmlspecialchars($request)."\n</pre>\n\n";
771 if ($this->timeout) {
772 $fp = @fsockopen($this->server, $this->port, $errno, $errstr, $this->timeout);
774 $fp = @fsockopen($this->server, $this->port, $errno, $errstr);
777 $this->error = new IXR_Error(-32300, 'transport error - could not open socket');
780 fputs($fp, $request);
783 $gotFirstLine = false;
784 $gettingHeaders = true;
786 $line = fgets($fp, 4096);
787 if (!$gotFirstLine) {
788 // Check line for '200'
789 if (strstr($line, '200') === false) {
790 $this->error = new IXR_Error(-32300, 'transport error - HTTP status code was not 200');
793 $gotFirstLine = true;
795 if (trim($line) == '') {
796 $gettingHeaders = false;
798 if (!$gettingHeaders) {
799 // merged from WP #12559 - remove trim
803 $debugContents .= $line;
807 echo '<pre class="ixr_response">'.htmlspecialchars($debugContents)."\n</pre>\n\n";
810 // Now parse what we've got back
811 $this->message = new IXR_Message($contents);
812 if (!$this->message->parse()) {
814 $this->error = new IXR_Error(-32700, 'parse error. not well formed');
818 // Is the message a fault?
819 if ($this->message->messageType == 'fault') {
820 $this->error = new IXR_Error($this->message->faultCode, $this->message->faultString);
824 // Message must be OK
828 function getResponse()
830 // methodResponses can only have one param - return that
831 return $this->message->params[0];
836 return (is_object($this->error));
839 function getErrorCode()
841 return $this->error->code;
844 function getErrorMessage()
846 return $this->error->message;
865 function __construct( $code, $message )
868 $this->message = htmlspecialchars($message);
874 public function IXR_Error( $code, $message ) {
875 self::__construct( $code, $message );
886 <name>faultCode</name>
887 <value><int>{$this->code}</int></value>
890 <name>faultString</name>
891 <value><string>{$this->message}</string></value>
921 function __construct( $time )
923 // $time can be a PHP timestamp or an ISO one
924 if (is_numeric($time)) {
925 $this->parseTimestamp($time);
927 $this->parseIso($time);
934 public function IXR_Date( $time ) {
935 self::__construct( $time );
938 function parseTimestamp($timestamp)
940 $this->year = date('Y', $timestamp);
941 $this->month = date('m', $timestamp);
942 $this->day = date('d', $timestamp);
943 $this->hour = date('H', $timestamp);
944 $this->minute = date('i', $timestamp);
945 $this->second = date('s', $timestamp);
946 $this->timezone = '';
949 function parseIso($iso)
951 $this->year = substr($iso, 0, 4);
952 $this->month = substr($iso, 4, 2);
953 $this->day = substr($iso, 6, 2);
954 $this->hour = substr($iso, 9, 2);
955 $this->minute = substr($iso, 12, 2);
956 $this->second = substr($iso, 15, 2);
957 $this->timezone = substr($iso, 17);
962 return $this->year.$this->month.$this->day.'T'.$this->hour.':'.$this->minute.':'.$this->second.$this->timezone;
967 return '<dateTime.iso8601>'.$this->getIso().'</dateTime.iso8601>';
970 function getTimestamp()
972 return mktime($this->hour, $this->minute, $this->second, $this->month, $this->day, $this->year);
989 function __construct( $data )
997 public function IXR_Base64( $data ) {
998 self::__construct( $data );
1003 return '<base64>'.base64_encode($this->data).'</base64>';
1008 * IXR_IntrospectionServer
1013 class IXR_IntrospectionServer extends IXR_Server
1021 function __construct()
1023 $this->setCallbacks();
1024 $this->setCapabilities();
1025 $this->capabilities['introspection'] = array(
1026 'specUrl' => 'http://xmlrpc.usefulinc.com/doc/reserved.html',
1030 'system.methodSignature',
1031 'this:methodSignature',
1032 array('array', 'string'),
1033 'Returns an array describing the return type and required parameters of a method'
1036 'system.getCapabilities',
1037 'this:getCapabilities',
1039 'Returns a struct describing the XML-RPC specifications supported by this server'
1042 'system.listMethods',
1045 'Returns an array of available methods on this server'
1048 'system.methodHelp',
1050 array('string', 'string'),
1051 'Returns a documentation string for the specified method'
1058 public function IXR_IntrospectionServer() {
1059 self::__construct();
1062 function addCallback($method, $callback, $args, $help)
1064 $this->callbacks[$method] = $callback;
1065 $this->signatures[$method] = $args;
1066 $this->help[$method] = $help;
1069 function call($methodname, $args)
1071 // Make sure it's in an array
1072 if ($args && !is_array($args)) {
1073 $args = array($args);
1076 // Over-rides default call method, adds signature check
1077 if (!$this->hasMethod($methodname)) {
1078 return new IXR_Error(-32601, 'server error. requested method "'.$this->message->methodName.'" not specified.');
1080 $method = $this->callbacks[$methodname];
1081 $signature = $this->signatures[$methodname];
1082 $returnType = array_shift($signature);
1084 // Check the number of arguments
1085 if (count($args) != count($signature)) {
1086 return new IXR_Error(-32602, 'server error. wrong number of method parameters');
1089 // Check the argument types
1091 $argsbackup = $args;
1092 for ($i = 0, $j = count($args); $i < $j; $i++) {
1093 $arg = array_shift($args);
1094 $type = array_shift($signature);
1098 if (is_array($arg) || !is_int($arg)) {
1104 if (!is_string($arg)) {
1109 if ($arg !== false && $arg !== true) {
1115 if (!is_float($arg)) {
1120 case 'dateTime.iso8601':
1121 if (!is_a($arg, 'IXR_Date')) {
1127 return new IXR_Error(-32602, 'server error. invalid method parameters');
1130 // It passed the test - run the "real" method call
1131 return parent::call($methodname, $argsbackup);
1134 function methodSignature($method)
1136 if (!$this->hasMethod($method)) {
1137 return new IXR_Error(-32601, 'server error. requested method "'.$method.'" not specified.');
1139 // We should be returning an array of types
1140 $types = $this->signatures[$method];
1142 foreach ($types as $type) {
1145 $return[] = 'string';
1154 case 'dateTime.iso8601':
1155 $return[] = new IXR_Date(time());
1161 $return[] = new IXR_Base64('base64');
1164 $return[] = array('array');
1167 $return[] = array('struct' => 'struct');
1174 function methodHelp($method)
1176 return $this->help[$method];
1181 * IXR_ClientMulticall
1186 class IXR_ClientMulticall extends IXR_Client
1188 var $calls = array();
1193 function __construct( $server, $path = false, $port = 80 )
1195 parent::IXR_Client($server, $path, $port);
1196 $this->useragent = 'The Incutio XML-RPC PHP Library (multicall client)';
1202 public function IXR_ClientMulticall( $server, $path = false, $port = 80 ) {
1203 self::__construct( $server, $path, $port );
1208 $args = func_get_args();
1209 $methodName = array_shift($args);
1211 'methodName' => $methodName,
1214 $this->calls[] = $struct;
1219 // Prepare multicall, then call the parent::query() method
1220 return parent::query('system.multicall', $this->calls);