6 * @copyright (c) 2007 phpBB Group
7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
14 if (!defined('IN_PHPBB'))
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
33 private $connection = null;
34 private $session = array();
35 private $timeout = 10;
38 private $connect_server;
43 private $resource = 'functions_jabber.phpbb.php';
45 private $enable_logging;
48 private $features = array();
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;
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
)
80 $this->enable_logging
= true;
81 $this->log_array
= array();
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;
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'))
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))
119 * Sets the resource which is used. No validation is done here, only escaping.
120 * @param string $name
123 public function set_resource($name)
125 $this->resource = $name;
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);
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");
148 $this->add_to_log('Error: connect() #2');
152 // Now we listen what the server has to say...and give appropriate responses
153 $this->response($this->listen());
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
);
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())
192 public function login()
194 if (!sizeof($this->features
))
196 $this->add_to_log('Error: No feature information from server available.');
200 return $this->response($this->features
);
204 * Send data to the Jabber server
209 private function send($xml)
211 if ($this->connected())
214 $this->add_to_log('SEND: '. $xml);
215 return fwrite($this->connection
, $xml);
219 $this->add_to_log('Error: Could not send, connection lost (flood?).');
226 * @param string $server host to connect to
227 * @param int $port port number
228 * @param bool $use_ssl use ssl or not
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);
253 // Apparently an error occured...
254 $this->add_to_log('Error: open_socket() - ' . $errorstr);
261 public function get_log()
263 if ($this->enable_logging
&& sizeof($this->log_array
))
265 return implode("<br /><br />", $this->log_array
);
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.
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())
295 // Wait for a response until timeout is reached
301 $read = trim(fread($this->connection
, 4096));
304 while (time() <= $start +
$timeout && !feof($this->connection
) && ($wait ||
$data == '' ||
$read != '' ||
(substr(rtrim($data), -1) != '>')));
308 $this->add_to_log('RECV: '. $data);
309 return self
::xmlize($data);
313 $this->add_to_log('Timeout, no response from server.');
319 * Initiates account registration (based on data used for contructor)
323 private function register()
325 if (!isset($this->session
['id']) ||
isset($this->session
['jid']))
327 $this->add_to_log('Error: Cannot initiate registration.');
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
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.');
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
368 private function response($xml)
370 if (!is_array($xml) ||
!sizeof($xml))
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));
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)));
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]['#'];
411 $this->features
= $this->listen();
414 $second_time = isset($this->session
['id']);
415 $this->session
['id'] = $xml['stream:stream'][0]['@']['id'];
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
);
430 case 'stream:features':
431 // Resource binding after successful authentication
432 if (isset($this->session
['authenticated']))
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>
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
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
) .
483 else if (in_array('ANONYMOUS', $methods))
485 $this->send("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='ANONYMOUS'/>");
490 $this->add_to_log('Error: No authentication method supported.');
495 return $this->response($this->listen());
499 // ok, this is it. bye.
500 $this->add_to_log('Error: Server does not offer SASL authentication.');
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)));
520 if (isset($decoded['rspauth']))
522 $this->send("<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>");
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';
534 'username' => $this->username
,
535 'response' => $this->encrypt_password(array_merge($decoded, array('nc' => '00000001'))),
536 'charset' => 'utf-8',
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());
556 $this->add_to_log('Error: Server sent "failure".');
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.');
572 socket_set_blocking($this->connection
, $meta['blocked']);
573 $this->session
['tls'] = true;
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());
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());
592 // we are not interested in IQs we did not expect
593 if (!isset($xml['iq'][0]['@']['id']))
598 // multiple possibilities here
599 switch ($xml['iq'][0]['@']['id'])
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'/>
610 return $this->response($this->listen());
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>
627 return $this->response($this->listen());
632 if (isset($xml['iq'][0]['#']['error']))
634 $this->add_to_log('Warning: Registration failed.');
645 $this->add_to_log('Notice: Received unexpected IQ.');
652 // we are only interested in content...
653 if (!isset($xml['message'][0]['#']['body']))
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;
669 // hm...don't know this response
670 $this->add_to_log('Notice: Unknown server response (' . key($xml) . ')');
676 public function send_message($to, $text, $subject = '', $type = 'normal')
678 if (!isset($this->session
['jid']))
683 if (!in_array($type, array('chat', 'normal', 'error', 'groupchat', 'headline')))
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>
696 * Encrypts a password as in RFC 2831
697 * @param array $data Needs data from the client-server connection
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]))
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']);
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
733 * @return array a => b ...
735 private static function parse_data($data)
737 $data = explode(',', $data);
741 foreach ($data as $pair)
743 $dd = strpos($pair, '=');
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), '"');
762 * opposite of jabber::parse_data()
767 private function implode_data($data)
770 foreach ($data as $key => $value)
772 $return[] = $key . '="' . $value . '"';
774 return implode(',', $return);
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')
786 if (substr($data, 0, 5) != '<?xml')
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);
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]['#'];
815 * @author Hans Anderson
816 * @copyright Hans Anderson / http://www.hansanderson.com/php/xml/
818 private static function _xml_depth($vals, &$i)
822 if (isset($vals[$i]['value']))
824 array_push($children, $vals[$i]['value']);
827 while (++
$i < sizeof($vals))
829 switch ($vals[$i]['type'])
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);
846 array_push($children, $vals[$i]['value']);
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'];