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