3 IXR - The Inutio XML-RPC Library - (c) Incutio Ltd 2002-2005
4 Version 1.7 (beta) - Simon Willison, 23rd May 2005
5 Site: http://scripts.incutio.com/xmlrpc/
6 Manual: http://scripts.incutio.com/xmlrpc/manual.php
7 Made available under the BSD License: http://www.opensource.org/licenses/bsd-license.php
13 function IXR_Value ($data, $type = false) {
16 $type = $this->calculateType();
19 if ($type == 'struct') {
20 /* Turn all the values in the array in to new IXR_Value objects */
21 foreach ($this->data
as $key => $value) {
22 $this->data
[$key] = new IXR_Value($value);
25 if ($type == 'array') {
26 for ($i = 0, $j = count($this->data
); $i < $j; $i++
) {
27 $this->data
[$i] = new IXR_Value($this->data
[$i]);
31 function calculateType() {
32 if ($this->data
=== true ||
$this->data
=== false) {
35 if (is_integer($this->data
)) {
38 if (is_double($this->data
)) {
41 // Deal with IXR object types base64 and date
42 if (is_object($this->data
) && is_a($this->data
, 'IXR_Date')) {
45 if (is_object($this->data
) && is_a($this->data
, 'IXR_Base64')) {
48 // If it is a normal PHP object convert it in to a struct
49 if (is_object($this->data
)) {
51 $this->data
= get_object_vars($this->data
);
54 if (!is_array($this->data
)) {
57 /* We have an array - is it an array or a struct ? */
58 if ($this->isStruct($this->data
)) {
65 /* Return XML for this value */
66 switch ($this->type
) {
68 return '<boolean>'.(($this->data
) ?
'1' : '0').'</boolean>';
71 return '<int>'.$this->data
.'</int>';
74 return '<double>'.$this->data
.'</double>';
77 return '<string>'.htmlspecialchars($this->data
).'</string>';
80 $return = '<array><data>'."\n";
81 foreach ($this->data
as $item) {
82 $return .= ' <value>'.$item->getXml()."</value>\n";
84 $return .= '</data></array>';
88 $return = '<struct>'."\n";
89 foreach ($this->data
as $name => $value) {
90 $name = htmlspecialchars($name);
91 $return .= " <member><name>$name</name><value>";
92 $return .= $value->getXml()."</value></member>\n";
94 $return .= '</struct>';
99 return $this->data
->getXml();
104 function isStruct($array) {
105 /* Nasty function to check if an array is a struct or not */
107 foreach ($array as $key => $value) {
108 if ((string)$key != (string)$expected) {
120 var $messageType; // methodCall / methodResponse / fault
125 // Current variable stacks
126 var $_arraystructs = array(); // The stack used to keep track of the current array/struct
127 var $_arraystructstypes = array(); // Stack keeping track of if things are structs or array
128 var $_currentStructName = array(); // A stack as well
132 var $_currentTagContents;
135 function IXR_Message ($message) {
136 $this->message
= $message;
139 // first remove the XML declaration
140 $this->message
= preg_replace('/<\?xml(.*)?\?'.'>/', '', $this->message
);
141 if (trim($this->message
) == '') {
144 $this->_parser
= xml_parser_create();
145 // Set XML parser to take the case of tags in to account
146 xml_parser_set_option($this->_parser
, XML_OPTION_CASE_FOLDING
, false);
147 // Set XML parser callback functions
148 xml_set_object($this->_parser
, $this);
149 xml_set_element_handler($this->_parser
, 'tag_open', 'tag_close');
150 xml_set_character_data_handler($this->_parser
, 'cdata');
151 if (!xml_parse($this->_parser
, $this->message
)) {
152 /* die(sprintf('XML error: %s at line %d',
153 xml_error_string(xml_get_error_code($this->_parser)),
154 xml_get_current_line_number($this->_parser))); */
157 xml_parser_free($this->_parser
);
158 // Grab the error messages, if any
159 if ($this->messageType
== 'fault') {
160 $this->faultCode
= $this->params
[0]['faultCode'];
161 $this->faultString
= $this->params
[0]['faultString'];
165 function tag_open($parser, $tag, $attr) {
166 $this->_currentTagContents
= '';
167 $this->currentTag
= $tag;
170 case 'methodResponse':
172 $this->messageType
= $tag;
174 /* Deal with stacks of arrays and structs */
175 case 'data': // data is to all intents and puposes more interesting than array
176 $this->_arraystructstypes
[] = 'array';
177 $this->_arraystructs
[] = array();
180 $this->_arraystructstypes
[] = 'struct';
181 $this->_arraystructs
[] = array();
185 function cdata($parser, $cdata) {
186 $this->_currentTagContents
.= $cdata;
188 function tag_close($parser, $tag) {
193 $value = (int) trim($this->_currentTagContents
);
197 $value = (double) trim($this->_currentTagContents
);
201 $value = $this->_currentTagContents
;
204 case 'dateTime.iso8601':
205 $value = new IXR_Date(trim($this->_currentTagContents
));
206 // $value = $iso->getTimestamp();
210 // "If no type is indicated, the type is string."
211 if (trim($this->_currentTagContents
) != '') {
212 $value = (string)$this->_currentTagContents
;
217 $value = (boolean
) trim($this->_currentTagContents
);
221 $value = base64_decode( trim( $this->_currentTagContents
) );
224 /* Deal with stacks of arrays and structs */
227 $value = array_pop($this->_arraystructs
);
228 array_pop($this->_arraystructstypes
);
232 array_pop($this->_currentStructName
);
235 $this->_currentStructName
[] = trim($this->_currentTagContents
);
238 $this->methodName
= trim($this->_currentTagContents
);
242 if (count($this->_arraystructs
) > 0) {
243 // Add value to struct or array
244 if ($this->_arraystructstypes
[count($this->_arraystructstypes
)-1] == 'struct') {
246 $this->_arraystructs
[count($this->_arraystructs
)-1][$this->_currentStructName
[count($this->_currentStructName
)-1]] = $value;
249 $this->_arraystructs
[count($this->_arraystructs
)-1][] = $value;
252 // Just add as a paramater
253 $this->params
[] = $value;
256 $this->_currentTagContents
= '';
263 var $callbacks = array();
266 function IXR_Server($callbacks = false, $data = false) {
267 $this->setCapabilities();
269 $this->callbacks
= $callbacks;
271 $this->setCallbacks();
274 function serve($data = false) {
276 global $HTTP_RAW_POST_DATA;
277 if (!$HTTP_RAW_POST_DATA) {
278 die('XML-RPC server accepts POST requests only.');
280 $data = $HTTP_RAW_POST_DATA;
282 $this->message
= new IXR_Message($data);
283 if (!$this->message
->parse()) {
284 $this->error(-32700, 'parse error. not well formed');
286 if ($this->message
->messageType
!= 'methodCall') {
287 $this->error(-32600, 'server error. invalid xml-rpc. not conforming to spec. Request must be a methodCall');
289 $result = $this->call($this->message
->methodName
, $this->message
->params
);
290 // Is the result an error?
291 if (is_a($result, 'IXR_Error')) {
292 $this->error($result);
295 $r = new IXR_Value($result);
296 $resultxml = $r->getXml();
313 function call($methodname, $args) {
314 if (!$this->hasMethod($methodname)) {
315 return new IXR_Error(-32601, 'server error. requested method '.$methodname.' does not exist.');
317 $method = $this->callbacks
[$methodname];
318 // Perform the callback and send the response
319 if (count($args) == 1) {
320 // If only one paramater just send that instead of the whole array
323 // Are we dealing with a function or a method?
324 if (substr($method, 0, 5) == 'this:') {
325 // It's a class method - check it exists
326 $method = substr($method, 5);
327 if (!method_exists($this, $method)) {
328 return new IXR_Error(-32601, 'server error. requested class method "'.$method.'" does not exist.');
331 $result = $this->$method($args);
333 // It's a function - does it exist?
334 if (is_array($method)) {
335 if (!method_exists($method[0], $method[1])) {
336 return new IXR_Error(-32601, 'server error. requested object method "'.$method[1].'" does not exist.');
338 } else if (!function_exists($method)) {
339 return new IXR_Error(-32601, 'server error. requested function "'.$method.'" does not exist.');
342 $result = call_user_func($method, $args);
347 function error($error, $message = false) {
348 // Accepts either an error object or an error code and message
349 if ($message && !is_object($error)) {
350 $error = new IXR_Error($error, $message);
352 $this->output($error->getXml());
354 function output($xml) {
355 $xml = '<?xml version="1.0"?>'."\n".$xml;
356 $length = strlen($xml);
357 header('Connection: close');
358 header('Content-Length: '.$length);
359 header('Content-Type: text/xml');
360 header('Date: '.date('r'));
364 function hasMethod($method) {
365 return in_array($method, array_keys($this->callbacks
));
367 function setCapabilities() {
368 // Initialises capabilities array
369 $this->capabilities
= array(
371 'specUrl' => 'http://www.xmlrpc.com/spec',
374 'faults_interop' => array(
375 'specUrl' => 'http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php',
376 'specVersion' => 20010516
378 'system.multicall' => array(
379 'specUrl' => 'http://www.xmlrpc.com/discuss/msgReader$1208',
384 function getCapabilities($args) {
385 return $this->capabilities
;
387 function setCallbacks() {
388 $this->callbacks
['system.getCapabilities'] = 'this:getCapabilities';
389 $this->callbacks
['system.listMethods'] = 'this:listMethods';
390 $this->callbacks
['system.multicall'] = 'this:multiCall';
392 function listMethods($args) {
393 // Returns a list of methods - uses array_reverse to ensure user defined
394 // methods are listed before server defined methods
395 return array_reverse(array_keys($this->callbacks
));
397 function multiCall($methodcalls) {
398 // See http://www.xmlrpc.com/discuss/msgReader$1208
400 foreach ($methodcalls as $call) {
401 $method = $call['methodName'];
402 $params = $call['params'];
403 if ($method == 'system.multicall') {
404 $result = new IXR_Error(-32600, 'Recursive calls to system.multicall are forbidden');
406 $result = $this->call($method, $params);
408 if (is_a($result, 'IXR_Error')) {
410 'faultCode' => $result->code
,
411 'faultString' => $result->message
414 $return[] = array($result);
425 function IXR_Request($method, $args) {
426 $this->method
= $method;
429 <?xml version="1.0"?>
431 <methodName>{$this->method}</methodName>
435 foreach ($this->args
as $arg) {
436 $this->xml
.= '<param><value>';
437 $v = new IXR_Value($arg);
438 $this->xml
.= $v->getXml();
439 $this->xml
.= "</value></param>\n";
441 $this->xml
.= '</params></methodCall>';
443 function getLength() {
444 return strlen($this->xml
);
458 var $message = false;
461 // Storage place for an error message
463 function IXR_Client($server, $path = false, $port = 80, $timeout = false) {
465 // Assume we have been given a URL instead
466 $bits = parse_url($server);
467 $this->server
= $bits['host'];
468 $this->port
= isset($bits['port']) ?
$bits['port'] : 80;
469 $this->path
= isset($bits['path']) ?
$bits['path'] : '/';
470 // Make absolutely sure we have a path
475 $this->server
= $server;
479 $this->useragent
= 'Incutio XML-RPC';
480 $this->timeout
= $timeout;
483 $args = func_get_args();
484 $method = array_shift($args);
485 $request = new IXR_Request($method, $args);
486 $length = $request->getLength();
487 $xml = $request->getXml();
489 $request = "POST {$this->path} HTTP/1.0$r";
490 $request .= "Host: {$this->server}$r";
491 $request .= "Content-Type: text/xml$r";
492 $request .= "User-Agent: {$this->useragent}$r";
493 $request .= "Content-length: {$length}$r$r";
495 // Now send the request
497 echo '<pre>'.htmlspecialchars($request)."\n</pre>\n\n";
499 if ($this->timeout
) {
500 $fp = @fsockopen
($this->server
, $this->port
, $errno, $errstr, $this->timeout
);
502 $fp = @fsockopen
($this->server
, $this->port
, $errno, $errstr);
505 $this->error
= new IXR_Error(-32300, "transport error - could not open socket: $errno $errstr");
508 fputs($fp, $request);
510 $gotFirstLine = false;
511 $gettingHeaders = true;
513 $line = fgets($fp, 4096);
514 if (!$gotFirstLine) {
515 // Check line for '200'
516 if (strstr($line, '200') === false) {
517 $this->error
= new IXR_Error(-32300, 'transport error - HTTP status code was not 200');
520 $gotFirstLine = true;
522 if (trim($line) == '') {
523 $gettingHeaders = false;
525 if (!$gettingHeaders) {
526 $contents .= trim($line)."\n";
530 echo '<pre>'.htmlspecialchars($contents)."\n</pre>\n\n";
532 // Now parse what we've got back
533 $this->message
= new IXR_Message($contents);
534 if (!$this->message
->parse()) {
536 $this->error
= new IXR_Error(-32700, 'parse error. not well formed');
539 // Is the message a fault?
540 if ($this->message
->messageType
== 'fault') {
541 $this->error
= new IXR_Error($this->message
->faultCode
, $this->message
->faultString
);
544 // Message must be OK
547 function getResponse() {
548 // methodResponses can only have one param - return that
549 return $this->message
->params
[0];
552 return (is_object($this->error
));
554 function getErrorCode() {
555 return $this->error
->code
;
557 function getErrorMessage() {
558 return $this->error
->message
;
566 function IXR_Error($code, $message) {
568 $this->message
= $message;
577 <name>faultCode</name>
578 <value><int>{$this->code}</int></value>
581 <name>faultString</name>
582 <value><string>{$this->message}</string></value>
602 function IXR_Date($time) {
603 // $time can be a PHP timestamp or an ISO one
604 if (is_numeric($time)) {
605 $this->parseTimestamp($time);
607 $this->parseIso($time);
610 function parseTimestamp($timestamp) {
611 $this->year
= date('Y', $timestamp);
612 $this->month
= date('m', $timestamp);
613 $this->day
= date('d', $timestamp);
614 $this->hour
= date('H', $timestamp);
615 $this->minute
= date('i', $timestamp);
616 $this->second
= date('s', $timestamp);
618 function parseIso($iso) {
619 $this->year
= substr($iso, 0, 4);
620 $this->month
= substr($iso, 4, 2);
621 $this->day
= substr($iso, 6, 2);
622 $this->hour
= substr($iso, 9, 2);
623 $this->minute
= substr($iso, 12, 2);
624 $this->second
= substr($iso, 15, 2);
625 $this->timezone
= substr($iso, 17);
628 return $this->year
.$this->month
.$this->day
.'T'.$this->hour
.':'.$this->minute
.':'.$this->second
.$this->timezone
;
631 return '<dateTime.iso8601>'.$this->getIso().'</dateTime.iso8601>';
633 function getTimestamp() {
634 return mktime($this->hour
, $this->minute
, $this->second
, $this->month
, $this->day
, $this->year
);
641 function IXR_Base64($data) {
645 return '<base64>'.base64_encode($this->data
).'</base64>';
650 class IXR_IntrospectionServer
extends IXR_Server
{
653 function IXR_IntrospectionServer() {
654 $this->setCallbacks();
655 $this->setCapabilities();
656 $this->capabilities
['introspection'] = array(
657 'specUrl' => 'http://xmlrpc.usefulinc.com/doc/reserved.html',
661 'system.methodSignature',
662 'this:methodSignature',
663 array('array', 'string'),
664 'Returns an array describing the return type and required parameters of a method'
667 'system.getCapabilities',
668 'this:getCapabilities',
670 'Returns a struct describing the XML-RPC specifications supported by this server'
673 'system.listMethods',
676 'Returns an array of available methods on this server'
681 array('string', 'string'),
682 'Returns a documentation string for the specified method'
685 function addCallback($method, $callback, $args, $help) {
686 $this->callbacks
[$method] = $callback;
687 $this->signatures
[$method] = $args;
688 $this->help
[$method] = $help;
690 function call($methodname, $args) {
691 // Make sure it's in an array
692 if ($args && !is_array($args)) {
693 $args = array($args);
695 // Over-rides default call method, adds signature check
696 if (!$this->hasMethod($methodname)) {
697 return new IXR_Error(-32601, 'server error. requested method "'.$this->message
->methodName
.'" not specified.');
699 $method = $this->callbacks
[$methodname];
700 $signature = $this->signatures
[$methodname];
701 $returnType = array_shift($signature);
702 // Check the number of arguments
703 if (count($args) != count($signature)) {
704 return new IXR_Error(-32602, 'server error. wrong number of method parameters');
706 // Check the argument types
709 for ($i = 0, $j = count($args); $i < $j; $i++
) {
710 $arg = array_shift($args);
711 $type = array_shift($signature);
715 if (is_array($arg) ||
!is_int($arg)) {
721 if (!is_string($arg)) {
726 if ($arg !== false && $arg !== true) {
732 if (!is_float($arg)) {
737 case 'dateTime.iso8601':
738 if (!is_a($arg, 'IXR_Date')) {
744 return new IXR_Error(-32602, 'server error. invalid method parameters');
747 // It passed the test - run the "real" method call
748 return parent
::call($methodname, $argsbackup);
750 function methodSignature($method) {
751 if (!$this->hasMethod($method)) {
752 return new IXR_Error(-32601, 'server error. requested method "'.$method.'" not specified.');
754 // We should be returning an array of types
755 $types = $this->signatures
[$method];
757 foreach ($types as $type) {
760 $return[] = 'string';
769 case 'dateTime.iso8601':
770 $return[] = new IXR_Date(time());
776 $return[] = new IXR_Base64('base64');
779 $return[] = array('array');
782 $return[] = array('struct' => 'struct');
788 function methodHelp($method) {
789 return $this->help
[$method];
794 class IXR_ClientMulticall
extends IXR_Client
{
795 var $calls = array();
796 function IXR_ClientMulticall($server, $path = false, $port = 80) {
797 parent
::IXR_Client($server, $path, $port);
798 $this->useragent
= 'The Incutio XML-RPC PHP Library (multicall client)';
801 $args = func_get_args();
802 $methodName = array_shift($args);
804 'methodName' => $methodName,
807 $this->calls
[] = $struct;
810 // Prepare multicall, then call the parent::query() method
811 return parent
::query('system.multicall', $this->calls
);