3 * IXR - The Inutio XML-RPC Library
8 * @copyright Incutio Ltd 2002-2005
9 * @version 1.7 (beta) 23rd May 2005
10 * @author Simon Willison
11 * @link http://scripts.incutio.com/xmlrpc/ Site
12 * @link http://scripts.incutio.com/xmlrpc/manual.php Manual
13 * @license BSD License http://www.opensource.org/licenses/bsd-license.php
26 function IXR_Value ($data, $type = false) {
29 $type = $this->calculateType();
32 if ($type == 'struct') {
33 /* Turn all the values in the array in to new IXR_Value objects */
34 foreach ($this->data as $key => $value) {
35 $this->data[$key] = new IXR_Value($value);
38 if ($type == 'array') {
39 for ($i = 0, $j = count($this->data); $i < $j; $i++) {
40 $this->data[$i] = new IXR_Value($this->data[$i]);
45 function calculateType() {
46 if ($this->data === true || $this->data === false) {
49 if (is_integer($this->data)) {
52 if (is_double($this->data)) {
55 // Deal with IXR object types base64 and date
56 if (is_object($this->data) && is_a($this->data, 'IXR_Date')) {
59 if (is_object($this->data) && is_a($this->data, 'IXR_Base64')) {
62 // If it is a normal PHP object convert it in to a struct
63 if (is_object($this->data)) {
65 $this->data = get_object_vars($this->data);
68 if (!is_array($this->data)) {
71 /* We have an array - is it an array or a struct ? */
72 if ($this->isStruct($this->data)) {
80 /* Return XML for this value */
81 switch ($this->type) {
83 return '<boolean>'.(($this->data) ? '1' : '0').'</boolean>';
86 return '<int>'.$this->data.'</int>';
89 return '<double>'.$this->data.'</double>';
92 return '<string>'.htmlspecialchars($this->data).'</string>';
95 $return = '<array><data>'."\n";
96 foreach ($this->data as $item) {
97 $return .= ' <value>'.$item->getXml()."</value>\n";
99 $return .= '</data></array>';
103 $return = '<struct>'."\n";
104 foreach ($this->data as $name => $value) {
105 $name = htmlspecialchars($name);
106 $return .= " <member><name>$name</name><value>";
107 $return .= $value->getXml()."</value></member>\n";
109 $return .= '</struct>';
114 return $this->data->getXml();
120 function isStruct($array) {
121 /* Nasty function to check if an array is a struct or not */
123 foreach ($array as $key => $value) {
124 if ((string)$key != (string)$expected) {
141 var $messageType; // methodCall / methodResponse / fault
146 // Current variable stacks
147 var $_arraystructs = array(); // The stack used to keep track of the current array/struct
148 var $_arraystructstypes = array(); // Stack keeping track of if things are structs or array
149 var $_currentStructName = array(); // A stack as well
153 var $_currentTagContents;
156 function IXR_Message (&$message) {
157 $this->message = &$message;
160 // first remove the XML declaration
161 // this method avoids the RAM usage of preg_replace on very large messages
162 $header = preg_replace( '/<\?xml.*?\?'.'>/', '', substr( $this->message, 0, 100 ), 1 );
163 $this->message = substr_replace($this->message, $header, 0, 100);
164 if (trim($this->message) == '') {
167 $this->_parser = xml_parser_create();
168 // Set XML parser to take the case of tags in to account
169 xml_parser_set_option($this->_parser, XML_OPTION_CASE_FOLDING, false);
170 // Set XML parser callback functions
171 xml_set_object($this->_parser, $this);
172 xml_set_element_handler($this->_parser, 'tag_open', 'tag_close');
173 xml_set_character_data_handler($this->_parser, 'cdata');
174 $chunk_size = 262144; // 256Kb, parse in chunks to avoid the RAM usage on very large messages
176 if ( strlen($this->message) <= $chunk_size )
178 $part = substr( $this->message, 0, $chunk_size );
179 $this->message = substr( $this->message, $chunk_size );
180 if ( !xml_parse( $this->_parser, $part, $final ) )
185 xml_parser_free($this->_parser);
186 // Grab the error messages, if any
187 if ($this->messageType == 'fault') {
188 $this->faultCode = $this->params[0]['faultCode'];
189 $this->faultString = $this->params[0]['faultString'];
193 function tag_open($parser, $tag, $attr) {
194 $this->_currentTagContents = '';
195 $this->currentTag = $tag;
198 case 'methodResponse':
200 $this->messageType = $tag;
202 /* Deal with stacks of arrays and structs */
203 case 'data': // data is to all intents and puposes more interesting than array
204 $this->_arraystructstypes[] = 'array';
205 $this->_arraystructs[] = array();
208 $this->_arraystructstypes[] = 'struct';
209 $this->_arraystructs[] = array();
213 function cdata($parser, $cdata) {
214 $this->_currentTagContents .= $cdata;
216 function tag_close($parser, $tag) {
221 $value = (int) trim($this->_currentTagContents);
225 $value = (double) trim($this->_currentTagContents);
229 $value = $this->_currentTagContents;
232 case 'dateTime.iso8601':
233 $value = new IXR_Date(trim($this->_currentTagContents));
234 // $value = $iso->getTimestamp();
238 // "If no type is indicated, the type is string."
239 if (trim($this->_currentTagContents) != '') {
240 $value = (string)$this->_currentTagContents;
245 $value = (boolean) trim($this->_currentTagContents);
249 $value = base64_decode( trim( $this->_currentTagContents ) );
252 /* Deal with stacks of arrays and structs */
255 $value = array_pop($this->_arraystructs);
256 array_pop($this->_arraystructstypes);
260 array_pop($this->_currentStructName);
263 $this->_currentStructName[] = trim($this->_currentTagContents);
266 $this->methodName = trim($this->_currentTagContents);
270 if (count($this->_arraystructs) > 0) {
271 // Add value to struct or array
272 if ($this->_arraystructstypes[count($this->_arraystructstypes)-1] == 'struct') {
274 $this->_arraystructs[count($this->_arraystructs)-1][$this->_currentStructName[count($this->_currentStructName)-1]] = $value;
277 $this->_arraystructs[count($this->_arraystructs)-1][] = $value;
280 // Just add as a paramater
281 $this->params[] = $value;
284 $this->_currentTagContents = '';
296 var $callbacks = array();
299 function IXR_Server($callbacks = false, $data = false) {
300 $this->setCapabilities();
302 $this->callbacks = $callbacks;
304 $this->setCallbacks();
307 function serve($data = false) {
309 global $HTTP_RAW_POST_DATA;
310 if (!$HTTP_RAW_POST_DATA) {
311 header( 'Content-Type: text/plain' );
312 die('XML-RPC server accepts POST requests only.');
314 $data = &$HTTP_RAW_POST_DATA;
316 $this->message = new IXR_Message($data);
317 if (!$this->message->parse()) {
318 $this->error(-32700, 'parse error. not well formed');
320 if ($this->message->messageType != 'methodCall') {
321 $this->error(-32600, 'server error. invalid xml-rpc. not conforming to spec. Request must be a methodCall');
323 $result = $this->call($this->message->methodName, $this->message->params);
324 // Is the result an error?
325 if (is_a($result, 'IXR_Error')) {
326 $this->error($result);
329 $r = new IXR_Value($result);
330 $resultxml = $r->getXml();
347 function call($methodname, $args) {
348 if (!$this->hasMethod($methodname)) {
349 return new IXR_Error(-32601, 'server error. requested method '.
350 $methodname.' does not exist.');
352 $method = $this->callbacks[$methodname];
353 // Perform the callback and send the response
354 if (count($args) == 1) {
355 // If only one paramater just send that instead of the whole array
358 // Are we dealing with a function or a method?
359 if (substr($method, 0, 5) == 'this:') {
360 // It's a class method - check it exists
361 $method = substr($method, 5);
362 if (!method_exists($this, $method)) {
363 return new IXR_Error(-32601, 'server error. requested class method "'.
364 $method.'" does not exist.');
367 $result = $this->$method($args);
369 // It's a function - does it exist?
370 if (is_array($method)) {
371 if (!method_exists($method[0], $method[1])) {
372 return new IXR_Error(-32601, 'server error. requested object method "'.
373 $method[1].'" does not exist.');
375 } else if (!function_exists($method)) {
376 return new IXR_Error(-32601, 'server error. requested function "'.
377 $method.'" does not exist.');
380 $result = call_user_func($method, $args);
385 function error($error, $message = false) {
386 // Accepts either an error object or an error code and message
387 if ($message && !is_object($error)) {
388 $error = new IXR_Error($error, $message);
390 $this->output($error->getXml());
392 function output($xml) {
393 $xml = '<?xml version="1.0"?>'."\n".$xml;
394 $length = strlen($xml);
395 header('Connection: close');
396 header('Content-Length: '.$length);
397 header('Content-Type: text/xml');
398 header('Date: '.date('r'));
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($args) {
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($args) {
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);
469 function IXR_Request($method, $args) {
470 $this->method = $method;
473 <?xml version="1.0"?>
475 <methodName>{$this->method}</methodName>
479 foreach ($this->args as $arg) {
480 $this->xml .= '<param><value>';
481 $v = new IXR_Value($arg);
482 $this->xml .= $v->getXml();
483 $this->xml .= "</value></param>\n";
485 $this->xml .= '</params></methodCall>';
487 function getLength() {
488 return strlen($this->xml);
508 var $message = false;
511 // Storage place for an error message
513 function IXR_Client($server, $path = false, $port = 80, $timeout = false) {
515 // Assume we have been given a URL instead
516 $bits = parse_url($server);
517 $this->server = $bits['host'];
518 $this->port = isset($bits['port']) ? $bits['port'] : 80;
519 $this->path = isset($bits['path']) ? $bits['path'] : '/';
520 // Make absolutely sure we have a path
525 $this->server = $server;
529 $this->useragent = 'The Incutio XML-RPC PHP Library';
530 $this->timeout = $timeout;
533 $args = func_get_args();
534 $method = array_shift($args);
535 $request = new IXR_Request($method, $args);
536 $length = $request->getLength();
537 $xml = $request->getXml();
539 $request = "POST {$this->path} HTTP/1.0$r";
541 $this->headers['Host'] = $this->server;
542 $this->headers['Content-Type'] = 'text/xml';
543 $this->headers['User-Agent'] = $this->useragent;
544 $this->headers['Content-Length']= $length;
546 foreach( $this->headers as $header => $value ) {
547 $request .= "{$header}: {$value}{$r}";
552 // Now send the request
554 echo '<pre class="ixr_request">'.htmlspecialchars($request)."\n</pre>\n\n";
556 if ($this->timeout) {
557 $fp = @fsockopen($this->server, $this->port, $errno, $errstr, $this->timeout);
559 $fp = @fsockopen($this->server, $this->port, $errno, $errstr);
562 $this->error = new IXR_Error(-32300, "transport error - could not open socket: $errno $errstr");
565 fputs($fp, $request);
567 $debug_contents = '';
568 $gotFirstLine = false;
569 $gettingHeaders = true;
571 $line = fgets($fp, 4096);
572 if (!$gotFirstLine) {
573 // Check line for '200'
574 if (strstr($line, '200') === false) {
575 $this->error = new IXR_Error(-32301, 'transport error - HTTP status code was not 200');
578 $gotFirstLine = true;
580 if (trim($line) == '') {
581 $gettingHeaders = false;
583 if (!$gettingHeaders) {
584 $contents .= trim($line);
587 $debug_contents .= $line;
591 echo '<pre class="ixr_response">'.htmlspecialchars($debug_contents)."\n</pre>\n\n";
593 // Now parse what we've got back
594 $this->message = new IXR_Message($contents);
595 if (!$this->message->parse()) {
597 $this->error = new IXR_Error(-32700, 'parse error. not well formed');
600 // Is the message a fault?
601 if ($this->message->messageType == 'fault') {
602 $this->error = new IXR_Error($this->message->faultCode, $this->message->faultString);
605 // Message must be OK
608 function getResponse() {
609 // methodResponses can only have one param - return that
610 return $this->message->params[0];
613 return (is_object($this->error));
615 function getErrorCode() {
616 return $this->error->code;
618 function getErrorMessage() {
619 return $this->error->message;
632 function IXR_Error($code, $message) {
634 // WP adds htmlspecialchars(). See #5666
635 $this->message = htmlspecialchars($message);
644 <name>faultCode</name>
645 <value><int>{$this->code}</int></value>
648 <name>faultString</name>
649 <value><string>{$this->message}</string></value>
675 function IXR_Date($time) {
676 // $time can be a PHP timestamp or an ISO one
677 if (is_numeric($time)) {
678 $this->parseTimestamp($time);
680 $this->parseIso($time);
683 function parseTimestamp($timestamp) {
684 $this->year = date('Y', $timestamp);
685 $this->month = date('m', $timestamp);
686 $this->day = date('d', $timestamp);
687 $this->hour = date('H', $timestamp);
688 $this->minute = date('i', $timestamp);
689 $this->second = date('s', $timestamp);
690 // WP adds timezone. See #2036
691 $this->timezone = '';
693 function parseIso($iso) {
694 $this->year = substr($iso, 0, 4);
695 $this->month = substr($iso, 4, 2);
696 $this->day = substr($iso, 6, 2);
697 $this->hour = substr($iso, 9, 2);
698 $this->minute = substr($iso, 12, 2);
699 $this->second = substr($iso, 15, 2);
700 // WP adds timezone. See #2036
701 $this->timezone = substr($iso, 17);
704 // WP adds timezone. See #2036
705 return $this->year.$this->month.$this->day.'T'.$this->hour.':'.$this->minute.':'.$this->second.$this->timezone;
708 return '<dateTime.iso8601>'.$this->getIso().'</dateTime.iso8601>';
710 function getTimestamp() {
711 return mktime($this->hour, $this->minute, $this->second, $this->month, $this->day, $this->year);
723 function IXR_Base64($data) {
727 return '<base64>'.base64_encode($this->data).'</base64>';
732 * IXR_IntrospectionServer
737 class IXR_IntrospectionServer extends IXR_Server {
740 function IXR_IntrospectionServer() {
741 $this->setCallbacks();
742 $this->setCapabilities();
743 $this->capabilities['introspection'] = array(
744 'specUrl' => 'http://xmlrpc.usefulinc.com/doc/reserved.html',
748 'system.methodSignature',
749 'this:methodSignature',
750 array('array', 'string'),
751 'Returns an array describing the return type and required parameters of a method'
754 'system.getCapabilities',
755 'this:getCapabilities',
757 'Returns a struct describing the XML-RPC specifications supported by this server'
760 'system.listMethods',
763 'Returns an array of available methods on this server'
768 array('string', 'string'),
769 'Returns a documentation string for the specified method'
772 function addCallback($method, $callback, $args, $help) {
773 $this->callbacks[$method] = $callback;
774 $this->signatures[$method] = $args;
775 $this->help[$method] = $help;
777 function call($methodname, $args) {
778 // Make sure it's in an array
779 if ($args && !is_array($args)) {
780 $args = array($args);
782 // Over-rides default call method, adds signature check
783 if (!$this->hasMethod($methodname)) {
784 return new IXR_Error(-32601, 'server error. requested method "'.$this->message->methodName.'" not specified.');
786 $method = $this->callbacks[$methodname];
787 $signature = $this->signatures[$methodname];
788 $returnType = array_shift($signature);
789 // Check the number of arguments
790 if (count($args) != count($signature)) {
791 return new IXR_Error(-32602, 'server error. wrong number of method parameters');
793 // Check the argument types
796 for ($i = 0, $j = count($args); $i < $j; $i++) {
797 $arg = array_shift($args);
798 $type = array_shift($signature);
802 if (is_array($arg) || !is_int($arg)) {
808 if (!is_string($arg)) {
813 if ($arg !== false && $arg !== true) {
819 if (!is_float($arg)) {
824 case 'dateTime.iso8601':
825 if (!is_a($arg, 'IXR_Date')) {
831 return new IXR_Error(-32602, 'server error. invalid method parameters');
834 // It passed the test - run the "real" method call
835 return parent::call($methodname, $argsbackup);
837 function methodSignature($method) {
838 if (!$this->hasMethod($method)) {
839 return new IXR_Error(-32601, 'server error. requested method "'.$method.'" not specified.');
841 // We should be returning an array of types
842 $types = $this->signatures[$method];
844 foreach ($types as $type) {
847 $return[] = 'string';
856 case 'dateTime.iso8601':
857 $return[] = new IXR_Date(time());
863 $return[] = new IXR_Base64('base64');
866 $return[] = array('array');
869 $return[] = array('struct' => 'struct');
875 function methodHelp($method) {
876 return $this->help[$method];
881 * IXR_ClientMulticall
886 class IXR_ClientMulticall extends IXR_Client {
887 var $calls = array();
888 function IXR_ClientMulticall($server, $path = false, $port = 80) {
889 parent::IXR_Client($server, $path, $port);
890 $this->useragent = 'The Incutio XML-RPC PHP Library (multicall client)';
893 $args = func_get_args();
894 $methodName = array_shift($args);
896 'methodName' => $methodName,
899 $this->calls[] = $struct;
902 // Prepare multicall, then call the parent::query() method
903 return parent::query('system.multicall', $this->calls);