]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Mollom/MollomPlugin.php
XSS vulnerability when remote-subscribing
[quix0rs-gnu-social.git] / plugins / Mollom / MollomPlugin.php
1 <?php
2 /**
3  * Laconica, the distributed open-source microblogging tool
4  *
5  * Plugin to check submitted notices with Mollom
6  *
7  * PHP version 5
8  *
9  * LICENCE: This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Affero General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Affero General Public License for more details.
18  *
19  * You should have received a copy of the GNU Affero General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  * Mollom is a bayesian spam checker, wrapped into a webservice
23  * This plugin is based on the Drupal Mollom module
24  *
25  * @category  Plugin
26  * @package   Laconica
27  * @author    Brenda Wallace <brenda@cpan.org>
28  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
29  *
30  */
31
32 if (!defined('STATUSNET')) {
33     exit(1);
34 }
35
36 define('MOLLOMPLUGIN_VERSION', '0.1');
37 define('MOLLOM_API_VERSION', '1.0');
38
39 define('MOLLOM_ANALYSIS_UNKNOWN' , 0);
40 define('MOLLOM_ANALYSIS_HAM'     , 1);
41 define('MOLLOM_ANALYSIS_SPAM'    , 2);
42 define('MOLLOM_ANALYSIS_UNSURE'  , 3);
43
44 define('MOLLOM_MODE_DISABLED', 0);
45 define('MOLLOM_MODE_CAPTCHA' , 1);
46 define('MOLLOM_MODE_ANALYSIS', 2);
47
48 define('MOLLOM_FALLBACK_BLOCK' , 0);
49 define('MOLLOM_FALLBACK_ACCEPT', 1);
50
51 define('MOLLOM_ERROR'   , 1000);
52 define('MOLLOM_REFRESH' , 1100);
53 define('MOLLOM_REDIRECT', 1200);
54
55 /**
56  * Plugin to check submitted notices with Mollom
57  *
58  * Mollom is a bayesian spam filter provided by webservice.
59  *
60  * @category Plugin
61  * @package  Laconica
62  * @author   Brenda Wallace <shiny@cpan.org>
63  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
64  *
65  * @see      Event
66  */
67 class MollomPlugin extends Plugin
68 {
69     public $public_key;
70     public $private_key;
71     public $servers;
72
73     function onStartNoticeSave($notice)
74     {
75       if ( $this->public_key ) {
76         //Check spam
77         $data = array(
78             'post_body'      => $notice->content,
79             'author_name'    => $profile->nickname,
80             'author_url'     => $profile->homepage,
81             'author_id'      => $profile->id,
82             'author_ip'      => $this->getClientIp(),
83         );
84         $response = $this->mollom('mollom.checkContent', $data);
85         if ($response['spam'] == MOLLOM_ANALYSIS_SPAM) {
86           // TRANS: Client exception thrown when notice content triggers the spam filter.
87           throw new ClientException(_m('Spam Detected.'), 400);
88         }
89         if ($response['spam'] == MOLLOM_ANALYSIS_UNSURE) {
90           //if unsure, let through
91         }
92         if($response['spam'] == MOLLOM_ANALYSIS_HAM) {
93           // all good! :-)
94         }
95       }
96
97       return true;
98     }
99
100     function getClientIP() {
101         if (isset($_SERVER) && array_key_exists('REQUEST_METHOD', $_SERVER)) {
102             // Note: order matters here; use proxy-forwarded stuff first
103             foreach (array('HTTP_X_FORWARDED_FOR', 'CLIENT-IP', 'REMOTE_ADDR') as $k) {
104                 if (isset($_SERVER[$k])) {
105                     return $_SERVER[$k];
106                 }
107             }
108         }
109         return '127.0.0.1';
110     }
111
112     /**
113      * Call a remote procedure at the Mollom server.  This function will
114      * automatically add the information required to authenticate against
115      * Mollom.
116      */
117     function mollom($method, $data = array()) {
118         if (!extension_loaded('xmlrpc')) {
119             if (!dl('xmlrpc.so')) {
120                 common_log(LOG_ERR, "Can't pingback; xmlrpc extension not available.");
121             }
122         }
123
124       // Construct the server URL:
125       $public_key = $this->public_key;
126       // Retrieve the list of Mollom servers from the database:
127       $servers = $this->servers;
128
129       if ($servers == NULL) {
130         // Retrieve a list of valid Mollom servers from mollom.com:
131         $servers = $this->xmlrpc('http://xmlrpc.mollom.com/'. MOLLOM_API_VERSION, 'mollom.getServerList', $this->authentication());
132
133         // Store the list of servers in the database:
134         // TODO!    variable_set('mollom_servers', $servers);
135       }
136
137       if (is_array($servers)) {
138         // Send the request to the first server, if that fails, try the other servers in the list:
139         foreach ($servers as $server) {
140           $auth = $this->authentication();
141           $data = array_merge($data, $auth);
142           $result = $this->xmlrpc($server .'/'. MOLLOM_API_VERSION, $method, $data);
143
144           // Debug output:
145           if (isset($data['session_id'])) {
146             common_debug("called $method at server $server with session ID '". $data['session_id'] ."'");
147           }
148           else {
149             common_debug("called $method at server $server with no session ID");
150           }
151
152           if ($errno = $this->xmlrpc_errno()) {
153             common_log(LOG_ERR, sprintf('Error @errno: %s - %s - %s - <pre>%s</pre>', $this->xmlrpc_errno(), $server, $this->xmlrpc_error_msg(), $method, print_r($data, TRUE)));
154
155             if ($errno == MOLLOM_REFRESH) {
156               // Retrieve a list of valid Mollom servers from mollom.com:
157               $servers = $this->xmlrpc('http://xmlrpc.mollom.com/'. MOLLOM_API_VERSION, 'mollom.getServerList', $this->authentication());
158
159               // Store the updated list of servers in the database:
160               //tODO variable_set('mollom_servers', $servers);
161             }
162             else if ($errno == MOLLOM_ERROR) {
163               return $result;
164             }
165             else if ($errno == MOLLOM_REDIRECT) {
166               // Do nothing, we select the next client automatically.
167             }
168
169             // Reset the XMLRPC error:
170             $this->xmlrpc_error(0);  // FIXME: this is crazy.
171           }
172           else {
173             common_debug("Result = " . print_r($result, TRUE));
174             return $result;
175           }
176         }
177       }
178
179       // If none of the servers worked, activate the fallback mechanism:
180       common_debug("none of the servers worked");
181       //   _mollom_fallback();
182
183       // If everything failed, we reset the server list to force Mollom to request a new list:
184       //TODO variable_set('mollom_servers', array());
185     }
186
187     /**
188      * This function generate an array with all the information required to
189      * authenticate against Mollom. To prevent that requests are forged and
190      * that you are impersonated, each request is signed with a hash computed
191      * based on a private key and a timestamp.
192      *
193      * Both the client and the server share the secret key that is used to
194      * create the authentication hash based on a timestamp.  They both hash
195      * the timestamp with the secret key, and if the hashes match, the
196      * authenticity of the message has been validated.
197      *
198      * To avoid that someone can intercept a (hash, timestamp)-pair and
199      * use that to impersonate a client, Mollom will reject the request
200      * when the timestamp is more than 15 minutes off.
201      *
202      * Make sure your server's time is synchronized with the world clocks,
203      * and that you don't share your private key with anyone else.
204      */
205     private function authentication() {
206
207       $public_key = $this->public_key;
208       $private_key = $this->private_key;
209
210       // Generate a timestamp according to the dateTime format (http://www.w3.org/TR/xmlschema-2/#dateTime):
211       $time = gmdate("Y-m-d\TH:i:s.\\0\\0\\0O", time());
212
213       // Calculate a HMAC-SHA1 according to RFC2104 (http://www.ietf.org/rfc/rfc2104.txt):
214       $hash =  base64_encode(
215       pack("H*", sha1((str_pad($private_key, 64, chr(0x00)) ^ (str_repeat(chr(0x5c), 64))) .
216       pack("H*", sha1((str_pad($private_key, 64, chr(0x00)) ^ (str_repeat(chr(0x36), 64))) .
217       $time))))
218       );
219
220       // Store everything in an array. Elsewhere in the code, we'll add the
221       // acutal data before we pass it onto the XML-RPC library:
222       $data['public_key'] = $public_key;
223       $data['time'] = $time;
224       $data['hash'] = $hash;
225
226       return $data;
227     }
228
229     function xmlrpc($url) {
230       //require_once './includes/xmlrpc.inc';
231       $args = func_get_args();
232       return call_user_func_array(array('MollomPlugin', '_xmlrpc'), $args);
233     }
234
235     /**
236      * Recursively turn a data structure into objects with 'data' and 'type' attributes.
237      *
238      * @param $data
239      *   The data structure.
240      * @param  $type
241      *   Optional type assign to $data.
242      * @return
243      *   Object.
244      */
245     function xmlrpc_value($data, $type = FALSE) {
246       $xmlrpc_value = new stdClass();
247       $xmlrpc_value->data = $data;
248       if (!$type) {
249         $type = $this->xmlrpc_value_calculate_type($xmlrpc_value);
250       }
251       $xmlrpc_value->type = $type;
252       if ($type == 'struct') {
253         // Turn all the values in the array into new xmlrpc_values
254         foreach ($xmlrpc_value->data as $key => $value) {
255           $xmlrpc_value->data[$key] = $this->xmlrpc_value($value);
256         }
257       }
258       if ($type == 'array') {
259         for ($i = 0, $j = count($xmlrpc_value->data); $i < $j; $i++) {
260           $xmlrpc_value->data[$i] = $this->xmlrpc_value($xmlrpc_value->data[$i]);
261         }
262       }
263       return $xmlrpc_value;
264     }
265
266     /**
267      * Map PHP type to XML-RPC type.
268      *
269      * @param $xmlrpc_value
270      *   Variable whose type should be mapped.
271      * @return
272      *   XML-RPC type as string.
273      * @see
274      *   http://www.xmlrpc.com/spec#scalars
275      */
276     function xmlrpc_value_calculate_type(&$xmlrpc_value) {
277       // http://www.php.net/gettype: Never use gettype() to test for a certain type [...] Instead, use the is_* functions.
278       if (is_bool($xmlrpc_value->data)) {
279         return 'boolean';
280       }
281       if (is_double($xmlrpc_value->data)) {
282         return 'double';
283       }
284       if (is_int($xmlrpc_value->data)) {
285           return 'int';
286       }
287       if (is_array($xmlrpc_value->data)) {
288         // empty or integer-indexed arrays are 'array', string-indexed arrays 'struct'
289         return empty($xmlrpc_value->data) || range(0, count($xmlrpc_value->data) - 1) === array_keys($xmlrpc_value->data) ? 'array' : 'struct';
290       }
291       if (is_object($xmlrpc_value->data)) {
292         if ($xmlrpc_value->data->is_date) {
293           return 'date';
294         }
295         if ($xmlrpc_value->data->is_base64) {
296           return 'base64';
297         }
298         $xmlrpc_value->data = get_object_vars($xmlrpc_value->data);
299         return 'struct';
300       }
301       // default
302       return 'string';
303     }
304
305     /**
306      * Generate XML representing the given value.
307      *
308      * @param $xmlrpc_value
309      * @return
310      *   XML representation of value.
311      */
312     function xmlrpc_value_get_xml($xmlrpc_value) {
313       switch ($xmlrpc_value->type) {
314         case 'boolean':
315           return '<boolean>'. (($xmlrpc_value->data) ? '1' : '0') .'</boolean>';
316           break;
317         case 'int':
318           return '<int>'. $xmlrpc_value->data .'</int>';
319           break;
320         case 'double':
321           return '<double>'. $xmlrpc_value->data .'</double>';
322           break;
323         case 'string':
324           // Note: we don't escape apostrophes because of the many blogging clients
325           // that don't support numerical entities (and XML in general) properly.
326           return '<string>'. htmlspecialchars($xmlrpc_value->data) .'</string>';
327           break;
328         case 'array':
329           $return = '<array><data>'."\n";
330           foreach ($xmlrpc_value->data as $item) {
331             $return .= '  <value>'. $this->xmlrpc_value_get_xml($item) ."</value>\n";
332           }
333           $return .= '</data></array>';
334           return $return;
335           break;
336         case 'struct':
337           $return = '<struct>'."\n";
338           foreach ($xmlrpc_value->data as $name => $value) {
339             $return .= "  <member><name>". htmlentities($name) ."</name><value>";
340             $return .= $this->xmlrpc_value_get_xml($value) ."</value></member>\n";
341           }
342           $return .= '</struct>';
343           return $return;
344           break;
345         case 'date':
346           return $this->xmlrpc_date_get_xml($xmlrpc_value->data);
347           break;
348         case 'base64':
349           return $this->xmlrpc_base64_get_xml($xmlrpc_value->data);
350           break;
351       }
352       return FALSE;
353     }
354
355     /**
356      * Perform an HTTP request.
357      *
358      * This is a flexible and powerful HTTP client implementation. Correctly handles
359      * GET, POST, PUT or any other HTTP requests. Handles redirects.
360      *
361      * @param $url
362      *   A string containing a fully qualified URI.
363      * @param $headers
364      *   An array containing an HTTP header => value pair.
365      * @param $method
366      *   A string defining the HTTP request to use.
367      * @param $data
368      *   A string containing data to include in the request.
369      * @param $retry
370      *   An integer representing how many times to retry the request in case of a
371      *   redirect.
372      * @return
373      *   An object containing the HTTP request headers, response code, headers,
374      *   data and redirect status.
375      */
376     function http_request($url, $headers = array(), $method = 'GET', $data = NULL, $retry = 3) {
377       global $db_prefix;
378
379       $result = new stdClass();
380
381       // Parse the URL and make sure we can handle the schema.
382       $uri = parse_url($url);
383
384       if ($uri == FALSE) {
385         $result->error = 'unable to parse URL';
386         return $result;
387       }
388
389       if (!isset($uri['scheme'])) {
390         $result->error = 'missing schema';
391         return $result;
392       }
393
394       switch ($uri['scheme']) {
395         case 'http':
396           $port = isset($uri['port']) ? $uri['port'] : 80;
397           $host = $uri['host'] . ($port != 80 ? ':'. $port : '');
398           $fp = @fsockopen($uri['host'], $port, $errno, $errstr, 15);
399           break;
400         case 'https':
401           // Note: Only works for PHP 4.3 compiled with OpenSSL.
402           $port = isset($uri['port']) ? $uri['port'] : 443;
403           $host = $uri['host'] . ($port != 443 ? ':'. $port : '');
404           $fp = @fsockopen('ssl://'. $uri['host'], $port, $errno, $errstr, 20);
405           break;
406         default:
407           $result->error = 'invalid schema '. $uri['scheme'];
408           return $result;
409       }
410
411       // Make sure the socket opened properly.
412       if (!$fp) {
413         // When a network error occurs, we use a negative number so it does not
414         // clash with the HTTP status codes.
415         $result->code = -$errno;
416         $result->error = trim($errstr);
417
418         // Mark that this request failed. This will trigger a check of the web
419         // server's ability to make outgoing HTTP requests the next time that
420         // requirements checking is performed.
421         // @see system_requirements()
422         //TODO variable_set('drupal_http_request_fails', TRUE);
423
424         return $result;
425       }
426
427       // Construct the path to act on.
428       $path = isset($uri['path']) ? $uri['path'] : '/';
429       if (isset($uri['query'])) {
430         $path .= '?'. $uri['query'];
431       }
432
433       // Create HTTP request.
434       $defaults = array(
435         // RFC 2616: "non-standard ports MUST, default ports MAY be included".
436         // We don't add the port to prevent from breaking rewrite rules checking the
437         // host that do not take into account the port number.
438         'Host' => "Host: $host",
439         'User-Agent' => 'User-Agent: Drupal (+http://drupal.org/)',
440         'Content-Length' => 'Content-Length: '. strlen($data)
441       );
442
443       // If the server url has a user then attempt to use basic authentication
444       if (isset($uri['user'])) {
445         $defaults['Authorization'] = 'Authorization: Basic '. base64_encode($uri['user'] . (!empty($uri['pass']) ? ":". $uri['pass'] : ''));
446       }
447
448       // If the database prefix is being used by SimpleTest to run the tests in a copied
449       // database then set the user-agent header to the database prefix so that any
450       // calls to other Drupal pages will run the SimpleTest prefixed database. The
451       // user-agent is used to ensure that multiple testing sessions running at the
452       // same time won't interfere with each other as they would if the database
453       // prefix were stored statically in a file or database variable.
454       if (is_string($db_prefix) && preg_match("/^simpletest\d+$/", $db_prefix, $matches)) {
455         $defaults['User-Agent'] = 'User-Agent: ' . $matches[0];
456       }
457
458       foreach ($headers as $header => $value) {
459         $defaults[$header] = $header .': '. $value;
460       }
461
462       $request = $method .' '. $path ." HTTP/1.0\r\n";
463       $request .= implode("\r\n", $defaults);
464       $request .= "\r\n\r\n";
465       $request .= $data;
466
467       $result->request = $request;
468
469       fwrite($fp, $request);
470
471       // Fetch response.
472       $response = '';
473       while (!feof($fp) && $chunk = fread($fp, 1024)) {
474         $response .= $chunk;
475       }
476       fclose($fp);
477
478       // Parse response.
479       list($split, $result->data) = explode("\r\n\r\n", $response, 2);
480       $split = preg_split("/\r\n|\n|\r/", $split);
481
482       list($protocol, $code, $text) = explode(' ', trim(array_shift($split)), 3);
483       $result->headers = array();
484
485       // Parse headers.
486       while ($line = trim(array_shift($split))) {
487         list($header, $value) = explode(':', $line, 2);
488         if (isset($result->headers[$header]) && $header == 'Set-Cookie') {
489           // RFC 2109: the Set-Cookie response header comprises the token Set-
490           // Cookie:, followed by a comma-separated list of one or more cookies.
491           $result->headers[$header] .= ','. trim($value);
492         }
493         else {
494           $result->headers[$header] = trim($value);
495         }
496       }
497
498       $responses = array(
499         100 => 'Continue', 101 => 'Switching Protocols',
500         200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content',
501         300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect',
502         400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Time-out', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Large', 415 => 'Unsupported Media Type', 416 => 'Requested range not satisfiable', 417 => 'Expectation Failed',
503         500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported'
504       );
505       // RFC 2616 states that all unknown HTTP codes must be treated the same as the
506       // base code in their class.
507       if (!isset($responses[$code])) {
508         $code = floor($code / 100) * 100;
509       }
510
511       switch ($code) {
512         case 200: // OK
513         case 304: // Not modified
514           break;
515         case 301: // Moved permanently
516         case 302: // Moved temporarily
517         case 307: // Moved temporarily
518           $location = $result->headers['Location'];
519
520           if ($retry) {
521             $result = drupal_http_request($result->headers['Location'], $headers, $method, $data, --$retry);
522             $result->redirect_code = $result->code;
523           }
524           $result->redirect_url = $location;
525
526           break;
527         default:
528           $result->error = $text;
529       }
530
531       $result->code = $code;
532       return $result;
533     }
534
535     /**
536      * Construct an object representing an XML-RPC message.
537      *
538      * @param $message
539      *   String containing XML as defined at http://www.xmlrpc.com/spec
540      * @return
541      *   Object
542      */
543     function xmlrpc_message($message) {
544       $xmlrpc_message = new stdClass();
545       $xmlrpc_message->array_structs = array();   // The stack used to keep track of the current array/struct
546       $xmlrpc_message->array_structs_types = array(); // The stack used to keep track of if things are structs or array
547       $xmlrpc_message->current_struct_name = array();  // A stack as well
548       $xmlrpc_message->message = $message;
549       return $xmlrpc_message;
550     }
551
552     /**
553      * Parse an XML-RPC message. If parsing fails, the faultCode and faultString
554      * will be added to the message object.
555      *
556      * @param $xmlrpc_message
557      *   Object generated by xmlrpc_message()
558      * @return
559      *   TRUE if parsing succeeded; FALSE otherwise
560      */
561     function xmlrpc_message_parse(&$xmlrpc_message) {
562       // First remove the XML declaration
563       $xmlrpc_message->message = preg_replace('/<\?xml(.*)?\?'.'>/', '', $xmlrpc_message->message);
564       if (trim($xmlrpc_message->message) == '') {
565         return FALSE;
566       }
567       $xmlrpc_message->_parser = xml_parser_create();
568       // Set XML parser to take the case of tags into account.
569       xml_parser_set_option($xmlrpc_message->_parser, XML_OPTION_CASE_FOLDING, FALSE);
570       // Set XML parser callback functions
571       xml_set_element_handler($xmlrpc_message->_parser, array('MollomPlugin', 'xmlrpc_message_tag_open'), array('MollomPlugin', 'xmlrpc_message_tag_close'));
572       xml_set_character_data_handler($xmlrpc_message->_parser, array('MollomPlugin', 'xmlrpc_message_cdata'));
573       $this->xmlrpc_message_set($xmlrpc_message);
574       if (!xml_parse($xmlrpc_message->_parser, $xmlrpc_message->message)) {
575         return FALSE;
576       }
577       xml_parser_free($xmlrpc_message->_parser);
578       // Grab the error messages, if any
579       $xmlrpc_message = $this->xmlrpc_message_get();
580       if ($xmlrpc_message->messagetype == 'fault') {
581         $xmlrpc_message->fault_code = $xmlrpc_message->params[0]['faultCode'];
582         $xmlrpc_message->fault_string = $xmlrpc_message->params[0]['faultString'];
583       }
584       return TRUE;
585     }
586
587     /**
588      * Store a copy of the $xmlrpc_message object temporarily.
589      *
590      * @param $value
591      *   Object
592      * @return
593      *   The most recently stored $xmlrpc_message
594      */
595     function xmlrpc_message_set($value = NULL) {
596       static $xmlrpc_message;
597       if ($value) {
598         $xmlrpc_message = $value;
599       }
600       return $xmlrpc_message;
601     }
602
603     function xmlrpc_message_get() {
604       return $this->xmlrpc_message_set();
605     }
606
607     function xmlrpc_message_tag_open($parser, $tag, $attr) {
608       $xmlrpc_message = $this->xmlrpc_message_get();
609       $xmlrpc_message->current_tag_contents = '';
610       $xmlrpc_message->last_open = $tag;
611       switch ($tag) {
612         case 'methodCall':
613         case 'methodResponse':
614         case 'fault':
615           $xmlrpc_message->messagetype = $tag;
616           break;
617         // Deal with stacks of arrays and structs
618         case 'data':
619           $xmlrpc_message->array_structs_types[] = 'array';
620           $xmlrpc_message->array_structs[] = array();
621           break;
622         case 'struct':
623           $xmlrpc_message->array_structs_types[] = 'struct';
624           $xmlrpc_message->array_structs[] = array();
625           break;
626       }
627       $this->xmlrpc_message_set($xmlrpc_message);
628     }
629
630     function xmlrpc_message_cdata($parser, $cdata) {
631       $xmlrpc_message = $this->xmlrpc_message_get();
632       $xmlrpc_message->current_tag_contents .= $cdata;
633       $this->xmlrpc_message_set($xmlrpc_message);
634     }
635
636     function xmlrpc_message_tag_close($parser, $tag) {
637       $xmlrpc_message = $this->xmlrpc_message_get();
638       $value_flag = FALSE;
639       switch ($tag) {
640         case 'int':
641         case 'i4':
642           $value = (int)trim($xmlrpc_message->current_tag_contents);
643           $value_flag = TRUE;
644           break;
645         case 'double':
646           $value = (double)trim($xmlrpc_message->current_tag_contents);
647           $value_flag = TRUE;
648           break;
649         case 'string':
650           $value = $xmlrpc_message->current_tag_contents;
651           $value_flag = TRUE;
652           break;
653         case 'dateTime.iso8601':
654           $value = xmlrpc_date(trim($xmlrpc_message->current_tag_contents));
655           // $value = $iso->getTimestamp();
656           $value_flag = TRUE;
657           break;
658         case 'value':
659           // If no type is indicated, the type is string
660           // We take special care for empty values
661           if (trim($xmlrpc_message->current_tag_contents) != '' || (isset($xmlrpc_message->last_open) && ($xmlrpc_message->last_open == 'value'))) {
662             $value = (string)$xmlrpc_message->current_tag_contents;
663             $value_flag = TRUE;
664           }
665           unset($xmlrpc_message->last_open);
666           break;
667         case 'boolean':
668           $value = (boolean)trim($xmlrpc_message->current_tag_contents);
669           $value_flag = TRUE;
670           break;
671         case 'base64':
672           $value = base64_decode(trim($xmlrpc_message->current_tag_contents));
673           $value_flag = TRUE;
674           break;
675         // Deal with stacks of arrays and structs
676         case 'data':
677         case 'struct':
678           $value = array_pop($xmlrpc_message->array_structs );
679           array_pop($xmlrpc_message->array_structs_types);
680           $value_flag = TRUE;
681           break;
682         case 'member':
683           array_pop($xmlrpc_message->current_struct_name);
684           break;
685         case 'name':
686           $xmlrpc_message->current_struct_name[] = trim($xmlrpc_message->current_tag_contents);
687           break;
688         case 'methodName':
689           $xmlrpc_message->methodname = trim($xmlrpc_message->current_tag_contents);
690           break;
691       }
692
693       if ($value_flag) {
694         if (count($xmlrpc_message->array_structs ) > 0) {
695           // Add value to struct or array
696           if ($xmlrpc_message->array_structs_types[count($xmlrpc_message->array_structs_types)-1] == 'struct') {
697             // Add to struct
698             $xmlrpc_message->array_structs [count($xmlrpc_message->array_structs )-1][$xmlrpc_message->current_struct_name[count($xmlrpc_message->current_struct_name)-1]] = $value;
699           }
700           else {
701             // Add to array
702             $xmlrpc_message->array_structs [count($xmlrpc_message->array_structs )-1][] = $value;
703           }
704         }
705         else {
706           // Just add as a parameter
707           $xmlrpc_message->params[] = $value;
708         }
709       }
710       if (!in_array($tag, array("data", "struct", "member"))) {
711         $xmlrpc_message->current_tag_contents = '';
712       }
713       $this->xmlrpc_message_set($xmlrpc_message);
714     }
715
716     /**
717      * Construct an object representing an XML-RPC request
718      *
719      * @param $method
720      *   The name of the method to be called
721      * @param $args
722      *   An array of parameters to send with the method.
723      * @return
724      *   Object
725      */
726     function xmlrpc_request($method, $args) {
727       $xmlrpc_request = new stdClass();
728       $xmlrpc_request->method = $method;
729       $xmlrpc_request->args = $args;
730       $xmlrpc_request->xml = <<<EOD
731     <?xml version="1.0"?>
732     <methodCall>
733     <methodName>{$xmlrpc_request->method}</methodName>
734     <params>
735
736 EOD;
737
738       foreach ($xmlrpc_request->args as $arg) {
739         $xmlrpc_request->xml .= '<param><value>';
740         $v = $this->xmlrpc_value($arg);
741         $xmlrpc_request->xml .= $this->xmlrpc_value_get_xml($v);
742         $xmlrpc_request->xml .= "</value></param>\n";
743       }
744       $xmlrpc_request->xml .= '</params></methodCall>';
745       return $xmlrpc_request;
746     }
747
748
749     function xmlrpc_error($code = NULL, $message = NULL, $reset = FALSE) {
750       static $xmlrpc_error;
751       if (isset($code)) {
752         $xmlrpc_error = new stdClass();
753         $xmlrpc_error->is_error = TRUE;
754         $xmlrpc_error->code = $code;
755         $xmlrpc_error->message = $message;
756       }
757       elseif ($reset) {
758         $xmlrpc_error = NULL;
759       }
760       return $xmlrpc_error;
761     }
762
763     function xmlrpc_error_get_xml($xmlrpc_error) {
764       return <<<EOD
765     <methodResponse>
766       <fault>
767       <value>
768         <struct>
769         <member>
770           <name>faultCode</name>
771           <value><int>{$xmlrpc_error->code}</int></value>
772         </member>
773         <member>
774           <name>faultString</name>
775           <value><string>{$xmlrpc_error->message}</string></value>
776         </member>
777         </struct>
778       </value>
779       </fault>
780     </methodResponse>
781
782 EOD;
783     }
784
785     function xmlrpc_date($time) {
786       $xmlrpc_date = new stdClass();
787       $xmlrpc_date->is_date = TRUE;
788       // $time can be a PHP timestamp or an ISO one
789       if (is_numeric($time)) {
790         $xmlrpc_date->year = gmdate('Y', $time);
791         $xmlrpc_date->month = gmdate('m', $time);
792         $xmlrpc_date->day = gmdate('d', $time);
793         $xmlrpc_date->hour = gmdate('H', $time);
794         $xmlrpc_date->minute = gmdate('i', $time);
795         $xmlrpc_date->second = gmdate('s', $time);
796         $xmlrpc_date->iso8601 = gmdate('Ymd\TH:i:s', $time);
797       }
798       else {
799         $xmlrpc_date->iso8601 = $time;
800         $time = str_replace(array('-', ':'), '', $time);
801         $xmlrpc_date->year = substr($time, 0, 4);
802         $xmlrpc_date->month = substr($time, 4, 2);
803         $xmlrpc_date->day = substr($time, 6, 2);
804         $xmlrpc_date->hour = substr($time, 9, 2);
805         $xmlrpc_date->minute = substr($time, 11, 2);
806         $xmlrpc_date->second = substr($time, 13, 2);
807       }
808       return $xmlrpc_date;
809     }
810
811     function xmlrpc_date_get_xml($xmlrpc_date) {
812       return '<dateTime.iso8601>'. $xmlrpc_date->year . $xmlrpc_date->month . $xmlrpc_date->day .'T'. $xmlrpc_date->hour .':'. $xmlrpc_date->minute .':'. $xmlrpc_date->second .'</dateTime.iso8601>';
813     }
814
815     function xmlrpc_base64($data) {
816       $xmlrpc_base64 = new stdClass();
817       $xmlrpc_base64->is_base64 = TRUE;
818       $xmlrpc_base64->data = $data;
819       return $xmlrpc_base64;
820     }
821
822     function xmlrpc_base64_get_xml($xmlrpc_base64) {
823       return '<base64>'. base64_encode($xmlrpc_base64->data) .'</base64>';
824     }
825
826     /**
827     * Execute an XML remote procedural call. This is private function; call xmlrpc()
828     * in common.inc instead of this function.
829     *
830     * @return
831     *   A $xmlrpc_message object if the call succeeded; FALSE if the call failed
832     */
833     function _xmlrpc() {
834       $args = func_get_args();
835       $url = array_shift($args);
836       $this->xmlrpc_clear_error();
837       if (is_array($args[0])) {
838         $method = 'system.multicall';
839         $multicall_args = array();
840         foreach ($args[0] as $call) {
841           $multicall_args[] = array('methodName' => array_shift($call), 'params' => $call);
842         }
843         $args = array($multicall_args);
844       }
845       else {
846         $method = array_shift($args);
847       }
848       $xmlrpc_request = $this->xmlrpc_request($method, $args);
849       $result = $this->http_request($url, array("Content-Type" => "text/xml"), 'POST', $xmlrpc_request->xml);
850       if ($result->code != 200) {
851         $this->xmlrpc_error($result->code, $result->error);
852         return FALSE;
853       }
854       $message = $this->xmlrpc_message($result->data);
855       // Now parse what we've got back
856       if (!$this->xmlrpc_message_parse($message)) {
857         // XML error
858         $this->xmlrpc_error(-32700, t('Parse error. Not well formed'));
859         return FALSE;
860       }
861       // Is the message a fault?
862       if ($message->messagetype == 'fault') {
863         $this->xmlrpc_error($message->fault_code, $message->fault_string);
864         return FALSE;
865       }
866       // Message must be OK
867       return $message->params[0];
868     }
869
870     /**
871      * Returns the last XML-RPC client error number
872      */
873     function xmlrpc_errno() {
874       $error = $this->xmlrpc_error();
875       return ($error != NULL ? $error->code : NULL);
876     }
877
878     /**
879      * Returns the last XML-RPC client error message
880      */
881     function xmlrpc_error_msg() {
882       $error = xmlrpc_error();
883       return ($error != NULL ? $error->message : NULL);
884     }
885
886     /**
887      * Clears any previous error.
888      */
889     function xmlrpc_clear_error() {
890       $this->xmlrpc_error(NULL, NULL, TRUE);
891     }
892 }