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