[ Index ]

PHP Cross Reference of phpBB-3.2.2-deutsch

title

Body

[close]

/includes/ -> functions_jabber.php (source)

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


Generated: Thu Jan 11 23:14:31 2018 Cross-referenced by PHPXref 0.7.1