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 * @copyright 2008 Nathanael C. Fritz
28 /** XMPPHP_Exception */
29 require_once 'Exception.php';
32 require_once 'XMLObj.php';
35 require_once 'Log.php';
42 * @author Nathanael C. Fritz <JID: fritzy@netflint.net>
43 * @author Stephan Wentz <JID: stephan@jabber.wentz.it>
44 * @copyright 2008 Nathanael C. Fritz
47 class XMPPHP_XMLStream {
63 protected $xml_depth = 0;
75 protected $stream_start = '<stream>';
79 protected $stream_end = '</stream>';
83 protected $disconnected = false;
87 protected $sent_disconnect = false;
91 protected $ns_map = array();
95 protected $current_ns = array();
99 protected $xmlobj = null;
103 protected $nshandlers = array();
107 protected $idhandlers = array();
111 protected $eventhandlers = array();
115 protected $lastid = 0;
119 protected $default_ns;
123 protected $until = '';
127 protected $until_happened = false;
131 protected $until_payload = array();
139 protected $reconnect = true;
143 protected $been_reset = false;
147 protected $is_server;
151 protected $last_send = 0;
155 protected $use_ssl = false;
159 protected $reconnectTimeout = 30;
164 * @param string $host
165 * @param string $port
166 * @param boolean $printlog
167 * @param string $loglevel
168 * @param boolean $is_server
170 public function __construct($host = null, $port = null, $printlog = false, $loglevel = null, $is_server = false) {
171 $this->reconnect = !$is_server;
172 $this->is_server = $is_server;
175 $this->setupParser();
176 $this->log = new XMPPHP_Log($printlog, $loglevel);
183 public function __destruct() {
184 if(!$this->disconnected && $this->socket) {
190 * Return the log instance
194 public function getLog() {
203 public function getId() {
205 return $this->lastid;
213 public function useSSL($use=true) {
214 $this->use_ssl = $use;
221 * @param string $pointer
224 public function addIdHandler($id, $pointer, $obj = null) {
225 $this->idhandlers[$id] = array($pointer, $obj);
233 * @param string $pointer
235 * @param integer $depth
237 public function addHandler($name, $ns, $pointer, $obj = null, $depth = 1) {
238 $this->nshandlers[] = array($name,$ns,$pointer,$obj, $depth);
245 * @param string $pointer
248 public function addEventHandler($name, $pointer, $obj) {
249 $this->eventhandlers[] = array($name, $pointer, $obj);
253 * Connect to XMPP Host
255 * @param integer $timeout
256 * @param boolean $persistent
257 * @param boolean $sendinit
259 public function connect($timeout = 30, $persistent = false, $sendinit = true) {
263 $this->disconnected = false;
264 $this->sent_disconnect = false;
266 $conflag = STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT;
268 $conflag = STREAM_CLIENT_CONNECT;
271 if($this->use_ssl) $conntype = 'ssl';
272 $this->log->log("Connecting to $conntype://{$this->host}:{$this->port}");
274 $this->socket = @stream_socket_client("$conntype://{$this->host}:{$this->port}", $errno, $errstr, $timeout, $conflag);
275 } catch (Exception $e) {
276 throw new XMPPHP_Exception($e->getMessage());
279 $this->log->log("Could not connect.", XMPPHP_Log::LEVEL_ERROR);
280 $this->disconnected = true;
281 # Take it easy for a few seconds
282 sleep(min($timeout, 5));
284 } while (!$this->socket && (time() - $starttime) < $timeout);
287 stream_set_blocking($this->socket, 1);
288 if($sendinit) $this->send($this->stream_start);
290 throw new XMPPHP_Exception("Could not connect before timeout.");
295 * Reconnect XMPP Host
297 public function doReconnect() {
298 if(!$this->is_server) {
299 $this->log->log("Reconnecting ($this->reconnectTimeout)...", XMPPHP_Log::LEVEL_WARNING);
300 $this->connect($this->reconnectTimeout, false, false);
302 $this->event('reconnect');
306 public function setReconnectTimeout($timeout) {
307 $this->reconnectTimeout = $timeout;
311 * Disconnect from XMPP Host
313 public function disconnect() {
314 $this->log->log("Disconnecting...", XMPPHP_Log::LEVEL_VERBOSE);
315 $this->reconnect = false;
316 $this->send($this->stream_end);
317 $this->sent_disconnect = true;
318 $this->processUntil('end_stream', 5);
319 $this->disconnected = true;
323 * Are we are disconnected?
327 public function isDisconnected() {
328 return $this->disconnected;
333 * 0 -> only read if data is immediately ready
334 * NULL -> wait forever and ever
335 * integer -> process for this amount of time
338 private function __process($maximum=0) {
340 $remaining = $maximum;
343 $starttime = (microtime(true) * 1000000);
344 $read = array($this->socket);
347 if (is_null($maximum)) {
350 } else if ($maximum == 0) {
354 $usecs = $remaining % 1000000;
355 $secs = floor(($remaining - $usecs) / 1000000);
357 $updated = @stream_select($read, $write, $except, $secs, $usecs);
358 if ($updated === false) {
359 $this->log->log("Error on stream_select()", XMPPHP_Log::LEVEL_VERBOSE);
360 if ($this->reconnect) {
361 $this->doReconnect();
363 fclose($this->socket);
364 $this->socket = NULL;
367 } else if ($updated > 0) {
368 # XXX: Is this big enough?
369 $buff = @fread($this->socket, 4096);
371 if($this->reconnect) {
372 $this->doReconnect();
374 fclose($this->socket);
375 $this->socket = NULL;
379 $this->log->log("RECV: $buff", XMPPHP_Log::LEVEL_VERBOSE);
380 xml_parse($this->parser, $buff, false);
382 # $updated == 0 means no changes during timeout.
384 $endtime = (microtime(true)*1000000);
385 $time_past = $endtime - $starttime;
386 $remaining = $remaining - $time_past;
387 } while (is_null($maximum) || $remaining > 0);
396 public function process() {
397 $this->__process(NULL);
401 * Process until a timeout occurs
403 * @param integer $timeout
406 public function processTime($timeout=NULL) {
407 if (is_null($timeout)) {
408 return $this->__process(NULL);
410 return $this->__process($timeout * 1000000);
415 * Process until a specified event or a timeout occurs
417 * @param string|array $event
418 * @param integer $timeout
421 public function processUntil($event, $timeout=-1) {
423 if(!is_array($event)) $event = array($event);
424 $this->until[] = $event;
426 $event_key = key($this->until);
429 while(!$this->disconnected and $this->until[$event_key] and (time() - $start < $timeout or $timeout == -1)) {
432 if(array_key_exists($event_key, $this->until_payload)) {
433 $payload = $this->until_payload[$event_key];
437 unset($this->until_payload[$event_key]);
444 public function Xapply_socket($socket) {
445 $this->socket = $socket;
451 * @see xml_set_element_handler
453 * @param resource $parser
454 * @param string $name
456 public function startXML($parser, $name, $attr) {
457 if($this->been_reset) {
458 $this->been_reset = false;
459 $this->xml_depth = 0;
462 if(array_key_exists('XMLNS', $attr)) {
463 $this->current_ns[$this->xml_depth] = $attr['XMLNS'];
465 $this->current_ns[$this->xml_depth] = $this->current_ns[$this->xml_depth - 1];
466 if(!$this->current_ns[$this->xml_depth]) $this->current_ns[$this->xml_depth] = $this->default_ns;
468 $ns = $this->current_ns[$this->xml_depth];
469 foreach($attr as $key => $value) {
470 if(strstr($key, ":")) {
471 $key = explode(':', $key);
473 $this->ns_map[$key] = $value;
476 if(!strstr($name, ":") === false)
478 $name = explode(':', $name);
479 $ns = $this->ns_map[$name[0]];
482 $obj = new XMPPHP_XMLObj($name, $ns, $attr);
483 if($this->xml_depth > 1) {
484 $this->xmlobj[$this->xml_depth - 1]->subs[] = $obj;
486 $this->xmlobj[$this->xml_depth] = $obj;
492 * @see xml_set_element_handler
494 * @param resource $parser
495 * @param string $name
497 public function endXML($parser, $name) {
498 #$this->log->log("Ending $name", XMPPHP_Log::LEVEL_DEBUG);
500 if($this->been_reset) {
501 $this->been_reset = false;
502 $this->xml_depth = 0;
505 if($this->xml_depth == 1) {
506 #clean-up old objects
508 foreach($this->nshandlers as $handler) {
509 if($handler[4] != 1 and $this->xmlobj[2]->hasSub($handler[0])) {
510 $searchxml = $this->xmlobj[2]->sub($handler[0]);
511 } elseif(is_array($this->xmlobj) and array_key_exists(2, $this->xmlobj)) {
512 $searchxml = $this->xmlobj[2];
514 if($searchxml !== null and $searchxml->name == $handler[0] and ($searchxml->ns == $handler[1] or (!$handler[1] and $searchxml->ns == $this->default_ns))) {
515 if($handler[3] === null) $handler[3] = $this;
516 $this->log->log("Calling {$handler[2]}", XMPPHP_Log::LEVEL_DEBUG);
517 $handler[3]->$handler[2]($this->xmlobj[2]);
520 foreach($this->idhandlers as $id => $handler) {
521 if(array_key_exists('id', $this->xmlobj[2]->attrs) and $this->xmlobj[2]->attrs['id'] == $id) {
522 if($handler[1] === null) $handler[1] = $this;
523 $handler[1]->$handler[0]($this->xmlobj[2]);
524 #id handlers are only used once
525 unset($this->idhandlers[$id]);
529 if(is_array($this->xmlobj)) {
530 $this->xmlobj = array_slice($this->xmlobj, 0, 1);
531 if(isset($this->xmlobj[0]) && $this->xmlobj[0] instanceof XMPPHP_XMLObj) {
532 $this->xmlobj[0]->subs = null;
535 unset($this->xmlobj[2]);
537 if($this->xml_depth == 0 and !$this->been_reset) {
538 if(!$this->disconnected) {
539 if(!$this->sent_disconnect) {
540 $this->send($this->stream_end);
542 $this->disconnected = true;
543 $this->sent_disconnect = true;
544 fclose($this->socket);
545 if($this->reconnect) {
546 $this->doReconnect();
549 $this->event('end_stream');
554 * XML character callback
555 * @see xml_set_character_data_handler
557 * @param resource $parser
558 * @param string $data
560 public function charXML($parser, $data) {
561 if(array_key_exists($this->xml_depth, $this->xmlobj)) {
562 $this->xmlobj[$this->xml_depth]->data .= $data;
569 * @param string $name
570 * @param string $payload
572 public function event($name, $payload = null) {
573 $this->log->log("EVENT: $name", XMPPHP_Log::LEVEL_DEBUG);
574 foreach($this->eventhandlers as $handler) {
575 if($name == $handler[0]) {
576 if($handler[2] === null) {
579 $handler[2]->$handler[1]($payload);
582 foreach($this->until as $key => $until) {
583 if(is_array($until)) {
584 if(in_array($name, $until)) {
585 $this->until_payload[$key][] = array($name, $payload);
586 $this->until[$key] = false;
595 public function read() {
596 $buff = @fread($this->socket, 1024);
598 if($this->reconnect) {
599 $this->doReconnect();
601 fclose($this->socket);
605 $this->log->log("RECV: $buff", XMPPHP_Log::LEVEL_VERBOSE);
606 xml_parse($this->parser, $buff, false);
614 public function send($msg, $timeout=NULL) {
616 if (is_null($timeout)) {
619 } else if ($timeout == 0) {
623 $maximum = $timeout * 1000000;
624 $usecs = $maximum % 1000000;
625 $secs = floor(($maximum - $usecs) / 1000000);
629 $write = array($this->socket);
632 $select = @stream_select($read, $write, $except, $secs, $usecs);
634 if($select === False) {
635 $this->log->log("ERROR sending message; reconnecting.");
636 $this->doReconnect();
637 # TODO: retry send here
639 } elseif ($select > 0) {
640 $this->log->log("Socket is ready; send it.");
642 $this->log->log("Socket is not ready; break.");
646 $sentbytes = @fwrite($this->socket, $msg);
647 $this->log->log("SENT: " . mb_substr($msg, 0, $sentbytes, '8bit'), XMPPHP_Log::LEVEL_VERBOSE);
648 if($sentbytes === FALSE) {
649 $this->log->log("ERROR sending message; reconnecting.");
650 $this->doReconnect();
653 $this->log->log("Successfully sent $sentbytes bytes.");
657 public function time() {
658 list($usec, $sec) = explode(" ", microtime());
659 return (float)$sec + (float)$usec;
665 public function reset() {
666 $this->xml_depth = 0;
667 unset($this->xmlobj);
668 $this->xmlobj = array();
669 $this->setupParser();
670 if(!$this->is_server) {
671 $this->send($this->stream_start);
673 $this->been_reset = true;
677 * Setup the XML parser
679 public function setupParser() {
680 $this->parser = xml_parser_create('UTF-8');
681 xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);
682 xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
683 xml_set_object($this->parser, $this);
684 xml_set_element_handler($this->parser, 'startXML', 'endXML');
685 xml_set_character_data_handler($this->parser, 'charXML');
688 public function readyToProcess() {
689 $read = array($this->socket);
692 $updated = @stream_select($read, $write, $except, 0);
693 return (($updated !== false) && ($updated > 0));