add some properties
[phpbb.git] / phpBB / includes / functions_jabber.php
blob5fc7123db7322fbdefe0973e7c11b4e0b6aecb52
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 1595 2008-09-19 (0.9.9)
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 $connect_server;
39 private $port;
40 private $username;
41 private $password;
42 private $use_ssl;
43 private $resource = 'functions_jabber.phpbb.php';
45 private $enable_logging;
46 private $log_array;
48 private $features = array();
50 /**
52 function __construct($server, $port, $username, $password, $use_ssl = false)
54 $this->connect_server = ($server) ? $server : 'localhost';
55 $this->port = ($port) ? $port : 5222;
57 // Get the server and the username
58 if (strpos($username, '@') === false)
60 $this->server = $this->connect_server;
61 $this->username = $username;
63 else
65 $jid = explode('@', $username, 2);
67 $this->username = $jid[0];
68 $this->server = $jid[1];
71 $this->password = $password;
72 $this->use_ssl = ($use_ssl && self::can_use_ssl()) ? true : false;
74 // Change port if we use SSL
75 if ($this->port == 5222 && $this->use_ssl)
77 $this->port = 5223;
80 $this->enable_logging = true;
81 $this->log_array = array();
84 /**
85 * Able to use the SSL functionality?
87 public static function can_use_ssl()
89 // 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)
90 return ((version_compare(PHP_VERSION, '5.2.1', '<') || version_compare(PHP_VERSION, '5.2.3RC2', '>=')) && @extension_loaded('openssl')) ? true : false;
93 /**
94 * Able to use TLS?
96 public static function can_use_tls()
98 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'))
100 return false;
104 * Make sure the encryption stream is supported
105 * Also seem to work without the crypto stream if correctly compiled
107 $streams = stream_get_wrappers();
109 if (!in_array('streams.crypto', $streams))
111 return false;
115 return true;
119 * Sets the resource which is used. No validation is done here, only escaping.
120 * @param string $name
121 * @access public
123 public function set_resource($name)
125 $this->resource = $name;
129 * Connect
131 public function connect()
133 /* if (!$this->check_jid($this->username . '@' . $this->server))
135 $this->add_to_log('Error: Jabber ID is not valid: ' . $this->username . '@' . $this->server);
136 return false;
139 $this->session['ssl'] = $this->use_ssl;
141 if ($this->open_socket($this->connect_server, $this->port, $this->use_ssl))
143 $this->send("<?xml version='1.0' encoding='UTF-8' ?" . ">\n");
144 $this->send("<stream:stream to='{$this->server}' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>\n");
146 else
148 $this->add_to_log('Error: connect() #2');
149 return false;
152 // Now we listen what the server has to say...and give appropriate responses
153 $this->response($this->listen());
154 return true;
158 * Disconnect
160 public function disconnect()
162 if ($this->connected())
164 // disconnect gracefully
165 if (isset($this->session['sent_presence']))
167 $this->send_presence('offline', '', true);
170 $this->send('</stream:stream>');
171 $this->session = array();
172 return fclose($this->connection);
175 return false;
179 * Connected?
181 public function connected()
183 return (is_resource($this->connection) && !feof($this->connection)) ? true : false;
188 * Initiates login (using data from contructor, after calling connect())
189 * @access public
190 * @return bool
192 public function login()
194 if (!sizeof($this->features))
196 $this->add_to_log('Error: No feature information from server available.');
197 return false;
200 return $this->response($this->features);
204 * Send data to the Jabber server
205 * @param string $xml
206 * @access private
207 * @return bool
209 private function send($xml)
211 if ($this->connected())
213 $xml = trim($xml);
214 $this->add_to_log('SEND: '. $xml);
215 return fwrite($this->connection, $xml);
217 else
219 $this->add_to_log('Error: Could not send, connection lost (flood?).');
220 return false;
225 * OpenSocket
226 * @param string $server host to connect to
227 * @param int $port port number
228 * @param bool $use_ssl use ssl or not
229 * @access private
230 * @return bool
232 private function open_socket($server, $port, $use_ssl = false)
234 if (@function_exists('dns_get_record'))
236 $record = @dns_get_record("_xmpp-client._tcp.$server", DNS_SRV);
237 if (!empty($record) && !empty($record[0]['target']))
239 $server = $record[0]['target'];
243 $server = $use_ssl ? 'ssl://' . $server : $server;
245 if ($this->connection = @fsockopen($server, $port, $errorno, $errorstr, $this->timeout))
247 socket_set_blocking($this->connection, 0);
248 socket_set_timeout($this->connection, 60);
250 return true;
253 // Apparently an error occured...
254 $this->add_to_log('Error: open_socket() - ' . $errorstr);
255 return false;
259 * Return log
261 public function get_log()
263 if ($this->enable_logging && sizeof($this->log_array))
265 return implode("<br /><br />", $this->log_array);
268 return '';
272 * Add information to log
274 private function add_to_log($string)
276 if ($this->enable_logging)
278 $this->log_array[] = utf8_htmlspecialchars($string);
283 * Listens to the connection until it gets data or the timeout is reached.
284 * Thus, it should only be called if data is expected to be received.
285 * @access private
286 * @return mixed either false for timeout or an array with the received data
288 private function listen($timeout = 10, $wait = false)
290 if (!$this->connected())
292 return false;
295 // Wait for a response until timeout is reached
296 $start = time();
297 $data = '';
301 $read = trim(fread($this->connection, 4096));
302 $data .= $read;
304 while (time() <= $start + $timeout && !feof($this->connection) && ($wait || $data == '' || $read != '' || (substr(rtrim($data), -1) != '>')));
306 if ($data != '')
308 $this->add_to_log('RECV: '. $data);
309 return self::xmlize($data);
311 else
313 $this->add_to_log('Timeout, no response from server.');
314 return false;
319 * Initiates account registration (based on data used for contructor)
320 * @access private
321 * @return bool
323 private function register()
325 if (!isset($this->session['id']) || isset($this->session['jid']))
327 $this->add_to_log('Error: Cannot initiate registration.');
328 return false;
331 $this->send("<iq type='get' id='reg_1'><query xmlns='jabber:iq:register'/></iq>");
332 return $this->response($this->listen());
336 * Sets account presence. No additional info required (default is "online" status)
337 * @param $message online, offline...
338 * @param $type dnd, away, chat, xa or nothing
339 * @param $unavailable set this to true if you want to become unavailable
340 * @access private
341 * @return bool
343 private function send_presence($message = '', $type = '', $unavailable = false)
345 if (!isset($this->session['jid']))
347 $this->add_to_log('ERROR: send_presence() - Cannot set presence at this point, no jid given.');
348 return false;
351 $type = strtolower($type);
352 $type = (in_array($type, array('dnd', 'away', 'chat', 'xa'))) ? '<show>'. $type .'</show>' : '';
354 $unavailable = ($unavailable) ? " type='unavailable'" : '';
355 $message = ($message) ? '<status>' . utf8_htmlspecialchars($message) .'</status>' : '';
357 $this->session['sent_presence'] = !$unavailable;
359 return $this->send("<presence$unavailable>" . $type . $message . '</presence>');
363 * This handles all the different XML elements
364 * @param array $xml
365 * @access private
366 * @return bool
368 private function response($xml)
370 if (!is_array($xml) || !sizeof($xml))
372 return false;
375 // did we get multiple elements? do one after another
376 // array('message' => ..., 'presence' => ...)
377 if (sizeof($xml) > 1)
379 foreach ($xml as $key => $value)
381 $this->response(array($key => $value));
383 return;
385 else
387 // or even multiple elements of the same type?
388 // array('message' => array(0 => ..., 1 => ...))
389 if (sizeof(reset($xml)) > 1)
391 foreach (reset($xml) as $value)
393 $this->response(array(key($xml) => array(0 => $value)));
395 return;
399 switch (key($xml))
401 case 'stream:stream':
402 // Connection initialised (or after authentication). Not much to do here...
404 if (isset($xml['stream:stream'][0]['#']['stream:features']))
406 // we already got all info we need
407 $this->features = $xml['stream:stream'][0]['#'];
409 else
411 $this->features = $this->listen();
414 $second_time = isset($this->session['id']);
415 $this->session['id'] = $xml['stream:stream'][0]['@']['id'];
417 if ($second_time)
419 // If we are here for the second time after TLS, we need to continue logging in
420 return $this->login();
423 // go on with authentication?
424 if (isset($this->features['stream:features'][0]['#']['bind']) || !empty($this->session['tls']))
426 return $this->response($this->features);
428 break;
430 case 'stream:features':
431 // Resource binding after successful authentication
432 if (isset($this->session['authenticated']))
434 // session required?
435 $this->session['sess_required'] = isset($xml['stream:features'][0]['#']['session']);
437 $this->send("<iq type='set' id='bind_1'>
438 <bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'>
439 <resource>" . utf8_htmlspecialchars($this->resource) . '</resource>
440 </bind>
441 </iq>');
442 return $this->response($this->listen());
445 // Let's use TLS if SSL is not enabled and we can actually use it
446 if (!$this->session['ssl'] && self::can_use_tls() && self::can_use_ssl() && isset($xml['stream:features'][0]['#']['starttls']))
448 $this->add_to_log('Switching to TLS.');
449 $this->send("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>\n");
450 return $this->response($this->listen());
453 // Does the server support SASL authentication?
455 // I hope so, because we do (and no other method).
456 if (isset($xml['stream:features'][0]['#']['mechanisms'][0]['@']['xmlns']) && $xml['stream:features'][0]['#']['mechanisms'][0]['@']['xmlns'] == 'urn:ietf:params:xml:ns:xmpp-sasl')
458 // Now decide on method
459 $methods = array();
461 foreach ($xml['stream:features'][0]['#']['mechanisms'][0]['#']['mechanism'] as $value)
463 $methods[] = $value['#'];
466 // we prefer DIGEST-MD5
467 // we don't want to use plain authentication (neither does the server usually) if no encryption is in place
469 // http://www.xmpp.org/extensions/attic/jep-0078-1.7.html
470 // The plaintext mechanism SHOULD NOT be used unless the underlying stream is encrypted (using SSL or TLS)
471 // and the client has verified that the server certificate is signed by a trusted certificate authority.
473 if (in_array('DIGEST-MD5', $methods))
475 $this->send("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='DIGEST-MD5'/>");
477 else if (in_array('PLAIN', $methods) && ($this->session['ssl'] || !empty($this->session['tls'])))
479 $this->send("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>"
480 . base64_encode(chr(0) . $this->username . '@' . $this->server . chr(0) . $this->password) .
481 '</auth>');
483 else if (in_array('ANONYMOUS', $methods))
485 $this->send("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='ANONYMOUS'/>");
487 else
489 // not good...
490 $this->add_to_log('Error: No authentication method supported.');
491 $this->disconnect();
492 return false;
495 return $this->response($this->listen());
497 else
499 // ok, this is it. bye.
500 $this->add_to_log('Error: Server does not offer SASL authentication.');
501 $this->disconnect();
502 return false;
504 break;
506 case 'challenge':
507 // continue with authentication...a challenge literally -_-
508 $decoded = base64_decode($xml['challenge'][0]['#']);
509 $decoded = self::parse_data($decoded);
511 if (!isset($decoded['digest-uri']))
513 $decoded['digest-uri'] = 'xmpp/'. $this->server;
516 // better generate a cnonce, maybe it's needed
517 $decoded['cnonce'] = base64_encode(md5(uniqid(mt_rand(), true)));
519 // second challenge?
520 if (isset($decoded['rspauth']))
522 $this->send("<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>");
524 else
526 // Make sure we only use 'auth' for qop (relevant for $this->encrypt_password())
527 // If the <response> is choking up on the changed parameter we may need to adjust encrypt_password() directly
528 if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false)
530 $decoded['qop'] = 'auth';
533 $response = array(
534 'username' => $this->username,
535 'response' => $this->encrypt_password(array_merge($decoded, array('nc' => '00000001'))),
536 'charset' => 'utf-8',
537 'nc' => '00000001',
538 'qop' => 'auth', // only auth being supported
541 foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key)
543 if (isset($decoded[$key]))
545 $response[$key] = $decoded[$key];
549 $this->send("<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>" . base64_encode($this->implode_data($response)) . '</response>');
552 return $this->response($this->listen());
553 break;
555 case 'failure':
556 $this->add_to_log('Error: Server sent "failure".');
557 $this->disconnect();
558 return false;
559 break;
561 case 'proceed':
562 // continue switching to TLS
563 $meta = stream_get_meta_data($this->connection);
564 socket_set_blocking($this->connection, 1);
566 if (!stream_socket_enable_crypto($this->connection, true, STREAM_CRYPTO_METHOD_TLS_CLIENT))
568 $this->add_to_log('Error: TLS mode change failed.');
569 return false;
572 socket_set_blocking($this->connection, $meta['blocked']);
573 $this->session['tls'] = true;
575 // new stream
576 $this->send("<?xml version='1.0' encoding='UTF-8' ?" . ">\n");
577 $this->send("<stream:stream to='{$this->server}' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>\n");
579 return $this->response($this->listen());
580 break;
582 case 'success':
583 // Yay, authentication successful.
584 $this->send("<stream:stream to='{$this->server}' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>\n");
585 $this->session['authenticated'] = true;
587 // we have to wait for another response
588 return $this->response($this->listen());
589 break;
591 case 'iq':
592 // we are not interested in IQs we did not expect
593 if (!isset($xml['iq'][0]['@']['id']))
595 return false;
598 // multiple possibilities here
599 switch ($xml['iq'][0]['@']['id'])
601 case 'bind_1':
602 $this->session['jid'] = $xml['iq'][0]['#']['bind'][0]['#']['jid'][0]['#'];
604 // and (maybe) yet another request to be able to send messages *finally*
605 if ($this->session['sess_required'])
607 $this->send("<iq to='{$this->server}' type='set' id='sess_1'>
608 <session xmlns='urn:ietf:params:xml:ns:xmpp-session'/>
609 </iq>");
610 return $this->response($this->listen());
613 return true;
614 break;
616 case 'sess_1':
617 return true;
618 break;
620 case 'reg_1':
621 $this->send("<iq type='set' id='reg_2'>
622 <query xmlns='jabber:iq:register'>
623 <username>" . utf8_htmlspecialchars($this->username) . "</username>
624 <password>" . utf8_htmlspecialchars($this->password) . "</password>
625 </query>
626 </iq>");
627 return $this->response($this->listen());
628 break;
630 case 'reg_2':
631 // registration end
632 if (isset($xml['iq'][0]['#']['error']))
634 $this->add_to_log('Warning: Registration failed.');
635 return false;
637 return true;
638 break;
640 case 'unreg_1':
641 return true;
642 break;
644 default:
645 $this->add_to_log('Notice: Received unexpected IQ.');
646 return false;
647 break;
649 break;
651 case 'message':
652 // we are only interested in content...
653 if (!isset($xml['message'][0]['#']['body']))
655 return false;
658 $message['body'] = $xml['message'][0]['#']['body'][0]['#'];
659 $message['from'] = $xml['message'][0]['@']['from'];
661 if (isset($xml['message'][0]['#']['subject']))
663 $message['subject'] = $xml['message'][0]['#']['subject'][0]['#'];
665 $this->session['messages'][] = $message;
666 break;
668 default:
669 // hm...don't know this response
670 $this->add_to_log('Notice: Unknown server response (' . key($xml) . ')');
671 return false;
672 break;
676 public function send_message($to, $text, $subject = '', $type = 'normal')
678 if (!isset($this->session['jid']))
680 return false;
683 if (!in_array($type, array('chat', 'normal', 'error', 'groupchat', 'headline')))
685 $type = 'normal';
688 return $this->send("<message from='" . utf8_htmlspecialchars($this->session['jid']) . "' to='" . utf8_htmlspecialchars($to) . "' type='$type' id='" . uniqid('msg') . "'>
689 <subject>" . utf8_htmlspecialchars($subject) . "</subject>
690 <body>" . utf8_htmlspecialchars($text) . "</body>
691 </message>"
696 * Encrypts a password as in RFC 2831
697 * @param array $data Needs data from the client-server connection
698 * @access public
699 * @return string
701 public function encrypt_password($data)
703 // let's me think about <challenge> again...
704 foreach (array('realm', 'cnonce', 'digest-uri') as $key)
706 if (!isset($data[$key]))
708 $data[$key] = '';
712 $pack = md5($this->username . ':' . $data['realm'] . ':' . $this->password);
714 if (isset($data['authzid']))
716 $a1 = pack('H32', $pack) . sprintf(':%s:%s:%s', $data['nonce'], $data['cnonce'], $data['authzid']);
718 else
720 $a1 = pack('H32', $pack) . sprintf(':%s:%s', $data['nonce'], $data['cnonce']);
723 // should be: qop = auth
724 $a2 = 'AUTHENTICATE:'. $data['digest-uri'];
726 return md5(sprintf('%s:%s:%s:%s:%s:%s', md5($a1), $data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], md5($a2)));
730 * parse_data like a="b",c="d",... or like a="a, b", c, d="e", f=g,...
731 * @param string $data
732 * @access private
733 * @return array a => b ...
735 private static function parse_data($data)
737 $data = explode(',', $data);
738 $pairs = array();
739 $key = false;
741 foreach ($data as $pair)
743 $dd = strpos($pair, '=');
745 if ($dd)
747 $key = trim(substr($pair, 0, $dd));
748 $pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"');
750 else if (strpos(strrev(trim($pair)), '"') === 0 && $key)
752 // We are actually having something left from "a, b" values, add it to the last one we handled.
753 $pairs[$key] .= ',' . trim(trim($pair), '"');
754 continue;
758 return $pairs;
762 * opposite of jabber::parse_data()
763 * @param array $data
764 * @access private
765 * @return string
767 private function implode_data($data)
769 $return = array();
770 foreach ($data as $key => $value)
772 $return[] = $key . '="' . $value . '"';
774 return implode(',', $return);
778 * xmlize()
779 * @author Hans Anderson
780 * @copyright Hans Anderson / http://www.hansanderson.com/php/xml/
782 private static function xmlize($data, $skip_white = 1, $encoding = 'UTF-8')
784 $data = trim($data);
786 if (substr($data, 0, 5) != '<?xml')
788 // mod
789 $data = '<root>'. $data . '</root>';
792 $vals = $index = $array = array();
793 $parser = xml_parser_create($encoding);
794 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
795 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, $skip_white);
796 xml_parse_into_struct($parser, $data, $vals, $index);
797 xml_parser_free($parser);
799 $i = 0;
800 $tagname = $vals[$i]['tag'];
802 $array[$tagname][0]['@'] = (isset($vals[$i]['attributes'])) ? $vals[$i]['attributes'] : array();
803 $array[$tagname][0]['#'] = self::_xml_depth($vals, $i);
805 if (substr($data, 0, 5) != '<?xml')
807 $array = $array['root'][0]['#'];
810 return $array;
814 * _xml_depth()
815 * @author Hans Anderson
816 * @copyright Hans Anderson / http://www.hansanderson.com/php/xml/
818 private static function _xml_depth($vals, &$i)
820 $children = array();
822 if (isset($vals[$i]['value']))
824 array_push($children, $vals[$i]['value']);
827 while (++$i < sizeof($vals))
829 switch ($vals[$i]['type'])
831 case 'open':
833 $tagname = (isset($vals[$i]['tag'])) ? $vals[$i]['tag'] : '';
834 $size = (isset($children[$tagname])) ? sizeof($children[$tagname]) : 0;
836 if (isset($vals[$i]['attributes']))
838 $children[$tagname][$size]['@'] = $vals[$i]['attributes'];
841 $children[$tagname][$size]['#'] = self::_xml_depth($vals, $i);
843 break;
845 case 'cdata':
846 array_push($children, $vals[$i]['value']);
847 break;
849 case 'complete':
851 $tagname = $vals[$i]['tag'];
852 $size = (isset($children[$tagname])) ? sizeof($children[$tagname]) : 0;
853 $children[$tagname][$size]['#'] = (isset($vals[$i]['value'])) ? $vals[$i]['value'] : array();
855 if (isset($vals[$i]['attributes']))
857 $children[$tagname][$size]['@'] = $vals[$i]['attributes'];
860 break;
862 case 'close':
863 return $children;
864 break;
868 return $children;