]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/class-IXR.php
WordPress 4.3.1
[autoinstalls/wordpress.git] / wp-includes / class-IXR.php
1 <?php
2 /**
3  * IXR - The Incutio XML-RPC Library
4  *
5  * Copyright (c) 2010, Incutio Ltd.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions are met:
10  *
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.
19  *
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.
31  *
32  * @package IXR
33  * @since 1.5.0
34  *
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
40  */
41
42 /**
43  * IXR_Value
44  *
45  * @package IXR
46  * @since 1.5.0
47  */
48 class IXR_Value {
49     var $data;
50     var $type;
51
52         /**
53          * PHP5 constructor.
54          */
55         function __construct( $data, $type = false )
56     {
57         $this->data = $data;
58         if (!$type) {
59             $type = $this->calculateType();
60         }
61         $this->type = $type;
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);
66             }
67         }
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]);
71             }
72         }
73     }
74
75         /**
76          * PHP4 constructor.
77          */
78         public function IXR_Value( $data, $type = false ) {
79                 self::__construct( $data, $type );
80         }
81
82     function calculateType()
83     {
84         if ($this->data === true || $this->data === false) {
85             return 'boolean';
86         }
87         if (is_integer($this->data)) {
88             return 'int';
89         }
90         if (is_double($this->data)) {
91             return 'double';
92         }
93
94         // Deal with IXR object types base64 and date
95         if (is_object($this->data) && is_a($this->data, 'IXR_Date')) {
96             return 'date';
97         }
98         if (is_object($this->data) && is_a($this->data, 'IXR_Base64')) {
99             return 'base64';
100         }
101
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);
105             return 'struct';
106         }
107         if (!is_array($this->data)) {
108             return 'string';
109         }
110
111         // We have an array - is it an array or a struct?
112         if ($this->isStruct($this->data)) {
113             return 'struct';
114         } else {
115             return 'array';
116         }
117     }
118
119     function getXml()
120     {
121         // Return XML for this value
122         switch ($this->type) {
123             case 'boolean':
124                 return '<boolean>'.(($this->data) ? '1' : '0').'</boolean>';
125                 break;
126             case 'int':
127                 return '<int>'.$this->data.'</int>';
128                 break;
129             case 'double':
130                 return '<double>'.$this->data.'</double>';
131                 break;
132             case 'string':
133                 return '<string>'.htmlspecialchars($this->data).'</string>';
134                 break;
135             case 'array':
136                 $return = '<array><data>'."\n";
137                 foreach ($this->data as $item) {
138                     $return .= '  <value>'.$item->getXml()."</value>\n";
139                 }
140                 $return .= '</data></array>';
141                 return $return;
142                 break;
143             case 'struct':
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";
149                 }
150                 $return .= '</struct>';
151                 return $return;
152                 break;
153             case 'date':
154             case 'base64':
155                 return $this->data->getXml();
156                 break;
157         }
158         return false;
159     }
160
161     /**
162      * Checks whether or not the supplied array is a struct or not
163      *
164      * @param array $array
165      * @return bool
166      */
167     function isStruct($array)
168     {
169         $expected = 0;
170         foreach ($array as $key => $value) {
171             if ((string)$key != (string)$expected) {
172                 return true;
173             }
174             $expected++;
175         }
176         return false;
177     }
178 }
179
180 /**
181  * IXR_MESSAGE
182  *
183  * @package IXR
184  * @since 1.5.0
185  *
186  */
187 class IXR_Message
188 {
189     var $message;
190     var $messageType;  // methodCall / methodResponse / fault
191     var $faultCode;
192     var $faultString;
193     var $methodName;
194     var $params;
195
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
200     var $_param;
201     var $_value;
202     var $_currentTag;
203     var $_currentTagContents;
204     // The XML parser
205     var $_parser;
206
207         /**
208          * PHP5 constructor.
209          */
210     function __construct( $message )
211     {
212         $this->message =& $message;
213     }
214
215         /**
216          * PHP4 constructor.
217          */
218         public function IXR_Message( $message ) {
219                 self::__construct( $message );
220         }
221
222     function parse()
223     {
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 ) {
229             return false;
230         }
231
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 ) {
236             return false;
237         }
238
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 ) ) {
242             return false;
243         }
244         if ( ! in_array( $root_tag, array( '<methodCall', '<methodResponse', '<fault' ) ) ) {
245             return false;
246         }
247
248         // Bail if there are too many elements to parse
249         $element_limit = 30000;
250         if ( function_exists( 'apply_filters' ) ) {
251             /**
252              * Filter the number of elements to parse in an XML-RPC response.
253              *
254              * @since 4.0.0
255              *
256              * @param int $element_limit Default elements limit.
257              */
258             $element_limit = apply_filters( 'xmlrpc_element_limit', $element_limit );
259         }
260         if ( $element_limit && 2 * $element_limit < substr_count( $this->message, '<' ) ) {
261             return false;
262         }
263
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
272         $final = false;
273         do {
274             if (strlen($this->message) <= $chunk_size) {
275                 $final = true;
276             }
277             $part = substr($this->message, 0, $chunk_size);
278             $this->message = substr($this->message, $chunk_size);
279             if (!xml_parse($this->_parser, $part, $final)) {
280                 return false;
281             }
282             if ($final) {
283                 break;
284             }
285         } while (true);
286         xml_parser_free($this->_parser);
287
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'];
292         }
293         return true;
294     }
295
296     function tag_open($parser, $tag, $attr)
297     {
298         $this->_currentTagContents = '';
299         $this->currentTag = $tag;
300         switch($tag) {
301             case 'methodCall':
302             case 'methodResponse':
303             case 'fault':
304                 $this->messageType = $tag;
305                 break;
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();
310                 break;
311             case 'struct':
312                 $this->_arraystructstypes[] = 'struct';
313                 $this->_arraystructs[] = array();
314                 break;
315         }
316     }
317
318     function cdata($parser, $cdata)
319     {
320         $this->_currentTagContents .= $cdata;
321     }
322
323     function tag_close($parser, $tag)
324     {
325         $valueFlag = false;
326         switch($tag) {
327             case 'int':
328             case 'i4':
329                 $value = (int)trim($this->_currentTagContents);
330                 $valueFlag = true;
331                 break;
332             case 'double':
333                 $value = (double)trim($this->_currentTagContents);
334                 $valueFlag = true;
335                 break;
336             case 'string':
337                 $value = (string)trim($this->_currentTagContents);
338                 $valueFlag = true;
339                 break;
340             case 'dateTime.iso8601':
341                 $value = new IXR_Date(trim($this->_currentTagContents));
342                 $valueFlag = true;
343                 break;
344             case 'value':
345                 // "If no type is indicated, the type is string."
346                 if (trim($this->_currentTagContents) != '') {
347                     $value = (string)$this->_currentTagContents;
348                     $valueFlag = true;
349                 }
350                 break;
351             case 'boolean':
352                 $value = (boolean)trim($this->_currentTagContents);
353                 $valueFlag = true;
354                 break;
355             case 'base64':
356                 $value = base64_decode($this->_currentTagContents);
357                 $valueFlag = true;
358                 break;
359                 /* Deal with stacks of arrays and structs */
360             case 'data':
361             case 'struct':
362                 $value = array_pop($this->_arraystructs);
363                 array_pop($this->_arraystructstypes);
364                 $valueFlag = true;
365                 break;
366             case 'member':
367                 array_pop($this->_currentStructName);
368                 break;
369             case 'name':
370                 $this->_currentStructName[] = trim($this->_currentTagContents);
371                 break;
372             case 'methodName':
373                 $this->methodName = trim($this->_currentTagContents);
374                 break;
375         }
376
377         if ($valueFlag) {
378             if (count($this->_arraystructs) > 0) {
379                 // Add value to struct or array
380                 if ($this->_arraystructstypes[count($this->_arraystructstypes)-1] == 'struct') {
381                     // Add to struct
382                     $this->_arraystructs[count($this->_arraystructs)-1][$this->_currentStructName[count($this->_currentStructName)-1]] = $value;
383                 } else {
384                     // Add to array
385                     $this->_arraystructs[count($this->_arraystructs)-1][] = $value;
386                 }
387             } else {
388                 // Just add as a parameter
389                 $this->params[] = $value;
390             }
391         }
392         $this->_currentTagContents = '';
393     }
394 }
395
396 /**
397  * IXR_Server
398  *
399  * @package IXR
400  * @since 1.5.0
401  */
402 class IXR_Server
403 {
404     var $data;
405     var $callbacks = array();
406     var $message;
407     var $capabilities;
408
409         /**
410          * PHP5 constructor.
411          */
412     function __construct( $callbacks = false, $data = false, $wait = false )
413     {
414         $this->setCapabilities();
415         if ($callbacks) {
416             $this->callbacks = $callbacks;
417         }
418         $this->setCallbacks();
419         if (!$wait) {
420             $this->serve($data);
421         }
422     }
423
424         /**
425          * PHP4 constructor.
426          */
427         public function IXR_Server( $callbacks = false, $data = false, $wait = false ) {
428                 self::__construct( $callbacks, $data, $wait );
429         }
430
431     function serve($data = false)
432     {
433         if (!$data) {
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' );
438                 }
439                 header('Content-Type: text/plain'); // merged from WP #9093
440                 die('XML-RPC server accepts POST requests only.');
441             }
442
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');
447             } else {
448                 $data =& $HTTP_RAW_POST_DATA;
449             }
450         }
451         $this->message = new IXR_Message($data);
452         if (!$this->message->parse()) {
453             $this->error(-32700, 'parse error. not well formed');
454         }
455         if ($this->message->messageType != 'methodCall') {
456             $this->error(-32600, 'server error. invalid xml-rpc. not conforming to spec. Request must be a methodCall');
457         }
458         $result = $this->call($this->message->methodName, $this->message->params);
459
460         // Is the result an error?
461         if (is_a($result, 'IXR_Error')) {
462             $this->error($result);
463         }
464
465         // Encode the result
466         $r = new IXR_Value($result);
467         $resultxml = $r->getXml();
468
469         // Create the XML
470         $xml = <<<EOD
471 <methodResponse>
472   <params>
473     <param>
474       <value>
475       $resultxml
476       </value>
477     </param>
478   </params>
479 </methodResponse>
480
481 EOD;
482       // Send it
483       $this->output($xml);
484     }
485
486     function call($methodname, $args)
487     {
488         if (!$this->hasMethod($methodname)) {
489             return new IXR_Error(-32601, 'server error. requested method '.$methodname.' does not exist.');
490         }
491         $method = $this->callbacks[$methodname];
492
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
496             $args = $args[0];
497         }
498
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.');
505             }
506
507             //Call the method
508             $result = $this->$method($args);
509         } else {
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.');
514                 }
515             } else if (!function_exists($method)) {
516                 return new IXR_Error(-32601, 'server error. requested function "'.$method.'" does not exist.');
517             }
518
519             // Call the function
520             $result = call_user_func($method, $args);
521         }
522         return $result;
523     }
524
525     function error($error, $message = false)
526     {
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);
530         }
531         $this->output($error->getXml());
532     }
533
534     function output($xml)
535     {
536         $charset = function_exists('get_option') ? get_option('blog_charset') : '';
537         if ($charset)
538             $xml = '<?xml version="1.0" encoding="'.$charset.'"?>'."\n".$xml;
539         else
540             $xml = '<?xml version="1.0"?>'."\n".$xml;
541         $length = strlen($xml);
542         header('Connection: close');
543         header('Content-Length: '.$length);
544         if ($charset)
545             header('Content-Type: text/xml; charset='.$charset);
546         else
547             header('Content-Type: text/xml');
548         header('Date: '.date('r'));
549         echo $xml;
550         exit;
551     }
552
553     function hasMethod($method)
554     {
555         return in_array($method, array_keys($this->callbacks));
556     }
557
558     function setCapabilities()
559     {
560         // Initialises capabilities array
561         $this->capabilities = array(
562             'xmlrpc' => array(
563                 'specUrl' => 'http://www.xmlrpc.com/spec',
564                 'specVersion' => 1
565         ),
566             'faults_interop' => array(
567                 'specUrl' => 'http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php',
568                 'specVersion' => 20010516
569         ),
570             'system.multicall' => array(
571                 'specUrl' => 'http://www.xmlrpc.com/discuss/msgReader$1208',
572                 'specVersion' => 1
573         ),
574         );
575     }
576
577     function getCapabilities($args)
578     {
579         return $this->capabilities;
580     }
581
582     function setCallbacks()
583     {
584         $this->callbacks['system.getCapabilities'] = 'this:getCapabilities';
585         $this->callbacks['system.listMethods'] = 'this:listMethods';
586         $this->callbacks['system.multicall'] = 'this:multiCall';
587     }
588
589     function listMethods($args)
590     {
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));
594     }
595
596     function multiCall($methodcalls)
597     {
598         // See http://www.xmlrpc.com/discuss/msgReader$1208
599         $return = array();
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');
605             } else {
606                 $result = $this->call($method, $params);
607             }
608             if (is_a($result, 'IXR_Error')) {
609                 $return[] = array(
610                     'faultCode' => $result->code,
611                     'faultString' => $result->message
612                 );
613             } else {
614                 $return[] = array($result);
615             }
616         }
617         return $return;
618     }
619 }
620
621 /**
622  * IXR_Request
623  *
624  * @package IXR
625  * @since 1.5.0
626  */
627 class IXR_Request
628 {
629     var $method;
630     var $args;
631     var $xml;
632
633         /**
634          * PHP5 constructor.
635          */
636     function __construct($method, $args)
637     {
638         $this->method = $method;
639         $this->args = $args;
640         $this->xml = <<<EOD
641 <?xml version="1.0"?>
642 <methodCall>
643 <methodName>{$this->method}</methodName>
644 <params>
645
646 EOD;
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";
652         }
653         $this->xml .= '</params></methodCall>';
654     }
655
656         /**
657          * PHP4 constructor.
658          */
659         public function IXR_Request( $method, $args ) {
660                 self::__construct( $method, $args );
661         }
662
663     function getLength()
664     {
665         return strlen($this->xml);
666     }
667
668     function getXml()
669     {
670         return $this->xml;
671     }
672 }
673
674 /**
675  * IXR_Client
676  *
677  * @package IXR
678  * @since 1.5.0
679  *
680  */
681 class IXR_Client
682 {
683     var $server;
684     var $port;
685     var $path;
686     var $useragent;
687     var $response;
688     var $message = false;
689     var $debug = false;
690     var $timeout;
691     var $headers = array();
692
693     // Storage place for an error message
694     var $error = false;
695
696         /**
697          * PHP5 constructor.
698          */
699     function __construct( $server, $path = false, $port = 80, $timeout = 15 )
700     {
701         if (!$path) {
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'] : '/';
707
708             // Make absolutely sure we have a path
709             if (!$this->path) {
710                 $this->path = '/';
711             }
712
713             if ( ! empty( $bits['query'] ) ) {
714                 $this->path .= '?' . $bits['query'];
715             }
716         } else {
717             $this->server = $server;
718             $this->path = $path;
719             $this->port = $port;
720         }
721         $this->useragent = 'The Incutio XML-RPC PHP Library';
722         $this->timeout = $timeout;
723     }
724
725         /**
726          * PHP4 constructor.
727          */
728         public function IXR_Client( $server, $path = false, $port = 80, $timeout = 15 ) {
729                 self::__construct( $server, $path, $port, $timeout );
730         }
731
732     function query()
733     {
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();
739         $r = "\r\n";
740         $request  = "POST {$this->path} HTTP/1.0$r";
741
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;
747
748         foreach( $this->headers as $header => $value ) {
749             $request .= "{$header}: {$value}{$r}";
750         }
751         $request .= $r;
752
753         $request .= $xml;
754
755         // Now send the request
756         if ($this->debug) {
757             echo '<pre class="ixr_request">'.htmlspecialchars($request)."\n</pre>\n\n";
758         }
759
760         if ($this->timeout) {
761             $fp = @fsockopen($this->server, $this->port, $errno, $errstr, $this->timeout);
762         } else {
763             $fp = @fsockopen($this->server, $this->port, $errno, $errstr);
764         }
765         if (!$fp) {
766             $this->error = new IXR_Error(-32300, 'transport error - could not open socket');
767             return false;
768         }
769         fputs($fp, $request);
770         $contents = '';
771         $debugContents = '';
772         $gotFirstLine = false;
773         $gettingHeaders = true;
774         while (!feof($fp)) {
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');
780                     return false;
781                 }
782                 $gotFirstLine = true;
783             }
784             if (trim($line) == '') {
785                 $gettingHeaders = false;
786             }
787             if (!$gettingHeaders) {
788                 // merged from WP #12559 - remove trim
789                 $contents .= $line;
790             }
791             if ($this->debug) {
792                 $debugContents .= $line;
793             }
794         }
795         if ($this->debug) {
796             echo '<pre class="ixr_response">'.htmlspecialchars($debugContents)."\n</pre>\n\n";
797         }
798
799         // Now parse what we've got back
800         $this->message = new IXR_Message($contents);
801         if (!$this->message->parse()) {
802             // XML error
803             $this->error = new IXR_Error(-32700, 'parse error. not well formed');
804             return false;
805         }
806
807         // Is the message a fault?
808         if ($this->message->messageType == 'fault') {
809             $this->error = new IXR_Error($this->message->faultCode, $this->message->faultString);
810             return false;
811         }
812
813         // Message must be OK
814         return true;
815     }
816
817     function getResponse()
818     {
819         // methodResponses can only have one param - return that
820         return $this->message->params[0];
821     }
822
823     function isError()
824     {
825         return (is_object($this->error));
826     }
827
828     function getErrorCode()
829     {
830         return $this->error->code;
831     }
832
833     function getErrorMessage()
834     {
835         return $this->error->message;
836     }
837 }
838
839
840 /**
841  * IXR_Error
842  *
843  * @package IXR
844  * @since 1.5.0
845  */
846 class IXR_Error
847 {
848     var $code;
849     var $message;
850
851         /**
852          * PHP5 constructor.
853          */
854     function __construct( $code, $message )
855     {
856         $this->code = $code;
857         $this->message = htmlspecialchars($message);
858     }
859
860         /**
861          * PHP4 constructor.
862          */
863         public function IXR_Error( $code, $message ) {
864                 self::__construct( $code, $message );
865         }
866
867     function getXml()
868     {
869         $xml = <<<EOD
870 <methodResponse>
871   <fault>
872     <value>
873       <struct>
874         <member>
875           <name>faultCode</name>
876           <value><int>{$this->code}</int></value>
877         </member>
878         <member>
879           <name>faultString</name>
880           <value><string>{$this->message}</string></value>
881         </member>
882       </struct>
883     </value>
884   </fault>
885 </methodResponse>
886
887 EOD;
888         return $xml;
889     }
890 }
891
892 /**
893  * IXR_Date
894  *
895  * @package IXR
896  * @since 1.5.0
897  */
898 class IXR_Date {
899     var $year;
900     var $month;
901     var $day;
902     var $hour;
903     var $minute;
904     var $second;
905     var $timezone;
906
907         /**
908          * PHP5 constructor.
909          */
910     function __construct( $time )
911     {
912         // $time can be a PHP timestamp or an ISO one
913         if (is_numeric($time)) {
914             $this->parseTimestamp($time);
915         } else {
916             $this->parseIso($time);
917         }
918     }
919
920         /**
921          * PHP4 constructor.
922          */
923         public function IXR_Date( $time ) {
924                 self::__construct( $time );
925         }
926
927     function parseTimestamp($timestamp)
928     {
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 = '';
936     }
937
938     function parseIso($iso)
939     {
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);
947     }
948
949     function getIso()
950     {
951         return $this->year.$this->month.$this->day.'T'.$this->hour.':'.$this->minute.':'.$this->second.$this->timezone;
952     }
953
954     function getXml()
955     {
956         return '<dateTime.iso8601>'.$this->getIso().'</dateTime.iso8601>';
957     }
958
959     function getTimestamp()
960     {
961         return mktime($this->hour, $this->minute, $this->second, $this->month, $this->day, $this->year);
962     }
963 }
964
965 /**
966  * IXR_Base64
967  *
968  * @package IXR
969  * @since 1.5.0
970  */
971 class IXR_Base64
972 {
973     var $data;
974
975         /**
976          * PHP5 constructor.
977          */
978     function __construct( $data )
979     {
980         $this->data = $data;
981     }
982
983         /**
984          * PHP4 constructor.
985          */
986         public function IXR_Base64( $data ) {
987                 self::__construct( $data );
988         }
989
990     function getXml()
991     {
992         return '<base64>'.base64_encode($this->data).'</base64>';
993     }
994 }
995
996 /**
997  * IXR_IntrospectionServer
998  *
999  * @package IXR
1000  * @since 1.5.0
1001  */
1002 class IXR_IntrospectionServer extends IXR_Server
1003 {
1004     var $signatures;
1005     var $help;
1006
1007         /**
1008          * PHP5 constructor.
1009          */
1010     function __construct()
1011     {
1012         $this->setCallbacks();
1013         $this->setCapabilities();
1014         $this->capabilities['introspection'] = array(
1015             'specUrl' => 'http://xmlrpc.usefulinc.com/doc/reserved.html',
1016             'specVersion' => 1
1017         );
1018         $this->addCallback(
1019             'system.methodSignature',
1020             'this:methodSignature',
1021             array('array', 'string'),
1022             'Returns an array describing the return type and required parameters of a method'
1023         );
1024         $this->addCallback(
1025             'system.getCapabilities',
1026             'this:getCapabilities',
1027             array('struct'),
1028             'Returns a struct describing the XML-RPC specifications supported by this server'
1029         );
1030         $this->addCallback(
1031             'system.listMethods',
1032             'this:listMethods',
1033             array('array'),
1034             'Returns an array of available methods on this server'
1035         );
1036         $this->addCallback(
1037             'system.methodHelp',
1038             'this:methodHelp',
1039             array('string', 'string'),
1040             'Returns a documentation string for the specified method'
1041         );
1042     }
1043
1044         /**
1045          * PHP4 constructor.
1046          */
1047         public function IXR_IntrospectionServer() {
1048                 self::__construct();
1049         }
1050
1051     function addCallback($method, $callback, $args, $help)
1052     {
1053         $this->callbacks[$method] = $callback;
1054         $this->signatures[$method] = $args;
1055         $this->help[$method] = $help;
1056     }
1057
1058     function call($methodname, $args)
1059     {
1060         // Make sure it's in an array
1061         if ($args && !is_array($args)) {
1062             $args = array($args);
1063         }
1064
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.');
1068         }
1069         $method = $this->callbacks[$methodname];
1070         $signature = $this->signatures[$methodname];
1071         $returnType = array_shift($signature);
1072
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');
1076         }
1077
1078         // Check the argument types
1079         $ok = true;
1080         $argsbackup = $args;
1081         for ($i = 0, $j = count($args); $i < $j; $i++) {
1082             $arg = array_shift($args);
1083             $type = array_shift($signature);
1084             switch ($type) {
1085                 case 'int':
1086                 case 'i4':
1087                     if (is_array($arg) || !is_int($arg)) {
1088                         $ok = false;
1089                     }
1090                     break;
1091                 case 'base64':
1092                 case 'string':
1093                     if (!is_string($arg)) {
1094                         $ok = false;
1095                     }
1096                     break;
1097                 case 'boolean':
1098                     if ($arg !== false && $arg !== true) {
1099                         $ok = false;
1100                     }
1101                     break;
1102                 case 'float':
1103                 case 'double':
1104                     if (!is_float($arg)) {
1105                         $ok = false;
1106                     }
1107                     break;
1108                 case 'date':
1109                 case 'dateTime.iso8601':
1110                     if (!is_a($arg, 'IXR_Date')) {
1111                         $ok = false;
1112                     }
1113                     break;
1114             }
1115             if (!$ok) {
1116                 return new IXR_Error(-32602, 'server error. invalid method parameters');
1117             }
1118         }
1119         // It passed the test - run the "real" method call
1120         return parent::call($methodname, $argsbackup);
1121     }
1122
1123     function methodSignature($method)
1124     {
1125         if (!$this->hasMethod($method)) {
1126             return new IXR_Error(-32601, 'server error. requested method "'.$method.'" not specified.');
1127         }
1128         // We should be returning an array of types
1129         $types = $this->signatures[$method];
1130         $return = array();
1131         foreach ($types as $type) {
1132             switch ($type) {
1133                 case 'string':
1134                     $return[] = 'string';
1135                     break;
1136                 case 'int':
1137                 case 'i4':
1138                     $return[] = 42;
1139                     break;
1140                 case 'double':
1141                     $return[] = 3.1415;
1142                     break;
1143                 case 'dateTime.iso8601':
1144                     $return[] = new IXR_Date(time());
1145                     break;
1146                 case 'boolean':
1147                     $return[] = true;
1148                     break;
1149                 case 'base64':
1150                     $return[] = new IXR_Base64('base64');
1151                     break;
1152                 case 'array':
1153                     $return[] = array('array');
1154                     break;
1155                 case 'struct':
1156                     $return[] = array('struct' => 'struct');
1157                     break;
1158             }
1159         }
1160         return $return;
1161     }
1162
1163     function methodHelp($method)
1164     {
1165         return $this->help[$method];
1166     }
1167 }
1168
1169 /**
1170  * IXR_ClientMulticall
1171  *
1172  * @package IXR
1173  * @since 1.5.0
1174  */
1175 class IXR_ClientMulticall extends IXR_Client
1176 {
1177     var $calls = array();
1178
1179         /**
1180          * PHP5 constructor.
1181          */
1182     function __construct( $server, $path = false, $port = 80 )
1183     {
1184         parent::IXR_Client($server, $path, $port);
1185         $this->useragent = 'The Incutio XML-RPC PHP Library (multicall client)';
1186     }
1187
1188         /**
1189          * PHP4 constructor.
1190          */
1191         public function IXR_ClientMulticall( $server, $path = false, $port = 80 ) {
1192                 self::__construct( $server, $path, $port );
1193         }
1194
1195     function addCall()
1196     {
1197         $args = func_get_args();
1198         $methodName = array_shift($args);
1199         $struct = array(
1200             'methodName' => $methodName,
1201             'params' => $args
1202         );
1203         $this->calls[] = $struct;
1204     }
1205
1206     function query()
1207     {
1208         // Prepare multicall, then call the parent::query() method
1209         return parent::query('system.multicall', $this->calls);
1210     }
1211 }