From c7cdcc588aa47893ab41a1670c5dfe649674a4b0 Mon Sep 17 00:00:00 2001 From: Diogo Cordeiro Date: Tue, 18 Jun 2019 19:02:40 +0100 Subject: [PATCH] Modern version of XMPPHP extlib Original XMPPHP is no longer maintained Therefore I've done some optimizations and imported some commits from birkner and zorn-v forks. None of the forks really looked ready to be adopted... --- .gitignore | 6 + README | 59 - README.md | 20 + XMPPHP/BOSH.php | 523 ++++++--- XMPPHP/Exception.php | 34 +- XMPPHP/Log.php | 188 +-- XMPPHP/Roster.php | 288 ++--- XMPPHP/XMLObj.php | 278 ++--- XMPPHP/XMLStream.php | 1531 ++++++++++++------------- XMPPHP/XMPP.php | 936 +++++++-------- XMPPHP/XMPP_Old.php | 114 -- composer.json | 49 + examples/cli_longrun_example.php | 192 ++-- examples/cli_longrun_example_bosh.php | 125 +- examples/sendmessage_example.php | 51 +- examples/webclient_example.php | 149 ++- tests/AllTests.php | 110 +- tests/XMPPHP/LogTest.php | 136 ++- tests/XMPPHP/XMLObjTest.php | 83 +- tests/XMPPHP/XMPPTest.php | 52 +- 20 files changed, 2659 insertions(+), 2265 deletions(-) create mode 100644 .gitignore delete mode 100644 README create mode 100644 README.md mode change 100755 => 100644 XMPPHP/Exception.php delete mode 100644 XMPPHP/XMPP_Old.php create mode 100644 composer.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a67d42b --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +composer.phar +/vendor/ + +# Commit your application's lock file https://getcomposer.org/doc/01-basic-usage.md#commit-your-composer-lock-file-to-version-control +# You may choose to ignore a library lock file http://getcomposer.org/doc/02-libraries.md#lock-file +# composer.lock diff --git a/README b/README deleted file mode 100644 index 7e4aee7..0000000 --- a/README +++ /dev/null @@ -1,59 +0,0 @@ -About -================================================================================ -XMPPHP is an elegant PHP library for XMPP (aka Jabber, Google Talk, etc). - -Homepage: http://code.google.com/p/xmpphp -This fork: http://github.com/cweiske/xmpphp/ -Chatroom: xmpphp@conference.psi-im.org (XMPP MUC) -PEAR package: http://pearhub.org/projects/cwXMPPHP/ - -Author: Nathan Fritz, jabber id: fritzy [at] netflint.net -Co-Author: Stephan Wentz, jabber id: stephan [at] wentz.it -Maintainer of this fork: Christian Weiske - -If you have any questions (no matter how dumb), please send me an IM. I enjoy -helping people with my code. - - -Requirements -================================================================================ -* PHP 5.x -* SSL Support Compiled - -History -================================================================================ -Carlo Zottmann handed me maintenance of Class.Jabber.PHP years and years ago -(2003?). While I did fix some bugs, I never did much with it. I promised many -people that it would return as a PHP5 rewrite. That day has finally come. - -This code is based on my experience with Class.Jabber.PHP, but more closely -related to my Python library, SleekXMPP (http://code.google.com/p/sleekxmpp). - -Documentation -================================================================================ -For now, look at the examples. In the near future, I'll have better -documentation on the website. - -Installation -================================================================================ -Either get the code from github, the last release from google code -or install the PEAR package from pearhub.org: -$ pear channel-discover pearhub.org -$ pear install pearhub/cwXMPPHP - -The code on google code is not being actively maintained anymore, so -don't expect current releases there. - - -TODO -================================================================================ -* Documentation -* MUC Support - -License Exception -=============================================================================== -Please contact Nathan Fritz for library exceptions if you would like to -distribute XMPPHP with a non-GPL compatible license. - -Also, if you would like to distribute XMPPHP as part of a commercial package, -I sell commercial licenses. diff --git a/README.md b/README.md new file mode 100644 index 0000000..ec10b51 --- /dev/null +++ b/README.md @@ -0,0 +1,20 @@ +README +====== + +About XMPPHP +------------ + +XMPPHP is an elegant PHP library for XMPP (aka Jabber, Google Talk, etc). + +* Homepage: [http://code.google.com/p/xmpphp] +* Chatroom: [xmpphp@conference.psi-im.org] (XMPP MUC) +* Author: Nathan Fritz, jabber id: fritzy [at] netflint.net +* Co-Author: Stephan Wentz, jabber id: stephan [at] wentz.it +* This fork: https://github.com/diogogithub/xmpphp +* Maintainer of this fork: Diogo Cordeiro + +Requirements +------------ + +* PHP 7.0 +* SSL Support Compiled diff --git a/XMPPHP/BOSH.php b/XMPPHP/BOSH.php index dacb3b4..140ff7c 100644 --- a/XMPPHP/BOSH.php +++ b/XMPPHP/BOSH.php @@ -1,188 +1,409 @@ - * @author Stephan Wentz - * @author Michael Garvin + * @category xmpphp + * @package XMPPHP + * @author Nathanael C. Fritz + * @author Stephan Wentz + * @author Michael Garvin + * @author Alexander Birkner (https://github.com/BirknerAlex) + * @author zorn-v (https://github.com/zorn-v/xmpphp/) + * @author GNU social * @copyright 2008 Nathanael C. Fritz */ +namespace XMPPHP; + +use SimpleXMLElement; + /** XMPPHP_XMLStream */ -require_once 'XMPPHP/XMPP.php'; +require_once __DIR__ . "/XMPP.php"; /** - * XMPPHP Main Class - * - * @category xmpphp - * @package XMPPHP - * @author Nathanael C. Fritz - * @author Stephan Wentz - * @author Michael Garvin - * @copyright 2008 Nathanael C. Fritz - * @version $Id$ + * XMPPHP BOSH + * + * @property int lat + * @package XMPPHP + * @author Nathanael C. Fritz + * @author Stephan Wentz + * @author Michael Garvin + * @copyright 2008 Nathanael C. Fritz + * @version $Id$ */ -class XMPPHP_BOSH extends XMPPHP_XMPP { +class BOSH extends XMPP +{ + /** + * @var integer + */ + protected $rid; - protected $rid; - protected $sid; - protected $http_server; - protected $http_buffer = Array(); - protected $session = false; + /** + * @var string + */ + protected $sid; - public function connect($server, $wait='1', $session=false) { - $this->http_server = $server; - $this->use_encryption = false; - $this->session = $session; + /** + * @var string + */ + protected $http_server; - $this->rid = 3001; - $this->sid = null; - if($session) - { - $this->loadSession(); - } - if(!$this->sid) { - $body = $this->__buildBody(); - $body->addAttribute('hold','1'); - $body->addAttribute('to', $this->host); - $body->addAttribute('route', "xmpp:{$this->host}:{$this->port}"); - $body->addAttribute('secure','true'); - $body->addAttribute('xmpp:version','1.6', 'urn:xmpp:xbosh'); - $body->addAttribute('wait', strval($wait)); - $body->addAttribute('ack','1'); - $body->addAttribute('xmlns:xmpp','urn:xmpp:xbosh'); - $buff = ""; - xml_parse($this->parser, $buff, false); - $response = $this->__sendBody($body); - $rxml = new SimpleXMLElement($response); - $this->sid = $rxml['sid']; + /** + * @var array + */ + protected $http_buffer = array(); - } else { - $buff = ""; - xml_parse($this->parser, $buff, false); - } - } + /** + * @var string + */ + protected $session = false; - public function __sendBody($body=null, $recv=true) { - if(!$body) { - $body = $this->__buildBody(); - } - $ch = curl_init($this->http_server); - curl_setopt($ch, CURLOPT_HEADER, 0); - curl_setopt($ch, CURLOPT_POST, 1); - curl_setopt($ch, CURLOPT_POSTFIELDS, $body->asXML()); - curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); - $header = array('Accept-Encoding: gzip, deflate','Content-Type: text/xml; charset=utf-8'); - curl_setopt($ch, CURLOPT_HTTPHEADER, $header ); - curl_setopt($ch, CURLOPT_VERBOSE, 0); - $output = ''; - if($recv) { - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - $output = curl_exec($ch); - $this->http_buffer[] = $output; - } - curl_close($ch); - return $output; - } + /** + * @var integer + */ + protected $inactivity; - public function __buildBody($sub=null) { - $xml = new SimpleXMLElement(""); - $xml->addAttribute('content', 'text/xml; charset=utf-8'); - $xml->addAttribute('rid', $this->rid); - $this->rid += 1; - if($this->sid) $xml->addAttribute('sid', $this->sid); - #if($this->sid) $xml->addAttribute('xmlns', 'http://jabber.org/protocol/httpbind'); - $xml->addAttribute('xml:lang', 'en'); - if($sub) { // ok, so simplexml is lame - $p = dom_import_simplexml($xml); - $c = dom_import_simplexml($sub); - $cn = $p->ownerDocument->importNode($c, true); - $p->appendChild($cn); - $xml = simplexml_import_dom($p); - } - return $xml; - } + /** + * Connect + * + * @param $server + * @param $wait + * @param $session + * @throws Exception + * @throws Exception + */ + public function connect($server = null, $wait = '1', $session = false) + { - public function __process() { - if($this->http_buffer) { - $this->__parseBuffer(); - } else { - $this->__sendBody(); - $this->__parseBuffer(); - } - } + if (is_null($server)) { - public function __parseBuffer() { - while ($this->http_buffer) { - $idx = key($this->http_buffer); - $buffer = $this->http_buffer[$idx]; - unset($this->http_buffer[$idx]); - if($buffer) { - $xml = new SimpleXMLElement($buffer); - $children = $xml->xpath('child::node()'); - foreach ($children as $child) { - $buff = $child->asXML(); - $this->log->log("RECV: $buff", XMPPHP_Log::LEVEL_VERBOSE); - xml_parse($this->parser, $buff, false); - } - } - } - } + // If we aren't given the server http url, try and guess it + $port_string = ($this->port AND $this->port != 80) ? ':' . $this->port : ''; + $this->http_server = 'http://' . $this->host . $port_string . '/http-bind/'; + } else { + $this->http_server = $server; + } - public function send($msg) { - $this->log->log("SEND: $msg", XMPPHP_Log::LEVEL_VERBOSE); - $msg = new SimpleXMLElement($msg); - #$msg->addAttribute('xmlns', 'jabber:client'); - $this->__sendBody($this->__buildBody($msg), true); - #$this->__parseBuffer(); - } + $this->use_encryption = false; + $this->session = $session; + $this->rid = 3001; + $this->sid = null; + $this->inactivity = 0; - public function reset() { - $this->xml_depth = 0; - unset($this->xmlobj); - $this->xmlobj = array(); - $this->setupParser(); - #$this->send($this->stream_start); - $body = $this->__buildBody(); - $body->addAttribute('to', $this->host); - $body->addAttribute('xmpp:restart', 'true', 'urn:xmpp:xbosh'); - $buff = ""; - $response = $this->__sendBody($body); - $this->been_reset = true; - xml_parse($this->parser, $buff, false); - } + if ($session) { + $this->loadSession(); + } - public function loadSession() { - if(isset($_SESSION['XMPPHP_BOSH_RID'])) $this->rid = $_SESSION['XMPPHP_BOSH_RID']; - if(isset($_SESSION['XMPPHP_BOSH_SID'])) $this->sid = $_SESSION['XMPPHP_BOSH_SID']; - if(isset($_SESSION['XMPPHP_BOSH_authed'])) $this->authed = $_SESSION['XMPPHP_BOSH_authed']; - if(isset($_SESSION['XMPPHP_BOSH_jid'])) $this->jid = $_SESSION['XMPPHP_BOSH_jid']; - if(isset($_SESSION['XMPPHP_BOSH_fulljid'])) $this->fulljid = $_SESSION['XMPPHP_BOSH_fulljid']; - } + if (!$this->sid) { - public function saveSession() { - $_SESSION['XMPPHP_BOSH_RID'] = (string) $this->rid; - $_SESSION['XMPPHP_BOSH_SID'] = (string) $this->sid; - $_SESSION['XMPPHP_BOSH_authed'] = (boolean) $this->authed; - $_SESSION['XMPPHP_BOSH_jid'] = (string) $this->jid; - $_SESSION['XMPPHP_BOSH_fulljid'] = (string) $this->fulljid; - } + $body = $this->__buildBody(); + $body->addAttribute('hold', '1'); + $body->addAttribute('to', $this->server); + $body->addAttribute('route', 'xmpp:' . $this->host . ':' . $this->port); + $body->addAttribute('secure', 'true'); + $body->addAttribute('xmpp:version', '1.0', 'urn:xmpp:xbosh'); + $body->addAttribute('wait', strval($wait)); + $body->addAttribute('ack', '1'); + $body->addAttribute('xmlns:xmpp', 'urn:xmpp:xbosh'); + $buff = ''; + xml_parse($this->parser, $buff, false); + $response = $this->__sendBody($body); + $rxml = new SimpleXMLElement($response); + $this->sid = $rxml['sid']; + $this->inactivity = $rxml['inactivity']; + } else { + $buff = ''; + xml_parse($this->parser, $buff, false); + } + } + + /** + * Load session + * + */ + public function loadSession() + { + + if ($this->session == 'ON_FILE') { + + // Session not started so use session_file + $session_file = $this->getSessionFile(); + + // manage multiple accesses + if (!file_exists($session_file)) { + file_put_contents($session_file, ''); + } + $session_file_fp = fopen($session_file, 'r'); + flock($session_file_fp, LOCK_EX); + $session_serialized = file_get_contents($session_file, null, null, 6); + flock($session_file_fp, LOCK_UN); + fclose($session_file_fp); + + $this->log->log('SESSION: reading ' . $session_serialized . ' from ' . $session_file, Log::LEVEL_VERBOSE); + if ($session_serialized != '') { + $_SESSION['XMPPHP_BOSH'] = unserialize($session_serialized); + } + } + + if (isset($_SESSION['XMPPHP_BOSH']['inactivity'])) { + $this->inactivity = $_SESSION['XMPPHP_BOSH']['inactivity']; + } + + $this->lat = (time() - (isset($_SESSION['XMPPHP_BOSH']['lat']))) ? $_SESSION['XMPPHP_BOSH']['lat'] : 0; + + if ($this->lat < $this->inactivity) { + + if (isset($_SESSION['XMPPHP_BOSH']['RID'])) { + $this->rid = $_SESSION['XMPPHP_BOSH']['RID']; + } + if (isset($_SESSION['XMPPHP_BOSH']['SID'])) { + $this->sid = $_SESSION['XMPPHP_BOSH']['SID']; + } + if (isset($_SESSION['XMPPHP_BOSH']['authed'])) { + $this->authed = $_SESSION['XMPPHP_BOSH']['authed']; + } + if (isset($_SESSION['XMPPHP_BOSH']['basejid'])) { + $this->basejid = $_SESSION['XMPPHP_BOSH']['basejid']; + } + if (isset($_SESSION['XMPPHP_BOSH']['fulljid'])) { + $this->fulljid = $_SESSION['XMPPHP_BOSH']['fulljid']; + } + } + } + + /** + * Get the session file + * + */ + public function getSessionFile() + { + return sys_get_temp_dir() . '/' . $this->user . '_' . $this->server . '_session'; + } + + /** + * Build body + * + * @param $sub + * @return SimpleXMLElement|string + */ + public function __buildBody($sub = null) + { + + $xml = ''; + $xml = new SimpleXMLElement($xml); + $xml->addAttribute('content', 'text/xml; charset=utf-8'); + $xml->addAttribute('rid', $this->rid); + $this->rid++; + if ($this->sid) { + $xml->addAttribute('sid', $this->sid); + } + + $xml->addAttribute('xml:lang', 'en'); + + if ($sub !== null) { + + // Ok, so simplexml is lame + $parent = dom_import_simplexml($xml); + $content = dom_import_simplexml($sub); + $child = $parent->ownerDocument->importNode($content, true); + $parent->appendChild($child); + $xml = simplexml_import_dom($parent); + } + + return $xml; + } + + /** + * Send body + * + * @param $body + * @param $recv + * @return bool|string + * @throws Exception + * @throws Exception + */ + public function __sendBody($body = null, $recv = true) + { + + if (!$body) { + $body = $this->__buildBody(); + } + + $output = ''; + $header = array('Accept-Encoding: gzip, deflate', 'Content-Type: text/xml; charset=utf-8'); + $ch = curl_init(); + + curl_setopt($ch, CURLOPT_URL, $this->http_server); + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, $body->asXML()); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); + curl_setopt($ch, CURLOPT_HTTPHEADER, $header); + curl_setopt($ch, CURLOPT_VERBOSE, 0); + + if ($recv) { + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + $output = curl_exec($ch); + if (curl_getinfo($ch, CURLINFO_HTTP_CODE) != '200') { + throw new Exception('Wrong response from server!'); + } + + $this->http_buffer[] = $output; + } + curl_close($ch); + + return $output; + } + + /** + * Process + * + * @param $null1 + * @param $null2 + * + * null params are not used and just to statify Strict Function Declaration + * @return bool + * @throws Exception + * @throws Exception + */ + public function __process($null1 = null, $null2 = null) + { + + if ($this->http_buffer) { + $this->__parseBuffer(); + } else { + $this->__sendBody(); + $this->__parseBuffer(); + } + + $this->saveSession(); + + return true; + } + + public function __parseBuffer() + { + + while ($this->http_buffer) { + + $idx = key($this->http_buffer); + $buffer = $this->http_buffer[$idx]; + unset($this->http_buffer[$idx]); + + if ($buffer) { + + $xml = new SimpleXMLElement($buffer); + $children = $xml->xpath('child::node()'); + + foreach ($children as $child) { + $buff = $child->asXML(); + $this->log->log('RECV: ' . $buff, Log::LEVEL_VERBOSE); + xml_parse($this->parser, $buff, false); + } + } + } + } + + /** + * Save session + * + */ + public function saveSession() + { + + $_SESSION['XMPPHP_BOSH']['RID'] = (string)$this->rid; + $_SESSION['XMPPHP_BOSH']['SID'] = (string)$this->sid; + $_SESSION['XMPPHP_BOSH']['authed'] = (boolean)$this->authed; + $_SESSION['XMPPHP_BOSH']['basejid'] = (string)$this->basejid; + $_SESSION['XMPPHP_BOSH']['fulljid'] = (string)$this->fulljid; + $_SESSION['XMPPHP_BOSH']['inactivity'] = (string)$this->inactivity; + $_SESSION['XMPPHP_BOSH']['lat'] = (string)time(); + + if ($this->session == 'ON_FILE') { + + $session_file = $this->getSessionFile(); + $session_file_fp = fopen($session_file, 'r'); + flock($session_file_fp, LOCK_EX); + // log->log('SEND: ' . $msg, Log::LEVEL_VERBOSE); + $msg = new SimpleXMLElement($msg); + $this->__sendBody($this->__buildBody($msg), true); + } + + /** + * Reset + * + * @throws Exception + */ + public function reset() + { + + $this->xml_depth = 0; + unset($this->xmlobj); + $this->xmlobj = array(); + $this->setupParser(); + $body = $this->__buildBody(); + $body->addAttribute('to', $this->host); + $body->addAttribute('xmpp:restart', 'true', 'urn:xmpp:xbosh'); + $buff = ''; + $response = $this->__sendBody($body); + $this->been_reset = true; + xml_parse($this->parser, $buff, false); + } + + /** + * Disconnect + * + * @throws Exception + */ + public function disconnect() + { + + parent::disconnect(); + + if ($this->session == 'ON_FILE') { + unlink($this->getSessionFile()); + } else { + $keys = array('RID', 'SID', 'authed', 'basejid', 'fulljid', 'inactivity', 'lat'); + foreach ($keys as $key) { + unset($_SESSION['XMPPHP_BOSH'][$key]); + } + } + } } diff --git a/XMPPHP/Exception.php b/XMPPHP/Exception.php old mode 100755 new mode 100644 index da59bc7..525bdd9 --- a/XMPPHP/Exception.php +++ b/XMPPHP/Exception.php @@ -1,41 +1,49 @@ * @author Stephan Wentz - * @author Michael Garvin + * @author Michael Garvin + * @author Alexander Birkner (https://github.com/BirknerAlex) + * @author zorn-v (https://github.com/zorn-v/xmpphp/) + * @author GNU social * @copyright 2008 Nathanael C. Fritz */ +namespace XMPPHP; + +use Exception as ObjectException; + /** * XMPPHP Exception * - * @category xmpphp - * @package XMPPHP - * @author Nathanael C. Fritz - * @author Stephan Wentz - * @author Michael Garvin - * @copyright 2008 Nathanael C. Fritz - * @version $Id$ + * @package XMPPHP + * @author Nathanael C. Fritz + * @author Stephan Wentz + * @author Michael Garvin + * @copyright 2008 Nathanael C. Fritz + * @version $Id$ */ -class XMPPHP_Exception extends Exception { +class Exception extends ObjectException +{ } diff --git a/XMPPHP/Log.php b/XMPPHP/Log.php index a9bce3d..7b511d5 100644 --- a/XMPPHP/Log.php +++ b/XMPPHP/Log.php @@ -1,119 +1,129 @@ - * @author Stephan Wentz - * @author Michael Garvin + * @category xmpphp + * @package XMPPHP + * @author Nathanael C. Fritz + * @author Stephan Wentz + * @author Michael Garvin + * @author Alexander Birkner (https://github.com/BirknerAlex) + * @author zorn-v (https://github.com/zorn-v/xmpphp/) + * @author GNU social * @copyright 2008 Nathanael C. Fritz */ +namespace XMPPHP; + /** * XMPPHP Log - * - * @package XMPPHP - * @author Nathanael C. Fritz - * @author Stephan Wentz - * @author Michael Garvin - * @copyright 2008 Nathanael C. Fritz - * @version $Id$ + * + * @package XMPPHP + * @author Nathanael C. Fritz + * @author Stephan Wentz + * @author Michael Garvin + * @copyright 2008 Nathanael C. Fritz + * @version $Id$ */ -class XMPPHP_Log { - - const LEVEL_ERROR = 0; - const LEVEL_WARNING = 1; - const LEVEL_INFO = 2; - const LEVEL_DEBUG = 3; - const LEVEL_VERBOSE = 4; - - /** - * @var array - */ - protected $data = array(); +class Log +{ + const LEVEL_ERROR = 0; + const LEVEL_WARNING = 1; + const LEVEL_INFO = 2; + const LEVEL_DEBUG = 3; + const LEVEL_VERBOSE = 4; - /** - * @var array - */ - protected $names = array('ERROR', 'WARNING', 'INFO', 'DEBUG', 'VERBOSE'); + /** + * @var array + */ + protected $data = array(); - /** - * @var integer - */ - protected $runlevel; + /** + * @var array + */ + protected $names = array('ERROR', 'WARNING', 'INFO', 'DEBUG', 'VERBOSE'); - /** - * @var boolean - */ - protected $printout; + /** + * @var integer + */ + protected $runlevel; - /** - * Constructor - * - * @param boolean $printout - * @param string $runlevel - */ - public function __construct($printout = false, $runlevel = self::LEVEL_INFO) { - $this->printout = (boolean)$printout; - $this->runlevel = (int)$runlevel; - } + /** + * @var boolean + */ + protected $printout; - /** - * Add a message to the log data array - * If printout in this instance is set to true, directly output the message - * - * @param string $msg - * @param integer $runlevel - */ - public function log($msg, $runlevel = self::LEVEL_INFO) { - $time = time(); - #$this->data[] = array($this->runlevel, $msg, $time); - if($this->printout and $runlevel <= $this->runlevel) { - $this->writeLine($msg, $runlevel, $time); - } - } + /** + * Constructor + * + * @param boolean $printout + * @param int $runlevel + */ + public function __construct($printout = false, $runlevel = self::LEVEL_INFO) + { + $this->printout = (boolean)$printout; + $this->runlevel = (int)$runlevel; + } - /** - * Output the complete log. - * Log will be cleared if $clear = true - * - * @param boolean $clear - * @param integer $runlevel - */ - public function printout($clear = true, $runlevel = null) { - if($runlevel === null) { - $runlevel = $this->runlevel; - } - foreach($this->data as $data) { - if($runlevel <= $data[0]) { - $this->writeLine($data[1], $runlevel, $data[2]); - } - } - if($clear) { - $this->data = array(); - } - } - - protected function writeLine($msg, $runlevel, $time) { - //echo date('Y-m-d H:i:s', $time)." [".$this->names[$runlevel]."]: ".$msg."\n"; - echo $time." [".$this->names[$runlevel]."]: ".$msg."\n"; - flush(); - } + /** + * Add a message to the log data array + * If printout in this instance is set to true, directly output the message + * + * @param string $msg + * @param integer $runlevel + */ + public function log($msg, $runlevel = self::LEVEL_INFO) + { + $time = time(); + #$this->data[] = array($this->runlevel, $msg, $time); + if ($this->printout and $runlevel <= $this->runlevel) { + $this->writeLine($msg, $runlevel, $time); + } + } + + protected function writeLine($msg, $runlevel, $time) + { + //echo date('Y-m-d H:i:s', $time)." [".$this->names[$runlevel]."]: ".$msg."\n"; + echo $time . " [" . $this->names[$runlevel] . "]: " . $msg . "\n"; + flush(); + } + + /** + * Output the complete log. + * Log will be cleared if $clear = true + * + * @param boolean $clear + * @param integer $runlevel + */ + public function printout($clear = true, $runlevel = null) + { + if ($runlevel === null) { + $runlevel = $this->runlevel; + } + foreach ($this->data as $data) { + if ($runlevel <= $data[0]) { + $this->writeLine($data[1], $runlevel, $data[2]); + } + } + if ($clear) { + $this->data = array(); + } + } } diff --git a/XMPPHP/Roster.php b/XMPPHP/Roster.php index 30117bb..799c549 100644 --- a/XMPPHP/Roster.php +++ b/XMPPHP/Roster.php @@ -1,165 +1,183 @@ - * @author Stephan Wentz - * @author Michael Garvin + * @category xmpphp + * @package XMPPHP + * @author Nathanael C. Fritz + * @author Stephan Wentz + * @author Michael Garvin + * @author Alexander Birkner (https://github.com/BirknerAlex) + * @author zorn-v (https://github.com/zorn-v/xmpphp/) + * @author GNU social * @copyright 2008 Nathanael C. Fritz */ +namespace XMPPHP; + /** - * XMPPHP Roster Object - * - * @category xmpphp - * @package XMPPHP - * @author Nathanael C. Fritz - * @author Stephan Wentz - * @author Michael Garvin - * @copyright 2008 Nathanael C. Fritz - * @version $Id$ + * XMPPHP Roster + * + * @package XMPPHP + * @author Nathanael C. Fritz + * @author Stephan Wentz + * @author Michael Garvin + * @copyright 2008 Nathanael C. Fritz + * @version $Id$ */ +class Roster +{ + /** + * Roster array, handles contacts and presence. Indexed by jid. + * Contains array with potentially two indexes 'contact' and 'presence' + * @var array + */ + protected $roster_array = array(); -class Roster { - /** - * Roster array, handles contacts and presence. Indexed by jid. - * Contains array with potentially two indexes 'contact' and 'presence' - * @var array - */ - protected $roster_array = array(); - /** - * Constructor - * - */ - public function __construct($roster_array = array()) { - if ($this->verifyRoster($roster_array)) { - $this->roster_array = $roster_array; //Allow for prepopulation with existing roster - } else { - $this->roster_array = array(); - } - } + /** + * Constructor + * @param array $roster_array + */ + public function __construct($roster_array = array()) + { + if ($this->verifyRoster($roster_array)) { + $this->roster_array = $roster_array; //Allow for pre-population with existing roster + } else { + $this->roster_array = array(); + } + } - /** - * - * Check that a given roster array is of a valid structure (empty is still valid) - * - * @param array $roster_array - */ - protected function verifyRoster($roster_array) { - #TODO once we know *what* a valid roster array looks like - return True; - } + /** + * + * Check that a given roster array is of a valid structure (empty is still valid) + * + * @param array $roster_array + * @return bool + */ + protected function verifyRoster($roster_array) + { + #TODO once we know *what* a valid roster array looks like + return true; + } - /** - * - * Add given contact to roster - * - * @param string $jid - * @param string $subscription - * @param string $name - * @param array $groups - */ - public function addContact($jid, $subscription, $name='', $groups=array()) { - $contact = array('jid' => $jid, 'subscription' => $subscription, 'name' => $name, 'groups' => $groups); - if ($this->isContact($jid)) { - $this->roster_array[$jid]['contact'] = $contact; - } else { - $this->roster_array[$jid] = array('contact' => $contact); - } - } + /** + * + * Retrieve contact via jid + * + * @param string $jid + * @return mixed + */ + public function getContact($jid) + { + if ($this->isContact($jid)) { + return $this->roster_array[$jid]['contact']; + } + } - /** - * - * Retrieve contact via jid - * - * @param string $jid - */ - public function getContact($jid) { - if ($this->isContact($jid)) { - return $this->roster_array[$jid]['contact']; - } - } + /** + * + * Discover if a contact exists in the roster via jid + * + * @param string $jid + * @return bool + */ + public function isContact($jid) + { + return (array_key_exists($jid, $this->roster_array)); + } - /** - * - * Discover if a contact exists in the roster via jid - * - * @param string $jid - */ - public function isContact($jid) { - return (array_key_exists($jid, $this->roster_array)); - } + /** + * + * Set presence + * + * @param string $presence + * @param integer $priority + * @param string $show + * @param string $status + */ + public function setPresence($presence, $priority, $show, $status) + { + $presence = explode('/', $presence, 2); + $jid = $presence[0]; + $resource = isset($presence[1]) ? $presence[1] : ''; + if ($show != 'unavailable') { + if (!$this->isContact($jid)) { + $this->addContact($jid, 'not-in-roster'); + } + $this->roster_array[$jid]['presence'][$resource] = array('priority' => $priority, 'show' => $show, 'status' => $status); + } else { //Nuke unavailable resources to save memory + unset($this->roster_array[$jid]['resource'][$resource]); + unset($this->roster_array[$jid]['presence'][$resource]); + } + } - /** - * - * Set presence - * - * @param string $presence - * @param integer $priority - * @param string $show - * @param string $status - */ - public function setPresence($presence, $priority, $show, $status) { - $presence = explode('/', $presence, 2); - $jid = $presence[0]; - $resource = isset($presence[1]) ? $presence[1] : ''; - if ($show != 'unavailable') { - if (!$this->isContact($jid)) { - $this->addContact($jid, 'not-in-roster'); - } - $this->roster_array[$jid]['presence'][$resource] = array('priority' => $priority, 'show' => $show, 'status' => $status); - } else { //Nuke unavailable resources to save memory - unset($this->roster_array[$jid]['resource'][$resource]); - unset($this->roster_array[$jid]['presence'][$resource]); - } - } + /** + * + * Add given contact to roster + * + * @param string $jid + * @param string $subscription + * @param string $name + * @param array $groups + */ + public function addContact($jid, $subscription, $name = '', $groups = array()) + { + $contact = array('jid' => $jid, 'subscription' => $subscription, 'name' => $name, 'groups' => $groups); + if ($this->isContact($jid)) { + $this->roster_array[$jid]['contact'] = $contact; + } else { + $this->roster_array[$jid] = array('contact' => $contact); + } + } - /* - * - * Return best presence for jid - * - * @param string $jid - */ - public function getPresence($jid) { - $split = explode('/', $jid, 2); - $jid = $split[0]; - if($this->isContact($jid)) { - $current = array('resource' => '', 'active' => '', 'priority' => -129, 'show' => '', 'status' => ''); //Priorities can only be -128 = 127 - foreach($this->roster_array[$jid]['presence'] as $resource => $presence) { - //Highest available priority or just highest priority - if ($presence['priority'] > $current['priority'] and (($presence['show'] == "chat" or $presence['show'] == "available") or ($current['show'] != "chat" or $current['show'] != "available"))) { - $current = $presence; - $current['resource'] = $resource; - } - } - return $current; - } - } - /** - * - * Get roster - * - */ - public function getRoster() { - return $this->roster_array; - } + /* + * + * Return best presence for jid + * + * @param string $jid + */ + + public function getPresence($jid) + { + $split = explode('/', $jid, 2); + $jid = $split[0]; + if ($this->isContact($jid)) { + $current = array('resource' => '', 'active' => '', 'priority' => -129, 'show' => '', 'status' => ''); //Priorities can only be -128 = 127 + foreach ($this->roster_array[$jid]['presence'] as $resource => $presence) { + //Highest available priority or just highest priority + if ($presence['priority'] > $current['priority'] and (($presence['show'] == "chat" or $presence['show'] == "available") or ($current['show'] != "chat" or $current['show'] != "available"))) { + $current = $presence; + $current['resource'] = $resource; + } + } + return $current; + } + } + + /** + * + * Get roster + * + */ + public function getRoster() + { + return $this->roster_array; + } } -?> diff --git a/XMPPHP/XMLObj.php b/XMPPHP/XMLObj.php index 8570a5c..de359ae 100644 --- a/XMPPHP/XMLObj.php +++ b/XMPPHP/XMLObj.php @@ -1,158 +1,174 @@ - - * @author Stephan Wentz - * @author Michael Garvin + * @category xmpphp + * @package XMPPHP + * @author Nathanael C. Fritz + * @author Stephan Wentz + * @author Michael Garvin + * @author Alexander Birkner (https://github.com/BirknerAlex) + * @author zorn-v (https://github.com/zorn-v/xmpphp/) + * @author GNU social * @copyright 2008 Nathanael C. Fritz */ +namespace XMPPHP; + /** - * XMPPHP XML Object - * - * @category xmpphp - * @package XMPPHP - * @author Nathanael C. Fritz - * @author Stephan Wentz - * @author Michael Garvin - * @copyright 2008 Nathanael C. Fritz - * @version $Id$ + * XMPPHP XMLObject + * + * @package XMPPHP + * @author Nathanael C. Fritz + * @author Stephan Wentz + * @author Michael Garvin + * @copyright 2008 Nathanael C. Fritz + * @version $Id$ */ -class XMPPHP_XMLObj { - /** - * Tag name - * - * @var string - */ - public $name; - - /** - * Namespace - * - * @var string - */ - public $ns; - - /** - * Attributes - * - * @var array - */ - public $attrs = array(); - - /** - * Subs? - * - * @var array - */ - public $subs = array(); - - /** - * Node data - * - * @var string - */ - public $data = ''; +class XMLObj +{ + /** + * Tag name + * + * @var string + */ + public $name; - /** - * Constructor - * - * @param string $name - * @param string $ns - * @param array $attrs - * @param string $data - */ - public function __construct($name, $ns = '', $attrs = array(), $data = '') { - $this->name = strtolower($name); - $this->ns = $ns; - if(is_array($attrs) && count($attrs)) { - foreach($attrs as $key => $value) { - $this->attrs[strtolower($key)] = $value; - } - } - $this->data = $data; - } + /** + * Namespace + * + * @var string + */ + public $ns; - /** - * Dump this XML Object to output. - * - * @param integer $depth - */ - public function printObj($depth = 0) { - print str_repeat("\t", $depth) . $this->name . " " . $this->ns . ' ' . $this->data; - print "\n"; - foreach($this->subs as $sub) { - $sub->printObj($depth + 1); - } - } + /** + * Attributes + * + * @var array + */ + public $attrs = array(); - /** - * Return this XML Object in xml notation - * - * @param string $str - */ - public function toString($str = '') { - $str .= "<{$this->name} xmlns='{$this->ns}' "; - foreach($this->attrs as $key => $value) { - if($key != 'xmlns') { - $value = htmlspecialchars($value); - $str .= "$key=\"$value\" "; - } - } - $str .= ">"; - foreach($this->subs as $sub) { - $str .= $sub->toString(); - } - $body = htmlspecialchars($this->data); - $str .= "$bodyname}>"; - return $str; - } + /** + * Subs? + * + * @var array + */ + public $subs = array(); - /** - * Has this XML Object the given sub? - * - * @param string $name - * @return boolean - */ - public function hasSub($name, $ns = null) { - foreach($this->subs as $sub) { - if(($name == "*" or $sub->name == $name) and ($ns == null or $sub->ns == $ns)) return true; - } - return false; - } + /** + * Node data + * + * @var string + */ + public $data = ''; - /** - * Return a sub - * - * @param string $name - * @param string $attrs - * @param string $ns - */ - public function sub($name, $attrs = null, $ns = null) { - #TODO attrs is ignored - foreach($this->subs as $sub) { - if($sub->name == $name and ($ns == null or $sub->ns == $ns)) { - return $sub; - } - } - } + /** + * Constructor + * + * @param string $name + * @param string $ns + * @param array $attrs + * @param string $data + */ + public function __construct($name, $ns = '', $attrs = array(), $data = '') + { + $this->name = strtolower($name); + $this->ns = $ns; + if (is_array($attrs) && count($attrs)) { + foreach ($attrs as $key => $value) { + $this->attrs[strtolower($key)] = $value; + } + } + $this->data = $data; + } + + /** + * Dump this XML Object to output. + * + * @param integer $depth + */ + public function printObj($depth = 0) + { + print str_repeat("\t", $depth) . $this->name . " " . $this->ns . ' ' . $this->data; + print "\n"; + foreach ($this->subs as $sub) { + $sub->printObj($depth + 1); + } + } + + /** + * Return this XML Object in xml notation + * + * @param string $str + * @return string + */ + public function toString($str = '') + { + $str .= "<{$this->name} xmlns='{$this->ns}' "; + foreach ($this->attrs as $key => $value) { + if ($key != 'xmlns') { + $value = htmlspecialchars($value); + $str .= "$key='$value' "; + } + } + $str .= ">"; + foreach ($this->subs as $sub) { + $str .= $sub->toString(); + } + $body = htmlspecialchars($this->data); + $str .= "$bodyname}>"; + return $str; + } + + /** + * Has this XML Object the given sub? + * + * @param string $name + * @param null $ns + * @return boolean + */ + public function hasSub($name, $ns = null) + { + foreach ($this->subs as $sub) { + if (($name == "*" or $sub->name == $name) and ($ns == null or $sub->ns == $ns)) { + return true; + } + } + return false; + } + + /** + * Return a sub + * + * @param string $name + * @param string $attrs + * @param string $ns + * @return mixed + */ + public function sub($name, $attrs = null, $ns = null) + { + #TODO attrs is ignored + foreach ($this->subs as $sub) { + if ($sub->name == $name and ($ns == null or $sub->ns == $ns)) { + return $sub; + } + } + } } diff --git a/XMPPHP/XMLStream.php b/XMPPHP/XMLStream.php index 63c0624..615e7ca 100644 --- a/XMPPHP/XMLStream.php +++ b/XMPPHP/XMLStream.php @@ -1,847 +1,804 @@ - * @author Stephan Wentz - * @author Michael Garvin + * @category xmpphp + * @package XMPPHP + * @author Nathanael C. Fritz + * @author Stephan Wentz + * @author Michael Garvin + * @author Alexander Birkner (https://github.com/BirknerAlex) + * @author zorn-v (https://github.com/zorn-v/xmpphp/) + * @author GNU social * @copyright 2008 Nathanael C. Fritz */ -/** XMPPHP_Exception */ -require_once 'XMPPHP/Exception.php'; +namespace XMPPHP; -/** XMPPHP_XMLObj */ -require_once 'XMPPHP/XMLObj.php'; +/** Exception */ +require_once __DIR__ . DIRECTORY_SEPARATOR . 'Exception.php'; + +/** XMLObj */ +require_once __DIR__ . DIRECTORY_SEPARATOR . 'XMLObj.php'; + +/** Log */ +require_once __DIR__ . DIRECTORY_SEPARATOR . 'Log.php'; -/** XMPPHP_Log */ -require_once 'XMPPHP/Log.php'; /** - * XMPPHP XML Stream - * - * @category xmpphp - * @package XMPPHP - * @author Nathanael C. Fritz - * @author Stephan Wentz - * @author Michael Garvin - * @copyright 2008 Nathanael C. Fritz - * @version $Id$ + * XMPPHP XMLStream + * + * @package XMPPHP + * @author Nathanael C. Fritz + * @author Stephan Wentz + * @author Michael Garvin + * @copyright 2008 Nathanael C. Fritz + * @version $Id$ */ -class XMPPHP_XMLStream { - /** - * @var resource - */ - protected $socket; - /** - * @var resource - */ - protected $parser; - /** - * @var string - */ - protected $buffer; - /** - * @var integer - */ - protected $xml_depth = 0; - /** - * @var string - */ - protected $host; - /** - * @var integer - */ - protected $port; - /** - * @var string - */ - protected $stream_start = ''; - /** - * @var string - */ - protected $stream_end = ''; - /** - * @var boolean - */ - protected $disconnected = false; - /** - * @var boolean - */ - protected $sent_disconnect = false; - /** - * @var array - */ - protected $ns_map = array(); - /** - * @var array - */ - protected $current_ns = array(); - /** - * @var array - */ - protected $xmlobj = null; - /** - * @var array - */ - protected $nshandlers = array(); - /** - * @var array - */ - protected $xpathhandlers = array(); - /** - * @var array - */ - protected $idhandlers = array(); - /** - * @var array - */ - protected $eventhandlers = array(); - /** - * @var integer - */ - protected $lastid = 0; - /** - * @var string - */ - protected $default_ns; - /** - * @var string - */ - protected $until = ''; - /** - * @var string - */ - protected $until_count = ''; - /** - * @var array - */ - protected $until_happened = false; - /** - * @var array - */ - protected $until_payload = array(); - /** - * @var XMPPHP_Log - */ - protected $log; - /** - * @var boolean - */ - protected $reconnect = true; - /** - * @var boolean - */ - protected $been_reset = false; - /** - * @var boolean - */ - protected $is_server; - /** - * @var float - */ - protected $last_send = 0; - /** - * @var boolean - */ - protected $use_ssl = false; - /** - * @var integer - */ - protected $reconnectTimeout = 30; +class XMLStream +{ + /** + * @var resource + */ + protected $socket; + /** + * @var resource + */ + protected $parser; + /** + * @var string + */ + protected $buffer; + /** + * @var integer + */ + protected $xml_depth = 0; + /** + * @var string + */ + protected $host; + /** + * @var integer + */ + protected $port; + /** + * @var string + */ + protected $stream_start = ''; + /** + * @var string + */ + protected $stream_end = ''; + /** + * @var boolean + */ + protected $disconnected = false; + /** + * @var boolean + */ + protected $sent_disconnect = false; + /** + * @var array + */ + protected $ns_map = array(); + /** + * @var array + */ + protected $current_ns = array(); + /** + * @var array + */ + protected $xmlobj = null; + /** + * @var array + */ + protected $nshandlers = array(); + /** + * @var array + */ + protected $xpathhandlers = array(); + /** + * @var array + */ + protected $idhandlers = array(); + /** + * @var array + */ + protected $eventhandlers = array(); + /** + * @var integer + */ + protected $lastid = 0; + /** + * @var string + */ + protected $default_ns; + /** + * @var string[] + */ + protected $until = []; + /** + * @var int[] + */ + protected $until_count = []; + /** + * @var array + */ + protected $until_happened = false; + /** + * @var array + */ + protected $until_payload = array(); + /** + * @var Log + */ + protected $log; + /** + * @var boolean + */ + protected $reconnect = true; + /** + * @var boolean + */ + protected $been_reset = false; + /** + * @var boolean + */ + protected $is_server; + /** + * @var float + */ + protected $last_send = 0; + /** + * @var boolean + */ + protected $use_ssl = false; + /** + * @var integer + */ + protected $reconnectTimeout = 30; - /** - * Constructor - * - * @param string $host - * @param string $port - * @param boolean $printlog - * @param string $loglevel - * @param boolean $is_server - */ - public function __construct($host = null, $port = null, $printlog = false, $loglevel = null, $is_server = false) { - $this->reconnect = !$is_server; - $this->is_server = $is_server; - $this->host = $host; - $this->port = $port; - $this->setupParser(); - $this->log = new XMPPHP_Log($printlog, $loglevel); - } + /** + * Constructor + * + * @param string $host + * @param string $port + * @param boolean $printlog + * @param string $loglevel + * @param boolean $is_server + */ + public function __construct($host = null, $port = null, $printlog = false, $loglevel = null, $is_server = false) + { + $this->reconnect = !$is_server; + $this->is_server = $is_server; + $this->host = $host; + $this->port = $port; + $this->setupParser(); + $this->log = new Log($printlog, $loglevel); + } - /** - * Destructor - * Cleanup connection - */ - public function __destruct() { - if(!$this->disconnected && $this->socket) { - $this->disconnect(); - } - } - - /** - * Return the log instance - * - * @return XMPPHP_Log - */ - public function getLog() { - return $this->log; - } - - /** - * Get next ID - * - * @return integer - */ - public function getId() { - $this->lastid++; - return $this->lastid; - } + /** + * Setup the XML parser + */ + public function setupParser() + { + $this->parser = xml_parser_create('UTF-8'); + xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1); + xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, 'UTF-8'); + xml_set_object($this->parser, $this); + xml_set_element_handler($this->parser, 'startXML', 'endXML'); + xml_set_character_data_handler($this->parser, 'charXML'); + } - /** - * Set SSL - * - * @return integer - */ - public function useSSL($use=true) { - $this->use_ssl = $use; - } + /** + * Destructor + * Cleanup connection + */ + public function __destruct() + { + if (!$this->disconnected && $this->socket) { + $this->disconnect(); + } + } - /** - * Add ID Handler - * - * @param integer $id - * @param string $pointer - * @param string $obj - */ - public function addIdHandler($id, $pointer, $obj = null) { - $this->idhandlers[$id] = array($pointer, $obj); - } + /** + * Disconnect from XMPP Host + */ + public function disconnect() + { + $this->log->log("Disconnecting...", Log::LEVEL_VERBOSE); + if (false == (bool)$this->socket) { + return; + } + $this->reconnect = false; + $this->send($this->stream_end); + $this->sent_disconnect = true; + $this->processUntil('end_stream', 5); + $this->disconnected = true; + } - /** - * Add Handler - * - * @param string $name - * @param string $ns - * @param string $pointer - * @param string $obj - * @param integer $depth - */ - public function addHandler($name, $ns, $pointer, $obj = null, $depth = 1) { - #TODO deprication warning - $this->nshandlers[] = array($name,$ns,$pointer,$obj, $depth); - } + /** + * Send to socket + * + * @param string $msg + * @param null $timeout + * @return bool|int + * @throws Exception + */ + public function send($msg, $timeout = NULL) + { - /** - * Add XPath Handler - * - * @param string $xpath - * @param string $pointer - * @param - */ - public function addXPathHandler($xpath, $pointer, $obj = null) { - if (preg_match_all("/\(?{[^\}]+}\)?(\/?)[^\/]+/", $xpath, $regs)) { - $ns_tags = $regs[0]; - } else { - $ns_tags = array($xpath); - } - foreach($ns_tags as $ns_tag) { - list($l, $r) = explode('}', $ns_tag); - if ($r != null) { - $xpart = array(substr($l, 1), $r); - } else { - $xpart = array(null, $l); - } - $xpath_array[] = $xpart; - } - $this->xpathhandlers[] = array($xpath_array, $pointer, $obj); - } + if (is_null($timeout)) { + $secs = NULL; + $usecs = NULL; + } else if ($timeout == 0) { + $secs = 0; + $usecs = 0; + } else { + $maximum = $timeout * 1000000; + $usecs = $maximum % 1000000; + $secs = floor(($maximum - $usecs) / 1000000); + } - /** - * Add Event Handler - * - * @param integer $id - * @param string $pointer - * @param string $obj - */ - public function addEventHandler($name, $pointer, $obj) { - $this->eventhandlers[] = array($name, $pointer, $obj); - } + $read = array(); + $write = array($this->socket); + $except = array(); - /** - * Connect to XMPP Host - * - * @param integer $timeout Timeout in seconds - * @param boolean $persistent - * @param boolean $sendinit Send XMPP starting sequence after connect - * automatically - * - * @throws XMPPHP_Exception When the connection fails - */ - public function connect($timeout = 30, $persistent = false, $sendinit = true) { - $this->sent_disconnect = false; - $starttime = time(); - - do { - $this->disconnected = false; - $this->sent_disconnect = false; - if($persistent) { - $conflag = STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT; - } else { - $conflag = STREAM_CLIENT_CONNECT; - } - $conntype = 'tcp'; - if($this->use_ssl) $conntype = 'ssl'; - $this->log->log("Connecting to $conntype://{$this->host}:{$this->port}"); - try { - $this->socket = @stream_socket_client("$conntype://{$this->host}:{$this->port}", $errno, $errstr, $timeout, $conflag); - } catch (Exception $e) { - throw new XMPPHP_Exception($e->getMessage()); - } - if(!$this->socket) { - $this->log->log("Could not connect.", XMPPHP_Log::LEVEL_ERROR); - $this->disconnected = true; - # Take it easy for a few seconds - sleep(min($timeout, 5)); - } - } while (!$this->socket && (time() - $starttime) < $timeout); - - if ($this->socket) { - stream_set_blocking($this->socket, 1); - if($sendinit) $this->send($this->stream_start); - } else { - throw new XMPPHP_Exception("Could not connect before timeout."); - } - } + $select = @stream_select($read, $write, $except, $secs, $usecs); - /** - * Reconnect XMPP Host - * - * @throws XMPPHP_Exception When the connection fails - * @uses $reconnectTimeout - * @see setReconnectTimeout() - */ - public function doReconnect() { - if(!$this->is_server) { - $this->log->log("Reconnecting ($this->reconnectTimeout)...", XMPPHP_Log::LEVEL_WARNING); - $this->connect($this->reconnectTimeout, false, false); - $this->reset(); - $this->event('reconnect'); - } - } + if ($select === False) { + $this->log->log("ERROR sending message; reconnecting."); + $this->doReconnect(); + # TODO: retry send here + return false; + } elseif ($select > 0) { + $this->log->log("Socket is ready; send it.", Log::LEVEL_VERBOSE); + } else { + $this->log->log("Socket is not ready; break.", Log::LEVEL_ERROR); + return false; + } - public function setReconnectTimeout($timeout) { - $this->reconnectTimeout = $timeout; - } - - /** - * Disconnect from XMPP Host - */ - public function disconnect() { - $this->log->log("Disconnecting...", XMPPHP_Log::LEVEL_VERBOSE); - if(false == (bool) $this->socket) { - return; - } - $this->reconnect = false; - $this->send($this->stream_end); - $this->sent_disconnect = true; - $this->processUntil('end_stream', 5); - $this->disconnected = true; - } + $sentbytes = @fwrite($this->socket, $msg); + $this->log->log("SENT: " . mb_substr($msg, 0, $sentbytes, '8bit'), Log::LEVEL_VERBOSE); + if ($sentbytes === FALSE) { + $this->log->log("ERROR sending message; reconnecting.", Log::LEVEL_ERROR); + $this->doReconnect(); + return false; + } + $this->log->log("Successfully sent $sentbytes bytes.", Log::LEVEL_VERBOSE); + return $sentbytes; + } - /** - * Are we are disconnected? - * - * @return boolean - */ - public function isDisconnected() { - return $this->disconnected; - } + /** + * Reconnect XMPP Host + * @throws Exception + */ + public function doReconnect() + { + if (!$this->is_server) { + $this->log->log("Reconnecting ($this->reconnectTimeout)...", Log::LEVEL_WARNING); + $this->connect($this->reconnectTimeout, false, false); + $this->reset(); + $this->event('reconnect'); + } + } - /** - * Checks if the given string is closed with the same tag as it is - * opened. We try to be as fast as possible here. - * - * @param string $buff Read buffer of __process() - * - * @return boolean true if the buffer seems to be complete - */ - protected function bufferComplete($buff) - { - if (substr($buff, -1) != '>') { - return false; - } - //we always have a space since the namespace needs to be - //declared. could be a tab, though - $start = substr( - $buff, 1, - min(strpos($buff, '>', 2), strpos($buff, ' ', 2)) - 1 - ); - $stop = substr($buff, -strlen($start) - 3); + /** + * Connect to XMPP Host + * + * @param integer $timeout + * @param boolean $persistent + * @param boolean $sendinit + * @throws Exception + * @throws Exception + */ + public function connect($timeout = 30, $persistent = false, $sendinit = true) + { + $this->sent_disconnect = false; + $starttime = time(); - if ($start == '?xml') { - //starting with an xml tag. this means a stream is being - // opened, which is not much of data, so no fear it's - // not complete - return true; - } - if (substr($stop, -2) == '/>') { - //one tag, i.e. - return true; - } - if ('' == $stop) { - return true; - } + do { + $this->disconnected = false; + $this->sent_disconnect = false; + if ($persistent) { + $conflag = STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT; + } else { + $conflag = STREAM_CLIENT_CONNECT; + } + $conntype = 'tcp'; + if ($this->use_ssl) $conntype = 'ssl'; + $this->log->log("Connecting to $conntype://{$this->host}:{$this->port}"); + $this->socket = @stream_socket_client("$conntype://{$this->host}:{$this->port}", $errno, $errstr, $timeout, $conflag); + if (!$this->socket) { + $this->log->log("Could not connect.", Log::LEVEL_ERROR); + $this->disconnected = true; + # Take it easy for a few seconds + sleep(min($timeout, 5)); + } + } while (!$this->socket && (time() - $starttime) < $timeout); - return false; - } + if ($this->socket) { + stream_set_blocking($this->socket, 1); + if ($sendinit) $this->send($this->stream_start); + } else { + throw new Exception("Could not connect before timeout."); + } + } - /** - * Core reading tool - * - * @param mixed $maximum Limit when to return - * - 0: only read if data is immediately ready - * - NULL: wait forever and ever - * - integer: process for this amount of microseconds - * @param boolean $return_when_received Immediately return when data have been - * received - * - * @return boolean True when all goes well, false when something fails - */ - private function __process($maximum = 5, $return_when_received = false) - { - $remaining = $maximum; - - do { - $starttime = (microtime(true) * 1000000); - $read = array($this->socket); - $write = array(); - $except = array(); - if (is_null($maximum)) { - $secs = NULL; - $usecs = NULL; - } else if ($maximum == 0) { - $secs = 0; - $usecs = 0; - } else { - $usecs = $remaining % 1000000; - $secs = floor(($remaining - $usecs) / 1000000); - } - $updated = @stream_select($read, $write, $except, $secs, $usecs); - if ($updated === false) { - $this->log->log("Error on stream_select()", XMPPHP_Log::LEVEL_VERBOSE); - if ($this->reconnect) { - $this->doReconnect(); - } else { - fclose($this->socket); - $this->socket = NULL; - return false; - } - } else if ($updated > 0) { - $buff = ''; - do { - if ($buff != '') { - //disable blocking for now because fread() will - // block until the 4k are full if we already - // read a part of the packet - stream_set_blocking($this->socket, 0); - } - $part = fread($this->socket, 4096); - stream_set_blocking($this->socket, 1); - if ($part === false) { - if($this->reconnect) { - $this->doReconnect(); - } else { - fclose($this->socket); - $this->socket = NULL; - return false; - } - } - $this->log->log("RECV: $part", XMPPHP_Log::LEVEL_VERBOSE); - $buff .= $part; - } while (!$this->bufferComplete($buff)); + /** + * Reset connection + */ + public function reset() + { + $this->xml_depth = 0; + unset($this->xmlobj); + $this->xmlobj = array(); + $this->setupParser(); + if (!$this->is_server) { + $this->send($this->stream_start); + } + $this->been_reset = true; + } - xml_parse($this->parser, $buff, false); - if ($return_when_received) { - return true; - } - } else { - # $updated == 0 means no changes during timeout. - } - $endtime = (microtime(true)*1000000); - $time_past = $endtime - $starttime; - $remaining = $remaining - $time_past; - } while (is_null($maximum) || $remaining > 0); - return true; - } - - /** - * Process - * - * @return string - */ - public function process() { - $this->__process(NULL); - } + /** + * Event? + * + * @param string $name + * @param string $payload + */ + public function event($name, $payload = null) + { + $this->log->log("EVENT: $name", Log::LEVEL_DEBUG); + foreach ($this->eventhandlers as $handler) { + if ($name == $handler[0]) { + if ($handler[2] === null) { + $handler[2] = $this; + } + $handler[2]->{$handler[1]}($payload); + } + } + foreach ($this->until as $key => $until) { + if (is_array($until)) { + if (in_array($name, $until)) { + $this->until_payload[$key][] = array($name, $payload); + if (!isset($this->until_count[$key])) { + $this->until_count[$key] = 0; + } + $this->until_count[$key] += 1; + #$this->until[$key] = false; + } + } + } + } - /** - * Process until a timeout occurs - * - * @param integer $timeout Time in seconds - * - * @return string - * - * @see __process() - */ - public function processTime($timeout=NULL) { - if (is_null($timeout)) { - return $this->__process(NULL); - } else { - return $this->__process($timeout * 1000000); - } - } + /** + * Process until a specified event or a timeout occurs + * + * @param string|array $event + * @param integer $timeout + * @return string + * @throws Exception + */ + public function processUntil($event, $timeout = -1) + { + $start = time(); + if (!is_array($event)) $event = array($event); + $this->until[] = $event; + end($this->until); + $event_key = key($this->until); + reset($this->until); + $this->until_count[$event_key] = 0; + while (!$this->disconnected and $this->until_count[$event_key] < 1 and (time() - $start < $timeout or $timeout == -1)) { + $this->__process(); + } + if (array_key_exists($event_key, $this->until_payload)) { + $payload = $this->until_payload[$event_key]; + unset($this->until_payload[$event_key]); + unset($this->until_count[$event_key]); + unset($this->until[$event_key]); + } else { + $payload = array(); + } + return $payload; + } - /** - * Process until a specified event or a timeout occurs - * - * @param string|array $event Event name or array of event names - * @param integer $timeout Timeout in seconds - * - * @return array Payload - */ - public function processUntil($event, $timeout = -1) - { - $start = time(); - if (!is_array($event)) { - $event = array($event); - } + /** + * Core reading tool + * 0 -> only read if data is immediately ready + * NULL -> wait forever and ever + * integer -> process for this amount of time + * @param int $maximum + * @return bool + * @throws Exception + */ - $this->until[] = $event; - end($this->until); - $event_key = key($this->until); - reset($this->until); + private function __process($maximum = 5) + { - $this->until_count[$event_key] = 0; - $updated = ''; - while (!$this->disconnected - && $this->until_count[$event_key] < 1 - && ($timeout == -1 || time() - $start < $timeout) - ) { - $maximum = $timeout == -1 - ? NULL - : ($timeout - (time() - $start)) * 1000000; - $ret = $this->__process($maximum, true); - if (!$ret) { - break; - } - } + $remaining = $maximum; - if (array_key_exists($event_key, $this->until_payload)) { - $payload = $this->until_payload[$event_key]; - unset($this->until_payload[$event_key]); - unset($this->until_count[$event_key]); - unset($this->until[$event_key]); - } else { - $payload = array(); - } + do { + $starttime = (microtime(true) * 1000000); + $read = array($this->socket); + $write = array(); + $except = array(); + if (is_null($maximum)) { + $secs = NULL; + $usecs = NULL; + } else if ($maximum == 0) { + $secs = 0; + $usecs = 0; + } else { + $usecs = $remaining % 1000000; + $secs = floor(($remaining - $usecs) / 1000000); + } + $updated = @stream_select($read, $write, $except, $secs, $usecs); + if ($updated === false) { + $this->log->log("Error on stream_select()", Log::LEVEL_VERBOSE); + if ($this->reconnect) { + $this->doReconnect(); + } else { + fclose($this->socket); + $this->socket = NULL; + return false; + } + } else if ($updated > 0) { + # XXX: Is this big enough? + $buff = @fread($this->socket, 4096); + if (!$buff) { + if ($this->reconnect) { + $this->doReconnect(); + } else { + fclose($this->socket); + $this->socket = NULL; + return false; + } + } + $this->log->log("RECV: $buff", Log::LEVEL_VERBOSE); + xml_parse($this->parser, $buff, false); + } // Otherwise, + // $updated == 0 means no changes during timeout. - return $payload; - } + $endtime = (microtime(true) * 1000000); + $time_past = $endtime - $starttime; + $remaining = $remaining - $time_past; + } while (is_null($maximum) || $remaining > 0); + return true; + } - /** - * Obsolete? - */ - public function Xapply_socket($socket) { - $this->socket = $socket; - } + /** + * Return the log instance + * + * @return Log + */ + public function getLog() + { + return $this->log; + } - /** - * XML start callback - * - * @see xml_set_element_handler - * - * @param resource $parser - * @param string $name - */ - public function startXML($parser, $name, $attr) { - if($this->been_reset) { - $this->been_reset = false; - $this->xml_depth = 0; - } - $this->xml_depth++; - if(array_key_exists('XMLNS', $attr)) { - $this->current_ns[$this->xml_depth] = $attr['XMLNS']; - } else { - $this->current_ns[$this->xml_depth] = $this->current_ns[$this->xml_depth - 1]; - if(!$this->current_ns[$this->xml_depth]) $this->current_ns[$this->xml_depth] = $this->default_ns; - } - $ns = $this->current_ns[$this->xml_depth]; - foreach($attr as $key => $value) { - if(strstr($key, ":")) { - $key = explode(':', $key); - $key = $key[1]; - $this->ns_map[$key] = $value; - } - } - if(!strstr($name, ":") === false) - { - $name = explode(':', $name); - $ns = $this->ns_map[$name[0]]; - $name = $name[1]; - } - $obj = new XMPPHP_XMLObj($name, $ns, $attr); - if($this->xml_depth > 1) { - $this->xmlobj[$this->xml_depth - 1]->subs[] = $obj; - } - $this->xmlobj[$this->xml_depth] = $obj; - } + /** + * Get next ID + * + * @return integer + */ + public function getId() + { + $this->lastid++; + return $this->lastid; + } - /** - * XML end callback - * - * @see xml_set_element_handler - * - * @param resource $parser - * @param string $name - */ - public function endXML($parser, $name) { - #$this->log->log("Ending $name", XMPPHP_Log::LEVEL_DEBUG); - #print "$name\n"; - if($this->been_reset) { - $this->been_reset = false; - $this->xml_depth = 0; - } - $this->xml_depth--; - if($this->xml_depth == 1) { - #clean-up old objects - #$found = false; #FIXME This didn't appear to be in use --Gar - foreach($this->xpathhandlers as $handler) { - if (is_array($this->xmlobj) && array_key_exists(2, $this->xmlobj)) { - $searchxml = $this->xmlobj[2]; - $nstag = array_shift($handler[0]); - if (($nstag[0] == null or $searchxml->ns == $nstag[0]) and ($nstag[1] == "*" or $nstag[1] == $searchxml->name)) { - foreach($handler[0] as $nstag) { - if ($searchxml !== null and $searchxml->hasSub($nstag[1], $ns=$nstag[0])) { - $searchxml = $searchxml->sub($nstag[1], $ns=$nstag[0]); - } else { - $searchxml = null; - break; - } - } - if ($searchxml !== null) { - if($handler[2] === null) $handler[2] = $this; - $this->log->log("Calling {$handler[1]}", XMPPHP_Log::LEVEL_DEBUG); - $handler[2]->$handler[1]($this->xmlobj[2]); - } - } - } - } - foreach($this->nshandlers as $handler) { - if($handler[4] != 1 and array_key_exists(2, $this->xmlobj) and $this->xmlobj[2]->hasSub($handler[0])) { - $searchxml = $this->xmlobj[2]->sub($handler[0]); - } elseif(is_array($this->xmlobj) and array_key_exists(2, $this->xmlobj)) { - $searchxml = $this->xmlobj[2]; - } - if($searchxml !== null and $searchxml->name == $handler[0] and ($searchxml->ns == $handler[1] or (!$handler[1] and $searchxml->ns == $this->default_ns))) { - if($handler[3] === null) $handler[3] = $this; - $this->log->log("Calling {$handler[2]}", XMPPHP_Log::LEVEL_DEBUG); - $handler[3]->$handler[2]($this->xmlobj[2]); - } - } - foreach($this->idhandlers as $id => $handler) { - if(array_key_exists('id', $this->xmlobj[2]->attrs) and $this->xmlobj[2]->attrs['id'] == $id) { - if($handler[1] === null) $handler[1] = $this; - $handler[1]->$handler[0]($this->xmlobj[2]); - #id handlers are only used once - unset($this->idhandlers[$id]); - break; - } - } - if(is_array($this->xmlobj)) { - $this->xmlobj = array_slice($this->xmlobj, 0, 1); - if(isset($this->xmlobj[0]) && $this->xmlobj[0] instanceof XMPPHP_XMLObj) { - $this->xmlobj[0]->subs = null; - } - } - unset($this->xmlobj[2]); - } - if($this->xml_depth == 0 and !$this->been_reset) { - if(!$this->disconnected) { - if(!$this->sent_disconnect) { - $this->send($this->stream_end); - } - $this->disconnected = true; - $this->sent_disconnect = true; - fclose($this->socket); - if($this->reconnect) { - $this->doReconnect(); - } - } - $this->event('end_stream'); - } - } + /** + * Set SSL + * @param bool $use + */ + public function useSSL($use = true) + { + $this->use_ssl = $use; + } - /** - * XML character callback - * @see xml_set_character_data_handler - * - * @param resource $parser - * @param string $data - */ - public function charXML($parser, $data) { - if(array_key_exists($this->xml_depth, $this->xmlobj)) { - $this->xmlobj[$this->xml_depth]->data .= $data; - } - } + /** + * Add ID Handler + * + * @param integer $id + * @param string $pointer + * @param string $obj + */ + public function addIdHandler($id, $pointer, $obj = null) + { + $this->idhandlers[$id] = array($pointer, $obj); + } - /** - * Event? - * - * @param string $name - * @param string $payload - */ - public function event($name, $payload = null) { - $this->log->log("EVENT: $name", XMPPHP_Log::LEVEL_DEBUG); - foreach($this->eventhandlers as $handler) { - if($name == $handler[0]) { - if($handler[2] === null) { - $handler[2] = $this; - } - $handler[2]->$handler[1]($payload); - } - } - foreach($this->until as $key => $until) { - if(is_array($until)) { - if(in_array($name, $until)) { - $this->until_payload[$key][] = array($name, $payload); - if(!isset($this->until_count[$key])) { - $this->until_count[$key] = 0; - } - $this->until_count[$key] += 1; - #$this->until[$key] = false; - } - } - } - } + /** + * Add Handler + * + * @param string $name + * @param string $ns + * @param string $pointer + * @param string $obj + * @param integer $depth + */ + public function addHandler($name, $ns, $pointer, $obj = null, $depth = 1) + { + #TODO deprication warning + $this->nshandlers[] = array($name, $ns, $pointer, $obj, $depth); + } - /** - * Read from socket - */ - public function read() { - $buff = @fread($this->socket, 1024); - if(!$buff) { - if($this->reconnect) { - $this->doReconnect(); - } else { - fclose($this->socket); - return false; - } - } - $this->log->log("RECV: $buff", XMPPHP_Log::LEVEL_VERBOSE); - xml_parse($this->parser, $buff, false); - } + /** + * Add XPath Handler + * + * @param string $xpath + * @param string $pointer + * @param + */ + public function addXPathHandler($xpath, $pointer, $obj = null) + { + if (preg_match_all("/\(?{[^\}]+}\)?(\/?)[^\/]+/", $xpath, $regs)) { + $ns_tags = $regs[0]; + } else { + $ns_tags = array($xpath); + } + foreach ($ns_tags as $ns_tag) { + list($l, $r) = explode("}", $ns_tag); + if ($r != null) { + $xpart = array(substr($l, 1), $r); + } else { + $xpart = array(null, $l); + } + $xpath_array[] = $xpart; + } + $this->xpathhandlers[] = array($xpath_array, $pointer, $obj); + } - /** - * Send to socket - * - * @param string $msg - */ - public function send($msg, $timeout=NULL) { + /** + * Add Event Handler + * + * @param $name + * @param string $pointer + * @param string $obj + */ + public function addEventHandler($name, $pointer, $obj) + { + $this->eventhandlers[] = array($name, $pointer, $obj); + } - if (is_null($timeout)) { - $secs = NULL; - $usecs = NULL; - } else if ($timeout == 0) { - $secs = 0; - $usecs = 0; - } else { - $maximum = $timeout * 1000000; - $usecs = $maximum % 1000000; - $secs = floor(($maximum - $usecs) / 1000000); - } - - $read = array(); - $write = array($this->socket); - $except = array(); - - $select = @stream_select($read, $write, $except, $secs, $usecs); - - if($select === False) { - $this->log->log("ERROR sending message; reconnecting."); - $this->doReconnect(); - # TODO: retry send here - return false; - } elseif ($select > 0) { - $this->log->log("Socket is ready; send it.", XMPPHP_Log::LEVEL_VERBOSE); - } else { - $this->log->log("Socket is not ready; break.", XMPPHP_Log::LEVEL_ERROR); - return false; - } - - $sentbytes = @fwrite($this->socket, $msg); - $this->log->log("SENT: " . mb_substr($msg, 0, $sentbytes, '8bit'), XMPPHP_Log::LEVEL_VERBOSE); - if($sentbytes === FALSE) { - $this->log->log("ERROR sending message; reconnecting.", XMPPHP_Log::LEVEL_ERROR); - $this->doReconnect(); - return false; - } - $this->log->log("Successfully sent $sentbytes bytes.", XMPPHP_Log::LEVEL_VERBOSE); - return $sentbytes; - } + public function setReconnectTimeout($timeout) + { + $this->reconnectTimeout = $timeout; + } - public function time() { - list($usec, $sec) = explode(" ", microtime()); - return (float)$sec + (float)$usec; - } + /** + * Are we are disconnected? + * + * @return boolean + */ + public function isDisconnected() + { + return $this->disconnected; + } - /** - * Reset connection - */ - public function reset() { - $this->xml_depth = 0; - unset($this->xmlobj); - $this->xmlobj = array(); - $this->setupParser(); - if(!$this->is_server) { - $this->send($this->stream_start); - } - $this->been_reset = true; - } + /** + * Process + * + */ + public function process() + { + $this->__process(NULL); + } - /** - * Setup the XML parser - */ - public function setupParser() { - $this->parser = xml_parser_create('UTF-8'); - xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1); - xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, 'UTF-8'); - xml_set_object($this->parser, $this); - xml_set_element_handler($this->parser, 'startXML', 'endXML'); - xml_set_character_data_handler($this->parser, 'charXML'); - } + /** + * Process until a timeout occurs + * + * @param integer $timeout + * @return string + * @throws Exception + */ + public function processTime($timeout = NULL) + { + if (is_null($timeout)) { + return $this->__process(NULL); + } else { + return $this->__process($timeout * 1000000); + } + } - public function readyToProcess() { - $read = array($this->socket); - $write = array(); - $except = array(); - $updated = @stream_select($read, $write, $except, 0); - return (($updated !== false) && ($updated > 0)); - } + /** + * Obsolete? + * @param $socket + */ + public function Xapply_socket($socket) + { + $this->socket = $socket; + } + + /** + * XML start callback + * + * @param resource $parser + * @param string $name + * @param $attr + * @see xml_set_element_handler + */ + public function startXML($parser, $name, $attr) + { + if ($this->been_reset) { + $this->been_reset = false; + $this->xml_depth = 0; + } + $this->xml_depth++; + if (array_key_exists('XMLNS', $attr)) { + $this->current_ns[$this->xml_depth] = $attr['XMLNS']; + } else { + $this->current_ns[$this->xml_depth] = $this->current_ns[$this->xml_depth - 1]; + if (!$this->current_ns[$this->xml_depth]) $this->current_ns[$this->xml_depth] = $this->default_ns; + } + $ns = $this->current_ns[$this->xml_depth]; + foreach ($attr as $key => $value) { + if (strstr($key, ":")) { + $key = explode(':', $key); + $key = $key[1]; + $this->ns_map[$key] = $value; + } + } + if (!strstr($name, ":") === false) { + $name = explode(':', $name); + $ns = $this->ns_map[$name[0]]; + $name = $name[1]; + } + $obj = new XMLObj($name, $ns, $attr); + if ($this->xml_depth > 1) { + $this->xmlobj[$this->xml_depth - 1]->subs[] = $obj; + } + $this->xmlobj[$this->xml_depth] = $obj; + } + + /** + * XML end callback + * + * @param resource $parser + * @param string $name + * @throws Exception + * @see xml_set_element_handler + * + */ + public function endXML($parser, $name) + { + #$this->log->log("Ending $name", Log::LEVEL_DEBUG); + #print "$name\n"; + if ($this->been_reset) { + $this->been_reset = false; + $this->xml_depth = 0; + } + $this->xml_depth--; + if ($this->xml_depth == 1) { + #clean-up old objects + #$found = false; #FIXME This didn't appear to be in use --Gar + foreach ($this->xpathhandlers as $handler) { + if (is_array($this->xmlobj) && array_key_exists(2, $this->xmlobj)) { + $searchxml = $this->xmlobj[2]; + $nstag = array_shift($handler[0]); + if (($nstag[0] == null or $searchxml->ns == $nstag[0]) and ($nstag[1] == "*" or $nstag[1] == $searchxml->name)) { + foreach ($handler[0] as $nstag) { + if ($searchxml !== null and $searchxml->hasSub($nstag[1], $ns = $nstag[0])) { + $searchxml = $searchxml->sub($nstag[1], $ns = $nstag[0]); + } else { + $searchxml = null; + break; + } + } + if ($searchxml !== null) { + if ($handler[2] === null) $handler[2] = $this; + $this->log->log("Calling {$handler[1]}", Log::LEVEL_DEBUG); + $handler[2]->{$handler[1]}($this->xmlobj[2]); + } + } + } + } + foreach ($this->nshandlers as $handler) { + if ($handler[4] != 1 and array_key_exists(2, $this->xmlobj) and $this->xmlobj[2]->hasSub($handler[0])) { + $searchxml = $this->xmlobj[2]->sub($handler[0]); + } elseif (is_array($this->xmlobj) and array_key_exists(2, $this->xmlobj)) { + $searchxml = $this->xmlobj[2]; + } + if ($searchxml !== null and $searchxml->name == $handler[0] and ($searchxml->ns == $handler[1] or (!$handler[1] and $searchxml->ns == $this->default_ns))) { + if ($handler[3] === null) $handler[3] = $this; + $this->log->log("Calling {$handler[2]}", Log::LEVEL_DEBUG); + $handler[3]->{$handler[2]}($this->xmlobj[2]); + } + } + foreach ($this->idhandlers as $id => $handler) { + if (array_key_exists('id', $this->xmlobj[2]->attrs) and $this->xmlobj[2]->attrs['id'] == $id) { + if ($handler[1] === null) $handler[1] = $this; + $handler[1]->{$handler[0]}($this->xmlobj[2]); + #id handlers are only used once + unset($this->idhandlers[$id]); + break; + } + } + if (is_array($this->xmlobj)) { + $this->xmlobj = array_slice($this->xmlobj, 0, 1); + if (isset($this->xmlobj[0]) && $this->xmlobj[0] instanceof XMLObj) { + $this->xmlobj[0]->subs = null; + } + } + unset($this->xmlobj[2]); + } + if ($this->xml_depth == 0 and !$this->been_reset) { + if (!$this->disconnected) { + if (!$this->sent_disconnect) { + $this->send($this->stream_end); + } + $this->disconnected = true; + $this->sent_disconnect = true; + fclose($this->socket); + if ($this->reconnect) { + $this->doReconnect(); + } + } + $this->event('end_stream'); + } + } + + /** + * XML character callback + * @param resource $parser + * @param string $data + * @see xml_set_character_data_handler + * + */ + public function charXML($parser, $data) + { + if (array_key_exists($this->xml_depth, $this->xmlobj)) { + $this->xmlobj[$this->xml_depth]->data .= $data; + } + } + + /** + * Read from socket + */ + public function read() + { + $buff = @fread($this->socket, 1024); + if (!$buff) { + if ($this->reconnect) { + $this->doReconnect(); + } else { + fclose($this->socket); + return false; + } + } + $this->log->log("RECV: $buff", Log::LEVEL_VERBOSE); + xml_parse($this->parser, $buff, false); + } + + public function time() + { + list($usec, $sec) = explode(" ", microtime()); + return (float)$sec + (float)$usec; + } + + public function readyToProcess() + { + $read = array($this->socket); + $write = array(); + $except = array(); + $updated = @stream_select($read, $write, $except, 0); + return (($updated !== false) && ($updated > 0)); + } } diff --git a/XMPPHP/XMPP.php b/XMPPHP/XMPP.php index a724a5c..55b58db 100644 --- a/XMPPHP/XMPP.php +++ b/XMPPHP/XMPP.php @@ -1,565 +1,477 @@ - * @author Stephan Wentz - * @author Michael Garvin + * @category xmpphp + * @package XMPPHP + * @author Nathanael C. Fritz + * @author Stephan Wentz + * @author Michael Garvin + * @author Alexander Birkner (https://github.com/BirknerAlex) + * @author zorn-v (https://github.com/zorn-v/xmpphp/) + * @author GNU social * @copyright 2008 Nathanael C. Fritz */ +namespace XMPPHP; + /** XMPPHP_XMLStream */ -require_once 'XMPPHP/XMLStream.php'; -require_once 'XMPPHP/Roster.php'; +require_once __DIR__ . DIRECTORY_SEPARATOR . 'XMLStream.php'; +require_once __DIR__ . DIRECTORY_SEPARATOR . 'Roster.php'; + /** - * XMPPHP Main Class - * - * @category xmpphp - * @package XMPPHP - * @author Nathanael C. Fritz - * @author Stephan Wentz - * @author Michael Garvin - * @copyright 2008 Nathanael C. Fritz - * @version $Id$ + * XMPPHP XMPP + * + * @package XMPPHP + * @author Nathanael C. Fritz + * @author Stephan Wentz + * @author Michael Garvin + * @copyright 2008 Nathanael C. Fritz + * @version $Id$ */ -class XMPPHP_XMPP extends XMPPHP_XMLStream { - /** - * @var string - */ - public $server; +class XMPP extends XMLStream +{ + /** + * @var string + */ + public $server; - /** - * @var string - */ - public $user; - - /** - * @var string - */ - protected $password; - - /** - * @var string - */ - protected $resource; - - /** - * @var string - */ - protected $fulljid; - - /** - * @var string - */ - protected $basejid; - - /** - * @var boolean - */ - protected $authed = false; - protected $session_started = false; - - /** - * @var boolean - */ - protected $auto_subscribe = false; - - /** - * @var boolean - */ - protected $use_encryption = true; - - /** - * @var boolean - */ - public $track_presence = true; - - /** - * @var object - */ - public $roster; + /** + * @var string + */ + public $user; + /** + * @var boolean + */ + public $track_presence = true; + /** + * @var object + */ + public $roster; + /** + * @var string + */ + protected $password; + /** + * @var string + */ + protected $resource; + /** + * @var string + */ + protected $fulljid; + /** + * @var string + */ + protected $basejid; + /** + * @var boolean + */ + protected $authed = false; + protected $session_started = false; + /** + * @var boolean + */ + protected $auto_subscribe = false; + /** + * @var boolean + */ + protected $use_encryption = true; - /** - * @var array supported auth mechanisms - */ - protected $auth_mechanism_supported = array('PLAIN', 'DIGEST-MD5'); + /** + * Constructor + * + * @param string $host + * @param integer $port + * @param string $user + * @param string $password + * @param string $resource + * @param string $server + * @param boolean $printlog + * @param string $loglevel + */ + public function __construct($host, $port, $user, $password, $resource, $server = null, $printlog = false, $loglevel = null) + { + parent::__construct($host, $port, $printlog, $loglevel); - /** - * @var string default auth mechanism - */ - protected $auth_mechanism_default = 'PLAIN'; + $this->user = $user; + $this->password = $password; + $this->resource = $resource; + if (!$server) { + $server = $host; + } + $this->server = $server; + $this->basejid = $this->user . '@' . $this->host; - /** - * @var string prefered auth mechanism - */ - protected $auth_mechanism_preferred = 'DIGEST-MD5'; + $this->roster = new Roster(); + $this->track_presence = true; - /** - * Constructor - * - * @param string $host - * @param integer $port - * @param string $user - * @param string $password - * @param string $resource - * @param string $server - * @param boolean $printlog - * @param string $loglevel - */ - public function __construct($host, $port, $user, $password, $resource, $server = null, $printlog = false, $loglevel = null) { - parent::__construct($host, $port, $printlog, $loglevel); - - $this->user = $user; - $this->password = $password; - $this->resource = $resource; - if(!$server) $server = $host; - $this->server = $server; - $this->basejid = $this->user . '@' . $this->host; + $this->stream_start = ''; + $this->stream_end = ''; + $this->default_ns = 'jabber:client'; - $this->roster = new Roster(); - $this->track_presence = true; + $this->addXPathHandler('{http://etherx.jabber.org/streams}features', 'features_handler'); + $this->addXPathHandler('{urn:ietf:params:xml:ns:xmpp-sasl}success', 'sasl_success_handler'); + $this->addXPathHandler('{urn:ietf:params:xml:ns:xmpp-sasl}failure', 'sasl_failure_handler'); + $this->addXPathHandler('{urn:ietf:params:xml:ns:xmpp-tls}proceed', 'tls_proceed_handler'); + $this->addXPathHandler('{jabber:client}message', 'message_handler'); + $this->addXPathHandler('{jabber:client}presence', 'presence_handler'); + $this->addXPathHandler('iq/{jabber:iq:roster}query', 'roster_iq_handler'); + } - $this->stream_start = ''; - $this->stream_end = ''; - $this->default_ns = 'jabber:client'; - - $this->addXPathHandler('{http://etherx.jabber.org/streams}features', 'features_handler'); - $this->addXPathHandler('{urn:ietf:params:xml:ns:xmpp-sasl}success', 'sasl_success_handler'); - $this->addXPathHandler('{urn:ietf:params:xml:ns:xmpp-sasl}failure', 'sasl_failure_handler'); - $this->addXPathHandler('{urn:ietf:params:xml:ns:xmpp-tls}proceed', 'tls_proceed_handler'); - $this->addXPathHandler('{jabber:client}message', 'message_handler'); - $this->addXPathHandler('{jabber:client}presence', 'presence_handler'); - $this->addXPathHandler('iq/{jabber:iq:roster}query', 'roster_iq_handler'); - // For DIGEST-MD5 auth : - $this->addXPathHandler('{urn:ietf:params:xml:ns:xmpp-sasl}challenge', 'sasl_challenge_handler'); - } + /** + * Turn encryption on/ff + * + * @param boolean $useEncryption + */ + public function useEncryption($useEncryption = true) + { + $this->use_encryption = $useEncryption; + } - /** - * Turn encryption on/ff - * - * @param boolean $useEncryption - */ - public function useEncryption($useEncryption = true) { - $this->use_encryption = $useEncryption; - } - - /** - * Turn on auto-authorization of subscription requests. - * - * @param boolean $autoSubscribe - */ - public function autoSubscribe($autoSubscribe = true) { - $this->auto_subscribe = $autoSubscribe; - } + /** + * Turn on auto-authorization of subscription requests. + * + * @param boolean $autoSubscribe + */ + public function autoSubscribe($autoSubscribe = true) + { + $this->auto_subscribe = $autoSubscribe; + } - /** - * Send XMPP Message - * - * @param string $to - * @param string $body - * @param string $type - * @param string $subject - */ - public function message($to, $body, $type = 'chat', $subject = null, $payload = null) { - if(is_null($type)) - { - $type = 'chat'; - } - - $to = htmlspecialchars($to); - $body = htmlspecialchars($body); - $subject = htmlspecialchars($subject); - - $out = "fulljid}\" to=\"$to\" type='$type'>"; - if($subject) $out .= "$subject"; - $out .= "$body"; - if($payload) $out .= $payload; - $out .= ""; - - $this->send($out); - } + /** + * Send XMPP Message + * + * @param string $to + * @param string $body + * @param string $type + * @param string $subject + * @param null $payload + * @throws Exception + */ + public function message($to, $body, $type = 'chat', $subject = null, $payload = null) + { + if ($this->disconnected) { + throw new Exception('You need to connect first'); + } - /** - * Set Presence - * - * @param string $status - * @param string $show - * @param string $to - */ - public function presence($status = null, $show = 'available', $to = null, $type='available', $priority=null) { - if($type == 'available') $type = ''; - $to = htmlspecialchars($to); - $status = htmlspecialchars($status); - if($show == 'unavailable') $type = 'unavailable'; - - $out = "send($out); - } - /** - * Send Auth request - * - * @param string $jid - */ - public function subscribe($jid) { - $this->send(""); - #$this->send(""); - } + if (empty($type)) { + $type = 'chat'; + } - /** - * Add user to Roster - * - * @param string $jid user jid - * @param string $name user nickname - * @param string $group group to add - */ - public function RosterAddUser($jid, $name=null, $group=null) { - $payload = "\n". - ($group?''.htmlspecialchars($group, ENT_QUOTES, 'UTF-8').'':''); - $this->SendIq(NULL, 'set', "jabber:iq:roster", $payload); - } + $to = htmlspecialchars($to); + $body = htmlspecialchars($body); + $subject = htmlspecialchars($subject); + $subject = ($subject) ? '' . $subject . '' : ''; + $payload = ($payload) ? $payload : ''; + $sprintf = '%s%s%s'; + $output = sprintf($sprintf, $this->fulljid, $to, $type, $subject, $body, $payload); + $this->send($output); + } - /** - * Send ID action - * - * @param string $to to jid - * @param string $type type of ID - * @param string $xmlns xmlns name - * @param string $payload payload string - * @param string $from from jid - */ - private function sendIq($to = NULL, $type = 'get', $xmlns = NULL, $payload = NULL, $from = NULL) - { - $id = $this->getID(); - $xml = " - - $payload - - "; - return $this->send($xml); - } + /** + * Set Presence + * + * @param string $status + * @param string $show + * @param string $to + * @param string $type + * @param null $priority + * @throws Exception + */ + public function presence($status = null, $show = 'available', $to = null, $type = 'available', $priority = null) + { + if ($this->disconnected) { + throw new Exception('You need to connect first'); + } - /** - * Message handler - * - * @param string $xml - */ - public function message_handler($xml) { - if(isset($xml->attrs['type'])) { - $payload['type'] = $xml->attrs['type']; - } else { - $payload['type'] = 'chat'; - } - $body = $xml->sub('body'); - $payload['from'] = $xml->attrs['from']; - $payload['body'] = is_object($body) ? $body->data : FALSE; // $xml->sub('body')->data; - $payload['xml'] = $xml; - $this->log->log("Message: {$payload['body']}", XMPPHP_Log::LEVEL_DEBUG); - $this->event('message', $payload); - } + if ($type == 'available') { + $type = ''; + } + $to = htmlspecialchars($to); + $status = htmlspecialchars($status); + if ($show == 'unavailable') { + $type = 'unavailable'; + } - /** - * Presence handler - * - * @param string $xml - */ - public function presence_handler($xml) { - $payload['type'] = (isset($xml->attrs['type'])) ? $xml->attrs['type'] : 'available'; - $payload['show'] = (isset($xml->sub('show')->data)) ? $xml->sub('show')->data : $payload['type']; - $payload['from'] = $xml->attrs['from']; - $payload['status'] = (isset($xml->sub('status')->data)) ? $xml->sub('status')->data : ''; - $payload['priority'] = (isset($xml->sub('priority')->data)) ? intval($xml->sub('priority')->data) : 0; - $payload['xml'] = $xml; - if($this->track_presence) { - $this->roster->setPresence($payload['from'], $payload['priority'], $payload['show'], $payload['status']); - } - $this->log->log("Presence: {$payload['from']} [{$payload['show']}] {$payload['status']}", XMPPHP_Log::LEVEL_DEBUG); - if(array_key_exists('type', $xml->attrs) and $xml->attrs['type'] == 'subscribe') { - if($this->auto_subscribe) { - $this->send(""); - $this->send(""); - } - $this->event('subscription_requested', $payload); - } elseif(array_key_exists('type', $xml->attrs) and $xml->attrs['type'] == 'subscribed') { - $this->event('subscription_accepted', $payload); - } else { - $this->event('presence', $payload); - } - } + $out = "hasSub('starttls') and $this->use_encryption) { - $this->send(""); - } elseif($xml->hasSub('bind') and $this->authed) { - $id = $this->getId(); - $this->addIdHandler($id, 'resource_bind_handler'); - $this->send("{$this->resource}"); - } else { - $this->log->log("Attempting Auth..."); - if ($this->password) { - $mechanism = 'PLAIN'; // default; - if ($xml->hasSub('mechanisms') && $xml->sub('mechanisms')->hasSub('mechanism')) { - // Get the list of all available auth mechanism that we can use - $available = array(); - foreach ($xml->sub('mechanisms')->subs as $sub) { - if ($sub->name == 'mechanism') { - if (in_array($sub->data, $this->auth_mechanism_supported)) { - $available[$sub->data] = $sub->data; - } - } - } - if (isset($available[$this->auth_mechanism_preferred])) { - $mechanism = $this->auth_mechanism_preferred; - } else { - // use the first available - $mechanism = reset($available); - } - $this->log->log("Trying $mechanism (available : " . implode(',', $available) . ')'); - } - switch ($mechanism) { - case 'PLAIN': - $this->send("" . base64_encode("\x00" . $this->user . "\x00" . $this->password) . ""); - break; - case 'DIGEST-MD5': - $this->send(""); - break; - } - } else { - $this->send(""); - } - } - } + $this->send($out); + } - /** - * SASL success handler - * - * @param string $xml - */ - protected function sasl_success_handler($xml) { - $this->log->log("Auth success!"); - $this->authed = true; - $this->reset(); - } - - /** - * SASL feature handler - * - * @param string $xml - */ - protected function sasl_failure_handler($xml) { - $this->log->log("Auth failed!", XMPPHP_Log::LEVEL_ERROR); - $this->disconnect(); - - throw new XMPPHP_Exception('Auth failed!'); - } + /** + * Send Auth request + * + * @param string $jid + */ + public function subscribe($jid) + { + $this->send(""); + #$this->send(""); + } - /** - * Handle challenges for DIGEST-MD5 auth - * - * @param string $xml - */ - protected function sasl_challenge_handler($xml) { - // Decode and parse the challenge string - // (may be something like foo="bar",foo2="bar2,bar3,bar4",foo3=bar5 ) - $challenge = base64_decode($xml->data); - $vars = array(); - $matches = array(); - preg_match_all('/(\w+)=(?:"([^"]*)|([^,]*))/', $challenge, $matches); - $res = array(); - foreach ($matches[1] as $k => $v) { - $vars[$v] = (empty($matches[2][$k])?$matches[3][$k]:$matches[2][$k]); - } + /** + * Message handler + * + * @param string $xml + */ + public function message_handler($xml) + { + if (isset($xml->attrs['type'])) { + $payload['type'] = $xml->attrs['type']; + } else { + $payload['type'] = 'chat'; + } + $body = $xml->sub('body'); + $payload['from'] = $xml->attrs['from']; + $payload['body'] = is_object($body) ? $body->data : false; // $xml->sub('body')->data; + $payload['xml'] = $xml; + $this->log->log("Message: {$payload['body']}", Log::LEVEL_DEBUG); + $this->event('message', $payload); + } - if (isset($vars['nonce'])) { - // First step - $vars['cnonce'] = uniqid(mt_rand(), false); - $vars['nc'] = '00000001'; - $vars['qop'] = 'auth'; // Force qop to auth - if (!isset($vars['digest-uri'])) $vars['digest-uri'] = 'xmpp/' . $this->server; - if (!isset($vars['realm'])) $vars['realm'] = ''; + /** + * Presence handler + * + * @param string $xml + */ + public function presence_handler($xml) + { + $payload['type'] = (isset($xml->attrs['type'])) ? $xml->attrs['type'] : 'available'; + $payload['show'] = (isset($xml->sub('show')->data)) ? $xml->sub('show')->data : $payload['type']; + $payload['from'] = $xml->attrs['from']; + $payload['status'] = (isset($xml->sub('status')->data)) ? $xml->sub('status')->data : ''; + $payload['priority'] = (isset($xml->sub('priority')->data)) ? intval($xml->sub('priority')->data) : 0; + $payload['xml'] = $xml; + if ($this->track_presence) { + $this->roster->setPresence($payload['from'], $payload['priority'], $payload['show'], $payload['status']); + } + $this->log->log("Presence: {$payload['from']} [{$payload['show']}] {$payload['status']}", Log::LEVEL_DEBUG); + if (array_key_exists('type', $xml->attrs) and $xml->attrs['type'] == 'subscribe') { + if ($this->auto_subscribe) { + $this->send(""); + $this->send(""); + } + $this->event('subscription_requested', $payload); + } elseif (array_key_exists('type', $xml->attrs) and $xml->attrs['type'] == 'subscribed') { + $this->event('subscription_accepted', $payload); + } else { + $this->event('presence', $payload); + } + } - // now, the magic... - $a1 = sprintf('%s:%s:%s', $this->user, $vars['realm'], $this->password); - if ($vars['algorithm'] == 'md5-sess') { - $a1 = pack('H32',md5($a1)) . ':' . $vars['nonce'] . ':' . $vars['cnonce']; - } - $a2 = "AUTHENTICATE:" . $vars['digest-uri']; - $password = md5($a1) . ':' . $vars['nonce'] . ':' . $vars['nc'] . ':' . $vars['cnonce'] . ':' . $vars['qop'] . ':' .md5($a2); - $password = md5($password); - $response = sprintf('username="%s",realm="%s",nonce="%s",cnonce="%s",nc=%s,qop=%s,digest-uri="%s",response=%s,charset=utf-8', - $this->user, $vars['realm'], $vars['nonce'], $vars['cnonce'], $vars['nc'], $vars['qop'], $vars['digest-uri'], $password); + /** + * Retrieves the roster + * + */ + public function getRoster() + { + $id = $this->getID(); + $this->send(""); + } - // Send the response - $response = base64_encode($response); - $this->send("$response"); - } else { - if (isset($vars['rspauth'])) { - // Second step - $this->send(""); - } else { - $this->log->log("ERROR receiving challenge : " . $challenge, XMPPHP_Log::LEVEL_ERROR); - } + /** + * Retrieves the vcard + * @param null $jid + */ + public function getVCard($jid = null) + { + $id = $this->getID(); + $this->addIdHandler($id, 'vcard_get_handler'); + if ($jid) { + $this->send(""); + } else { + $this->send(""); + } + } - } - } + /** + * Features handler + * + * @param string $xml + */ + protected function features_handler($xml) + { + if ($xml->hasSub('starttls') and $this->use_encryption) { + $this->send(""); + } elseif ($xml->hasSub('bind') and $this->authed) { + $id = $this->getId(); + $this->addIdHandler($id, 'resource_bind_handler'); + $this->send("{$this->resource}"); + } else { + $this->log->log("Attempting Auth..."); + if ($this->password) { + $this->send("" . base64_encode("\x00" . $this->user . "\x00" . $this->password) . ""); + } else { + $this->send(""); + } + } + } - /** - * Resource bind handler - * - * @param string $xml - */ - protected function resource_bind_handler($xml) { - if($xml->attrs['type'] == 'result') { - $this->log->log("Bound to " . $xml->sub('bind')->sub('jid')->data); - $this->fulljid = $xml->sub('bind')->sub('jid')->data; - $jidarray = explode('/',$this->fulljid); - $this->jid = $jidarray[0]; - } - $id = $this->getId(); - $this->addIdHandler($id, 'session_start_handler'); - $this->send(""); - } + /** + * SASL success handler + * + * @param string $xml + */ + protected function sasl_success_handler($xml) + { + $this->log->log("Auth success!"); + $this->authed = true; + $this->reset(); + } - /** - * Retrieves the roster - * - */ - public function getRoster() { - $id = $this->getID(); - $this->send(""); - } + /** + * SASL feature handler + * + * @param string $xml + * @throws Exception + */ + protected function sasl_failure_handler($xml) + { + $this->log->log("Auth failed!", Log::LEVEL_ERROR); + $this->disconnect(); - /** - * Roster iq handler - * Gets all packets matching XPath "iq/{jabber:iq:roster}query' - * - * Implements RFC3921, 7.4. "Adding a Roster Item" - * - * @param string $xml - */ - protected function roster_iq_handler($xml) { - $status = "result"; - $xmlroster = $xml->sub('query'); - foreach($xmlroster->subs as $item) { - $groups = array(); - if ($item->name == 'item') { - $jid = $item->attrs['jid']; //REQUIRED - $name = $item->attrs['name']; //MAY - $subscription = $item->attrs['subscription']; - foreach($item->subs as $subitem) { - if ($subitem->name == 'group') { - $groups[] = $subitem->data; - } - } - $contacts[] = array($jid, $subscription, $name, $groups); //Store for action if no errors happen - } else { - $status = "error"; - } - } - if ($status == "result") { //No errors, add contacts - foreach($contacts as $contact) { - $this->roster->addContact($contact[0], $contact[1], $contact[2], $contact[3]); - } - } - if ($xml->attrs['type'] == 'set') { - $this->send("attrs['id']}\" to=\"{$xml->attrs['from']}\" />"); - } - } + throw new Exception('Auth failed!'); + } - /** - * Session start handler - * - * @param string $xml - */ - protected function session_start_handler($xml) { - $this->log->log("Session started"); - $this->session_started = true; - $this->event('session_start'); - } + /** + * Resource bind handler + * + * @param string $xml + */ + protected function resource_bind_handler($xml) + { + if ($xml->attrs['type'] == 'result') { + $this->log->log("Bound to " . $xml->sub('bind')->sub('jid')->data); + $this->fulljid = $xml->sub('bind')->sub('jid')->data; + $jidarray = explode('/', $this->fulljid); + $this->jid = $jidarray[0]; + } + $id = $this->getId(); + $this->addIdHandler($id, 'session_start_handler'); + $this->send(""); + } - /** - * TLS proceed handler - * - * @param string $xml - */ - protected function tls_proceed_handler($xml) { - $this->log->log("Starting TLS encryption"); - stream_socket_enable_crypto($this->socket, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT); - $this->reset(); - } + /** + * Roster iq handler + * Gets all packets matching XPath "iq/{jabber:iq:roster}query' + * + * @param string $xml + */ + protected function roster_iq_handler($xml) + { + $status = "result"; + $xmlroster = $xml->sub('query'); + foreach ($xmlroster->subs as $item) { + $groups = array(); + if ($item->name == 'item') { + $jid = $item->attrs['jid']; //REQUIRED + $name = $item->attrs['name']; //MAY + $subscription = $item->attrs['subscription']; + foreach ($item->subs as $subitem) { + if ($subitem->name == 'group') { + $groups[] = $subitem->data; + } + } + $contacts[] = array($jid, $subscription, $name, $groups); //Store for action if no errors happen + } else { + $status = "error"; + } + } + if ($status == "result") { //No errors, add contacts + foreach ($contacts as $contact) { + $this->roster->addContact($contact[0], $contact[1], $contact[2], $contact[3]); + } + } + if ($xml->attrs['type'] == 'set') { + $this->send("attrs['id']}\" to=\"{$xml->attrs['from']}\" />"); + } + } - /** - * Retrieves the vcard - * - */ - public function getVCard($jid = Null) { - $id = $this->getID(); - $this->addIdHandler($id, 'vcard_get_handler'); - if($jid) { - $this->send(""); - } else { - $this->send(""); - } - } + /** + * Session start handler + * + * @param string $xml + */ + protected function session_start_handler($xml) + { + $this->log->log("Session started"); + $this->session_started = true; + $this->event('session_start'); + } - /** - * VCard retrieval handler - * - * @param XML Object $xml - */ - protected function vcard_get_handler($xml) { - $vcard_array = array(); - $vcard = $xml->sub('vcard'); - // go through all of the sub elements and add them to the vcard array - foreach ($vcard->subs as $sub) { - if ($sub->subs) { - $vcard_array[$sub->name] = array(); - foreach ($sub->subs as $sub_child) { - $vcard_array[$sub->name][$sub_child->name] = $sub_child->data; - } - } else { - $vcard_array[$sub->name] = $sub->data; - } - } - $vcard_array['from'] = $xml->attrs['from']; - $this->event('vcard', $vcard_array); - } + /** + * TLS proceed handler + * + * @param string $xml + */ + protected function tls_proceed_handler($xml) + { + $this->log->log("Starting TLS encryption"); + stream_socket_enable_crypto($this->socket, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT); + $this->reset(); + } + + /** + * VCard retrieval handler + * + * @param XMLObj $xml + */ + protected function vcard_get_handler($xml) + { + $vcard_array = array(); + $vcard = $xml->sub('vcard'); + // go through all of the sub elements and add them to the vcard array + foreach ($vcard->subs as $sub) { + if ($sub->subs) { + $vcard_array[$sub->name] = array(); + foreach ($sub->subs as $sub_child) { + $vcard_array[$sub->name][$sub_child->name] = $sub_child->data; + } + } else { + $vcard_array[$sub->name] = $sub->data; + } + } + $vcard_array['from'] = $xml->attrs['from']; + $this->event('vcard', $vcard_array); + } } diff --git a/XMPPHP/XMPP_Old.php b/XMPPHP/XMPP_Old.php deleted file mode 100644 index 43f56b1..0000000 --- a/XMPPHP/XMPP_Old.php +++ /dev/null @@ -1,114 +0,0 @@ - - * @author Stephan Wentz - * @author Michael Garvin - * @copyright 2008 Nathanael C. Fritz - */ - -/** XMPPHP_XMPP - * - * This file is unnecessary unless you need to connect to older, non-XMPP-compliant servers like Dreamhost's. - * In this case, use instead of XMPPHP_XMPP, otherwise feel free to delete it. - * The old Jabber protocol wasn't standardized, so use at your own risk. - * - */ -require_once "XMPP.php"; - - class XMPPHP_XMPPOld extends XMPPHP_XMPP { - /** - * - * @var string - */ - protected $session_id; - - public function __construct($host, $port, $user, $password, $resource, $server = null, $printlog = false, $loglevel = null) { - parent::__construct($host, $port, $user, $password, $resource, $server, $printlog, $loglevel); - if(!$server) $server = $host; - $this->stream_start = ''; - $this->fulljid = "{$user}@{$server}/{$resource}"; - } - - /** - * Override XMLStream's startXML - * - * @param parser $parser - * @param string $name - * @param array $attr - */ - public function startXML($parser, $name, $attr) { - if($this->xml_depth == 0) { - $this->session_id = $attr['ID']; - $this->authenticate(); - } - parent::startXML($parser, $name, $attr); - } - - /** - * Send Authenticate Info Request - * - */ - public function authenticate() { - $id = $this->getId(); - $this->addidhandler($id, 'authfieldshandler'); - $this->send("{$this->user}"); - } - - /** - * Retrieve auth fields and send auth attempt - * - * @param XMLObj $xml - */ - public function authFieldsHandler($xml) { - $id = $this->getId(); - $this->addidhandler($id, 'oldAuthResultHandler'); - if($xml->sub('query')->hasSub('digest')) { - $hash = sha1($this->session_id . $this->password); - print "{$this->session_id} {$this->password}\n"; - $out = "{$this->user}{$hash}{$this->resource}"; - } else { - $out = "{$this->user}{$this->password}{$this->resource}"; - } - $this->send($out); - - } - - /** - * Determine authenticated or failure - * - * @param XMLObj $xml - */ - public function oldAuthResultHandler($xml) { - if($xml->attrs['type'] != 'result') { - $this->log->log("Auth failed!", XMPPHP_Log::LEVEL_ERROR); - $this->disconnect(); - throw new XMPPHP_Exception('Auth failed!'); - } else { - $this->log->log("Session started"); - $this->event('session_start'); - } - } - } - - -?> diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..35a8e66 --- /dev/null +++ b/composer.json @@ -0,0 +1,49 @@ +{ + "name": "diogocomposer/xmpphp", + "description": "XMPP PHP Library", + "type": "library", + "keywords": ["jabber", "xmpphp", "xmpp"], + "license": "GPL-2.0+", + "authors": [ + { + "name": "Nathan Fritz", + "email": "fritzy@netflint.net" + }, + { + "name": "Stephan Wentz", + "email": "stephan@wentz.it" + }, + { + "name": "Christian Weiske", + "email": "cweiske@cweiske.de" + }, + { + "name": "Vito Tafuni", + "email": "vitotafuni@gmail.com" + }, + { + "name": "Ivan Borzenkov", + "email": "ivan.borzenkov@gmail.com" + }, + { + "name": "bandroidx", + "email": "bandroidx@gmail.com" + }, + { + "name": "BirknerAlex", + "email": "alex.birkner@gmail.com" + }, + { + "name": "Diogo Cordeiro", + "email": "diogo@fc.up.pt" + } + ], + "autoload": { + "psr-4": { "XMPPHP\\": "XMPPHP" } + }, + "require": { + "php": ">=7.0.0", + "ext-mbstring": "*", + "ext-xml": "*" + } +} diff --git a/examples/cli_longrun_example.php b/examples/cli_longrun_example.php index 59bb29d..c997264 100644 --- a/examples/cli_longrun_example.php +++ b/examples/cli_longrun_example.php @@ -1,77 +1,141 @@ 'talk.google.com', + 'port' => 5222, + 'username' => 'username', + 'password' => 'password', + 'proto' => 'xmpphp', + 'domain' => 'gmail.com', + 'printlog' => true, + 'loglevel' => XMPPHP\Log::LEVEL_VERBOSE, +); + +// Easy and simple for access to variables with their names +extract($conf); + +$conn = new XMPPHP\XMPP($server, $port, $username, $password, $proto, $domain, $printlog, $loglevel); $conn->autoSubscribe(); $vcard_request = array(); try { $conn->connect(); - while(!$conn->isDisconnected()) { - $payloads = $conn->processUntil(array('message', 'presence', 'end_stream', 'session_start', 'vcard')); - foreach($payloads as $event) { - $pl = $event[1]; - switch($event[0]) { - case 'message': - print "---------------------------------------------------------------------------------\n"; - print "Message from: {$pl['from']}\n"; - if($pl['subject']) print "Subject: {$pl['subject']}\n"; - print $pl['body'] . "\n"; - print "---------------------------------------------------------------------------------\n"; - $conn->message($pl['from'], $body="Thanks for sending me \"{$pl['body']}\".", $type=$pl['type']); - $cmd = explode(' ', $pl['body']); - if($cmd[0] == 'quit') $conn->disconnect(); - if($cmd[0] == 'break') $conn->send(""); - if($cmd[0] == 'vcard') { - if(!($cmd[1])) $cmd[1] = $conn->user . '@' . $conn->server; - // take a note which user requested which vcard - $vcard_request[$pl['from']] = $cmd[1]; - // request the vcard - $conn->getVCard($cmd[1]); - } - break; - case 'presence': - print "Presence: {$pl['from']} [{$pl['show']}] {$pl['status']}\n"; - break; - case 'session_start': - print "Session Start\n"; - $conn->getRoster(); - $conn->presence($status="Cheese!"); - break; - case 'vcard': - // check to see who requested this vcard - $deliver = array_keys($vcard_request, $pl['from']); - // work through the array to generate a message - print_r($pl); - $msg = ''; - foreach($pl as $key => $item) { - $msg .= "$key: "; - if(is_array($item)) { - $msg .= "\n"; - foreach($item as $subkey => $subitem) { - $msg .= " $subkey: $subitem\n"; - } - } else { - $msg .= "$item\n"; - } - } - // deliver the vcard msg to everyone that requested that vcard - foreach($deliver as $sendjid) { - // remove the note on requests as we send out the message - unset($vcard_request[$sendjid]); - $conn->message($sendjid, $msg, 'chat'); - } - break; - } - } + + while (!$conn->isDisconnected()) { + $events = array('message', 'presence', 'end_stream', 'session_start', 'vcard'); + $payloads = $conn->processUntil($events); + + foreach ($payloads as $result) { + list($event, $data) = $result; + + if (isset($data)) { + extract($data); + } + + switch ($event) { + + case 'message': + + if (!$body) { + break; + } + + echo str_repeat('-', 80); + echo "Message from: $from"; + + if (isset($subject)) { + echo "Subject: $subject"; + } + + echo $body; + echo str_repeat('-', 80); + + $cmd = explode(' ', $body); + $body = "Mi no entender! '$body'"; + $conn->message($from, $body, $type); + + if (isset($cmd[0])) { + if ($cmd[0] == 'quit') { + $conn->disconnect(); + } + + if ($cmd[0] == 'break') { + $conn->send(''); + } + + if ($cmd[0] == 'vcard') { + if (!isset($cmd[1])) { + $cmd[1] = $conn->user; + } + + // Take a note which user requested which vcard + $vcard_request[$from] = $cmd[1]; + // Request the vcard + $conn->getVCard($cmd[1]); + } + } + break; + + case 'presence': + + echo "Presence: $from [$show] $status\n"; + break; + + case 'session_start': + + echo "Session start\n"; + $conn->getRoster(); + $conn->presence('Quasar!'); + break; + + case 'vcard': + + $deliver = array_keys($vcard_request, $from); + $msg = ''; + + foreach ($data as $key => $item) { + $msg .= $key . ': '; + + if (is_array($item)) { + $msg .= "\n"; + foreach ($item as $subkey => $subitem) { + $msg .= ' ' . $subkey . ':' . $subitem . "\n"; + } + } else { + $msg .= $item . "\n"; + } + } + + foreach ($deliver as $sendjid) { + unset($vcard_request[$sendjid]); + $conn->message($sendjid, $msg, 'chat'); + } + break; + } + } } -} catch(XMPPHP_Exception $e) { +} catch (XMPPHP\Exception $e) { die($e->getMessage()); } diff --git a/examples/cli_longrun_example_bosh.php b/examples/cli_longrun_example_bosh.php index 21b63f1..5a93e75 100644 --- a/examples/cli_longrun_example_bosh.php +++ b/examples/cli_longrun_example_bosh.php @@ -1,43 +1,104 @@ 'server.tld', + 'port' => 5280, + 'username' => 'username', + 'password' => 'password', + 'proto' => 'xmpphp', + 'domain' => 'server.tld', + 'printlog' => true, + 'loglevel' => XMPPHP\Log::LEVEL_VERBOSE, +); + +// Easy and simple for access to variables with their names +extract($conf); + +$conn = new XMPPHP\BOSH($server, $port, $username, $password, $proto, $domain, $printlog, $loglevel); $conn->autoSubscribe(); try { $conn->connect('http://server.tld:5280/xmpp-httpbind'); - while(!$conn->isDisconnected()) { - $payloads = $conn->processUntil(array('message', 'presence', 'end_stream', 'session_start')); - foreach($payloads as $event) { - $pl = $event[1]; - switch($event[0]) { - case 'message': - print "---------------------------------------------------------------------------------\n"; - print "Message from: {$pl['from']}\n"; - if($pl['subject']) print "Subject: {$pl['subject']}\n"; - print $pl['body'] . "\n"; - print "---------------------------------------------------------------------------------\n"; - $conn->message($pl['from'], $body="Thanks for sending me \"{$pl['body']}\".", $type=$pl['type']); - if($pl['body'] == 'quit') $conn->disconnect(); - if($pl['body'] == 'break') $conn->send(""); - break; - case 'presence': - print "Presence: {$pl['from']} [{$pl['show']}] {$pl['status']}\n"; - break; - case 'session_start': - print "Session Start\n"; - $conn->getRoster(); - $conn->presence($status="Cheese!"); - break; - } - } + + while (!$conn->isDisconnected()) { + $events = array('message', 'presence', 'end_stream', 'session_start'); + $payloads = $conn->processUntil($events); + + foreach ($payloads as $result) { + list($event, $data) = $result; + + if (isset($data)) { + extract($data); + } + + switch ($event) { + + case 'message': + + if (!$body) { + break; + } + + echo str_repeat('-', 80); + echo "Message from: $from"; + + if (isset($subject)) { + echo "Subject: $subject"; + } + + echo $body; + echo str_repeat('-', 80); + + $cmd = explode(' ', $body); + $body = "Mi no entender! '$body'"; + $conn->message($from, $body, $type); + + if (isset($cmd[0])) { + if ($cmd[0] == 'quit') { + $conn->disconnect(); + } + + if ($cmd[0] == 'break') { + $conn->send(''); + } + } + break; + + case 'presence': + + echo "Presence: $from [$show] $status\n"; + break; + + case 'session_start': + + echo "Session start\n"; + $conn->getRoster(); + $conn->presence('Quasar!'); + break; + } + } } -} catch(XMPPHP_Exception $e) { +} catch (XMPPHP\Exception $e) { die($e->getMessage()); } diff --git a/examples/sendmessage_example.php b/examples/sendmessage_example.php index e506130..b71290d 100644 --- a/examples/sendmessage_example.php +++ b/examples/sendmessage_example.php @@ -1,20 +1,47 @@ 'talk.google.com', + 'port' => 5222, + 'username' => 'username', + 'password' => 'password', + 'proto' => 'xmpphp', + 'domain' => 'gmail.com', + 'printlog' => true, + 'loglevel' => XMPPHP\Log::LEVEL_VERBOSE, +); + +// Easy and simple for access to variables with their names +extract($conf); + +$XMPP = new XMPPHP\XMPP($server, $port, $username, $password, $proto, $domain, $printlog, $loglevel); try { - $conn->connect(); - $conn->processUntil('session_start'); - $conn->presence(); - $conn->message('someguy@someserver.net', 'This is a test message!'); - $conn->disconnect(); -} catch(XMPPHP_Exception $e) { + $XMPP->connect(); + $XMPP->processUntil('session_start', 10); + $XMPP->presence(); + $XMPP->message('target.user@jabber.domain.com', 'Hello, how are you?', 'chat'); + $XMPP->disconnect(); +} catch (XMPPHP\Exception $e) { die($e->getMessage()); } diff --git a/examples/webclient_example.php b/examples/webclient_example.php index eb40e82..147281d 100644 --- a/examples/webclient_example.php +++ b/examples/webclient_example.php @@ -1,56 +1,117 @@ "; +require '../vendor/autoload.php'; -#Use XMPPHP_Log::LEVEL_VERBOSE to get more logging for error reports -#If this doesn't work, are you running 64-bit PHP with < 5.2.6? -$conn = new XMPPHP_BOSH('server.tld', 5280, 'user', 'password', 'xmpphp', 'server.tld', $printlog=true, $loglevel=XMPPHP_Log::LEVEL_INFO); +$conf = array( + 'server' => 'talk.google.com', + 'port' => 5222, + 'username' => 'username', + 'password' => 'password', + 'proto' => 'xmpphp', + 'domain' => 'gmail.com', + 'printlog' => true, + 'loglevel' => XMPPHP\Log::LEVEL_VERBOSE, +); + +// Easy and simple for access to variables with their names +extract($conf); + +$conn = new XMPPHP\XMPP($server, $port, $username, $password, $proto, $domain, $printlog, $loglevel); $conn->autoSubscribe(); try { - if(isset($_SESSION['messages'])) { - foreach($_SESSION['messages'] as $msg) { - print $msg; - flush(); - } - } - $conn->connect('http://server.tld:5280/xmpp-httpbind', 1, true); - #while(true) { - $payloads = $conn->processUntil(array('message', 'presence', 'end_stream', 'session_start')); - foreach($payloads as $event) { - $pl = $event[1]; - switch($event[0]) { - case 'message': - if(!isset($_SESSION['messages'])) $_SESSION['message'] = Array(); - $msg = "---------------------------------------------------------------------------------\n{$pl['from']}: {$pl['body']}\n"; - print $msg; - $_SESSION['messages'][] = $msg; - flush(); - $conn->message($pl['from'], $body="Thanks for sending me \"{$pl['body']}\".", $type=$pl['type']); - if($pl['body'] == 'quit') $conn->disconnect(); - if($pl['body'] == 'break') $conn->send(""); - break; - case 'presence': - print "Presence: {$pl['from']} [{$pl['show']}] {$pl['status']}\n"; - break; - case 'session_start': - print "Session Start\n"; - $conn->getRoster(); - $conn->presence($status="Cheese!"); - break; - } - } - #} -} catch(XMPPHP_Exception $e) { + if (isset($_SESSION['messages'])) { + foreach ($_SESSION['messages'] as $message) { + echo $message; + flush(); + } + } else { + $_SESSION['messages'] = array(); + } + + $conn->connect('http://server.tld:5280/xmpp-httpbind', 1, true); + $events = array('message', 'presence', 'end_stream', 'session_start', 'vcard'); + $payloads = $conn->processUntil($events); + + foreach ($payloads as $result) { + list($event, $data) = $result; + + if (isset($data)) { + extract($data); + } + + switch ($event) { + + case 'message': + + if (!$body) { + break; + } + + $cmd = explode(' ', $body); + $msg = str_repeat('-', 80); + $msg .= "\nMessage from: $from\n"; + + if (isset($subject)) { + $msg .= "Subject: $subject\n"; + } + + $msg .= $body . "\n"; + $msg .= str_repeat('-', 80); + echo "
$msg
"; + + if (isset($cmd[0])) { + if ($cmd[0] == 'quit') { + $conn->disconnect(); + } + + if ($cmd[0] == 'break') { + $conn->send(''); + } + } + $_SESSION['messages'][] = $msg; + flush(); + break; + + case 'presence': + + echo "Presence: $from [$show] $status\n"; + break; + + case 'session_start': + + echo "Session start\n"; + $conn->getRoster(); + $conn->presence('Quasar!'); + break; + } + } +} catch (XMPPHP\Exception $e) { die($e->getMessage()); } + $conn->saveSession(); -print ""; -print ""; -?> +echo ''; diff --git a/tests/AllTests.php b/tests/AllTests.php index 049325f..c8ad98c 100755 --- a/tests/AllTests.php +++ b/tests/AllTests.php @@ -1,31 +1,79 @@ -addTestSuite('XMPPHP_LogTest'); - $suite->addTestSuite('XMPPHP_XMLObjTest'); - $suite->addTestSuite('XMPPHP_XMPPTest'); - - return $suite; - } -} - -if (PHPUnit_MAIN_METHOD == 'AllTests::main') { - AllTests::main(); -} + + * @author Stephan Wentz + * @author Michael Garvin + * @copyright 2008 Nathanael C. Fritz + */ + +// Get current working directory with trailing slash +define('TESTS_DIR', dirname(__FILE__) . DIRECTORY_SEPARATOR); + +// Get class directory with trailing slash +define('CLASS_DIR', dirname(TESTS_DIR) . DIRECTORY_SEPARATOR); + +/** XMPPHP_LogTest */ +require_once TESTS_DIR . 'XMPPHP' . DIRECTORY_SEPARATOR . 'LogTest.php'; + +/** XMPPHP_XMLObjTest */ +require_once TESTS_DIR . 'XMPPHP' . DIRECTORY_SEPARATOR . 'XMLObjTest.php'; + +/** XMPPHP_XMPPTest */ +require_once TESTS_DIR . 'XMPPHP' . DIRECTORY_SEPARATOR . 'XMPPTest.php'; + +if (!defined('PHPUnit_MAIN_METHOD')) { + define('PHPUnit_MAIN_METHOD', 'AllTests::main'); +} + +/** + * XMPPHP AllTests + * + * @package XMPPHP + * @author Nathanael C. Fritz + * @author Stephan Wentz + * @author Michael Garvin + * @copyright 2008 Nathanael C. Fritz + * @version $Id$ + */ +class AllTests +{ + public static function main() + { + PHPUnit_TextUI_TestRunner::run(self::suite()); + } + + public static function suite() + { + $suite = new PHPUnit_Framework_TestSuite(); + $suite->addTestSuite('XMPPHP_LogTest'); + $suite->addTestSuite('XMPPHP_XMLObjTest'); + $suite->addTestSuite('XMPPHP_XMPPTest'); + + return $suite; + } +} + +if (PHPUnit_MAIN_METHOD == 'AllTests::main') { + AllTests::main(); +} diff --git a/tests/XMPPHP/LogTest.php b/tests/XMPPHP/LogTest.php index 03e2190..240da1b 100755 --- a/tests/XMPPHP/LogTest.php +++ b/tests/XMPPHP/LogTest.php @@ -1,162 +1,188 @@ + * @author Stephan Wentz + * @author Michael Garvin + * @copyright 2008 Nathanael C. Fritz + */ +/** XMPPHP_Log */ +require_once CLASS_DIR . 'XMPPHP' . DIRECTORY_SEPARATOR . 'Log.php'; + +/** + * XMPPHP LogTest + * + * @package XMPPHP + * @author Nathanael C. Fritz + * @author Stephan Wentz + * @author Michael Garvin + * @copyright 2008 Nathanael C. Fritz + * @version $Id$ + */ class XMPPHP_LogTest extends PHPUnit_Framework_TestCase { public function testPrintoutNoOutput() { $log = new XMPPHP_Log(); - $msg = 'I am a test log message'; - + ob_start(); $log->log('test'); $result = ob_get_clean(); - + $this->assertEquals('', $result); } - + public function testPrintoutOutput() { $log = new XMPPHP_Log(true); - $msg = 'I am a test log message'; - + ob_start(); $log->log($msg); $result = ob_get_clean(); - + $this->assertContains($msg, $result); } public function testPrintoutNoOutputWithDefaultLevel() { $log = new XMPPHP_Log(true, XMPPHP_Log::LEVEL_ERROR); - $msg = 'I am a test log message'; - + ob_start(); $log->log($msg); $result = ob_get_clean(); - + $this->assertSame('', $result); } public function testPrintoutOutputWithDefaultLevel() { $log = new XMPPHP_Log(true, XMPPHP_Log::LEVEL_INFO); - $msg = 'I am a test log message'; - + ob_start(); $log->log($msg); $result = ob_get_clean(); - + $this->assertContains($msg, $result); } public function testPrintoutNoOutputWithCustomLevel() { $log = new XMPPHP_Log(true, XMPPHP_Log::LEVEL_INFO); - $msg = 'I am a test log message'; - + ob_start(); $log->log($msg, XMPPHP_Log::LEVEL_DEBUG); $result = ob_get_clean(); - + $this->assertSame('', $result); } - + public function testPrintoutOutputWithCustomLevel() { $log = new XMPPHP_Log(true, XMPPHP_Log::LEVEL_INFO); - $msg = 'I am a test log message'; - + ob_start(); $log->log($msg, XMPPHP_Log::LEVEL_INFO); $result = ob_get_clean(); - + $this->assertContains($msg, $result); } public function testExplicitPrintout() { $log = new XMPPHP_Log(false); - $msg = 'I am a test log message'; - + ob_start(); $log->log($msg); $result = ob_get_clean(); - + $this->assertSame('', $result); } public function testExplicitPrintoutResult() { $log = new XMPPHP_Log(false); - $msg = 'I am a test log message'; - + ob_start(); $log->log($msg); $result = ob_get_clean(); - + $this->assertSame('', $result); - + ob_start(); $log->printout(); $result = ob_get_clean(); - + $this->assertContains($msg, $result); } public function testExplicitPrintoutClear() { $log = new XMPPHP_Log(false); - $msg = 'I am a test log message'; - + ob_start(); $log->log($msg); $result = ob_get_clean(); - + $this->assertSame('', $result); - + ob_start(); $log->printout(); $result = ob_get_clean(); - + $this->assertContains($msg, $result); ob_start(); $log->printout(); $result = ob_get_clean(); - - $this->assertSame('', $result); - } - - public function testExplicitPrintoutLevel() - { - $log = new XMPPHP_Log(false, XMPPHP_Log::LEVEL_ERROR); - - $msg = 'I am a test log message'; - - ob_start(); - $log->log($msg); - $result = ob_get_clean(); - - $this->assertSame('', $result); - - ob_start(); - $log->printout(true, XMPPHP_Log::LEVEL_INFO); - $result = ob_get_clean(); - + $this->assertSame('', $result); } - + public function testExplicitPrintoutLevel() + { + $log = new XMPPHP_Log(false, XMPPHP_Log::LEVEL_ERROR); + $msg = 'I am a test log message'; + + ob_start(); + $log->log($msg); + $result = ob_get_clean(); + + $this->assertSame('', $result); + + ob_start(); + $log->printout(true, XMPPHP_Log::LEVEL_INFO); + $result = ob_get_clean(); + + $this->assertSame('', $result); + } } diff --git a/tests/XMPPHP/XMLObjTest.php b/tests/XMPPHP/XMLObjTest.php index 75ad23c..f4f2e09 100755 --- a/tests/XMPPHP/XMLObjTest.php +++ b/tests/XMPPHP/XMLObjTest.php @@ -1,53 +1,78 @@ + * @author Stephan Wentz + * @author Michael Garvin + * @copyright 2008 Nathanael C. Fritz + */ +/** XMPPHP_XMLObj */ +require_once CLASS_DIR . 'XMPPHP' . DIRECTORY_SEPARATOR . 'XMLObj.php'; + +/** + * XMPPHP XMLObjectTest + * + * @package XMPPHP + * @author Nathanael C. Fritz + * @author Stephan Wentz + * @author Michael Garvin + * @copyright 2008 Nathanael C. Fritz + * @version $Id$ + */ class XMPPHP_XMLObjTest extends PHPUnit_Framework_TestCase { public function testToStringNameNamespace() { - $xmlobj = new XMPPHP_XMLObj('testname', 'testNameSpace'); - - $expected = ""; - - $result = $xmlobj->toString(); - + $xmlobj = new XMPPHP_XMLObj('testname', 'testNameSpace'); + $expected = ''; + $result = $xmlobj->toString(); $this->assertSame($expected, $result); } public function testToStringNameNamespaceAttr() { - $xmlobj = new XMPPHP_XMLObj('testName', 'testNameSpace', array('attr1'=>'valA', 'attr2'=>'valB')); - - $expected = ""; - - $result = $xmlobj->toString(); - + $xmlobj = new XMPPHP_XMLObj('testName', 'testNameSpace', array('attr1' => 'valA', 'attr2' => 'valB')); + $expected = ''; + $result = $xmlobj->toString(); $this->assertSame($expected, $result); } - + public function testToStringNameNamespaceData() { - $xmlobj = new XMPPHP_XMLObj('testName', 'testNameSpace', array(), 'I am test data'); - - $expected = "I am test data"; - - $result = $xmlobj->toString(); - + $xmlobj = new XMPPHP_XMLObj('testName', 'testNameSpace', array(), 'I am test data'); + $expected = 'I am test data'; + $result = $xmlobj->toString(); $this->assertSame($expected, $result); } - + public function testToStringNameNamespaceSub() { - $xmlobj = new XMPPHP_XMLObj('testName', 'testNameSpace'); - $sub1 = new XMPPHP_XMLObj('subName', 'subNameSpace'); + $xmlobj = new XMPPHP_XMLObj('testName', 'testNameSpace'); + $sub1 = new XMPPHP_XMLObj('subName', 'subNameSpace'); $xmlobj->subs = array($sub1); - - $expected = ""; - - $result = $xmlobj->toString(); - + $expected = ''; + $result = $xmlobj->toString(); $this->assertSame($expected, $result); } - } diff --git a/tests/XMPPHP/XMPPTest.php b/tests/XMPPHP/XMPPTest.php index 09a06aa..b77a1b9 100755 --- a/tests/XMPPHP/XMPPTest.php +++ b/tests/XMPPHP/XMPPTest.php @@ -1,7 +1,45 @@ + * @author Stephan Wentz + * @author Michael Garvin + * @copyright 2008 Nathanael C. Fritz + */ +/** XMPPHP_XMPP */ +require_once CLASS_DIR . 'XMPPHP' . DIRECTORY_SEPARATOR . 'XMPP.php'; + +/** + * XMPPHP XMPPTest + * + * @package XMPPHP + * @author Nathanael C. Fritz + * @author Stephan Wentz + * @author Michael Garvin + * @copyright 2008 Nathanael C. Fritz + * @version $Id$ + */ class XMPPHP_XMPPTest extends PHPUnit_Framework_TestCase { public function testConnectException() @@ -14,12 +52,12 @@ class XMPPHP_XMPPTest extends PHPUnit_Framework_TestCase $xmpp->presence(); $xmpp->message('stephan@jabber.wentz.it', 'This is a test message!'); $xmpp->disconnect(); - } catch(XMPPHP_Exception $e) { + } catch (XMPPHP_Exception $e) { return; - } catch(Exception $e) { + } catch (Exception $e) { $this->fail('Unexpected Exception thrown: '.$e->getMessage()); } - + $this->fail('Expected XMPPHP_Exception not thrown!'); } @@ -33,12 +71,12 @@ class XMPPHP_XMPPTest extends PHPUnit_Framework_TestCase $xmpp->presence(); $xmpp->message('stephan@jabber.wentz.it', 'This is a test message!'); $xmpp->disconnect(); - } catch(XMPPHP_Exception $e) { + } catch (XMPPHP_Exception $e) { return; - } catch(Exception $e) { + } catch (Exception $e) { $this->fail('Unexpected Exception thrown: '.$e->getMessage()); } - + $this->fail('Expected XMPPHP_Exception not thrown!'); } }