includes/functions_jabber.php
author indvdum (gotoindvdum[at]gmail[dot]com)
Sat, 10 Mar 2012 00:53:57 +0400
changeset 17 049ab39a9b9c
parent 0 ceef6d64c21d
permissions -rw-r--r--
Show gamers online everywhere
indvdum@0
     1
<?php
indvdum@0
     2
/**
indvdum@0
     3
*
indvdum@0
     4
* @package phpBB3
indvdum@0
     5
* @version $Id$
indvdum@0
     6
* @copyright (c) 2007 phpBB Group
indvdum@0
     7
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
indvdum@0
     8
*
indvdum@0
     9
*/
indvdum@0
    10
indvdum@0
    11
/**
indvdum@0
    12
* @ignore
indvdum@0
    13
*/
indvdum@0
    14
if (!defined('IN_PHPBB'))
indvdum@0
    15
{
indvdum@0
    16
	exit;
indvdum@0
    17
}
indvdum@0
    18
indvdum@0
    19
/**
indvdum@0
    20
*
indvdum@0
    21
* Jabber class from Flyspray project
indvdum@0
    22
*
indvdum@0
    23
* @version class.jabber2.php 1595 2008-09-19 (0.9.9)
indvdum@0
    24
* @copyright 2006 Flyspray.org
indvdum@0
    25
* @author Florian Schmitz (floele)
indvdum@0
    26
*
indvdum@0
    27
* Only slightly modified by Acyd Burn
indvdum@0
    28
*
indvdum@0
    29
* @package phpBB3
indvdum@0
    30
*/
indvdum@0
    31
class jabber
indvdum@0
    32
{
indvdum@0
    33
	var $connection = null;
indvdum@0
    34
	var $session = array();
indvdum@0
    35
	var $timeout = 10;
indvdum@0
    36
indvdum@0
    37
	var $server;
indvdum@0
    38
	var $connect_server;
indvdum@0
    39
	var $port;
indvdum@0
    40
	var $username;
indvdum@0
    41
	var $password;
indvdum@0
    42
	var $use_ssl;
indvdum@0
    43
	var $resource = 'functions_jabber.phpbb.php';
indvdum@0
    44
indvdum@0
    45
	var $enable_logging;
indvdum@0
    46
	var $log_array;
indvdum@0
    47
indvdum@0
    48
	var $features = array();
indvdum@0
    49
indvdum@0
    50
	/**
indvdum@0
    51
	*/
indvdum@0
    52
	function jabber($server, $port, $username, $password, $use_ssl = false)
indvdum@0
    53
	{
indvdum@0
    54
		$this->connect_server		= ($server) ? $server : 'localhost';
indvdum@0
    55
		$this->port					= ($port) ? $port : 5222;
indvdum@0
    56
indvdum@0
    57
		// Get the server and the username
indvdum@0
    58
		if (strpos($username, '@') === false)
indvdum@0
    59
		{
indvdum@0
    60
			$this->server = $this->connect_server;
indvdum@0
    61
			$this->username = $username;
indvdum@0
    62
		}
indvdum@0
    63
		else
indvdum@0
    64
		{
indvdum@0
    65
			$jid = explode('@', $username, 2);
indvdum@0
    66
indvdum@0
    67
			$this->username = $jid[0];
indvdum@0
    68
			$this->server = $jid[1];
indvdum@0
    69
		}
indvdum@0
    70
indvdum@0
    71
		$this->password				= $password;
indvdum@0
    72
		$this->use_ssl				= ($use_ssl && $this->can_use_ssl()) ? true : false;
indvdum@0
    73
indvdum@0
    74
		// Change port if we use SSL
indvdum@0
    75
		if ($this->port == 5222 && $this->use_ssl)
indvdum@0
    76
		{
indvdum@0
    77
			$this->port = 5223;
indvdum@0
    78
		}
indvdum@0
    79
indvdum@0
    80
		$this->enable_logging		= true;
indvdum@0
    81
		$this->log_array			= array();
indvdum@0
    82
	}
indvdum@0
    83
indvdum@0
    84
	/**
indvdum@0
    85
	* Able to use the SSL functionality?
indvdum@0
    86
	*/
indvdum@0
    87
	function can_use_ssl()
indvdum@0
    88
	{
indvdum@0
    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)
indvdum@0
    90
		return ((version_compare(PHP_VERSION, '5.2.1', '<') || version_compare(PHP_VERSION, '5.2.3RC2', '>=')) && @extension_loaded('openssl')) ? true : false;
indvdum@0
    91
	}
indvdum@0
    92
indvdum@0
    93
	/**
indvdum@0
    94
	* Able to use TLS?
indvdum@0
    95
	*/
indvdum@0
    96
	function can_use_tls()
indvdum@0
    97
	{
indvdum@0
    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'))
indvdum@0
    99
		{
indvdum@0
   100
			return false;
indvdum@0
   101
		}
indvdum@0
   102
indvdum@0
   103
		/**
indvdum@0
   104
		* Make sure the encryption stream is supported
indvdum@0
   105
		* Also seem to work without the crypto stream if correctly compiled
indvdum@0
   106
indvdum@0
   107
		$streams = stream_get_wrappers();
indvdum@0
   108
indvdum@0
   109
		if (!in_array('streams.crypto', $streams))
indvdum@0
   110
		{
indvdum@0
   111
			return false;
indvdum@0
   112
		}
indvdum@0
   113
		*/
indvdum@0
   114
indvdum@0
   115
		return true;
indvdum@0
   116
	}
indvdum@0
   117
indvdum@0
   118
	/**
indvdum@0
   119
	* Sets the resource which is used. No validation is done here, only escaping.
indvdum@0
   120
	* @param string $name
indvdum@0
   121
	* @access public
indvdum@0
   122
	*/
indvdum@0
   123
	function set_resource($name)
indvdum@0
   124
	{
indvdum@0
   125
		$this->resource = $name;
indvdum@0
   126
	}
indvdum@0
   127
indvdum@0
   128
	/**
indvdum@0
   129
	* Connect
indvdum@0
   130
	*/
indvdum@0
   131
	function connect()
indvdum@0
   132
	{
indvdum@0
   133
/*		if (!$this->check_jid($this->username . '@' . $this->server))
indvdum@0
   134
		{
indvdum@0
   135
			$this->add_to_log('Error: Jabber ID is not valid: ' . $this->username . '@' . $this->server);
indvdum@0
   136
			return false;
indvdum@0
   137
		}*/
indvdum@0
   138
indvdum@0
   139
		$this->session['ssl'] = $this->use_ssl;
indvdum@0
   140
indvdum@0
   141
		if ($this->open_socket($this->connect_server, $this->port, $this->use_ssl))
indvdum@0
   142
		{
indvdum@0
   143
			$this->send("<?xml version='1.0' encoding='UTF-8' ?" . ">\n");
indvdum@0
   144
			$this->send("<stream:stream to='{$this->server}' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>\n");
indvdum@0
   145
		}
indvdum@0
   146
		else
indvdum@0
   147
		{
indvdum@0
   148
			$this->add_to_log('Error: connect() #2');
indvdum@0
   149
			return false;
indvdum@0
   150
		}
indvdum@0
   151
indvdum@0
   152
		// Now we listen what the server has to say...and give appropriate responses
indvdum@0
   153
		$this->response($this->listen());
indvdum@0
   154
		return true;
indvdum@0
   155
	}
indvdum@0
   156
indvdum@0
   157
	/**
indvdum@0
   158
	* Disconnect
indvdum@0
   159
	*/
indvdum@0
   160
	function disconnect()
indvdum@0
   161
	{
indvdum@0
   162
		if ($this->connected())
indvdum@0
   163
		{
indvdum@0
   164
			// disconnect gracefully
indvdum@0
   165
			if (isset($this->session['sent_presence']))
indvdum@0
   166
			{
indvdum@0
   167
				$this->send_presence('offline', '', true);
indvdum@0
   168
			}
indvdum@0
   169
indvdum@0
   170
			$this->send('</stream:stream>');
indvdum@0
   171
			$this->session = array();
indvdum@0
   172
			return fclose($this->connection);
indvdum@0
   173
		}
indvdum@0
   174
indvdum@0
   175
		return false;
indvdum@0
   176
	}
indvdum@0
   177
indvdum@0
   178
	/**
indvdum@0
   179
	* Connected?
indvdum@0
   180
	*/
indvdum@0
   181
	function connected()
indvdum@0
   182
	{
indvdum@0
   183
		return (is_resource($this->connection) && !feof($this->connection)) ? true : false;
indvdum@0
   184
	}
indvdum@0
   185
indvdum@0
   186
indvdum@0
   187
	/**
indvdum@0
   188
	* Initiates login (using data from contructor, after calling connect())
indvdum@0
   189
	* @access public
indvdum@0
   190
	* @return bool
indvdum@0
   191
	*/
indvdum@0
   192
	function login()
indvdum@0
   193
	{
indvdum@0
   194
		if (!sizeof($this->features))
indvdum@0
   195
		{
indvdum@0
   196
			$this->add_to_log('Error: No feature information from server available.');
indvdum@0
   197
			return false;
indvdum@0
   198
		}
indvdum@0
   199
indvdum@0
   200
		return $this->response($this->features);
indvdum@0
   201
	}
indvdum@0
   202
indvdum@0
   203
	/**
indvdum@0
   204
	* Send data to the Jabber server
indvdum@0
   205
	* @param string $xml
indvdum@0
   206
	* @access public
indvdum@0
   207
	* @return bool
indvdum@0
   208
	*/
indvdum@0
   209
	function send($xml)
indvdum@0
   210
	{
indvdum@0
   211
		if ($this->connected())
indvdum@0
   212
		{
indvdum@0
   213
			$xml = trim($xml);
indvdum@0
   214
			$this->add_to_log('SEND: '. $xml);
indvdum@0
   215
			return fwrite($this->connection, $xml);
indvdum@0
   216
		}
indvdum@0
   217
		else
indvdum@0
   218
		{
indvdum@0
   219
			$this->add_to_log('Error: Could not send, connection lost (flood?).');
indvdum@0
   220
			return false;
indvdum@0
   221
		}
indvdum@0
   222
	}
indvdum@0
   223
indvdum@0
   224
	/**
indvdum@0
   225
	* OpenSocket
indvdum@0
   226
	* @param string $server host to connect to
indvdum@0
   227
	* @param int $port port number
indvdum@0
   228
	* @param bool $use_ssl use ssl or not
indvdum@0
   229
	* @access public
indvdum@0
   230
	* @return bool
indvdum@0
   231
	*/
indvdum@0
   232
	function open_socket($server, $port, $use_ssl = false)
indvdum@0
   233
	{
indvdum@0
   234
		if (@function_exists('dns_get_record'))
indvdum@0
   235
		{
indvdum@0
   236
			$record = @dns_get_record("_xmpp-client._tcp.$server", DNS_SRV);
indvdum@0
   237
			if (!empty($record) && !empty($record[0]['target']))
indvdum@0
   238
			{
indvdum@0
   239
				$server = $record[0]['target'];
indvdum@0
   240
			}
indvdum@0
   241
		}
indvdum@0
   242
indvdum@0
   243
		$server = $use_ssl ? 'ssl://' . $server : $server;
indvdum@0
   244
indvdum@0
   245
		if ($this->connection = @fsockopen($server, $port, $errorno, $errorstr, $this->timeout))
indvdum@0
   246
		{
indvdum@0
   247
			socket_set_blocking($this->connection, 0);
indvdum@0
   248
			socket_set_timeout($this->connection, 60);
indvdum@0
   249
indvdum@0
   250
			return true;
indvdum@0
   251
		}
indvdum@0
   252
indvdum@0
   253
		// Apparently an error occured...
indvdum@0
   254
		$this->add_to_log('Error: open_socket() - ' . $errorstr);
indvdum@0
   255
		return false;
indvdum@0
   256
	}
indvdum@0
   257
indvdum@0
   258
	/**
indvdum@0
   259
	* Return log
indvdum@0
   260
	*/
indvdum@0
   261
	function get_log()
indvdum@0
   262
	{
indvdum@0
   263
		if ($this->enable_logging && sizeof($this->log_array))
indvdum@0
   264
		{
indvdum@0
   265
			return implode("<br /><br />", $this->log_array);
indvdum@0
   266
		}
indvdum@0
   267
indvdum@0
   268
		return '';
indvdum@0
   269
	}
indvdum@0
   270
indvdum@0
   271
	/**
indvdum@0
   272
	* Add information to log
indvdum@0
   273
	*/
indvdum@0
   274
	function add_to_log($string)
indvdum@0
   275
	{
indvdum@0
   276
		if ($this->enable_logging)
indvdum@0
   277
		{
indvdum@0
   278
			$this->log_array[] = utf8_htmlspecialchars($string);
indvdum@0
   279
		}
indvdum@0
   280
	}
indvdum@0
   281
indvdum@0
   282
	/**
indvdum@0
   283
	* Listens to the connection until it gets data or the timeout is reached.
indvdum@0
   284
	* Thus, it should only be called if data is expected to be received.
indvdum@0
   285
	* @access public
indvdum@0
   286
	* @return mixed either false for timeout or an array with the received data
indvdum@0
   287
	*/
indvdum@0
   288
	function listen($timeout = 10, $wait = false)
indvdum@0
   289
	{
indvdum@0
   290
		if (!$this->connected())
indvdum@0
   291
		{
indvdum@0
   292
			return false;
indvdum@0
   293
		}
indvdum@0
   294
indvdum@0
   295
		// Wait for a response until timeout is reached
indvdum@0
   296
		$start = time();
indvdum@0
   297
		$data = '';
indvdum@0
   298
indvdum@0
   299
		do
indvdum@0
   300
		{
indvdum@0
   301
			$read = trim(fread($this->connection, 4096));
indvdum@0
   302
			$data .= $read;
indvdum@0
   303
		}
indvdum@0
   304
		while (time() <= $start + $timeout && !feof($this->connection) && ($wait || $data == '' || $read != '' || (substr(rtrim($data), -1) != '>')));
indvdum@0
   305
indvdum@0
   306
		if ($data != '')
indvdum@0
   307
		{
indvdum@0
   308
			$this->add_to_log('RECV: '. $data);
indvdum@0
   309
			return $this->xmlize($data);
indvdum@0
   310
		}
indvdum@0
   311
		else
indvdum@0
   312
		{
indvdum@0
   313
			$this->add_to_log('Timeout, no response from server.');
indvdum@0
   314
			return false;
indvdum@0
   315
		}
indvdum@0
   316
	}
indvdum@0
   317
indvdum@0
   318
	/**
indvdum@0
   319
	* Initiates account registration (based on data used for contructor)
indvdum@0
   320
	* @access public
indvdum@0
   321
	* @return bool
indvdum@0
   322
	*/
indvdum@0
   323
	function register()
indvdum@0
   324
	{
indvdum@0
   325
		if (!isset($this->session['id']) || isset($this->session['jid']))
indvdum@0
   326
		{
indvdum@0
   327
			$this->add_to_log('Error: Cannot initiate registration.');
indvdum@0
   328
			return false;
indvdum@0
   329
		}
indvdum@0
   330
indvdum@0
   331
		$this->send("<iq type='get' id='reg_1'><query xmlns='jabber:iq:register'/></iq>");
indvdum@0
   332
		return $this->response($this->listen());
indvdum@0
   333
	}
indvdum@0
   334
indvdum@0
   335
	/**
indvdum@0
   336
	* Sets account presence. No additional info required (default is "online" status)
indvdum@0
   337
	* @param $message online, offline...
indvdum@0
   338
	* @param $type dnd, away, chat, xa or nothing
indvdum@0
   339
	* @param $unavailable set this to true if you want to become unavailable
indvdum@0
   340
	* @access public
indvdum@0
   341
	* @return bool
indvdum@0
   342
	*/
indvdum@0
   343
	function send_presence($message = '', $type = '', $unavailable = false)
indvdum@0
   344
	{
indvdum@0
   345
		if (!isset($this->session['jid']))
indvdum@0
   346
		{
indvdum@0
   347
			$this->add_to_log('ERROR: send_presence() - Cannot set presence at this point, no jid given.');
indvdum@0
   348
			return false;
indvdum@0
   349
		}
indvdum@0
   350
indvdum@0
   351
		$type = strtolower($type);
indvdum@0
   352
		$type = (in_array($type, array('dnd', 'away', 'chat', 'xa'))) ? '<show>'. $type .'</show>' : '';
indvdum@0
   353
indvdum@0
   354
		$unavailable = ($unavailable) ? " type='unavailable'" : '';
indvdum@0
   355
		$message = ($message) ? '<status>' . utf8_htmlspecialchars($message) .'</status>' : '';
indvdum@0
   356
indvdum@0
   357
		$this->session['sent_presence'] = !$unavailable;
indvdum@0
   358
indvdum@0
   359
		return $this->send("<presence$unavailable>" . $type . $message . '</presence>');
indvdum@0
   360
	}
indvdum@0
   361
indvdum@0
   362
	/**
indvdum@0
   363
	* This handles all the different XML elements
indvdum@0
   364
	* @param array $xml
indvdum@0
   365
	* @access public
indvdum@0
   366
	* @return bool
indvdum@0
   367
	*/
indvdum@0
   368
	function response($xml)
indvdum@0
   369
	{
indvdum@0
   370
		if (!is_array($xml) || !sizeof($xml))
indvdum@0
   371
		{
indvdum@0
   372
			return false;
indvdum@0
   373
		}
indvdum@0
   374
indvdum@0
   375
		// did we get multiple elements? do one after another
indvdum@0
   376
		// array('message' => ..., 'presence' => ...)
indvdum@0
   377
		if (sizeof($xml) > 1)
indvdum@0
   378
		{
indvdum@0
   379
			foreach ($xml as $key => $value)
indvdum@0
   380
			{
indvdum@0
   381
				$this->response(array($key => $value));
indvdum@0
   382
			}
indvdum@0
   383
			return;
indvdum@0
   384
		}
indvdum@0
   385
		else
indvdum@0
   386
		{
indvdum@0
   387
			// or even multiple elements of the same type?
indvdum@0
   388
			// array('message' => array(0 => ..., 1 => ...))
indvdum@0
   389
			if (sizeof(reset($xml)) > 1)
indvdum@0
   390
			{
indvdum@0
   391
				foreach (reset($xml) as $value)
indvdum@0
   392
				{
indvdum@0
   393
					$this->response(array(key($xml) => array(0 => $value)));
indvdum@0
   394
				}
indvdum@0
   395
				return;
indvdum@0
   396
			}
indvdum@0
   397
		}
indvdum@0
   398
indvdum@0
   399
		switch (key($xml))
indvdum@0
   400
		{
indvdum@0
   401
			case 'stream:stream':
indvdum@0
   402
				// Connection initialised (or after authentication). Not much to do here...
indvdum@0
   403
indvdum@0
   404
				if (isset($xml['stream:stream'][0]['#']['stream:features']))
indvdum@0
   405
				{
indvdum@0
   406
					// we already got all info we need
indvdum@0
   407
					$this->features = $xml['stream:stream'][0]['#'];
indvdum@0
   408
				}
indvdum@0
   409
				else
indvdum@0
   410
				{
indvdum@0
   411
					$this->features = $this->listen();
indvdum@0
   412
				}
indvdum@0
   413
indvdum@0
   414
				$second_time = isset($this->session['id']);
indvdum@0
   415
				$this->session['id'] = $xml['stream:stream'][0]['@']['id'];
indvdum@0
   416
indvdum@0
   417
				if ($second_time)
indvdum@0
   418
				{
indvdum@0
   419
					// If we are here for the second time after TLS, we need to continue logging in
indvdum@0
   420
					return $this->login();
indvdum@0
   421
				}
indvdum@0
   422
indvdum@0
   423
				// go on with authentication?
indvdum@0
   424
				if (isset($this->features['stream:features'][0]['#']['bind']) || !empty($this->session['tls']))
indvdum@0
   425
				{
indvdum@0
   426
					return $this->response($this->features);
indvdum@0
   427
				}
indvdum@0
   428
			break;
indvdum@0
   429
indvdum@0
   430
			case 'stream:features':
indvdum@0
   431
				// Resource binding after successful authentication
indvdum@0
   432
				if (isset($this->session['authenticated']))
indvdum@0
   433
				{
indvdum@0
   434
					// session required?
indvdum@0
   435
					$this->session['sess_required'] = isset($xml['stream:features'][0]['#']['session']);
indvdum@0
   436
indvdum@0
   437
					$this->send("<iq type='set' id='bind_1'>
indvdum@0
   438
						<bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'>
indvdum@0
   439
							<resource>" . utf8_htmlspecialchars($this->resource) . '</resource>
indvdum@0
   440
						</bind>
indvdum@0
   441
					</iq>');
indvdum@0
   442
					return $this->response($this->listen());
indvdum@0
   443
				}
indvdum@0
   444
indvdum@0
   445
				// Let's use TLS if SSL is not enabled and we can actually use it
indvdum@0
   446
				if (!$this->session['ssl'] && $this->can_use_tls() && $this->can_use_ssl() && isset($xml['stream:features'][0]['#']['starttls']))
indvdum@0
   447
				{
indvdum@0
   448
					$this->add_to_log('Switching to TLS.');
indvdum@0
   449
					$this->send("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>\n");
indvdum@0
   450
					return $this->response($this->listen());
indvdum@0
   451
				}
indvdum@0
   452
indvdum@0
   453
				// Does the server support SASL authentication?
indvdum@0
   454
indvdum@0
   455
				// I hope so, because we do (and no other method).
indvdum@0
   456
				if (isset($xml['stream:features'][0]['#']['mechanisms'][0]['@']['xmlns']) && $xml['stream:features'][0]['#']['mechanisms'][0]['@']['xmlns'] == 'urn:ietf:params:xml:ns:xmpp-sasl')
indvdum@0
   457
				{
indvdum@0
   458
					// Now decide on method
indvdum@0
   459
					$methods = array();
indvdum@0
   460
indvdum@0
   461
					foreach ($xml['stream:features'][0]['#']['mechanisms'][0]['#']['mechanism'] as $value)
indvdum@0
   462
					{
indvdum@0
   463
						$methods[] = $value['#'];
indvdum@0
   464
					}
indvdum@0
   465
indvdum@0
   466
					// we prefer DIGEST-MD5
indvdum@0
   467
					// we don't want to use plain authentication (neither does the server usually) if no encryption is in place
indvdum@0
   468
indvdum@0
   469
					// http://www.xmpp.org/extensions/attic/jep-0078-1.7.html
indvdum@0
   470
					// The plaintext mechanism SHOULD NOT be used unless the underlying stream is encrypted (using SSL or TLS)
indvdum@0
   471
					// and the client has verified that the server certificate is signed by a trusted certificate authority.
indvdum@0
   472
indvdum@0
   473
					if (in_array('DIGEST-MD5', $methods))
indvdum@0
   474
					{
indvdum@0
   475
						$this->send("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='DIGEST-MD5'/>");
indvdum@0
   476
					}
indvdum@0
   477
					else if (in_array('PLAIN', $methods) && ($this->session['ssl'] || !empty($this->session['tls'])))
indvdum@0
   478
					{
indvdum@0
   479
						// http://www.ietf.org/rfc/rfc4616.txt (PLAIN SASL Mechanism)
indvdum@0
   480
						$this->send("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>"
indvdum@0
   481
							. base64_encode($this->username . '@' . $this->server . chr(0) . $this->username . chr(0) . $this->password) .
indvdum@0
   482
							'</auth>');
indvdum@0
   483
					}
indvdum@0
   484
					else if (in_array('ANONYMOUS', $methods))
indvdum@0
   485
					{
indvdum@0
   486
						$this->send("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='ANONYMOUS'/>");
indvdum@0
   487
					}
indvdum@0
   488
					else
indvdum@0
   489
					{
indvdum@0
   490
						// not good...
indvdum@0
   491
						$this->add_to_log('Error: No authentication method supported.');
indvdum@0
   492
						$this->disconnect();
indvdum@0
   493
						return false;
indvdum@0
   494
					}
indvdum@0
   495
indvdum@0
   496
					return $this->response($this->listen());
indvdum@0
   497
				}
indvdum@0
   498
				else
indvdum@0
   499
				{
indvdum@0
   500
					// ok, this is it. bye.
indvdum@0
   501
					$this->add_to_log('Error: Server does not offer SASL authentication.');
indvdum@0
   502
					$this->disconnect();
indvdum@0
   503
					return false;
indvdum@0
   504
				}
indvdum@0
   505
			break;
indvdum@0
   506
indvdum@0
   507
			case 'challenge':
indvdum@0
   508
				// continue with authentication...a challenge literally -_-
indvdum@0
   509
				$decoded = base64_decode($xml['challenge'][0]['#']);
indvdum@0
   510
				$decoded = $this->parse_data($decoded);
indvdum@0
   511
indvdum@0
   512
				if (!isset($decoded['digest-uri']))
indvdum@0
   513
				{
indvdum@0
   514
					$decoded['digest-uri'] = 'xmpp/'. $this->server;
indvdum@0
   515
				}
indvdum@0
   516
indvdum@0
   517
				// better generate a cnonce, maybe it's needed
indvdum@0
   518
				$decoded['cnonce'] = base64_encode(md5(uniqid(mt_rand(), true)));
indvdum@0
   519
indvdum@0
   520
				// second challenge?
indvdum@0
   521
				if (isset($decoded['rspauth']))
indvdum@0
   522
				{
indvdum@0
   523
					$this->send("<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>");
indvdum@0
   524
				}
indvdum@0
   525
				else
indvdum@0
   526
				{
indvdum@0
   527
					// Make sure we only use 'auth' for qop (relevant for $this->encrypt_password())
indvdum@0
   528
					// If the <response> is choking up on the changed parameter we may need to adjust encrypt_password() directly
indvdum@0
   529
					if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false)
indvdum@0
   530
					{
indvdum@0
   531
						$decoded['qop'] = 'auth';
indvdum@0
   532
					}
indvdum@0
   533
indvdum@0
   534
					$response = array(
indvdum@0
   535
						'username'	=> $this->username,
indvdum@0
   536
						'response'	=> $this->encrypt_password(array_merge($decoded, array('nc' => '00000001'))),
indvdum@0
   537
						'charset'	=> 'utf-8',
indvdum@0
   538
						'nc'		=> '00000001',
indvdum@0
   539
						'qop'		=> 'auth',			// only auth being supported
indvdum@0
   540
					);
indvdum@0
   541
indvdum@0
   542
					foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key)
indvdum@0
   543
					{
indvdum@0
   544
						if (isset($decoded[$key]))
indvdum@0
   545
						{
indvdum@0
   546
							$response[$key] = $decoded[$key];
indvdum@0
   547
						}
indvdum@0
   548
					}
indvdum@0
   549
indvdum@0
   550
					$this->send("<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>" . base64_encode($this->implode_data($response)) . '</response>');
indvdum@0
   551
				}
indvdum@0
   552
indvdum@0
   553
				return $this->response($this->listen());
indvdum@0
   554
			break;
indvdum@0
   555
indvdum@0
   556
			case 'failure':
indvdum@0
   557
				$this->add_to_log('Error: Server sent "failure".');
indvdum@0
   558
				$this->disconnect();
indvdum@0
   559
				return false;
indvdum@0
   560
			break;
indvdum@0
   561
indvdum@0
   562
			case 'proceed':
indvdum@0
   563
				// continue switching to TLS
indvdum@0
   564
				$meta = stream_get_meta_data($this->connection);
indvdum@0
   565
				socket_set_blocking($this->connection, 1);
indvdum@0
   566
indvdum@0
   567
				if (!stream_socket_enable_crypto($this->connection, true, STREAM_CRYPTO_METHOD_TLS_CLIENT))
indvdum@0
   568
				{
indvdum@0
   569
					$this->add_to_log('Error: TLS mode change failed.');
indvdum@0
   570
					return false;
indvdum@0
   571
				}
indvdum@0
   572
indvdum@0
   573
				socket_set_blocking($this->connection, $meta['blocked']);
indvdum@0
   574
				$this->session['tls'] = true;
indvdum@0
   575
indvdum@0
   576
				// new stream
indvdum@0
   577
				$this->send("<?xml version='1.0' encoding='UTF-8' ?" . ">\n");
indvdum@0
   578
				$this->send("<stream:stream to='{$this->server}' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>\n");
indvdum@0
   579
indvdum@0
   580
				return $this->response($this->listen());
indvdum@0
   581
			break;
indvdum@0
   582
indvdum@0
   583
			case 'success':
indvdum@0
   584
				// Yay, authentication successful.
indvdum@0
   585
				$this->send("<stream:stream to='{$this->server}' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>\n");
indvdum@0
   586
				$this->session['authenticated'] = true;
indvdum@0
   587
indvdum@0
   588
				// we have to wait for another response
indvdum@0
   589
				return $this->response($this->listen());
indvdum@0
   590
			break;
indvdum@0
   591
indvdum@0
   592
			case 'iq':
indvdum@0
   593
				// we are not interested in IQs we did not expect
indvdum@0
   594
				if (!isset($xml['iq'][0]['@']['id']))
indvdum@0
   595
				{
indvdum@0
   596
					return false;
indvdum@0
   597
				}
indvdum@0
   598
indvdum@0
   599
				// multiple possibilities here
indvdum@0
   600
				switch ($xml['iq'][0]['@']['id'])
indvdum@0
   601
				{
indvdum@0
   602
					case 'bind_1':
indvdum@0
   603
						$this->session['jid'] = $xml['iq'][0]['#']['bind'][0]['#']['jid'][0]['#'];
indvdum@0
   604
indvdum@0
   605
						// and (maybe) yet another request to be able to send messages *finally*
indvdum@0
   606
						if ($this->session['sess_required'])
indvdum@0
   607
						{
indvdum@0
   608
							$this->send("<iq to='{$this->server}' type='set' id='sess_1'>
indvdum@0
   609
								<session xmlns='urn:ietf:params:xml:ns:xmpp-session'/>
indvdum@0
   610
								</iq>");
indvdum@0
   611
							return $this->response($this->listen());
indvdum@0
   612
						}
indvdum@0
   613
indvdum@0
   614
						return true;
indvdum@0
   615
					break;
indvdum@0
   616
indvdum@0
   617
					case 'sess_1':
indvdum@0
   618
						return true;
indvdum@0
   619
					break;
indvdum@0
   620
indvdum@0
   621
					case 'reg_1':
indvdum@0
   622
						$this->send("<iq type='set' id='reg_2'>
indvdum@0
   623
								<query xmlns='jabber:iq:register'>
indvdum@0
   624
									<username>" . utf8_htmlspecialchars($this->username) . "</username>
indvdum@0
   625
									<password>" . utf8_htmlspecialchars($this->password) . "</password>
indvdum@0
   626
								</query>
indvdum@0
   627
							</iq>");
indvdum@0
   628
						return $this->response($this->listen());
indvdum@0
   629
					break;
indvdum@0
   630
indvdum@0
   631
					case 'reg_2':
indvdum@0
   632
						// registration end
indvdum@0
   633
						if (isset($xml['iq'][0]['#']['error']))
indvdum@0
   634
						{
indvdum@0
   635
							$this->add_to_log('Warning: Registration failed.');
indvdum@0
   636
							return false;
indvdum@0
   637
						}
indvdum@0
   638
						return true;
indvdum@0
   639
					break;
indvdum@0
   640
indvdum@0
   641
					case 'unreg_1':
indvdum@0
   642
						return true;
indvdum@0
   643
					break;
indvdum@0
   644
indvdum@0
   645
					default:
indvdum@0
   646
						$this->add_to_log('Notice: Received unexpected IQ.');
indvdum@0
   647
						return false;
indvdum@0
   648
					break;
indvdum@0
   649
				}
indvdum@0
   650
			break;
indvdum@0
   651
indvdum@0
   652
			case 'message':
indvdum@0
   653
				// we are only interested in content...
indvdum@0
   654
				if (!isset($xml['message'][0]['#']['body']))
indvdum@0
   655
				{
indvdum@0
   656
					return false;
indvdum@0
   657
				}
indvdum@0
   658
indvdum@0
   659
				$message['body'] = $xml['message'][0]['#']['body'][0]['#'];
indvdum@0
   660
				$message['from'] = $xml['message'][0]['@']['from'];
indvdum@0
   661
indvdum@0
   662
				if (isset($xml['message'][0]['#']['subject']))
indvdum@0
   663
				{
indvdum@0
   664
					$message['subject'] = $xml['message'][0]['#']['subject'][0]['#'];
indvdum@0
   665
				}
indvdum@0
   666
				$this->session['messages'][] = $message;
indvdum@0
   667
			break;
indvdum@0
   668
indvdum@0
   669
			default:
indvdum@0
   670
				// hm...don't know this response
indvdum@0
   671
				$this->add_to_log('Notice: Unknown server response (' . key($xml) . ')');
indvdum@0
   672
				return false;
indvdum@0
   673
			break;
indvdum@0
   674
		}
indvdum@0
   675
	}
indvdum@0
   676
indvdum@0
   677
	function send_message($to, $text, $subject = '', $type = 'normal')
indvdum@0
   678
	{
indvdum@0
   679
		if (!isset($this->session['jid']))
indvdum@0
   680
		{
indvdum@0
   681
			return false;
indvdum@0
   682
		}
indvdum@0
   683
indvdum@0
   684
		if (!in_array($type, array('chat', 'normal', 'error', 'groupchat', 'headline')))
indvdum@0
   685
		{
indvdum@0
   686
			$type = 'normal';
indvdum@0
   687
		}
indvdum@0
   688
indvdum@0
   689
		return $this->send("<message from='" . utf8_htmlspecialchars($this->session['jid']) . "' to='" . utf8_htmlspecialchars($to) . "' type='$type' id='" . uniqid('msg') . "'>
indvdum@0
   690
			<subject>" . utf8_htmlspecialchars($subject) . "</subject>
indvdum@0
   691
			<body>" . utf8_htmlspecialchars($text) . "</body>
indvdum@0
   692
			</message>"
indvdum@0
   693
		);
indvdum@0
   694
	}
indvdum@0
   695
indvdum@0
   696
	/**
indvdum@0
   697
	* Encrypts a password as in RFC 2831
indvdum@0
   698
	* @param array $data Needs data from the client-server connection
indvdum@0
   699
	* @access public
indvdum@0
   700
	* @return string
indvdum@0
   701
	*/
indvdum@0
   702
	function encrypt_password($data)
indvdum@0
   703
	{
indvdum@0
   704
		// let's me think about <challenge> again...
indvdum@0
   705
		foreach (array('realm', 'cnonce', 'digest-uri') as $key)
indvdum@0
   706
		{
indvdum@0
   707
			if (!isset($data[$key]))
indvdum@0
   708
			{
indvdum@0
   709
				$data[$key] = '';
indvdum@0
   710
			}
indvdum@0
   711
		}
indvdum@0
   712
indvdum@0
   713
		$pack = md5($this->username . ':' . $data['realm'] . ':' . $this->password);
indvdum@0
   714
indvdum@0
   715
		if (isset($data['authzid']))
indvdum@0
   716
		{
indvdum@0
   717
			$a1 = pack('H32', $pack)  . sprintf(':%s:%s:%s', $data['nonce'], $data['cnonce'], $data['authzid']);
indvdum@0
   718
		}
indvdum@0
   719
		else
indvdum@0
   720
		{
indvdum@0
   721
			$a1 = pack('H32', $pack)  . sprintf(':%s:%s', $data['nonce'], $data['cnonce']);
indvdum@0
   722
		}
indvdum@0
   723
indvdum@0
   724
		// should be: qop = auth
indvdum@0
   725
		$a2 = 'AUTHENTICATE:'. $data['digest-uri'];
indvdum@0
   726
indvdum@0
   727
		return md5(sprintf('%s:%s:%s:%s:%s:%s', md5($a1), $data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], md5($a2)));
indvdum@0
   728
	}
indvdum@0
   729
indvdum@0
   730
	/**
indvdum@0
   731
	* parse_data like a="b",c="d",... or like a="a, b", c, d="e", f=g,...
indvdum@0
   732
	* @param string $data
indvdum@0
   733
	* @access public
indvdum@0
   734
	* @return array a => b ...
indvdum@0
   735
	*/
indvdum@0
   736
	function parse_data($data)
indvdum@0
   737
	{
indvdum@0
   738
		$data = explode(',', $data);
indvdum@0
   739
		$pairs = array();
indvdum@0
   740
		$key = false;
indvdum@0
   741
indvdum@0
   742
		foreach ($data as $pair)
indvdum@0
   743
		{
indvdum@0
   744
			$dd = strpos($pair, '=');
indvdum@0
   745
indvdum@0
   746
			if ($dd)
indvdum@0
   747
			{
indvdum@0
   748
				$key = trim(substr($pair, 0, $dd));
indvdum@0
   749
				$pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"');
indvdum@0
   750
			}
indvdum@0
   751
			else if (strpos(strrev(trim($pair)), '"') === 0 && $key)
indvdum@0
   752
			{
indvdum@0
   753
				// We are actually having something left from "a, b" values, add it to the last one we handled.
indvdum@0
   754
				$pairs[$key] .= ',' . trim(trim($pair), '"');
indvdum@0
   755
				continue;
indvdum@0
   756
			}
indvdum@0
   757
		}
indvdum@0
   758
indvdum@0
   759
		return $pairs;
indvdum@0
   760
	}
indvdum@0
   761
indvdum@0
   762
	/**
indvdum@0
   763
	* opposite of jabber::parse_data()
indvdum@0
   764
	* @param array $data
indvdum@0
   765
	* @access public
indvdum@0
   766
	* @return string
indvdum@0
   767
	*/
indvdum@0
   768
	function implode_data($data)
indvdum@0
   769
	{
indvdum@0
   770
		$return = array();
indvdum@0
   771
		foreach ($data as $key => $value)
indvdum@0
   772
		{
indvdum@0
   773
			$return[] = $key . '="' . $value . '"';
indvdum@0
   774
		}
indvdum@0
   775
		return implode(',', $return);
indvdum@0
   776
	}
indvdum@0
   777
indvdum@0
   778
	/**
indvdum@0
   779
	* xmlize()
indvdum@0
   780
	* @author Hans Anderson
indvdum@0
   781
	* @copyright Hans Anderson / http://www.hansanderson.com/php/xml/
indvdum@0
   782
	*/
indvdum@0
   783
	function xmlize($data, $skip_white = 1, $encoding = 'UTF-8')
indvdum@0
   784
	{
indvdum@0
   785
		$data = trim($data);
indvdum@0
   786
indvdum@0
   787
		if (substr($data, 0, 5) != '<?xml')
indvdum@0
   788
		{
indvdum@0
   789
			// mod
indvdum@0
   790
			$data = '<root>'. $data . '</root>';
indvdum@0
   791
		}
indvdum@0
   792
indvdum@0
   793
		$vals = $index = $array = array();
indvdum@0
   794
		$parser = xml_parser_create($encoding);
indvdum@0
   795
		xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
indvdum@0
   796
		xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, $skip_white);
indvdum@0
   797
		xml_parse_into_struct($parser, $data, $vals, $index);
indvdum@0
   798
		xml_parser_free($parser);
indvdum@0
   799
indvdum@0
   800
		$i = 0;
indvdum@0
   801
		$tagname = $vals[$i]['tag'];
indvdum@0
   802
indvdum@0
   803
		$array[$tagname][0]['@'] = (isset($vals[$i]['attributes'])) ? $vals[$i]['attributes'] : array();
indvdum@0
   804
		$array[$tagname][0]['#'] = $this->_xml_depth($vals, $i);
indvdum@0
   805
indvdum@0
   806
		if (substr($data, 0, 5) != '<?xml')
indvdum@0
   807
		{
indvdum@0
   808
			$array = $array['root'][0]['#'];
indvdum@0
   809
		}
indvdum@0
   810
indvdum@0
   811
		return $array;
indvdum@0
   812
	}
indvdum@0
   813
indvdum@0
   814
	/**
indvdum@0
   815
	* _xml_depth()
indvdum@0
   816
	* @author Hans Anderson
indvdum@0
   817
	* @copyright Hans Anderson / http://www.hansanderson.com/php/xml/
indvdum@0
   818
	*/
indvdum@0
   819
	function _xml_depth($vals, &$i)
indvdum@0
   820
	{
indvdum@0
   821
		$children = array();
indvdum@0
   822
indvdum@0
   823
		if (isset($vals[$i]['value']))
indvdum@0
   824
		{
indvdum@0
   825
			array_push($children, $vals[$i]['value']);
indvdum@0
   826
		}
indvdum@0
   827
indvdum@0
   828
		while (++$i < sizeof($vals))
indvdum@0
   829
		{
indvdum@0
   830
			switch ($vals[$i]['type'])
indvdum@0
   831
			{
indvdum@0
   832
				case 'open':
indvdum@0
   833
indvdum@0
   834
					$tagname = (isset($vals[$i]['tag'])) ? $vals[$i]['tag'] : '';
indvdum@0
   835
					$size = (isset($children[$tagname])) ? sizeof($children[$tagname]) : 0;
indvdum@0
   836
indvdum@0
   837
					if (isset($vals[$i]['attributes']))
indvdum@0
   838
					{
indvdum@0
   839
						$children[$tagname][$size]['@'] = $vals[$i]['attributes'];
indvdum@0
   840
					}
indvdum@0
   841
indvdum@0
   842
					$children[$tagname][$size]['#'] = $this->_xml_depth($vals, $i);
indvdum@0
   843
indvdum@0
   844
				break;
indvdum@0
   845
indvdum@0
   846
				case 'cdata':
indvdum@0
   847
					array_push($children, $vals[$i]['value']);
indvdum@0
   848
				break;
indvdum@0
   849
indvdum@0
   850
				case 'complete':
indvdum@0
   851
indvdum@0
   852
					$tagname = $vals[$i]['tag'];
indvdum@0
   853
					$size = (isset($children[$tagname])) ? sizeof($children[$tagname]) : 0;
indvdum@0
   854
					$children[$tagname][$size]['#'] = (isset($vals[$i]['value'])) ? $vals[$i]['value'] : array();
indvdum@0
   855
indvdum@0
   856
					if (isset($vals[$i]['attributes']))
indvdum@0
   857
					{
indvdum@0
   858
						$children[$tagname][$size]['@'] = $vals[$i]['attributes'];
indvdum@0
   859
					}
indvdum@0
   860
indvdum@0
   861
				break;
indvdum@0
   862
indvdum@0
   863
				case 'close':
indvdum@0
   864
					return $children;
indvdum@0
   865
				break;
indvdum@0
   866
			}
indvdum@0
   867
		}
indvdum@0
   868
indvdum@0
   869
		return $children;
indvdum@0
   870
	}
indvdum@0
   871
}
indvdum@0
   872
indvdum@0
   873
?>