3 * XMPPHP: The PHP XMPP Library
4 * Copyright (C) 2008 Nathanael C. Fritz
5 * This file is part of SleekXMPP.
7 * XMPPHP is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * XMPPHP is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with XMPPHP; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
23 * @author Nathanael C. Fritz <JID: fritzy@netflint.net>
24 * @author Stephan Wentz <JID: stephan@jabber.wentz.it>
25 * @author Michael Garvin <JID: gar@netflint.net>
26 * @copyright 2008 Nathanael C. Fritz
29 /** XMPPHP_Exception */
30 require_once dirname(__FILE__) . '/Exception.php';
33 require_once dirname(__FILE__) . '/XMLObj.php';
36 require_once dirname(__FILE__) . '/Log.php';
43 * @author Nathanael C. Fritz <JID: fritzy@netflint.net>
44 * @author Stephan Wentz <JID: stephan@jabber.wentz.it>
45 * @author Michael Garvin <JID: gar@netflint.net>
46 * @copyright 2008 Nathanael C. Fritz
49 class XMPPHP_XMLStream {
65 protected $xml_depth = 0;
77 protected $stream_start = '<stream>';
81 protected $stream_end = '</stream>';
85 protected $disconnected = false;
89 protected $sent_disconnect = false;
93 protected $ns_map = array();
97 protected $current_ns = array();
101 protected $xmlobj = null;
105 protected $nshandlers = array();
109 protected $xpathhandlers = array();
113 protected $idhandlers = array();
117 protected $eventhandlers = array();
121 protected $lastid = 0;
125 protected $default_ns;
129 protected $until = '';
133 protected $until_count = '';
137 protected $until_happened = false;
141 protected $until_payload = array();
149 protected $reconnect = true;
153 protected $been_reset = false;
157 protected $is_server;
161 protected $last_send = 0;
165 protected $use_ssl = false;
169 protected $reconnectTimeout = 30;
174 * @param string $host
175 * @param string $port
176 * @param boolean $printlog
177 * @param string $loglevel
178 * @param boolean $is_server
180 public function __construct($host = null, $port = null, $printlog = false, $loglevel = null, $is_server = false) {
181 $this->reconnect = !$is_server;
182 $this->is_server = $is_server;
185 $this->setupParser();
186 $this->log = new XMPPHP_Log($printlog, $loglevel);
193 public function __destruct() {
194 if(!$this->disconnected && $this->socket) {
200 * Return the log instance
204 public function getLog() {
213 public function getId() {
215 return $this->lastid;
223 public function useSSL($use=true) {
224 $this->use_ssl = $use;
231 * @param string $pointer
234 public function addIdHandler($id, $pointer, $obj = null) {
235 $this->idhandlers[$id] = array($pointer, $obj);
241 * @param string $name
243 * @param string $pointer
245 * @param integer $depth
247 public function addHandler($name, $ns, $pointer, $obj = null, $depth = 1) {
248 #TODO deprication warning
249 $this->nshandlers[] = array($name,$ns,$pointer,$obj, $depth);
255 * @param string $xpath
256 * @param string $pointer
259 public function addXPathHandler($xpath, $pointer, $obj = null) {
260 if (preg_match_all("/\(?{[^\}]+}\)?(\/?)[^\/]+/", $xpath, $regs)) {
263 $ns_tags = array($xpath);
265 foreach($ns_tags as $ns_tag) {
266 list($l, $r) = split("}", $ns_tag);
268 $xpart = array(substr($l, 1), $r);
270 $xpart = array(null, $l);
272 $xpath_array[] = $xpart;
274 $this->xpathhandlers[] = array($xpath_array, $pointer, $obj);
281 * @param string $pointer
284 public function addEventHandler($name, $pointer, $obj) {
285 $this->eventhandlers[] = array($name, $pointer, $obj);
289 * Connect to XMPP Host
291 * @param integer $timeout
292 * @param boolean $persistent
293 * @param boolean $sendinit
295 public function connect($timeout = 30, $persistent = false, $sendinit = true) {
296 $this->sent_disconnect = false;
300 $this->disconnected = false;
301 $this->sent_disconnect = false;
303 $conflag = STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT;
305 $conflag = STREAM_CLIENT_CONNECT;
308 if($this->use_ssl) $conntype = 'ssl';
309 $this->log->log("Connecting to $conntype://{$this->host}:{$this->port}");
311 $this->socket = @stream_socket_client("$conntype://{$this->host}:{$this->port}", $errno, $errstr, $timeout, $conflag);
312 } catch (Exception $e) {
313 throw new XMPPHP_Exception($e->getMessage());
316 $this->log->log("Could not connect.", XMPPHP_Log::LEVEL_ERROR);
317 $this->disconnected = true;
318 # Take it easy for a few seconds
319 sleep(min($timeout, 5));
321 } while (!$this->socket && (time() - $starttime) < $timeout);
324 stream_set_blocking($this->socket, 1);
325 if($sendinit) $this->send($this->stream_start);
327 throw new XMPPHP_Exception("Could not connect before timeout.");
332 * Reconnect XMPP Host
334 public function doReconnect() {
335 if(!$this->is_server) {
336 $this->log->log("Reconnecting ($this->reconnectTimeout)...", XMPPHP_Log::LEVEL_WARNING);
337 $this->connect($this->reconnectTimeout, false, false);
339 $this->event('reconnect');
343 public function setReconnectTimeout($timeout) {
344 $this->reconnectTimeout = $timeout;
348 * Disconnect from XMPP Host
350 public function disconnect() {
351 $this->log->log("Disconnecting...", XMPPHP_Log::LEVEL_VERBOSE);
352 if(false == (bool) $this->socket) {
355 $this->reconnect = false;
356 $this->send($this->stream_end);
357 $this->sent_disconnect = true;
358 $this->processUntil('end_stream', 5);
359 $this->disconnected = true;
363 * Are we are disconnected?
367 public function isDisconnected() {
368 return $this->disconnected;
373 * 0 -> only read if data is immediately ready
374 * NULL -> wait forever and ever
375 * integer -> process for this amount of time
378 private function __process($maximum=5) {
380 $remaining = $maximum;
383 $starttime = (microtime(true) * 1000000);
384 $read = array($this->socket);
387 if (is_null($maximum)) {
390 } else if ($maximum == 0) {
394 $usecs = $remaining % 1000000;
395 $secs = floor(($remaining - $usecs) / 1000000);
397 $updated = @stream_select($read, $write, $except, $secs, $usecs);
398 if ($updated === false) {
399 $this->log->log("Error on stream_select()", XMPPHP_Log::LEVEL_VERBOSE);
400 if ($this->reconnect) {
401 $this->doReconnect();
403 fclose($this->socket);
404 $this->socket = NULL;
407 } else if ($updated > 0) {
408 # XXX: Is this big enough?
409 $buff = @fread($this->socket, 4096);
411 if($this->reconnect) {
412 $this->doReconnect();
414 fclose($this->socket);
415 $this->socket = NULL;
419 $this->log->log("RECV: $buff", XMPPHP_Log::LEVEL_VERBOSE);
420 $ok = xml_parse($this->parser, $buff, false);
422 $errcode = xml_get_error_code($this->parser);
423 $errstr = xml_error_string($errcode);
424 $this->log->log("XML ERROR: $errstr", XMPPHP_Log::LEVEL_VERBOSE);
427 # $updated == 0 means no changes during timeout.
429 $endtime = (microtime(true)*1000000);
430 $time_past = $endtime - $starttime;
431 $remaining = $remaining - $time_past;
432 } while (is_null($maximum) || $remaining > 0);
441 public function process() {
442 $this->__process(NULL);
446 * Process until a timeout occurs
448 * @param integer $timeout
451 public function processTime($timeout=NULL) {
452 if (is_null($timeout)) {
453 return $this->__process(NULL);
455 return $this->__process($timeout * 1000000);
460 * Process until a specified event or a timeout occurs
462 * @param string|array $event
463 * @param integer $timeout
466 public function processUntil($event, $timeout=-1) {
468 if(!is_array($event)) $event = array($event);
469 $this->until[] = $event;
471 $event_key = key($this->until);
473 $this->until_count[$event_key] = 0;
475 while(!$this->disconnected and $this->until_count[$event_key] < 1 and (time() - $start < $timeout or $timeout == -1)) {
478 if(array_key_exists($event_key, $this->until_payload)) {
479 $payload = $this->until_payload[$event_key];
480 unset($this->until_payload[$event_key]);
481 unset($this->until_count[$event_key]);
482 unset($this->until[$event_key]);
492 public function Xapply_socket($socket) {
493 $this->socket = $socket;
499 * @see xml_set_element_handler
501 * @param resource $parser
502 * @param string $name
504 public function startXML($parser, $name, $attr) {
505 if($this->been_reset) {
506 $this->been_reset = false;
507 $this->xml_depth = 0;
510 if(array_key_exists('XMLNS', $attr)) {
511 $this->current_ns[$this->xml_depth] = $attr['XMLNS'];
513 $this->current_ns[$this->xml_depth] = $this->current_ns[$this->xml_depth - 1];
514 if(!$this->current_ns[$this->xml_depth]) $this->current_ns[$this->xml_depth] = $this->default_ns;
516 $ns = $this->current_ns[$this->xml_depth];
517 foreach($attr as $key => $value) {
518 if(strstr($key, ":")) {
519 $key = explode(':', $key);
521 $this->ns_map[$key] = $value;
524 if(!strstr($name, ":") === false)
526 $name = explode(':', $name);
527 $ns = $this->ns_map[$name[0]];
530 $obj = new XMPPHP_XMLObj($name, $ns, $attr);
531 if($this->xml_depth > 1) {
532 $this->xmlobj[$this->xml_depth - 1]->subs[] = $obj;
534 $this->xmlobj[$this->xml_depth] = $obj;
540 * @see xml_set_element_handler
542 * @param resource $parser
543 * @param string $name
545 public function endXML($parser, $name) {
546 #$this->log->log("Ending $name", XMPPHP_Log::LEVEL_DEBUG);
548 if($this->been_reset) {
549 $this->been_reset = false;
550 $this->xml_depth = 0;
553 if($this->xml_depth == 1) {
554 #clean-up old objects
555 #$found = false; #FIXME This didn't appear to be in use --Gar
556 foreach($this->xpathhandlers as $handler) {
557 if (is_array($this->xmlobj) && array_key_exists(2, $this->xmlobj)) {
558 $searchxml = $this->xmlobj[2];
559 $nstag = array_shift($handler[0]);
560 if (($nstag[0] == null or $searchxml->ns == $nstag[0]) and ($nstag[1] == "*" or $nstag[1] == $searchxml->name)) {
561 foreach($handler[0] as $nstag) {
562 if ($searchxml !== null and $searchxml->hasSub($nstag[1], $ns=$nstag[0])) {
563 $searchxml = $searchxml->sub($nstag[1], $ns=$nstag[0]);
569 if ($searchxml !== null) {
570 if($handler[2] === null) $handler[2] = $this;
571 $this->log->log("Calling {$handler[1]}", XMPPHP_Log::LEVEL_DEBUG);
572 $handler[2]->$handler[1]($this->xmlobj[2]);
577 foreach($this->nshandlers as $handler) {
578 if($handler[4] != 1 and array_key_exists(2, $this->xmlobj) and $this->xmlobj[2]->hasSub($handler[0])) {
579 $searchxml = $this->xmlobj[2]->sub($handler[0]);
580 } elseif(is_array($this->xmlobj) and array_key_exists(2, $this->xmlobj)) {
581 $searchxml = $this->xmlobj[2];
583 if($searchxml !== null and $searchxml->name == $handler[0] and ($searchxml->ns == $handler[1] or (!$handler[1] and $searchxml->ns == $this->default_ns))) {
584 if($handler[3] === null) $handler[3] = $this;
585 $this->log->log("Calling {$handler[2]}", XMPPHP_Log::LEVEL_DEBUG);
586 $handler[3]->$handler[2]($this->xmlobj[2]);
589 foreach($this->idhandlers as $id => $handler) {
590 if(array_key_exists('id', $this->xmlobj[2]->attrs) and $this->xmlobj[2]->attrs['id'] == $id) {
591 if($handler[1] === null) $handler[1] = $this;
592 $handler[1]->$handler[0]($this->xmlobj[2]);
593 #id handlers are only used once
594 unset($this->idhandlers[$id]);
598 if(is_array($this->xmlobj)) {
599 $this->xmlobj = array_slice($this->xmlobj, 0, 1);
600 if(isset($this->xmlobj[0]) && $this->xmlobj[0] instanceof XMPPHP_XMLObj) {
601 $this->xmlobj[0]->subs = null;
604 unset($this->xmlobj[2]);
606 if($this->xml_depth == 0 and !$this->been_reset) {
607 if(!$this->disconnected) {
608 if(!$this->sent_disconnect) {
609 $this->send($this->stream_end);
611 $this->disconnected = true;
612 $this->sent_disconnect = true;
613 fclose($this->socket);
614 if($this->reconnect) {
615 $this->doReconnect();
618 $this->event('end_stream');
623 * XML character callback
624 * @see xml_set_character_data_handler
626 * @param resource $parser
627 * @param string $data
629 public function charXML($parser, $data) {
630 if(array_key_exists($this->xml_depth, $this->xmlobj)) {
631 $this->xmlobj[$this->xml_depth]->data .= $data;
638 * @param string $name
639 * @param string $payload
641 public function event($name, $payload = null) {
642 $this->log->log("EVENT: $name", XMPPHP_Log::LEVEL_DEBUG);
643 foreach($this->eventhandlers as $handler) {
644 if($name == $handler[0]) {
645 if($handler[2] === null) {
648 $handler[2]->$handler[1]($payload);
651 foreach($this->until as $key => $until) {
652 if(is_array($until)) {
653 if(in_array($name, $until)) {
654 $this->until_payload[$key][] = array($name, $payload);
655 if(!isset($this->until_count[$key])) {
656 $this->until_count[$key] = 0;
658 $this->until_count[$key] += 1;
659 #$this->until[$key] = false;
668 public function read() {
669 $buff = @fread($this->socket, 1024);
671 if($this->reconnect) {
672 $this->doReconnect();
674 fclose($this->socket);
678 $this->log->log("RECV: $buff", XMPPHP_Log::LEVEL_VERBOSE);
679 $ok = xml_parse($this->parser, $buff, false);
681 $errcode = xml_get_error_code($this->parser);
682 $errstr = xml_error_string($errcode);
683 $this->log->log("XML ERROR: $errstr", XMPPHP_Log::LEVEL_VERBOSE);
692 public function send($msg, $timeout=NULL) {
694 if (is_null($timeout)) {
697 } else if ($timeout == 0) {
701 $maximum = $timeout * 1000000;
702 $usecs = $maximum % 1000000;
703 $secs = floor(($maximum - $usecs) / 1000000);
707 $write = array($this->socket);
710 $select = @stream_select($read, $write, $except, $secs, $usecs);
712 if($select === False) {
713 $this->log->log("ERROR sending message; reconnecting.");
714 $this->doReconnect();
715 # TODO: retry send here
717 } elseif ($select > 0) {
718 $this->log->log("Socket is ready; send it.", XMPPHP_Log::LEVEL_VERBOSE);
720 $this->log->log("Socket is not ready; break.", XMPPHP_Log::LEVEL_ERROR);
724 $sentbytes = @fwrite($this->socket, $msg);
725 $this->log->log("SENT: " . mb_substr($msg, 0, $sentbytes, '8bit'), XMPPHP_Log::LEVEL_VERBOSE);
726 if($sentbytes === FALSE) {
727 $this->log->log("ERROR sending message; reconnecting.", XMPPHP_Log::LEVEL_ERROR);
728 $this->doReconnect();
731 $this->log->log("Successfully sent $sentbytes bytes.", XMPPHP_Log::LEVEL_VERBOSE);
735 public function time() {
736 list($usec, $sec) = explode(" ", microtime());
737 return (float)$sec + (float)$usec;
743 public function reset() {
744 $this->xml_depth = 0;
745 unset($this->xmlobj);
746 $this->xmlobj = array();
747 $this->setupParser();
748 if(!$this->is_server) {
749 $this->send($this->stream_start);
751 $this->been_reset = true;
755 * Setup the XML parser
757 public function setupParser() {
758 $this->parser = xml_parser_create('UTF-8');
759 xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);
760 xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
761 xml_set_object($this->parser, $this);
762 xml_set_element_handler($this->parser, 'startXML', 'endXML');
763 xml_set_character_data_handler($this->parser, 'charXML');
766 public function readyToProcess() {
767 $read = array($this->socket);
770 $updated = @stream_select($read, $write, $except, 0);
771 return (($updated !== false) && ($updated > 0));