5
* @version $Id: functions_jabber.php,v 1.40 2007/10/05 14:30:10 acydburn Exp $
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 1306 2007-06-21
24
* @copyright 2006 Flyspray.org
25
* @author Florian Schmitz (floele)
27
* Modified by Acyd Burn
33
var $connection = null;
34
var $session = array();
42
var $resource = 'functions_jabber.phpbb.php';
47
var $features = array();
51
function jabber($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 && $this->can_use_ssl()) ? true : false;
59
// Change port if we use SSL
60
if ($this->port == 5222 && $this->use_ssl)
65
$this->enable_logging = true;
66
$this->log_array = array();
70
* Able to use the SSL functionality?
72
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;
81
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'))
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))
104
* Sets the resource which is used. No validation is done here, only escaping.
105
* @param string $name
108
function set_resource($name)
110
$this->resource = $name;
118
/* if (!$this->check_jid($this->username . '@' . $this->server))
120
$this->add_to_log('Error: Jabber ID is not valid: ' . $this->username . '@' . $this->server);
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");
133
$this->add_to_log('Error: connect() #2');
137
// Now we listen what the server has to say...and give appropriate responses
138
$this->response($this->listen());
145
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);
168
return (is_resource($this->connection) && !feof($this->connection)) ? true : false;
173
* Initiates login (using data from contructor, after calling connect())
179
if (!sizeof($this->features))
181
$this->add_to_log('Error: No feature information from server available.');
185
return $this->response($this->features);
189
* Send data to the Jabber server
196
if ($this->connected())
199
$this->add_to_log('SEND: '. $xml);
200
return fwrite($this->connection, $xml);
204
$this->add_to_log('Error: Could not send, connection lost (flood?).');
211
* @param string $server host to connect to
212
* @param int $port port number
213
* @param bool $use_ssl use ssl or not
217
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);
238
// Apparently an error occured...
239
$this->add_to_log('Error: open_socket() - ' . $errorstr);
248
if ($this->enable_logging && sizeof($this->log_array))
250
return implode("<br /><br />", $this->log_array);
257
* Add information to log
259
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.
271
* @return mixed either false for timeout or an array with the received data
273
function listen($timeout = 10, $wait = false)
275
if (!$this->connected())
280
// Wait for a response until timeout is reached
286
$read = trim(fread($this->connection, 4096));
289
while (time() <= $start + $timeout && ($wait || $data == '' || $read != '' || (substr(rtrim($data), -1) != '>')));
293
$this->add_to_log('RECV: '. $data);
294
return $this->xmlize($data);
298
$this->add_to_log('Timeout, no response from server.');
304
* Initiates account registration (based on data used for contructor)
310
if (!isset($this->session['id']) || isset($this->session['jid']))
312
$this->add_to_log('Error: Cannot initiate registration.');
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
328
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.');
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
353
function response($xml)
355
if (!is_array($xml) || !sizeof($xml))
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));
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)));
386
case 'stream:stream':
387
// Connection initialised (or after authentication). Not much to do here...
388
$this->session['id'] = $xml['stream:stream'][0]['@']['id'];
390
if (isset($xml['stream:stream'][0]['#']['stream:features']))
392
// we already got all info we need
393
$this->features = $xml['stream:stream'][0]['#'];
397
$this->features = $this->listen();
400
// go on with authentication?
401
if (isset($this->features['stream:features'][0]['#']['bind']) || !empty($this->session['tls']))
403
return $this->response($this->features);
407
case 'stream:features':
408
// Resource binding after successful authentication
409
if (isset($this->session['authenticated']))
412
$this->session['sess_required'] = isset($xml['stream:features'][0]['#']['session']);
414
$this->send("<iq type='set' id='bind_1'>
415
<bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'>
416
<resource>" . utf8_htmlspecialchars($this->resource) . '</resource>
419
return $this->response($this->listen());
422
// Let's use TLS if SSL is not enabled and we can actually use it
423
if (!$this->session['ssl'] && $this->can_use_tls() && $this->can_use_ssl() && isset($xml['stream:features'][0]['#']['starttls']))
425
$this->add_to_log('Switching to TLS.');
426
$this->send("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>\n");
427
return $this->response($this->listen());
430
// Does the server support SASL authentication?
432
// I hope so, because we do (and no other method).
433
if (isset($xml['stream:features'][0]['#']['mechanisms'][0]['@']['xmlns']) && $xml['stream:features'][0]['#']['mechanisms'][0]['@']['xmlns'] == 'urn:ietf:params:xml:ns:xmpp-sasl')
435
// Now decide on method
438
foreach ($xml['stream:features'][0]['#']['mechanisms'][0]['#']['mechanism'] as $value)
440
$methods[] = $value['#'];
443
// we prefer DIGEST-MD5
444
// we don't want to use plain authentication (neither does the server usually) if no encryption is in place
446
// http://www.xmpp.org/extensions/attic/jep-0078-1.7.html
447
// The plaintext mechanism SHOULD NOT be used unless the underlying stream is encrypted (using SSL or TLS)
448
// and the client has verified that the server certificate is signed by a trusted certificate authority.
450
if (in_array('DIGEST-MD5', $methods))
452
$this->send("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='DIGEST-MD5'/>");
454
else if (in_array('PLAIN', $methods) && ($this->session['ssl'] || !empty($this->session['tls'])))
456
$this->send("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>"
457
. base64_encode(chr(0) . $this->username . '@' . $this->server . chr(0) . $this->password) .
460
else if (in_array('ANONYMOUS', $methods))
462
$this->send("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='ANONYMOUS'/>");
467
$this->add_to_log('Error: No authentication method supported.');
472
return $this->response($this->listen());
476
// ok, this is it. bye.
477
$this->add_to_log('Error: Server does not offer SASL authentication.');
484
// continue with authentication...a challenge literally -_-
485
$decoded = base64_decode($xml['challenge'][0]['#']);
486
$decoded = $this->parse_data($decoded);
488
if (!isset($decoded['digest-uri']))
490
$decoded['digest-uri'] = 'xmpp/'. $this->server;
493
// better generate a cnonce, maybe it's needed
495
mt_srand((double)microtime()*10000000);
497
for ($i = 0; $i < 32; $i++)
499
$str .= chr(mt_rand(0, 255));
501
$decoded['cnonce'] = base64_encode($str);
504
if (isset($decoded['rspauth']))
506
$this->send("<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>");
510
// Make sure we only use 'auth' for qop (relevant for $this->encrypt_password())
511
// If the <response> is choking up on the changed parameter we may need to adjust encrypt_password() directly
512
if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false)
514
$decoded['qop'] = 'auth';
518
'username' => $this->username,
519
'response' => $this->encrypt_password(array_merge($decoded, array('nc' => '00000001'))),
520
'charset' => 'utf-8',
524
foreach (array('nonce', 'qop', 'digest-uri', 'realm', 'cnonce') as $key)
526
if (isset($decoded[$key]))
528
$response[$key] = $decoded[$key];
532
$this->send("<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>" . base64_encode($this->implode_data($response)) . '</response>');
535
return $this->response($this->listen());
539
$this->add_to_log('Error: Server sent "failure".');
545
// continue switching to TLS
546
$meta = stream_get_meta_data($this->connection);
547
socket_set_blocking($this->connection, 1);
549
if (!stream_socket_enable_crypto($this->connection, true, STREAM_CRYPTO_METHOD_TLS_CLIENT))
551
$this->add_to_log('Error: TLS mode change failed.');
555
socket_set_blocking($this->connection, $meta['blocked']);
556
$this->session['tls'] = true;
559
$this->send("<?xml version='1.0' encoding='UTF-8' ?" . ">\n");
560
$this->send("<stream:stream to='{$this->server}' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>\n");
562
return $this->response($this->listen());
566
// Yay, authentication successful.
567
$this->send("<stream:stream to='{$this->server}' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>\n");
568
$this->session['authenticated'] = true;
570
// we have to wait for another response
571
return $this->response($this->listen());
575
// we are not interested in IQs we did not expect
576
if (!isset($xml['iq'][0]['@']['id']))
581
// multiple possibilities here
582
switch ($xml['iq'][0]['@']['id'])
585
$this->session['jid'] = $xml['iq'][0]['#']['bind'][0]['#']['jid'][0]['#'];
587
// and (maybe) yet another request to be able to send messages *finally*
588
if ($this->session['sess_required'])
590
$this->send("<iq to='{$this->server}' type='set' id='sess_1'>
591
<session xmlns='urn:ietf:params:xml:ns:xmpp-session'/>
593
return $this->response($this->listen());
604
$this->send("<iq type='set' id='reg_2'>
605
<query xmlns='jabber:iq:register'>
606
<username>" . utf8_htmlspecialchars($this->username) . "</username>
607
<password>" . utf8_htmlspecialchars($this->password) . "</password>
610
return $this->response($this->listen());
615
if (isset($xml['iq'][0]['#']['error']))
617
$this->add_to_log('Warning: Registration failed.');
628
$this->add_to_log('Notice: Received unexpected IQ.');
635
// we are only interested in content...
636
if (!isset($xml['message'][0]['#']['body']))
641
$message['body'] = $xml['message'][0]['#']['body'][0]['#'];
642
$message['from'] = $xml['message'][0]['@']['from'];
644
if (isset($xml['message'][0]['#']['subject']))
646
$message['subject'] = $xml['message'][0]['#']['subject'][0]['#'];
648
$this->session['messages'][] = $message;
652
// hm...don't know this response
653
$this->add_to_log('Notice: Unknown server response (' . key($xml) . ')');
659
function send_message($to, $text, $subject = '', $type = 'normal')
661
if (!isset($this->session['jid']))
666
if (!in_array($type, array('chat', 'normal', 'error', 'groupchat', 'headline')))
671
return $this->send("<message from='" . utf8_htmlspecialchars($this->session['jid']) . "' to='" . utf8_htmlspecialchars($to) . "' type='$type' id='" . uniqid('msg') . "'>
672
<subject>" . utf8_htmlspecialchars($subject) . "</subject>
673
<body>" . utf8_htmlspecialchars($text) . "</body>
679
* Encrypts a password as in RFC 2831
680
* @param array $data Needs data from the client-server connection
684
function encrypt_password($data)
686
// let's me think about <challenge> again...
687
foreach (array('realm', 'cnonce', 'digest-uri') as $key)
689
if (!isset($data[$key]))
695
$pack = md5($this->username . ':' . $data['realm'] . ':' . $this->password);
697
if (isset($data['authzid']))
699
$a1 = pack('H32', $pack) . sprintf(':%s:%s:%s', $data['nonce'], $data['cnonce'], $data['authzid']);
703
$a1 = pack('H32', $pack) . sprintf(':%s:%s', $data['nonce'], $data['cnonce']);
706
// should be: qop = auth
707
$a2 = 'AUTHENTICATE:'. $data['digest-uri'];
709
return md5(sprintf('%s:%s:%s:%s:%s:%s', md5($a1), $data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], md5($a2)));
713
* parse_data like a="b",c="d",... or like a="a, b", c, d="e", f=g,...
714
* @param string $data
716
* @return array a => b ...
718
function parse_data($data)
720
$data = explode(',', $data);
724
foreach ($data as $pair)
726
$dd = strpos($pair, '=');
730
$key = trim(substr($pair, 0, $dd));
731
$pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"');
733
else if (strpos(strrev(trim($pair)), '"') === 0 && $key)
735
// We are actually having something left from "a, b" values, add it to the last one we handled.
736
$pairs[$key] .= ',' . trim(trim($pair), '"');
745
* opposite of jabber::parse_data()
750
function implode_data($data)
753
foreach ($data as $key => $value)
755
$return[] = $key . '="' . $value . '"';
757
return implode(',', $return);
762
* @author Hans Anderson
763
* @copyright Hans Anderson / http://www.hansanderson.com/php/xml/
765
function xmlize($data, $skip_white = 1, $encoding = 'UTF-8')
769
if (substr($data, 0, 5) != '<?xml')
772
$data = '<root>'. $data . '</root>';
775
$vals = $index = $array = array();
776
$parser = xml_parser_create($encoding);
777
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
778
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, $skip_white);
779
xml_parse_into_struct($parser, $data, $vals, $index);
780
xml_parser_free($parser);
783
$tagname = $vals[$i]['tag'];
785
$array[$tagname][0]['@'] = (isset($vals[$i]['attributes'])) ? $vals[$i]['attributes'] : array();
786
$array[$tagname][0]['#'] = $this->_xml_depth($vals, $i);
788
if (substr($data, 0, 5) != '<?xml')
790
$array = $array['root'][0]['#'];
798
* @author Hans Anderson
799
* @copyright Hans Anderson / http://www.hansanderson.com/php/xml/
801
function _xml_depth($vals, &$i)
805
if (isset($vals[$i]['value']))
807
array_push($children, $vals[$i]['value']);
810
while (++$i < sizeof($vals))
812
switch ($vals[$i]['type'])
816
$tagname = (isset($vals[$i]['tag'])) ? $vals[$i]['tag'] : '';
817
$size = (isset($children[$tagname])) ? sizeof($children[$tagname]) : 0;
819
if (isset($vals[$i]['attributes']))
821
$children[$tagname][$size]['@'] = $vals[$i]['attributes'];
824
$children[$tagname][$size]['#'] = $this->_xml_depth($vals, $i);
829
array_push($children, $vals[$i]['value']);
834
$tagname = $vals[$i]['tag'];
835
$size = (isset($children[$tagname])) ? sizeof($children[$tagname]) : 0;
836
$children[$tagname][$size]['#'] = (isset($vals[$i]['value'])) ? $vals[$i]['value'] : array();
838
if (isset($vals[$i]['attributes']))
840
$children[$tagname][$size]['@'] = $vals[$i]['attributes'];
b'\\ No newline at end of file'