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 1488 2007-11-25
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;
42 private $resource = 'functions_jabber.phpbb.php';
44 private $enable_logging;
47 private $features = array();
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
)
65 $this->enable_logging
= true;
66 $this->log_array
= array();
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;
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'))
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 public function set_resource($name)
110 $this->resource = $name;
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);
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 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
);
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())
177 public function login()
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
194 private function send($xml)
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 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);
238 // Apparently an error occured...
239 $this->add_to_log('Error: open_socket() - ' . $errorstr);
246 public function get_log()
248 if ($this->enable_logging
&& sizeof($this->log_array
))
250 return implode("<br /><br />", $this->log_array
);
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.
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())
280 // Wait for a response until timeout is reached
286 $read = trim(fread($this->connection
, 4096));
289 while (time() <= $start +
$timeout && !feof($this->connection
) && ($wait ||
$data == '' ||
$read != '' ||
(substr(rtrim($data), -1) != '>')));
293 $this->add_to_log('RECV: '. $data);
294 return self
::xmlize($data);
298 $this->add_to_log('Timeout, no response from server.');
304 * Initiates account registration (based on data used for contructor)
308 private function register()
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 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.');
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 private 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...
389 if (isset($xml['stream:stream'][0]['#']['stream:features']))
391 // we already got all info we need
392 $this->features
= $xml['stream:stream'][0]['#'];
396 $this->features
= $this->listen();
399 $second_time = isset($this->session
['id']);
400 $this->session
['id'] = $xml['stream:stream'][0]['@']['id'];
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
);
415 case 'stream:features':
416 // Resource binding after successful authentication
417 if (isset($this->session
['authenticated']))
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>
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
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
) .
468 else if (in_array('ANONYMOUS', $methods))
470 $this->send("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='ANONYMOUS'/>");
475 $this->add_to_log('Error: No authentication method supported.');
480 return $this->response($this->listen());
484 // ok, this is it. bye.
485 $this->add_to_log('Error: Server does not offer SASL authentication.');
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
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);
512 if (isset($decoded['rspauth']))
514 $this->send("<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>");
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';
526 'username' => $this->username
,
527 'response' => $this->encrypt_password(array_merge($decoded, array('nc' => '00000001'))),
528 'charset' => 'utf-8',
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());
548 $this->add_to_log('Error: Server sent "failure".');
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.');
564 socket_set_blocking($this->connection
, $meta['blocked']);
565 $this->session
['tls'] = true;
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());
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());
584 // we are not interested in IQs we did not expect
585 if (!isset($xml['iq'][0]['@']['id']))
590 // multiple possibilities here
591 switch ($xml['iq'][0]['@']['id'])
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'/>
602 return $this->response($this->listen());
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>
619 return $this->response($this->listen());
624 if (isset($xml['iq'][0]['#']['error']))
626 $this->add_to_log('Warning: Registration failed.');
637 $this->add_to_log('Notice: Received unexpected IQ.');
644 // we are only interested in content...
645 if (!isset($xml['message'][0]['#']['body']))
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;
661 // hm...don't know this response
662 $this->add_to_log('Notice: Unknown server response (' . key($xml) . ')');
668 public function send_message($to, $text, $subject = '', $type = 'normal')
670 if (!isset($this->session
['jid']))
675 if (!in_array($type, array('chat', 'normal', 'error', 'groupchat', 'headline')))
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>
688 * Encrypts a password as in RFC 2831
689 * @param array $data Needs data from the client-server connection
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]))
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']);
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
725 * @return array a => b ...
727 private static function parse_data($data)
729 $data = explode(',', $data);
733 foreach ($data as $pair)
735 $dd = strpos($pair, '=');
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), '"');
754 * opposite of jabber::parse_data()
759 private function implode_data($data)
762 foreach ($data as $key => $value)
764 $return[] = $key . '="' . $value . '"';
766 return implode(',', $return);
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')
778 if (substr($data, 0, 5) != '<?xml')
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);
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]['#'];
807 * @author Hans Anderson
808 * @copyright Hans Anderson / http://www.hansanderson.com/php/xml/
810 private static function _xml_depth($vals, &$i)
814 if (isset($vals[$i]['value']))
816 array_push($children, $vals[$i]['value']);
819 while (++
$i < sizeof($vals))
821 switch ($vals[$i]['type'])
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);
838 array_push($children, $vals[$i]['value']);
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'];