marge
[phpbb.git] / phpBB / includes / functions_jabber.php
blob3af7881043024bfd5c807df290d609cf1204623b
1 <?php
2 /**
4 * @package phpBB3
5 * @version $Id$
6 * @copyright (c) 2007 phpBB Group
7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
9 */
11 /**
12 * @ignore
14 if (!defined('IN_PHPBB'))
16 exit;
19 /**
21 * Jabber class from Flyspray project
23 * @version class.jabber2.php 1488 2007-11-25
24 * @copyright 2006 Flyspray.org
25 * @author Florian Schmitz (floele)
27 * Only slightly modified by Acyd Burn
29 * @package phpBB3
31 class jabber
33 private $connection = null;
34 private $session = array();
35 private $timeout = 10;
37 private $server;
38 private $port;
39 private $username;
40 private $password;
41 private $use_ssl;
42 private $resource = 'functions_jabber.phpbb.php';
44 private $enable_logging;
45 private $log_array;
47 private $features = array();
49 /**
51 function __construct($server, $port, $username, $password, $use_ssl = false)
53 $this->server = ($server) ? $server : 'localhost';
54 $this->port = ($port) ? $port : 5222;
55 $this->username = $username;
56 $this->password = $password;
57 $this->use_ssl = ($use_ssl && self::can_use_ssl()) ? true : false;
59 // Change port if we use SSL
60 if ($this->port == 5222 && $this->use_ssl)
62 $this->port = 5223;
65 $this->enable_logging = true;
66 $this->log_array = array();
69 /**
70 * Able to use the SSL functionality?
72 public static function can_use_ssl()
74 // Will not work with PHP >= 5.2.1 or < 5.2.3RC2 until timeout problem with ssl hasn't been fixed (http://bugs.php.net/41236)
75 return ((version_compare(PHP_VERSION, '5.2.1', '<') || version_compare(PHP_VERSION, '5.2.3RC2', '>=')) && @extension_loaded('openssl')) ? true : false;
78 /**
79 * Able to use TLS?
81 public static function can_use_tls()
83 if (!@extension_loaded('openssl') || !function_exists('stream_socket_enable_crypto') || !function_exists('stream_get_meta_data') || !function_exists('socket_set_blocking') || !function_exists('stream_get_wrappers'))
85 return false;
88 /**
89 * Make sure the encryption stream is supported
90 * Also seem to work without the crypto stream if correctly compiled
92 $streams = stream_get_wrappers();
94 if (!in_array('streams.crypto', $streams))
96 return false;
100 return true;
104 * Sets the resource which is used. No validation is done here, only escaping.
105 * @param string $name
106 * @access public
108 public function set_resource($name)
110 $this->resource = $name;
114 * Connect
116 public function connect()
118 /* if (!$this->check_jid($this->username . '@' . $this->server))
120 $this->add_to_log('Error: Jabber ID is not valid: ' . $this->username . '@' . $this->server);
121 return false;
124 $this->session['ssl'] = $this->use_ssl;
126 if ($this->open_socket($this->server, $this->port, $this->use_ssl))
128 $this->send("<?xml version='1.0' encoding='UTF-8' ?" . ">\n");
129 $this->send("<stream:stream to='{$this->server}' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>\n");
131 else
133 $this->add_to_log('Error: connect() #2');
134 return false;
137 // Now we listen what the server has to say...and give appropriate responses
138 $this->response($this->listen());
139 return true;
143 * Disconnect
145 public function disconnect()
147 if ($this->connected())
149 // disconnect gracefully
150 if (isset($this->session['sent_presence']))
152 $this->send_presence('offline', '', true);
155 $this->send('</stream:stream>');
156 $this->session = array();
157 return fclose($this->connection);
160 return false;
164 * Connected?
166 public function connected()
168 return (is_resource($this->connection) && !feof($this->connection)) ? true : false;
173 * Initiates login (using data from contructor, after calling connect())
174 * @access public
175 * @return bool
177 public function login()
179 if (!sizeof($this->features))
181 $this->add_to_log('Error: No feature information from server available.');
182 return false;
185 return $this->response($this->features);
189 * Send data to the Jabber server
190 * @param string $xml
191 * @access private
192 * @return bool
194 private function send($xml)
196 if ($this->connected())
198 $xml = trim($xml);
199 $this->add_to_log('SEND: '. $xml);
200 return fwrite($this->connection, $xml);
202 else
204 $this->add_to_log('Error: Could not send, connection lost (flood?).');
205 return false;
210 * OpenSocket
211 * @param string $server host to connect to
212 * @param int $port port number
213 * @param bool $use_ssl use ssl or not
214 * @access private
215 * @return bool
217 private function open_socket($server, $port, $use_ssl = false)
219 if (@function_exists('dns_get_record'))
221 $record = @dns_get_record("_xmpp-client._tcp.$server", DNS_SRV);
222 if (!empty($record) && !empty($record[0]['target']))
224 $server = $record[0]['target'];
228 $server = $use_ssl ? 'ssl://' . $server : $server;
230 if ($this->connection = @fsockopen($server, $port, $errorno, $errorstr, $this->timeout))
232 socket_set_blocking($this->connection, 0);
233 socket_set_timeout($this->connection, 60);
235 return true;
238 // Apparently an error occured...
239 $this->add_to_log('Error: open_socket() - ' . $errorstr);
240 return false;
244 * Return log
246 public function get_log()
248 if ($this->enable_logging && sizeof($this->log_array))
250 return implode("<br /><br />", $this->log_array);
253 return '';
257 * Add information to log
259 private function add_to_log($string)
261 if ($this->enable_logging)
263 $this->log_array[] = utf8_htmlspecialchars($string);
268 * Listens to the connection until it gets data or the timeout is reached.
269 * Thus, it should only be called if data is expected to be received.
270 * @access private
271 * @return mixed either false for timeout or an array with the received data
273 private function listen($timeout = 10, $wait = false)
275 if (!$this->connected())
277 return false;
280 // Wait for a response until timeout is reached
281 $start = time();
282 $data = '';
286 $read = trim(fread($this->connection, 4096));
287 $data .= $read;
289 while (time() <= $start + $timeout && !feof($this->connection) && ($wait || $data == '' || $read != '' || (substr(rtrim($data), -1) != '>')));
291 if ($data != '')
293 $this->add_to_log('RECV: '. $data);
294 return self::xmlize($data);
296 else
298 $this->add_to_log('Timeout, no response from server.');
299 return false;
304 * Initiates account registration (based on data used for contructor)
305 * @access private
306 * @return bool
308 private function register()
310 if (!isset($this->session['id']) || isset($this->session['jid']))
312 $this->add_to_log('Error: Cannot initiate registration.');
313 return false;
316 $this->send("<iq type='get' id='reg_1'><query xmlns='jabber:iq:register'/></iq>");
317 return $this->response($this->listen());
321 * Sets account presence. No additional info required (default is "online" status)
322 * @param $message online, offline...
323 * @param $type dnd, away, chat, xa or nothing
324 * @param $unavailable set this to true if you want to become unavailable
325 * @access private
326 * @return bool
328 private function send_presence($message = '', $type = '', $unavailable = false)
330 if (!isset($this->session['jid']))
332 $this->add_to_log('ERROR: send_presence() - Cannot set presence at this point, no jid given.');
333 return false;
336 $type = strtolower($type);
337 $type = (in_array($type, array('dnd', 'away', 'chat', 'xa'))) ? '<show>'. $type .'</show>' : '';
339 $unavailable = ($unavailable) ? " type='unavailable'" : '';
340 $message = ($message) ? '<status>' . utf8_htmlspecialchars($message) .'</status>' : '';
342 $this->session['sent_presence'] = !$unavailable;
344 return $this->send("<presence$unavailable>" . $type . $message . '</presence>');
348 * This handles all the different XML elements
349 * @param array $xml
350 * @access private
351 * @return bool
353 private function response($xml)
355 if (!is_array($xml) || !sizeof($xml))
357 return false;
360 // did we get multiple elements? do one after another
361 // array('message' => ..., 'presence' => ...)
362 if (sizeof($xml) > 1)
364 foreach ($xml as $key => $value)
366 $this->response(array($key => $value));
368 return;
370 else
372 // or even multiple elements of the same type?
373 // array('message' => array(0 => ..., 1 => ...))
374 if (sizeof(reset($xml)) > 1)
376 foreach (reset($xml) as $value)
378 $this->response(array(key($xml) => array(0 => $value)));
380 return;
384 switch (key($xml))
386 case 'stream:stream':
387 // Connection initialised (or after authentication). Not much to do here...
389 if (isset($xml['stream:stream'][0]['#']['stream:features']))
391 // we already got all info we need
392 $this->features = $xml['stream:stream'][0]['#'];
394 else
396 $this->features = $this->listen();
399 $second_time = isset($this->session['id']);
400 $this->session['id'] = $xml['stream:stream'][0]['@']['id'];
402 if ($second_time)
404 // If we are here for the second time after TLS, we need to continue logging in
405 return $this->login();
408 // go on with authentication?
409 if (isset($this->features['stream:features'][0]['#']['bind']) || !empty($this->session['tls']))
411 return $this->response($this->features);
413 break;
415 case 'stream:features':
416 // Resource binding after successful authentication
417 if (isset($this->session['authenticated']))
419 // session required?
420 $this->session['sess_required'] = isset($xml['stream:features'][0]['#']['session']);
422 $this->send("<iq type='set' id='bind_1'>
423 <bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'>
424 <resource>" . utf8_htmlspecialchars($this->resource) . '</resource>
425 </bind>
426 </iq>');
427 return $this->response($this->listen());
430 // Let's use TLS if SSL is not enabled and we can actually use it
431 if (!$this->session['ssl'] && self::can_use_tls() && self::can_use_ssl() && isset($xml['stream:features'][0]['#']['starttls']))
433 $this->add_to_log('Switching to TLS.');
434 $this->send("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>\n");
435 return $this->response($this->listen());
438 // Does the server support SASL authentication?
440 // I hope so, because we do (and no other method).
441 if (isset($xml['stream:features'][0]['#']['mechanisms'][0]['@']['xmlns']) && $xml['stream:features'][0]['#']['mechanisms'][0]['@']['xmlns'] == 'urn:ietf:params:xml:ns:xmpp-sasl')
443 // Now decide on method
444 $methods = array();
446 foreach ($xml['stream:features'][0]['#']['mechanisms'][0]['#']['mechanism'] as $value)
448 $methods[] = $value['#'];
451 // we prefer DIGEST-MD5
452 // we don't want to use plain authentication (neither does the server usually) if no encryption is in place
454 // http://www.xmpp.org/extensions/attic/jep-0078-1.7.html
455 // The plaintext mechanism SHOULD NOT be used unless the underlying stream is encrypted (using SSL or TLS)
456 // and the client has verified that the server certificate is signed by a trusted certificate authority.
458 if (in_array('DIGEST-MD5', $methods))
460 $this->send("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='DIGEST-MD5'/>");
462 else if (in_array('PLAIN', $methods) && ($this->session['ssl'] || !empty($this->session['tls'])))
464 $this->send("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>"
465 . base64_encode(chr(0) . $this->username . '@' . $this->server . chr(0) . $this->password) .
466 '</auth>');
468 else if (in_array('ANONYMOUS', $methods))
470 $this->send("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='ANONYMOUS'/>");
472 else
474 // not good...
475 $this->add_to_log('Error: No authentication method supported.');
476 $this->disconnect();
477 return false;
480 return $this->response($this->listen());
482 else
484 // ok, this is it. bye.
485 $this->add_to_log('Error: Server does not offer SASL authentication.');
486 $this->disconnect();
487 return false;
489 break;
491 case 'challenge':
492 // continue with authentication...a challenge literally -_-
493 $decoded = base64_decode($xml['challenge'][0]['#']);
494 $decoded = self::parse_data($decoded);
496 if (!isset($decoded['digest-uri']))
498 $decoded['digest-uri'] = 'xmpp/'. $this->server;
501 // better generate a cnonce, maybe it's needed
502 $str = '';
503 mt_srand((double)microtime()*10000000);
505 for ($i = 0; $i < 32; $i++)
507 $str .= chr(mt_rand(0, 255));
509 $decoded['cnonce'] = base64_encode($str);
511 // second challenge?
512 if (isset($decoded['rspauth']))
514 $this->send("<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>");
516 else
518 // Make sure we only use 'auth' for qop (relevant for $this->encrypt_password())
519 // If the <response> is choking up on the changed parameter we may need to adjust encrypt_password() directly
520 if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false)
522 $decoded['qop'] = 'auth';
525 $response = array(
526 'username' => $this->username,
527 'response' => $this->encrypt_password(array_merge($decoded, array('nc' => '00000001'))),
528 'charset' => 'utf-8',
529 'nc' => '00000001',
530 'qop' => 'auth', // only auth being supported
533 foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key)
535 if (isset($decoded[$key]))
537 $response[$key] = $decoded[$key];
541 $this->send("<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>" . base64_encode($this->implode_data($response)) . '</response>');
544 return $this->response($this->listen());
545 break;
547 case 'failure':
548 $this->add_to_log('Error: Server sent "failure".');
549 $this->disconnect();
550 return false;
551 break;
553 case 'proceed':
554 // continue switching to TLS
555 $meta = stream_get_meta_data($this->connection);
556 socket_set_blocking($this->connection, 1);
558 if (!stream_socket_enable_crypto($this->connection, true, STREAM_CRYPTO_METHOD_TLS_CLIENT))
560 $this->add_to_log('Error: TLS mode change failed.');
561 return false;
564 socket_set_blocking($this->connection, $meta['blocked']);
565 $this->session['tls'] = true;
567 // new stream
568 $this->send("<?xml version='1.0' encoding='UTF-8' ?" . ">\n");
569 $this->send("<stream:stream to='{$this->server}' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>\n");
571 return $this->response($this->listen());
572 break;
574 case 'success':
575 // Yay, authentication successful.
576 $this->send("<stream:stream to='{$this->server}' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>\n");
577 $this->session['authenticated'] = true;
579 // we have to wait for another response
580 return $this->response($this->listen());
581 break;
583 case 'iq':
584 // we are not interested in IQs we did not expect
585 if (!isset($xml['iq'][0]['@']['id']))
587 return false;
590 // multiple possibilities here
591 switch ($xml['iq'][0]['@']['id'])
593 case 'bind_1':
594 $this->session['jid'] = $xml['iq'][0]['#']['bind'][0]['#']['jid'][0]['#'];
596 // and (maybe) yet another request to be able to send messages *finally*
597 if ($this->session['sess_required'])
599 $this->send("<iq to='{$this->server}' type='set' id='sess_1'>
600 <session xmlns='urn:ietf:params:xml:ns:xmpp-session'/>
601 </iq>");
602 return $this->response($this->listen());
605 return true;
606 break;
608 case 'sess_1':
609 return true;
610 break;
612 case 'reg_1':
613 $this->send("<iq type='set' id='reg_2'>
614 <query xmlns='jabber:iq:register'>
615 <username>" . utf8_htmlspecialchars($this->username) . "</username>
616 <password>" . utf8_htmlspecialchars($this->password) . "</password>
617 </query>
618 </iq>");
619 return $this->response($this->listen());
620 break;
622 case 'reg_2':
623 // registration end
624 if (isset($xml['iq'][0]['#']['error']))
626 $this->add_to_log('Warning: Registration failed.');
627 return false;
629 return true;
630 break;
632 case 'unreg_1':
633 return true;
634 break;
636 default:
637 $this->add_to_log('Notice: Received unexpected IQ.');
638 return false;
639 break;
641 break;
643 case 'message':
644 // we are only interested in content...
645 if (!isset($xml['message'][0]['#']['body']))
647 return false;
650 $message['body'] = $xml['message'][0]['#']['body'][0]['#'];
651 $message['from'] = $xml['message'][0]['@']['from'];
653 if (isset($xml['message'][0]['#']['subject']))
655 $message['subject'] = $xml['message'][0]['#']['subject'][0]['#'];
657 $this->session['messages'][] = $message;
658 break;
660 default:
661 // hm...don't know this response
662 $this->add_to_log('Notice: Unknown server response (' . key($xml) . ')');
663 return false;
664 break;
668 public function send_message($to, $text, $subject = '', $type = 'normal')
670 if (!isset($this->session['jid']))
672 return false;
675 if (!in_array($type, array('chat', 'normal', 'error', 'groupchat', 'headline')))
677 $type = 'normal';
680 return $this->send("<message from='" . utf8_htmlspecialchars($this->session['jid']) . "' to='" . utf8_htmlspecialchars($to) . "' type='$type' id='" . uniqid('msg') . "'>
681 <subject>" . utf8_htmlspecialchars($subject) . "</subject>
682 <body>" . utf8_htmlspecialchars($text) . "</body>
683 </message>"
688 * Encrypts a password as in RFC 2831
689 * @param array $data Needs data from the client-server connection
690 * @access public
691 * @return string
693 public function encrypt_password($data)
695 // let's me think about <challenge> again...
696 foreach (array('realm', 'cnonce', 'digest-uri') as $key)
698 if (!isset($data[$key]))
700 $data[$key] = '';
704 $pack = md5($this->username . ':' . $data['realm'] . ':' . $this->password);
706 if (isset($data['authzid']))
708 $a1 = pack('H32', $pack) . sprintf(':%s:%s:%s', $data['nonce'], $data['cnonce'], $data['authzid']);
710 else
712 $a1 = pack('H32', $pack) . sprintf(':%s:%s', $data['nonce'], $data['cnonce']);
715 // should be: qop = auth
716 $a2 = 'AUTHENTICATE:'. $data['digest-uri'];
718 return md5(sprintf('%s:%s:%s:%s:%s:%s', md5($a1), $data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], md5($a2)));
722 * parse_data like a="b",c="d",... or like a="a, b", c, d="e", f=g,...
723 * @param string $data
724 * @access private
725 * @return array a => b ...
727 private static function parse_data($data)
729 $data = explode(',', $data);
730 $pairs = array();
731 $key = false;
733 foreach ($data as $pair)
735 $dd = strpos($pair, '=');
737 if ($dd)
739 $key = trim(substr($pair, 0, $dd));
740 $pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"');
742 else if (strpos(strrev(trim($pair)), '"') === 0 && $key)
744 // We are actually having something left from "a, b" values, add it to the last one we handled.
745 $pairs[$key] .= ',' . trim(trim($pair), '"');
746 continue;
750 return $pairs;
754 * opposite of jabber::parse_data()
755 * @param array $data
756 * @access private
757 * @return string
759 private function implode_data($data)
761 $return = array();
762 foreach ($data as $key => $value)
764 $return[] = $key . '="' . $value . '"';
766 return implode(',', $return);
770 * xmlize()
771 * @author Hans Anderson
772 * @copyright Hans Anderson / http://www.hansanderson.com/php/xml/
774 private static function xmlize($data, $skip_white = 1, $encoding = 'UTF-8')
776 $data = trim($data);
778 if (substr($data, 0, 5) != '<?xml')
780 // mod
781 $data = '<root>'. $data . '</root>';
784 $vals = $index = $array = array();
785 $parser = xml_parser_create($encoding);
786 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
787 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, $skip_white);
788 xml_parse_into_struct($parser, $data, $vals, $index);
789 xml_parser_free($parser);
791 $i = 0;
792 $tagname = $vals[$i]['tag'];
794 $array[$tagname][0]['@'] = (isset($vals[$i]['attributes'])) ? $vals[$i]['attributes'] : array();
795 $array[$tagname][0]['#'] = self::_xml_depth($vals, $i);
797 if (substr($data, 0, 5) != '<?xml')
799 $array = $array['root'][0]['#'];
802 return $array;
806 * _xml_depth()
807 * @author Hans Anderson
808 * @copyright Hans Anderson / http://www.hansanderson.com/php/xml/
810 private static function _xml_depth($vals, &$i)
812 $children = array();
814 if (isset($vals[$i]['value']))
816 array_push($children, $vals[$i]['value']);
819 while (++$i < sizeof($vals))
821 switch ($vals[$i]['type'])
823 case 'open':
825 $tagname = (isset($vals[$i]['tag'])) ? $vals[$i]['tag'] : '';
826 $size = (isset($children[$tagname])) ? sizeof($children[$tagname]) : 0;
828 if (isset($vals[$i]['attributes']))
830 $children[$tagname][$size]['@'] = $vals[$i]['attributes'];
833 $children[$tagname][$size]['#'] = self::_xml_depth($vals, $i);
835 break;
837 case 'cdata':
838 array_push($children, $vals[$i]['value']);
839 break;
841 case 'complete':
843 $tagname = $vals[$i]['tag'];
844 $size = (isset($children[$tagname])) ? sizeof($children[$tagname]) : 0;
845 $children[$tagname][$size]['#'] = (isset($vals[$i]['value'])) ? $vals[$i]['value'] : array();
847 if (isset($vals[$i]['attributes']))
849 $children[$tagname][$size]['@'] = $vals[$i]['attributes'];
852 break;
854 case 'close':
855 return $children;
856 break;
860 return $children;