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
52
function IXR_Value($data, $type = false)
56
$type = $this->calculateType();
59
if ($type == 'struct') {
60
// Turn all the values in the array in to new IXR_Value objects
61
foreach ($this->data as $key => $value) {
62
$this->data[$key] = new IXR_Value($value);
65
if ($type == 'array') {
66
for ($i = 0, $j = count($this->data); $i < $j; $i++) {
67
$this->data[$i] = new IXR_Value($this->data[$i]);
72
function calculateType()
74
if ($this->data === true || $this->data === false) {
77
if (is_integer($this->data)) {
80
if (is_double($this->data)) {
84
// Deal with IXR object types base64 and date
85
if (is_object($this->data) && is_a($this->data, 'IXR_Date')) {
88
if (is_object($this->data) && is_a($this->data, 'IXR_Base64')) {
92
// If it is a normal PHP object convert it in to a struct
93
if (is_object($this->data)) {
94
$this->data = get_object_vars($this->data);
97
if (!is_array($this->data)) {
101
// We have an array - is it an array or a struct?
102
if ($this->isStruct($this->data)) {
111
// Return XML for this value
112
switch ($this->type) {
114
return '<boolean>'.(($this->data) ? '1' : '0').'</boolean>';
117
return '<int>'.$this->data.'</int>';
120
return '<double>'.$this->data.'</double>';
123
return '<string>'.htmlspecialchars($this->data).'</string>';
126
$return = '<array><data>'."\n";
127
foreach ($this->data as $item) {
128
$return .= ' <value>'.$item->getXml()."</value>\n";
130
$return .= '</data></array>';
134
$return = '<struct>'."\n";
135
foreach ($this->data as $name => $value) {
136
$name = htmlspecialchars($name);
137
$return .= " <member><name>$name</name><value>";
138
$return .= $value->getXml()."</value></member>\n";
140
$return .= '</struct>';
145
return $this->data->getXml();
152
* Checks whether or not the supplied array is a struct or not
154
* @param unknown_type $array
157
function isStruct($array)
160
foreach ($array as $key => $value) {
161
if ((string)$key != (string)$expected) {
180
var $messageType; // methodCall / methodResponse / fault
186
// Current variable stacks
187
var $_arraystructs = array(); // The stack used to keep track of the current array/struct
188
var $_arraystructstypes = array(); // Stack keeping track of if things are structs or array
189
var $_currentStructName = array(); // A stack as well
193
var $_currentTagContents;
197
function IXR_Message($message)
199
$this->message =& $message;
204
// first remove the XML declaration
205
// merged from WP #10698 - this method avoids the RAM usage of preg_replace on very large messages
206
$header = preg_replace( '/<\?xml.*?\?'.'>/s', '', substr( $this->message, 0, 100 ), 1 );
207
$this->message = trim( substr_replace( $this->message, $header, 0, 100 ) );
208
if ( '' == $this->message ) {
212
// Then remove the DOCTYPE
213
$header = preg_replace( '/^<!DOCTYPE[^>]*+>/i', '', substr( $this->message, 0, 200 ), 1 );
214
$this->message = trim( substr_replace( $this->message, $header, 0, 200 ) );
215
if ( '' == $this->message ) {
219
// Check that the root tag is valid
220
$root_tag = substr( $this->message, 0, strcspn( substr( $this->message, 0, 20 ), "> \t\r\n" ) );
221
if ( '<!DOCTYPE' === strtoupper( $root_tag ) ) {
224
if ( ! in_array( $root_tag, array( '<methodCall', '<methodResponse', '<fault' ) ) ) {
228
// Bail if there are too many elements to parse
229
$element_limit = 30000;
230
if ( function_exists( 'apply_filters' ) ) {
231
$element_limit = apply_filters( 'xmlrpc_element_limit', $element_limit );
233
if ( $element_limit && 2 * $element_limit < substr_count( $this->message, '<' ) ) {
237
$this->_parser = xml_parser_create();
238
// Set XML parser to take the case of tags in to account
239
xml_parser_set_option($this->_parser, XML_OPTION_CASE_FOLDING, false);
240
// Set XML parser callback functions
241
xml_set_object($this->_parser, $this);
242
xml_set_element_handler($this->_parser, 'tag_open', 'tag_close');
243
xml_set_character_data_handler($this->_parser, 'cdata');
244
$chunk_size = 262144; // 256Kb, parse in chunks to avoid the RAM usage on very large messages
247
if (strlen($this->message) <= $chunk_size) {
250
$part = substr($this->message, 0, $chunk_size);
251
$this->message = substr($this->message, $chunk_size);
252
if (!xml_parse($this->_parser, $part, $final)) {
259
xml_parser_free($this->_parser);
261
// Grab the error messages, if any
262
if ($this->messageType == 'fault') {
263
$this->faultCode = $this->params[0]['faultCode'];
264
$this->faultString = $this->params[0]['faultString'];
269
function tag_open($parser, $tag, $attr)
271
$this->_currentTagContents = '';
272
$this->currentTag = $tag;
275
case 'methodResponse':
277
$this->messageType = $tag;
279
/* Deal with stacks of arrays and structs */
280
case 'data': // data is to all intents and puposes more interesting than array
281
$this->_arraystructstypes[] = 'array';
282
$this->_arraystructs[] = array();
285
$this->_arraystructstypes[] = 'struct';
286
$this->_arraystructs[] = array();
291
function cdata($parser, $cdata)
293
$this->_currentTagContents .= $cdata;
296
function tag_close($parser, $tag)
302
$value = (int)trim($this->_currentTagContents);
306
$value = (double)trim($this->_currentTagContents);
310
$value = (string)trim($this->_currentTagContents);
313
case 'dateTime.iso8601':
314
$value = new IXR_Date(trim($this->_currentTagContents));
318
// "If no type is indicated, the type is string."
319
if (trim($this->_currentTagContents) != '') {
320
$value = (string)$this->_currentTagContents;
325
$value = (boolean)trim($this->_currentTagContents);
329
$value = base64_decode($this->_currentTagContents);
332
/* Deal with stacks of arrays and structs */
335
$value = array_pop($this->_arraystructs);
336
array_pop($this->_arraystructstypes);
340
array_pop($this->_currentStructName);
343
$this->_currentStructName[] = trim($this->_currentTagContents);
346
$this->methodName = trim($this->_currentTagContents);
351
if (count($this->_arraystructs) > 0) {
352
// Add value to struct or array
353
if ($this->_arraystructstypes[count($this->_arraystructstypes)-1] == 'struct') {
355
$this->_arraystructs[count($this->_arraystructs)-1][$this->_currentStructName[count($this->_currentStructName)-1]] = $value;
358
$this->_arraystructs[count($this->_arraystructs)-1][] = $value;
361
// Just add as a parameter
362
$this->params[] = $value;
365
$this->_currentTagContents = '';
378
var $callbacks = array();
382
function IXR_Server($callbacks = false, $data = false, $wait = false)
384
$this->setCapabilities();
386
$this->callbacks = $callbacks;
388
$this->setCallbacks();
394
function serve($data = false)
397
if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] !== 'POST') {
398
header('Content-Type: text/plain'); // merged from WP #9093
399
die('XML-RPC server accepts POST requests only.');
402
global $HTTP_RAW_POST_DATA;
403
if (empty($HTTP_RAW_POST_DATA)) {
404
// workaround for a bug in PHP 5.2.2 - http://bugs.php.net/bug.php?id=41293
405
$data = file_get_contents('php://input');
407
$data =& $HTTP_RAW_POST_DATA;
410
$this->message = new IXR_Message($data);
411
if (!$this->message->parse()) {
412
$this->error(-32700, 'parse error. not well formed');
414
if ($this->message->messageType != 'methodCall') {
415
$this->error(-32600, 'server error. invalid xml-rpc. not conforming to spec. Request must be a methodCall');
417
$result = $this->call($this->message->methodName, $this->message->params);
419
// Is the result an error?
420
if (is_a($result, 'IXR_Error')) {
421
$this->error($result);
425
$r = new IXR_Value($result);
426
$resultxml = $r->getXml();
445
function call($methodname, $args)
447
if (!$this->hasMethod($methodname)) {
448
return new IXR_Error(-32601, 'server error. requested method '.$methodname.' does not exist.');
450
$method = $this->callbacks[$methodname];
452
// Perform the callback and send the response
453
if (count($args) == 1) {
454
// If only one parameter just send that instead of the whole array
458
// Are we dealing with a function or a method?
459
if (is_string($method) && substr($method, 0, 5) == 'this:') {
460
// It's a class method - check it exists
461
$method = substr($method, 5);
462
if (!method_exists($this, $method)) {
463
return new IXR_Error(-32601, 'server error. requested class method "'.$method.'" does not exist.');
467
$result = $this->$method($args);
469
// It's a function - does it exist?
470
if (is_array($method)) {
471
if (!is_callable(array($method[0], $method[1]))) {
472
return new IXR_Error(-32601, 'server error. requested object method "'.$method[1].'" does not exist.');
474
} else if (!function_exists($method)) {
475
return new IXR_Error(-32601, 'server error. requested function "'.$method.'" does not exist.');
479
$result = call_user_func($method, $args);
484
function error($error, $message = false)
486
// Accepts either an error object or an error code and message
487
if ($message && !is_object($error)) {
488
$error = new IXR_Error($error, $message);
490
$this->output($error->getXml());
493
function output($xml)
495
$charset = function_exists('get_option') ? get_option('blog_charset') : '';
497
$xml = '<?xml version="1.0" encoding="'.$charset.'"?>'."\n".$xml;
499
$xml = '<?xml version="1.0"?>'."\n".$xml;
500
$length = strlen($xml);
501
header('Connection: close');
502
header('Content-Length: '.$length);
504
header('Content-Type: text/xml; charset='.$charset);
506
header('Content-Type: text/xml');
507
header('Date: '.date('r'));
512
function hasMethod($method)
514
return in_array($method, array_keys($this->callbacks));
517
function setCapabilities()
519
// Initialises capabilities array
520
$this->capabilities = array(
522
'specUrl' => 'http://www.xmlrpc.com/spec',
525
'faults_interop' => array(
526
'specUrl' => 'http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php',
527
'specVersion' => 20010516
529
'system.multicall' => array(
530
'specUrl' => 'http://www.xmlrpc.com/discuss/msgReader$1208',
536
function getCapabilities($args)
538
return $this->capabilities;
541
function setCallbacks()
543
$this->callbacks['system.getCapabilities'] = 'this:getCapabilities';
544
$this->callbacks['system.listMethods'] = 'this:listMethods';
545
$this->callbacks['system.multicall'] = 'this:multiCall';
548
function listMethods($args)
550
// Returns a list of methods - uses array_reverse to ensure user defined
551
// methods are listed before server defined methods
552
return array_reverse(array_keys($this->callbacks));
555
function multiCall($methodcalls)
557
// See http://www.xmlrpc.com/discuss/msgReader$1208
559
foreach ($methodcalls as $call) {
560
$method = $call['methodName'];
561
$params = $call['params'];
562
if ($method == 'system.multicall') {
563
$result = new IXR_Error(-32600, 'Recursive calls to system.multicall are forbidden');
565
$result = $this->call($method, $params);
567
if (is_a($result, 'IXR_Error')) {
569
'faultCode' => $result->code,
570
'faultString' => $result->message
573
$return[] = array($result);
592
function IXR_Request($method, $args)
594
$this->method = $method;
597
<?xml version="1.0"?>
599
<methodName>{$this->method}</methodName>
603
foreach ($this->args as $arg) {
604
$this->xml .= '<param><value>';
605
$v = new IXR_Value($arg);
606
$this->xml .= $v->getXml();
607
$this->xml .= "</value></param>\n";
609
$this->xml .= '</params></methodCall>';
614
return strlen($this->xml);
637
var $message = false;
640
var $headers = array();
642
// Storage place for an error message
645
function IXR_Client($server, $path = false, $port = 80, $timeout = 15)
648
// Assume we have been given a URL instead
649
$bits = parse_url($server);
650
$this->server = $bits['host'];
651
$this->port = isset($bits['port']) ? $bits['port'] : 80;
652
$this->path = isset($bits['path']) ? $bits['path'] : '/';
654
// Make absolutely sure we have a path
659
if ( ! empty( $bits['query'] ) ) {
660
$this->path .= '?' . $bits['query'];
663
$this->server = $server;
667
$this->useragent = 'The Incutio XML-RPC PHP Library';
668
$this->timeout = $timeout;
673
$args = func_get_args();
674
$method = array_shift($args);
675
$request = new IXR_Request($method, $args);
676
$length = $request->getLength();
677
$xml = $request->getXml();
679
$request = "POST {$this->path} HTTP/1.0$r";
681
// Merged from WP #8145 - allow custom headers
682
$this->headers['Host'] = $this->server;
683
$this->headers['Content-Type'] = 'text/xml';
684
$this->headers['User-Agent'] = $this->useragent;
685
$this->headers['Content-Length']= $length;
687
foreach( $this->headers as $header => $value ) {
688
$request .= "{$header}: {$value}{$r}";
694
// Now send the request
696
echo '<pre class="ixr_request">'.htmlspecialchars($request)."\n</pre>\n\n";
699
if ($this->timeout) {
700
$fp = @fsockopen($this->server, $this->port, $errno, $errstr, $this->timeout);
702
$fp = @fsockopen($this->server, $this->port, $errno, $errstr);
705
$this->error = new IXR_Error(-32300, 'transport error - could not open socket');
708
fputs($fp, $request);
711
$gotFirstLine = false;
712
$gettingHeaders = true;
714
$line = fgets($fp, 4096);
715
if (!$gotFirstLine) {
716
// Check line for '200'
717
if (strstr($line, '200') === false) {
718
$this->error = new IXR_Error(-32300, 'transport error - HTTP status code was not 200');
721
$gotFirstLine = true;
723
if (trim($line) == '') {
724
$gettingHeaders = false;
726
if (!$gettingHeaders) {
727
// merged from WP #12559 - remove trim
731
$debugContents .= $line;
735
echo '<pre class="ixr_response">'.htmlspecialchars($debugContents)."\n</pre>\n\n";
738
// Now parse what we've got back
739
$this->message = new IXR_Message($contents);
740
if (!$this->message->parse()) {
742
$this->error = new IXR_Error(-32700, 'parse error. not well formed');
746
// Is the message a fault?
747
if ($this->message->messageType == 'fault') {
748
$this->error = new IXR_Error($this->message->faultCode, $this->message->faultString);
752
// Message must be OK
756
function getResponse()
758
// methodResponses can only have one param - return that
759
return $this->message->params[0];
764
return (is_object($this->error));
767
function getErrorCode()
769
return $this->error->code;
772
function getErrorMessage()
774
return $this->error->message;
790
function IXR_Error($code, $message)
793
$this->message = htmlspecialchars($message);
804
<name>faultCode</name>
805
<value><int>{$this->code}</int></value>
808
<name>faultString</name>
809
<value><string>{$this->message}</string></value>
836
function IXR_Date($time)
838
// $time can be a PHP timestamp or an ISO one
839
if (is_numeric($time)) {
840
$this->parseTimestamp($time);
842
$this->parseIso($time);
846
function parseTimestamp($timestamp)
848
$this->year = date('Y', $timestamp);
849
$this->month = date('m', $timestamp);
850
$this->day = date('d', $timestamp);
851
$this->hour = date('H', $timestamp);
852
$this->minute = date('i', $timestamp);
853
$this->second = date('s', $timestamp);
854
$this->timezone = '';
857
function parseIso($iso)
859
$this->year = substr($iso, 0, 4);
860
$this->month = substr($iso, 4, 2);
861
$this->day = substr($iso, 6, 2);
862
$this->hour = substr($iso, 9, 2);
863
$this->minute = substr($iso, 12, 2);
864
$this->second = substr($iso, 15, 2);
865
$this->timezone = substr($iso, 17);
870
return $this->year.$this->month.$this->day.'T'.$this->hour.':'.$this->minute.':'.$this->second.$this->timezone;
875
return '<dateTime.iso8601>'.$this->getIso().'</dateTime.iso8601>';
878
function getTimestamp()
880
return mktime($this->hour, $this->minute, $this->second, $this->month, $this->day, $this->year);
894
function IXR_Base64($data)
901
return '<base64>'.base64_encode($this->data).'</base64>';
906
* IXR_IntrospectionServer
911
class IXR_IntrospectionServer extends IXR_Server
916
function IXR_IntrospectionServer()
918
$this->setCallbacks();
919
$this->setCapabilities();
920
$this->capabilities['introspection'] = array(
921
'specUrl' => 'http://xmlrpc.usefulinc.com/doc/reserved.html',
925
'system.methodSignature',
926
'this:methodSignature',
927
array('array', 'string'),
928
'Returns an array describing the return type and required parameters of a method'
931
'system.getCapabilities',
932
'this:getCapabilities',
934
'Returns a struct describing the XML-RPC specifications supported by this server'
937
'system.listMethods',
940
'Returns an array of available methods on this server'
945
array('string', 'string'),
946
'Returns a documentation string for the specified method'
950
function addCallback($method, $callback, $args, $help)
952
$this->callbacks[$method] = $callback;
953
$this->signatures[$method] = $args;
954
$this->help[$method] = $help;
957
function call($methodname, $args)
959
// Make sure it's in an array
960
if ($args && !is_array($args)) {
961
$args = array($args);
964
// Over-rides default call method, adds signature check
965
if (!$this->hasMethod($methodname)) {
966
return new IXR_Error(-32601, 'server error. requested method "'.$this->message->methodName.'" not specified.');
968
$method = $this->callbacks[$methodname];
969
$signature = $this->signatures[$methodname];
970
$returnType = array_shift($signature);
972
// Check the number of arguments
973
if (count($args) != count($signature)) {
974
return new IXR_Error(-32602, 'server error. wrong number of method parameters');
977
// Check the argument types
980
for ($i = 0, $j = count($args); $i < $j; $i++) {
981
$arg = array_shift($args);
982
$type = array_shift($signature);
986
if (is_array($arg) || !is_int($arg)) {
992
if (!is_string($arg)) {
997
if ($arg !== false && $arg !== true) {
1003
if (!is_float($arg)) {
1008
case 'dateTime.iso8601':
1009
if (!is_a($arg, 'IXR_Date')) {
1015
return new IXR_Error(-32602, 'server error. invalid method parameters');
1018
// It passed the test - run the "real" method call
1019
return parent::call($methodname, $argsbackup);
1022
function methodSignature($method)
1024
if (!$this->hasMethod($method)) {
1025
return new IXR_Error(-32601, 'server error. requested method "'.$method.'" not specified.');
1027
// We should be returning an array of types
1028
$types = $this->signatures[$method];
1030
foreach ($types as $type) {
1033
$return[] = 'string';
1042
case 'dateTime.iso8601':
1043
$return[] = new IXR_Date(time());
1049
$return[] = new IXR_Base64('base64');
1052
$return[] = array('array');
1055
$return[] = array('struct' => 'struct');
1062
function methodHelp($method)
1064
return $this->help[$method];
1069
* IXR_ClientMulticall
1074
class IXR_ClientMulticall extends IXR_Client
1076
var $calls = array();
1078
function IXR_ClientMulticall($server, $path = false, $port = 80)
1080
parent::IXR_Client($server, $path, $port);
1081
$this->useragent = 'The Incutio XML-RPC PHP Library (multicall client)';
1086
$args = func_get_args();
1087
$methodName = array_shift($args);
1089
'methodName' => $methodName,
1092
$this->calls[] = $struct;
1097
// Prepare multicall, then call the parent::query() method
1098
return parent::query('system.multicall', $this->calls);