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...
This commit is contained in:
Diogo Cordeiro 2019-06-18 19:02:40 +01:00
parent fd9cac3c17
commit c7cdcc588a
20 changed files with 2659 additions and 2265 deletions

6
.gitignore vendored Normal file
View File

@ -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

59
README
View File

@ -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 <cweiske@cweiske.de>
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.

20
README.md Normal file
View File

@ -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 <diogo@fc.up.pt>
Requirements
------------
* PHP 7.0
* SSL Support Compiled

View File

@ -1,188 +1,409 @@
<?php <?php
/** /**
* XMPPHP: The PHP XMPP Library * XMPPHP: The PHP XMPP Library
* Copyright (C) 2008 Nathanael C. Fritz * Copyright (C) 2008 Nathanael C. Fritz
* This file is part of SleekXMPP. * This file is part of SleekXMPP.
* *
* XMPPHP is free software; you can redistribute it and/or modify * XMPPHP is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or * the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* XMPPHP is distributed in the hope that it will be useful, * XMPPHP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with XMPPHP; if not, write to the Free Software * along with XMPPHP; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
* *
* @category xmpphp * @category xmpphp
* @package XMPPHP * @package XMPPHP
* @author Nathanael C. Fritz <JID: fritzy@netflint.net> * @author Nathanael C. Fritz <JID: fritzy@netflint.net>
* @author Stephan Wentz <JID: stephan@jabber.wentz.it> * @author Stephan Wentz <JID: stephan@jabber.wentz.it>
* @author Michael Garvin <JID: gar@netflint.net> * @author Michael Garvin <JID: gar@netflint.net>
* @author Alexander Birkner (https://github.com/BirknerAlex)
* @author zorn-v (https://github.com/zorn-v/xmpphp/)
* @author GNU social
* @copyright 2008 Nathanael C. Fritz * @copyright 2008 Nathanael C. Fritz
*/ */
namespace XMPPHP;
use SimpleXMLElement;
/** XMPPHP_XMLStream */ /** XMPPHP_XMLStream */
require_once 'XMPPHP/XMPP.php'; require_once __DIR__ . "/XMPP.php";
/** /**
* XMPPHP Main Class * XMPPHP BOSH
* *
* @category xmpphp * @property int lat
* @package XMPPHP * @package XMPPHP
* @author Nathanael C. Fritz <JID: fritzy@netflint.net> * @author Nathanael C. Fritz <JID: fritzy@netflint.net>
* @author Stephan Wentz <JID: stephan@jabber.wentz.it> * @author Stephan Wentz <JID: stephan@jabber.wentz.it>
* @author Michael Garvin <JID: gar@netflint.net> * @author Michael Garvin <JID: gar@netflint.net>
* @copyright 2008 Nathanael C. Fritz * @copyright 2008 Nathanael C. Fritz
* @version $Id$ * @version $Id$
*/ */
class XMPPHP_BOSH extends XMPPHP_XMPP { class BOSH extends XMPP
{
/**
* @var integer
*/
protected $rid;
protected $rid; /**
protected $sid; * @var string
protected $http_server; */
protected $http_buffer = Array(); protected $sid;
protected $session = false;
public function connect($server, $wait='1', $session=false) { /**
$this->http_server = $server; * @var string
$this->use_encryption = false; */
$this->session = $session; protected $http_server;
$this->rid = 3001; /**
$this->sid = null; * @var array
if($session) */
{ protected $http_buffer = array();
$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 = "<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'>";
xml_parse($this->parser, $buff, false);
$response = $this->__sendBody($body);
$rxml = new SimpleXMLElement($response);
$this->sid = $rxml['sid'];
} else { /**
$buff = "<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'>"; * @var string
xml_parse($this->parser, $buff, false); */
} protected $session = false;
}
public function __sendBody($body=null, $recv=true) { /**
if(!$body) { * @var integer
$body = $this->__buildBody(); */
} protected $inactivity;
$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;
}
public function __buildBody($sub=null) { /**
$xml = new SimpleXMLElement("<body xmlns='http://jabber.org/protocol/httpbind' xmlns:xmpp='urn:xmpp:xbosh' />"); * Connect
$xml->addAttribute('content', 'text/xml; charset=utf-8'); *
$xml->addAttribute('rid', $this->rid); * @param $server
$this->rid += 1; * @param $wait
if($this->sid) $xml->addAttribute('sid', $this->sid); * @param $session
#if($this->sid) $xml->addAttribute('xmlns', 'http://jabber.org/protocol/httpbind'); * @throws Exception
$xml->addAttribute('xml:lang', 'en'); * @throws Exception
if($sub) { // ok, so simplexml is lame */
$p = dom_import_simplexml($xml); public function connect($server = null, $wait = '1', $session = false)
$c = dom_import_simplexml($sub); {
$cn = $p->ownerDocument->importNode($c, true);
$p->appendChild($cn);
$xml = simplexml_import_dom($p);
}
return $xml;
}
public function __process() { if (is_null($server)) {
if($this->http_buffer) {
$this->__parseBuffer();
} else {
$this->__sendBody();
$this->__parseBuffer();
}
}
public function __parseBuffer() { // If we aren't given the server http url, try and guess it
while ($this->http_buffer) { $port_string = ($this->port AND $this->port != 80) ? ':' . $this->port : '';
$idx = key($this->http_buffer); $this->http_server = 'http://' . $this->host . $port_string . '/http-bind/';
$buffer = $this->http_buffer[$idx]; } else {
unset($this->http_buffer[$idx]); $this->http_server = $server;
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);
}
}
}
}
public function send($msg) { $this->use_encryption = false;
$this->log->log("SEND: $msg", XMPPHP_Log::LEVEL_VERBOSE); $this->session = $session;
$msg = new SimpleXMLElement($msg); $this->rid = 3001;
#$msg->addAttribute('xmlns', 'jabber:client'); $this->sid = null;
$this->__sendBody($this->__buildBody($msg), true); $this->inactivity = 0;
#$this->__parseBuffer();
}
public function reset() { if ($session) {
$this->xml_depth = 0; $this->loadSession();
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 = "<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'>";
$response = $this->__sendBody($body);
$this->been_reset = true;
xml_parse($this->parser, $buff, false);
}
public function loadSession() { if (!$this->sid) {
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'];
}
public function saveSession() { $body = $this->__buildBody();
$_SESSION['XMPPHP_BOSH_RID'] = (string) $this->rid; $body->addAttribute('hold', '1');
$_SESSION['XMPPHP_BOSH_SID'] = (string) $this->sid; $body->addAttribute('to', $this->server);
$_SESSION['XMPPHP_BOSH_authed'] = (boolean) $this->authed; $body->addAttribute('route', 'xmpp:' . $this->host . ':' . $this->port);
$_SESSION['XMPPHP_BOSH_jid'] = (string) $this->jid; $body->addAttribute('secure', 'true');
$_SESSION['XMPPHP_BOSH_fulljid'] = (string) $this->fulljid; $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 = '<stream:stream xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams">';
xml_parse($this->parser, $buff, false);
$response = $this->__sendBody($body);
$rxml = new SimpleXMLElement($response);
$this->sid = $rxml['sid'];
$this->inactivity = $rxml['inactivity'];
} else {
$buff = '<stream:stream xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams">';
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 = '<body xmlns="http://jabber.org/protocol/httpbind" xmlns:xmpp="urn:xmpp:xbosh" />';
$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);
// <?php prefix used to mask the content of the session file
$session_serialized = '<?php ' . serialize($_SESSION);
file_put_contents($session_file, $session_serialized);
flock($session_file_fp, LOCK_UN);
fclose($session_file_fp);
}
}
/**
* Process
*
* @param $msg
* @param $null
*
* null param are not used and just to statify Strict Function Declaration
* @throws Exception
* @throws Exception
*/
public function send($msg, $null = null)
{
$this->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 = '<stream:stream xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams">';
$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]);
}
}
}
} }

34
XMPPHP/Exception.php Executable file → Normal file
View File

@ -1,41 +1,49 @@
<?php <?php
/** /**
* XMPPHP: The PHP XMPP Library * XMPPHP: The PHP XMPP Library
* Copyright (C) 2008 Nathanael C. Fritz * Copyright (C) 2008 Nathanael C. Fritz
* This file is part of SleekXMPP. * This file is part of SleekXMPP.
* *
* XMPPHP is free software; you can redistribute it and/or modify * XMPPHP is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or * the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* XMPPHP is distributed in the hope that it will be useful, * XMPPHP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with XMPPHP; if not, write to the Free Software * along with XMPPHP; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
* *
* @category xmpphp * @category xmpphp
* @package XMPPHP * @package XMPPHP
* @author Nathanael C. Fritz <JID: fritzy@netflint.net> * @author Nathanael C. Fritz <JID: fritzy@netflint.net>
* @author Stephan Wentz <JID: stephan@jabber.wentz.it> * @author Stephan Wentz <JID: stephan@jabber.wentz.it>
* @author Michael Garvin <JID: gar@netflint.net> * @author Michael Garvin <JID: gar@netflint.net>
* @author Alexander Birkner (https://github.com/BirknerAlex)
* @author zorn-v (https://github.com/zorn-v/xmpphp/)
* @author GNU social
* @copyright 2008 Nathanael C. Fritz * @copyright 2008 Nathanael C. Fritz
*/ */
namespace XMPPHP;
use Exception as ObjectException;
/** /**
* XMPPHP Exception * XMPPHP Exception
* *
* @category xmpphp * @package XMPPHP
* @package XMPPHP * @author Nathanael C. Fritz <JID: fritzy@netflint.net>
* @author Nathanael C. Fritz <JID: fritzy@netflint.net> * @author Stephan Wentz <JID: stephan@jabber.wentz.it>
* @author Stephan Wentz <JID: stephan@jabber.wentz.it> * @author Michael Garvin <JID: gar@netflint.net>
* @author Michael Garvin <JID: gar@netflint.net> * @copyright 2008 Nathanael C. Fritz
* @copyright 2008 Nathanael C. Fritz * @version $Id$
* @version $Id$
*/ */
class XMPPHP_Exception extends Exception { class Exception extends ObjectException
{
} }

View File

@ -1,119 +1,129 @@
<?php <?php
/** /**
* XMPPHP: The PHP XMPP Library * XMPPHP: The PHP XMPP Library
* Copyright (C) 2008 Nathanael C. Fritz * Copyright (C) 2008 Nathanael C. Fritz
* This file is part of SleekXMPP. * This file is part of SleekXMPP.
* *
* XMPPHP is free software; you can redistribute it and/or modify * XMPPHP is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or * the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* XMPPHP is distributed in the hope that it will be useful, * XMPPHP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with XMPPHP; if not, write to the Free Software * along with XMPPHP; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
* *
* @category xmpphp * @category xmpphp
* @package XMPPHP * @package XMPPHP
* @author Nathanael C. Fritz <JID: fritzy@netflint.net> * @author Nathanael C. Fritz <JID: fritzy@netflint.net>
* @author Stephan Wentz <JID: stephan@jabber.wentz.it> * @author Stephan Wentz <JID: stephan@jabber.wentz.it>
* @author Michael Garvin <JID: gar@netflint.net> * @author Michael Garvin <JID: gar@netflint.net>
* @author Alexander Birkner (https://github.com/BirknerAlex)
* @author zorn-v (https://github.com/zorn-v/xmpphp/)
* @author GNU social
* @copyright 2008 Nathanael C. Fritz * @copyright 2008 Nathanael C. Fritz
*/ */
namespace XMPPHP;
/** /**
* XMPPHP Log * XMPPHP Log
* *
* @package XMPPHP * @package XMPPHP
* @author Nathanael C. Fritz <JID: fritzy@netflint.net> * @author Nathanael C. Fritz <JID: fritzy@netflint.net>
* @author Stephan Wentz <JID: stephan@jabber.wentz.it> * @author Stephan Wentz <JID: stephan@jabber.wentz.it>
* @author Michael Garvin <JID: gar@netflint.net> * @author Michael Garvin <JID: gar@netflint.net>
* @copyright 2008 Nathanael C. Fritz * @copyright 2008 Nathanael C. Fritz
* @version $Id$ * @version $Id$
*/ */
class XMPPHP_Log { class Log
{
const LEVEL_ERROR = 0; const LEVEL_ERROR = 0;
const LEVEL_WARNING = 1; const LEVEL_WARNING = 1;
const LEVEL_INFO = 2; const LEVEL_INFO = 2;
const LEVEL_DEBUG = 3; const LEVEL_DEBUG = 3;
const LEVEL_VERBOSE = 4; const LEVEL_VERBOSE = 4;
/**
* @var array
*/
protected $data = array();
/** /**
* @var array * @var array
*/ */
protected $names = array('ERROR', 'WARNING', 'INFO', 'DEBUG', 'VERBOSE'); protected $data = array();
/** /**
* @var integer * @var array
*/ */
protected $runlevel; protected $names = array('ERROR', 'WARNING', 'INFO', 'DEBUG', 'VERBOSE');
/** /**
* @var boolean * @var integer
*/ */
protected $printout; protected $runlevel;
/** /**
* Constructor * @var boolean
* */
* @param boolean $printout protected $printout;
* @param string $runlevel
*/
public function __construct($printout = false, $runlevel = self::LEVEL_INFO) {
$this->printout = (boolean)$printout;
$this->runlevel = (int)$runlevel;
}
/** /**
* Add a message to the log data array * Constructor
* If printout in this instance is set to true, directly output the message *
* * @param boolean $printout
* @param string $msg * @param int $runlevel
* @param integer $runlevel */
*/ public function __construct($printout = false, $runlevel = self::LEVEL_INFO)
public function log($msg, $runlevel = self::LEVEL_INFO) { {
$time = time(); $this->printout = (boolean)$printout;
#$this->data[] = array($this->runlevel, $msg, $time); $this->runlevel = (int)$runlevel;
if($this->printout and $runlevel <= $this->runlevel) { }
$this->writeLine($msg, $runlevel, $time);
}
}
/** /**
* Output the complete log. * Add a message to the log data array
* Log will be cleared if $clear = true * If printout in this instance is set to true, directly output the message
* *
* @param boolean $clear * @param string $msg
* @param integer $runlevel * @param integer $runlevel
*/ */
public function printout($clear = true, $runlevel = null) { public function log($msg, $runlevel = self::LEVEL_INFO)
if($runlevel === null) { {
$runlevel = $this->runlevel; $time = time();
} #$this->data[] = array($this->runlevel, $msg, $time);
foreach($this->data as $data) { if ($this->printout and $runlevel <= $this->runlevel) {
if($runlevel <= $data[0]) { $this->writeLine($msg, $runlevel, $time);
$this->writeLine($data[1], $runlevel, $data[2]); }
} }
}
if($clear) { protected function writeLine($msg, $runlevel, $time)
$this->data = array(); {
} //echo date('Y-m-d H:i:s', $time)." [".$this->names[$runlevel]."]: ".$msg."\n";
} echo $time . " [" . $this->names[$runlevel] . "]: " . $msg . "\n";
flush();
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();
}
}
} }

View File

@ -1,165 +1,183 @@
<?php <?php
/** /**
* XMPPHP: The PHP XMPP Library * XMPPHP: The PHP XMPP Library
* Copyright (C) 2008 Nathanael C. Fritz * Copyright (C) 2008 Nathanael C. Fritz
* This file is part of SleekXMPP. * This file is part of SleekXMPP.
* *
* XMPPHP is free software; you can redistribute it and/or modify * XMPPHP is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or * the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* XMPPHP is distributed in the hope that it will be useful, * XMPPHP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with XMPPHP; if not, write to the Free Software * along with XMPPHP; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
* *
* @category xmpphp * @category xmpphp
* @package XMPPHP * @package XMPPHP
* @author Nathanael C. Fritz <JID: fritzy@netflint.net> * @author Nathanael C. Fritz <JID: fritzy@netflint.net>
* @author Stephan Wentz <JID: stephan@jabber.wentz.it> * @author Stephan Wentz <JID: stephan@jabber.wentz.it>
* @author Michael Garvin <JID: gar@netflint.net> * @author Michael Garvin <JID: gar@netflint.net>
* @author Alexander Birkner (https://github.com/BirknerAlex)
* @author zorn-v (https://github.com/zorn-v/xmpphp/)
* @author GNU social
* @copyright 2008 Nathanael C. Fritz * @copyright 2008 Nathanael C. Fritz
*/ */
namespace XMPPHP;
/** /**
* XMPPHP Roster Object * XMPPHP Roster
* *
* @category xmpphp * @package XMPPHP
* @package XMPPHP * @author Nathanael C. Fritz <JID: fritzy@netflint.net>
* @author Nathanael C. Fritz <JID: fritzy@netflint.net> * @author Stephan Wentz <JID: stephan@jabber.wentz.it>
* @author Stephan Wentz <JID: stephan@jabber.wentz.it> * @author Michael Garvin <JID: gar@netflint.net>
* @author Michael Garvin <JID: gar@netflint.net> * @copyright 2008 Nathanael C. Fritz
* @copyright 2008 Nathanael C. Fritz * @version $Id$
* @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 { /**
/** * Constructor
* Roster array, handles contacts and presence. Indexed by jid. * @param array $roster_array
* Contains array with potentially two indexes 'contact' and 'presence' */
* @var array public function __construct($roster_array = array())
*/ {
protected $roster_array = array(); if ($this->verifyRoster($roster_array)) {
/** $this->roster_array = $roster_array; //Allow for pre-population with existing roster
* Constructor } else {
* $this->roster_array = array();
*/ }
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();
}
}
/** /**
* *
* Check that a given roster array is of a valid structure (empty is still valid) * Check that a given roster array is of a valid structure (empty is still valid)
* *
* @param array $roster_array * @param array $roster_array
*/ * @return bool
protected function verifyRoster($roster_array) { */
#TODO once we know *what* a valid roster array looks like protected function verifyRoster($roster_array)
return True; {
} #TODO once we know *what* a valid roster array looks like
return true;
}
/** /**
* *
* Add given contact to roster * Retrieve contact via jid
* *
* @param string $jid * @param string $jid
* @param string $subscription * @return mixed
* @param string $name */
* @param array $groups public function getContact($jid)
*/ {
public function addContact($jid, $subscription, $name='', $groups=array()) { if ($this->isContact($jid)) {
$contact = array('jid' => $jid, 'subscription' => $subscription, 'name' => $name, 'groups' => $groups); return $this->roster_array[$jid]['contact'];
if ($this->isContact($jid)) { }
$this->roster_array[$jid]['contact'] = $contact; }
} else {
$this->roster_array[$jid] = array('contact' => $contact);
}
}
/** /**
* *
* Retrieve contact via jid * Discover if a contact exists in the roster via jid
* *
* @param string $jid * @param string $jid
*/ * @return bool
public function getContact($jid) { */
if ($this->isContact($jid)) { public function isContact($jid)
return $this->roster_array[$jid]['contact']; {
} return (array_key_exists($jid, $this->roster_array));
} }
/** /**
* *
* Discover if a contact exists in the roster via jid * Set presence
* *
* @param string $jid * @param string $presence
*/ * @param integer $priority
public function isContact($jid) { * @param string $show
return (array_key_exists($jid, $this->roster_array)); * @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 * Add given contact to roster
* *
* @param string $presence * @param string $jid
* @param integer $priority * @param string $subscription
* @param string $show * @param string $name
* @param string $status * @param array $groups
*/ */
public function setPresence($presence, $priority, $show, $status) { public function addContact($jid, $subscription, $name = '', $groups = array())
$presence = explode('/', $presence, 2); {
$jid = $presence[0]; $contact = array('jid' => $jid, 'subscription' => $subscription, 'name' => $name, 'groups' => $groups);
$resource = isset($presence[1]) ? $presence[1] : ''; if ($this->isContact($jid)) {
if ($show != 'unavailable') { $this->roster_array[$jid]['contact'] = $contact;
if (!$this->isContact($jid)) { } else {
$this->addContact($jid, 'not-in-roster'); $this->roster_array[$jid] = array('contact' => $contact);
} }
$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]);
}
}
/* /*
* *
* Return best presence for jid * Return best presence for jid
* *
* @param string $jid * @param string $jid
*/ */
public function getPresence($jid) {
$split = explode('/', $jid, 2); public function getPresence($jid)
$jid = $split[0]; {
if($this->isContact($jid)) { $split = explode('/', $jid, 2);
$current = array('resource' => '', 'active' => '', 'priority' => -129, 'show' => '', 'status' => ''); //Priorities can only be -128 = 127 $jid = $split[0];
foreach($this->roster_array[$jid]['presence'] as $resource => $presence) { if ($this->isContact($jid)) {
//Highest available priority or just highest priority $current = array('resource' => '', 'active' => '', 'priority' => -129, 'show' => '', 'status' => ''); //Priorities can only be -128 = 127
if ($presence['priority'] > $current['priority'] and (($presence['show'] == "chat" or $presence['show'] == "available") or ($current['show'] != "chat" or $current['show'] != "available"))) { foreach ($this->roster_array[$jid]['presence'] as $resource => $presence) {
$current = $presence; //Highest available priority or just highest priority
$current['resource'] = $resource; 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; }
} }
} return $current;
/** }
* }
* Get roster
* /**
*/ *
public function getRoster() { * Get roster
return $this->roster_array; *
} */
public function getRoster()
{
return $this->roster_array;
}
} }
?>

View File

@ -1,158 +1,174 @@
<?php <?php
/** /**
* XMPPHP: The PHP XMPP Library * XMPPHP: The PHP XMPP Library
* Copyright (C) 2008 Nathanael C. Fritz * Copyright (C) 2008 Nathanael C. Fritz
* This file is part of SleekXMPP. * This file is part of SleekXMPP.
* *
* XMPPHP is free software; you can redistribute it and/or modify * XMPPHP is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or * the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* XMPPHP is distributed in the hope that it will be useful, * XMPPHP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with XMPPHP; if not, write to the Free Software * along with XMPPHP; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
* *
* @category xmpphp * @category xmpphp
* @package XMPPHP * @package XMPPHP
* @author Nathanael C. Fritz <JID: fritzy@netflint.net> * @author Nathanael C. Fritz <JID: fritzy@netflint.net>
* @author Stephan Wentz <JID: stephan@jabber.wentz.it> * @author Stephan Wentz <JID: stephan@jabber.wentz.it>
* @author Michael Garvin <JID: gar@netflint.net> * @author Michael Garvin <JID: gar@netflint.net>
* @author Alexander Birkner (https://github.com/BirknerAlex)
* @author zorn-v (https://github.com/zorn-v/xmpphp/)
* @author GNU social
* @copyright 2008 Nathanael C. Fritz * @copyright 2008 Nathanael C. Fritz
*/ */
namespace XMPPHP;
/** /**
* XMPPHP XML Object * XMPPHP XMLObject
* *
* @category xmpphp * @package XMPPHP
* @package XMPPHP * @author Nathanael C. Fritz <JID: fritzy@netflint.net>
* @author Nathanael C. Fritz <JID: fritzy@netflint.net> * @author Stephan Wentz <JID: stephan@jabber.wentz.it>
* @author Stephan Wentz <JID: stephan@jabber.wentz.it> * @author Michael Garvin <JID: gar@netflint.net>
* @author Michael Garvin <JID: gar@netflint.net> * @copyright 2008 Nathanael C. Fritz
* @copyright 2008 Nathanael C. Fritz * @version $Id$
* @version $Id$
*/ */
class XMPPHP_XMLObj { class XMLObj
/** {
* Tag name /**
* * Tag name
* @var string *
*/ * @var string
public $name; */
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 = '';
/** /**
* Constructor * Namespace
* *
* @param string $name * @var string
* @param string $ns */
* @param array $attrs public $ns;
* @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. * Attributes
* *
* @param integer $depth * @var array
*/ */
public function printObj($depth = 0) { public $attrs = array();
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 * Subs?
* *
* @param string $str * @var array
*/ */
public function toString($str = '') { public $subs = array();
$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 .= "$body</{$this->name}>";
return $str;
}
/** /**
* Has this XML Object the given sub? * Node data
* *
* @param string $name * @var string
* @return boolean */
*/ public $data = '';
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 * Constructor
* *
* @param string $name * @param string $name
* @param string $attrs * @param string $ns
* @param string $ns * @param array $attrs
*/ * @param string $data
public function sub($name, $attrs = null, $ns = null) { */
#TODO attrs is ignored public function __construct($name, $ns = '', $attrs = array(), $data = '')
foreach($this->subs as $sub) { {
if($sub->name == $name and ($ns == null or $sub->ns == $ns)) { $this->name = strtolower($name);
return $sub; $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 .= "$body</{$this->name}>";
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;
}
}
}
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,565 +1,477 @@
<?php <?php
/** /**
* XMPPHP: The PHP XMPP Library * XMPPHP: The PHP XMPP Library
* Copyright (C) 2008 Nathanael C. Fritz * Copyright (C) 2008 Nathanael C. Fritz
* This file is part of SleekXMPP. * This file is part of SleekXMPP.
* *
* XMPPHP is free software; you can redistribute it and/or modify * XMPPHP is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or * the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* XMPPHP is distributed in the hope that it will be useful, * XMPPHP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with XMPPHP; if not, write to the Free Software * along with XMPPHP; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
* *
* @category xmpphp * @category xmpphp
* @package XMPPHP * @package XMPPHP
* @author Nathanael C. Fritz <JID: fritzy@netflint.net> * @author Nathanael C. Fritz <JID: fritzy@netflint.net>
* @author Stephan Wentz <JID: stephan@jabber.wentz.it> * @author Stephan Wentz <JID: stephan@jabber.wentz.it>
* @author Michael Garvin <JID: gar@netflint.net> * @author Michael Garvin <JID: gar@netflint.net>
* @author Alexander Birkner (https://github.com/BirknerAlex)
* @author zorn-v (https://github.com/zorn-v/xmpphp/)
* @author GNU social
* @copyright 2008 Nathanael C. Fritz * @copyright 2008 Nathanael C. Fritz
*/ */
namespace XMPPHP;
/** XMPPHP_XMLStream */ /** XMPPHP_XMLStream */
require_once 'XMPPHP/XMLStream.php'; require_once __DIR__ . DIRECTORY_SEPARATOR . 'XMLStream.php';
require_once 'XMPPHP/Roster.php'; require_once __DIR__ . DIRECTORY_SEPARATOR . 'Roster.php';
/** /**
* XMPPHP Main Class * XMPPHP XMPP
* *
* @category xmpphp * @package XMPPHP
* @package XMPPHP * @author Nathanael C. Fritz <JID: fritzy@netflint.net>
* @author Nathanael C. Fritz <JID: fritzy@netflint.net> * @author Stephan Wentz <JID: stephan@jabber.wentz.it>
* @author Stephan Wentz <JID: stephan@jabber.wentz.it> * @author Michael Garvin <JID: gar@netflint.net>
* @author Michael Garvin <JID: gar@netflint.net> * @copyright 2008 Nathanael C. Fritz
* @copyright 2008 Nathanael C. Fritz * @version $Id$
* @version $Id$
*/ */
class XMPPHP_XMPP extends XMPPHP_XMLStream { class XMPP extends XMLStream
/** {
* @var string /**
*/ * @var string
public $server; */
public $server;
/** /**
* @var string * @var string
*/ */
public $user; public $user;
/**
/** * @var boolean
* @var string */
*/ public $track_presence = true;
protected $password; /**
* @var object
/** */
* @var string public $roster;
*/ /**
protected $resource; * @var string
*/
/** protected $password;
* @var string /**
*/ * @var string
protected $fulljid; */
protected $resource;
/** /**
* @var string * @var string
*/ */
protected $basejid; protected $fulljid;
/**
/** * @var string
* @var boolean */
*/ protected $basejid;
protected $authed = false; /**
protected $session_started = false; * @var boolean
*/
/** protected $authed = false;
* @var boolean protected $session_started = false;
*/ /**
protected $auto_subscribe = false; * @var boolean
*/
/** protected $auto_subscribe = false;
* @var boolean /**
*/ * @var boolean
protected $use_encryption = true; */
protected $use_encryption = true;
/**
* @var boolean
*/
public $track_presence = true;
/**
* @var object
*/
public $roster;
/** /**
* @var array supported auth mechanisms * Constructor
*/ *
protected $auth_mechanism_supported = array('PLAIN', 'DIGEST-MD5'); * @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;
* @var string default auth mechanism $this->password = $password;
*/ $this->resource = $resource;
protected $auth_mechanism_default = 'PLAIN'; if (!$server) {
$server = $host;
}
$this->server = $server;
$this->basejid = $this->user . '@' . $this->host;
/** $this->roster = new Roster();
* @var string prefered auth mechanism $this->track_presence = true;
*/
protected $auth_mechanism_preferred = 'DIGEST-MD5';
/** $this->stream_start = '<stream:stream to="' . $server . '" xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client" version="1.0">';
* Constructor $this->stream_end = '</stream:stream>';
* $this->default_ns = 'jabber:client';
* @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->roster = new Roster(); $this->addXPathHandler('{http://etherx.jabber.org/streams}features', 'features_handler');
$this->track_presence = true; $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 = '<stream:stream to="' . $server . '" xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client" version="1.0">'; /**
$this->stream_end = '</stream:stream>'; * Turn encryption on/ff
$this->default_ns = 'jabber:client'; *
* @param boolean $useEncryption
$this->addXPathHandler('{http://etherx.jabber.org/streams}features', 'features_handler'); */
$this->addXPathHandler('{urn:ietf:params:xml:ns:xmpp-sasl}success', 'sasl_success_handler'); public function useEncryption($useEncryption = true)
$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->use_encryption = $useEncryption;
$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 * Turn on auto-authorization of subscription requests.
* *
* @param boolean $useEncryption * @param boolean $autoSubscribe
*/ */
public function useEncryption($useEncryption = true) { public function autoSubscribe($autoSubscribe = true)
$this->use_encryption = $useEncryption; {
} $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 * Send XMPP Message
* *
* @param string $to * @param string $to
* @param string $body * @param string $body
* @param string $type * @param string $type
* @param string $subject * @param string $subject
*/ * @param null $payload
public function message($to, $body, $type = 'chat', $subject = null, $payload = null) { * @throws Exception
if(is_null($type)) */
{ public function message($to, $body, $type = 'chat', $subject = null, $payload = null)
$type = 'chat'; {
} if ($this->disconnected) {
throw new Exception('You need to connect first');
$to = htmlspecialchars($to); }
$body = htmlspecialchars($body);
$subject = htmlspecialchars($subject);
$out = "<message from=\"{$this->fulljid}\" to=\"$to\" type='$type'>";
if($subject) $out .= "<subject>$subject</subject>";
$out .= "<body>$body</body>";
if($payload) $out .= $payload;
$out .= "</message>";
$this->send($out);
}
/** if (empty($type)) {
* Set Presence $type = 'chat';
* }
* @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 = "<presence";
if($to) $out .= " to=\"$to\"";
if($type) $out .= " type='$type'";
if($show == 'available' and !$status and $priority !== null) {
$out .= "/>";
} else {
$out .= ">";
if($show != 'available') $out .= "<show>$show</show>";
if($status) $out .= "<status>$status</status>";
if($priority !== null) $out .= "<priority>$priority</priority>";
$out .= "</presence>";
}
$this->send($out);
}
/**
* Send Auth request
*
* @param string $jid
*/
public function subscribe($jid) {
$this->send("<presence type='subscribe' to='{$jid}' from='{$this->fulljid}' />");
#$this->send("<presence type='subscribed' to='{$jid}' from='{$this->fulljid}' />");
}
/** $to = htmlspecialchars($to);
* Add user to Roster $body = htmlspecialchars($body);
* $subject = htmlspecialchars($subject);
* @param string $jid user jid $subject = ($subject) ? '<subject>' . $subject . '</subject>' : '';
* @param string $name user nickname $payload = ($payload) ? $payload : '';
* @param string $group group to add $sprintf = '<message from="%s" to="%s" type="%s">%s<body>%s</body>%s</message>';
*/ $output = sprintf($sprintf, $this->fulljid, $to, $type, $subject, $body, $payload);
public function RosterAddUser($jid, $name=null, $group=null) { $this->send($output);
$payload = "<item jid='$jid'".($name ? " name='" . htmlspecialchars($name) . "'" : '')."/>\n". }
($group?'<group>'.htmlspecialchars($group, ENT_QUOTES, 'UTF-8').'</group>':'');
$this->SendIq(NULL, 'set', "jabber:iq:roster", $payload);
}
/** /**
* Send ID action * Set Presence
* *
* @param string $to to jid * @param string $status
* @param string $type type of ID * @param string $show
* @param string $xmlns xmlns name * @param string $to
* @param string $payload payload string * @param string $type
* @param string $from from jid * @param null $priority
*/ * @throws Exception
private function sendIq($to = NULL, $type = 'get', $xmlns = NULL, $payload = NULL, $from = NULL) */
{ public function presence($status = null, $show = 'available', $to = null, $type = 'available', $priority = null)
$id = $this->getID(); {
$xml = "<iq type='$type' id='$id'". if ($this->disconnected) {
($to ? " to='$to'" : ''). throw new Exception('You need to connect first');
($from ? " from='$from'" : ''). }
">
<query xmlns='$xmlns'>
$payload
</query>
</iq>";
return $this->send($xml);
}
/** if ($type == 'available') {
* Message handler $type = '';
* }
* @param string $xml $to = htmlspecialchars($to);
*/ $status = htmlspecialchars($status);
public function message_handler($xml) { if ($show == 'unavailable') {
if(isset($xml->attrs['type'])) { $type = 'unavailable';
$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);
}
/** $out = "<presence";
* Presence handler if ($to) {
* $out .= " to=\"$to\"";
* @param string $xml }
*/ if ($type) {
public function presence_handler($xml) { $out .= " type='$type'";
$payload['type'] = (isset($xml->attrs['type'])) ? $xml->attrs['type'] : 'available'; }
$payload['show'] = (isset($xml->sub('show')->data)) ? $xml->sub('show')->data : $payload['type']; if ($show == 'available' and !$status and $priority !== null) {
$payload['from'] = $xml->attrs['from']; $out .= "/>";
$payload['status'] = (isset($xml->sub('status')->data)) ? $xml->sub('status')->data : ''; } else {
$payload['priority'] = (isset($xml->sub('priority')->data)) ? intval($xml->sub('priority')->data) : 0; $out .= ">";
$payload['xml'] = $xml; if ($show != 'available') {
if($this->track_presence) { $out .= "<show>$show</show>";
$this->roster->setPresence($payload['from'], $payload['priority'], $payload['show'], $payload['status']); }
} if ($status) {
$this->log->log("Presence: {$payload['from']} [{$payload['show']}] {$payload['status']}", XMPPHP_Log::LEVEL_DEBUG); $out .= "<status>$status</status>";
if(array_key_exists('type', $xml->attrs) and $xml->attrs['type'] == 'subscribe') { }
if($this->auto_subscribe) { if ($priority !== null) {
$this->send("<presence type='subscribed' to='{$xml->attrs['from']}' from='{$this->fulljid}' />"); $out .= "<priority>$priority</priority>";
$this->send("<presence type='subscribe' to='{$xml->attrs['from']}' from='{$this->fulljid}' />"); }
} $out .= "</presence>";
$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);
}
}
/** $this->send($out);
* Features handler }
*
* @param string $xml
*/
protected function features_handler($xml) {
if($xml->hasSub('starttls') and $this->use_encryption) {
$this->send("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'><required /></starttls>");
} elseif($xml->hasSub('bind') and $this->authed) {
$id = $this->getId();
$this->addIdHandler($id, 'resource_bind_handler');
$this->send("<iq xmlns=\"jabber:client\" type=\"set\" id=\"$id\"><bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"><resource>{$this->resource}</resource></bind></iq>");
} 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("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>" . base64_encode("\x00" . $this->user . "\x00" . $this->password) . "</auth>");
break;
case 'DIGEST-MD5':
$this->send("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='DIGEST-MD5' />");
break;
}
} else {
$this->send("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='ANONYMOUS'/>");
}
}
}
/** /**
* SASL success handler * Send Auth request
* *
* @param string $xml * @param string $jid
*/ */
protected function sasl_success_handler($xml) { public function subscribe($jid)
$this->log->log("Auth success!"); {
$this->authed = true; $this->send("<presence type='subscribe' to='{$jid}' from='{$this->fulljid}' />");
$this->reset(); #$this->send("<presence type='subscribed' to='{$jid}' from='{$this->fulljid}' />");
} }
/**
* 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!');
}
/** /**
* Handle challenges for DIGEST-MD5 auth * Message handler
* *
* @param string $xml * @param string $xml
*/ */
protected function sasl_challenge_handler($xml) { public function message_handler($xml)
// Decode and parse the challenge string {
// (may be something like foo="bar",foo2="bar2,bar3,bar4",foo3=bar5 ) if (isset($xml->attrs['type'])) {
$challenge = base64_decode($xml->data); $payload['type'] = $xml->attrs['type'];
$vars = array(); } else {
$matches = array(); $payload['type'] = 'chat';
preg_match_all('/(\w+)=(?:"([^"]*)|([^,]*))/', $challenge, $matches); }
$res = array(); $body = $xml->sub('body');
foreach ($matches[1] as $k => $v) { $payload['from'] = $xml->attrs['from'];
$vars[$v] = (empty($matches[2][$k])?$matches[3][$k]:$matches[2][$k]); $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 * Presence handler
$vars['cnonce'] = uniqid(mt_rand(), false); *
$vars['nc'] = '00000001'; * @param string $xml
$vars['qop'] = 'auth'; // Force qop to auth */
if (!isset($vars['digest-uri'])) $vars['digest-uri'] = 'xmpp/' . $this->server; public function presence_handler($xml)
if (!isset($vars['realm'])) $vars['realm'] = ''; {
$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("<presence type='subscribed' to='{$xml->attrs['from']}' from='{$this->fulljid}' />");
$this->send("<presence type='subscribe' to='{$xml->attrs['from']}' from='{$this->fulljid}' />");
}
$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); * Retrieves the roster
if ($vars['algorithm'] == 'md5-sess') { *
$a1 = pack('H32',md5($a1)) . ':' . $vars['nonce'] . ':' . $vars['cnonce']; */
} public function getRoster()
$a2 = "AUTHENTICATE:" . $vars['digest-uri']; {
$password = md5($a1) . ':' . $vars['nonce'] . ':' . $vars['nc'] . ':' . $vars['cnonce'] . ':' . $vars['qop'] . ':' .md5($a2); $id = $this->getID();
$password = md5($password); $this->send("<iq xmlns='jabber:client' type='get' id='$id'><query xmlns='jabber:iq:roster' /></iq>");
$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);
// Send the response /**
$response = base64_encode($response); * Retrieves the vcard
$this->send("<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>$response</response>"); * @param null $jid
} else { */
if (isset($vars['rspauth'])) { public function getVCard($jid = null)
// Second step {
$this->send("<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>"); $id = $this->getID();
} else { $this->addIdHandler($id, 'vcard_get_handler');
$this->log->log("ERROR receiving challenge : " . $challenge, XMPPHP_Log::LEVEL_ERROR); if ($jid) {
} $this->send("<iq type='get' id='$id' to='$jid'><vCard xmlns='vcard-temp' /></iq>");
} else {
$this->send("<iq type='get' id='$id'><vCard xmlns='vcard-temp' /></iq>");
}
}
} /**
} * Features handler
*
* @param string $xml
*/
protected function features_handler($xml)
{
if ($xml->hasSub('starttls') and $this->use_encryption) {
$this->send("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'><required /></starttls>");
} elseif ($xml->hasSub('bind') and $this->authed) {
$id = $this->getId();
$this->addIdHandler($id, 'resource_bind_handler');
$this->send("<iq xmlns=\"jabber:client\" type=\"set\" id=\"$id\"><bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"><resource>{$this->resource}</resource></bind></iq>");
} else {
$this->log->log("Attempting Auth...");
if ($this->password) {
$this->send("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>" . base64_encode("\x00" . $this->user . "\x00" . $this->password) . "</auth>");
} else {
$this->send("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='ANONYMOUS'/>");
}
}
}
/** /**
* Resource bind handler * SASL success handler
* *
* @param string $xml * @param string $xml
*/ */
protected function resource_bind_handler($xml) { protected function sasl_success_handler($xml)
if($xml->attrs['type'] == 'result') { {
$this->log->log("Bound to " . $xml->sub('bind')->sub('jid')->data); $this->log->log("Auth success!");
$this->fulljid = $xml->sub('bind')->sub('jid')->data; $this->authed = true;
$jidarray = explode('/',$this->fulljid); $this->reset();
$this->jid = $jidarray[0]; }
}
$id = $this->getId();
$this->addIdHandler($id, 'session_start_handler');
$this->send("<iq xmlns='jabber:client' type='set' id='$id'><session xmlns='urn:ietf:params:xml:ns:xmpp-session' /></iq>");
}
/** /**
* Retrieves the roster * SASL feature handler
* *
*/ * @param string $xml
public function getRoster() { * @throws Exception
$id = $this->getID(); */
$this->send("<iq xmlns='jabber:client' type='get' id='$id'><query xmlns='jabber:iq:roster' /></iq>"); protected function sasl_failure_handler($xml)
} {
$this->log->log("Auth failed!", Log::LEVEL_ERROR);
$this->disconnect();
/** throw new Exception('Auth failed!');
* 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("<iq type=\"result\" id=\"{$xml->attrs['id']}\" to=\"{$xml->attrs['from']}\" />");
}
}
/** /**
* Session start handler * Resource bind handler
* *
* @param string $xml * @param string $xml
*/ */
protected function session_start_handler($xml) { protected function resource_bind_handler($xml)
$this->log->log("Session started"); {
$this->session_started = true; if ($xml->attrs['type'] == 'result') {
$this->event('session_start'); $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("<iq xmlns='jabber:client' type='set' id='$id'><session xmlns='urn:ietf:params:xml:ns:xmpp-session' /></iq>");
}
/** /**
* TLS proceed handler * Roster iq handler
* * Gets all packets matching XPath "iq/{jabber:iq:roster}query'
* @param string $xml *
*/ * @param string $xml
protected function tls_proceed_handler($xml) { */
$this->log->log("Starting TLS encryption"); protected function roster_iq_handler($xml)
stream_socket_enable_crypto($this->socket, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT); {
$this->reset(); $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("<iq type=\"reply\" id=\"{$xml->attrs['id']}\" to=\"{$xml->attrs['from']}\" />");
}
}
/** /**
* Retrieves the vcard * Session start handler
* *
*/ * @param string $xml
public function getVCard($jid = Null) { */
$id = $this->getID(); protected function session_start_handler($xml)
$this->addIdHandler($id, 'vcard_get_handler'); {
if($jid) { $this->log->log("Session started");
$this->send("<iq type='get' id='$id' to='$jid'><vCard xmlns='vcard-temp' /></iq>"); $this->session_started = true;
} else { $this->event('session_start');
$this->send("<iq type='get' id='$id'><vCard xmlns='vcard-temp' /></iq>"); }
}
}
/** /**
* VCard retrieval handler * TLS proceed handler
* *
* @param XML Object $xml * @param string $xml
*/ */
protected function vcard_get_handler($xml) { protected function tls_proceed_handler($xml)
$vcard_array = array(); {
$vcard = $xml->sub('vcard'); $this->log->log("Starting TLS encryption");
// go through all of the sub elements and add them to the vcard array stream_socket_enable_crypto($this->socket, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
foreach ($vcard->subs as $sub) { $this->reset();
if ($sub->subs) { }
$vcard_array[$sub->name] = array();
foreach ($sub->subs as $sub_child) { /**
$vcard_array[$sub->name][$sub_child->name] = $sub_child->data; * VCard retrieval handler
} *
} else { * @param XMLObj $xml
$vcard_array[$sub->name] = $sub->data; */
} protected function vcard_get_handler($xml)
} {
$vcard_array['from'] = $xml->attrs['from']; $vcard_array = array();
$this->event('vcard', $vcard_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);
}
} }

View File

@ -1,114 +0,0 @@
<?php
/**
* XMPPHP: The PHP XMPP Library
* Copyright (C) 2008 Nathanael C. Fritz
* This file is part of SleekXMPP.
*
* XMPPHP is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* XMPPHP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XMPPHP; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category xmpphp
* @package XMPPHP
* @author Nathanael C. Fritz <JID: fritzy@netflint.net>
* @author Stephan Wentz <JID: stephan@jabber.wentz.it>
* @author Michael Garvin <JID: gar@netflint.net>
* @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 = '<stream:stream to="' . $server . '" xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client">';
$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("<iq type='get' id='$id'><query xmlns='jabber:iq:auth'><username>{$this->user}</username></query></iq>");
}
/**
* 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 = "<iq type='set' id='$id'><query xmlns='jabber:iq:auth'><username>{$this->user}</username><digest>{$hash}</digest><resource>{$this->resource}</resource></query></iq>";
} else {
$out = "<iq type='set' id='$id'><query xmlns='jabber:iq:auth'><username>{$this->user}</username><password>{$this->password}</password><resource>{$this->resource}</resource></query></iq>";
}
$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');
}
}
}
?>

49
composer.json Normal file
View File

@ -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": "*"
}
}

View File

@ -1,77 +1,141 @@
<?php <?php
// activate full error reporting /**
//error_reporting(E_ALL & E_STRICT); * @file: XMPPHP Cli example
*
* @info: If this script doesn't work, are you running 64-bit PHP with < 5.2.6?
*/
include 'XMPPHP/XMPP.php'; /**
* Activate full error reporting
* error_reporting(E_ALL & E_STRICT);
*
* XMPPHP Log levels:
*
* LEVEL_ERROR = 0;
* LEVEL_WARNING = 1;
* LEVEL_INFO = 2;
* LEVEL_DEBUG = 3;
* LEVEL_VERBOSE = 4;
*/
#Use XMPPHP_Log::LEVEL_VERBOSE to get more logging for error reports require '../vendor/autoload.php';
#If this doesn't work, are you running 64-bit PHP with < 5.2.6?
$conn = new XMPPHP_XMPP('talk.google.com', 5222, 'username', 'password', 'xmpphp', 'gmail.com', $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(); $conn->autoSubscribe();
$vcard_request = array(); $vcard_request = array();
try { try {
$conn->connect(); $conn->connect();
while(!$conn->isDisconnected()) {
$payloads = $conn->processUntil(array('message', 'presence', 'end_stream', 'session_start', 'vcard')); while (!$conn->isDisconnected()) {
foreach($payloads as $event) { $events = array('message', 'presence', 'end_stream', 'session_start', 'vcard');
$pl = $event[1]; $payloads = $conn->processUntil($events);
switch($event[0]) {
case 'message': foreach ($payloads as $result) {
print "---------------------------------------------------------------------------------\n"; list($event, $data) = $result;
print "Message from: {$pl['from']}\n";
if($pl['subject']) print "Subject: {$pl['subject']}\n"; if (isset($data)) {
print $pl['body'] . "\n"; extract($data);
print "---------------------------------------------------------------------------------\n"; }
$conn->message($pl['from'], $body="Thanks for sending me \"{$pl['body']}\".", $type=$pl['type']);
$cmd = explode(' ', $pl['body']); switch ($event) {
if($cmd[0] == 'quit') $conn->disconnect();
if($cmd[0] == 'break') $conn->send("</end>"); case 'message':
if($cmd[0] == 'vcard') {
if(!($cmd[1])) $cmd[1] = $conn->user . '@' . $conn->server; if (!$body) {
// take a note which user requested which vcard break;
$vcard_request[$pl['from']] = $cmd[1]; }
// request the vcard
$conn->getVCard($cmd[1]); echo str_repeat('-', 80);
} echo "Message from: $from";
break;
case 'presence': if (isset($subject)) {
print "Presence: {$pl['from']} [{$pl['show']}] {$pl['status']}\n"; echo "Subject: $subject";
break; }
case 'session_start':
print "Session Start\n"; echo $body;
$conn->getRoster(); echo str_repeat('-', 80);
$conn->presence($status="Cheese!");
break; $cmd = explode(' ', $body);
case 'vcard': $body = "Mi no entender! '$body'";
// check to see who requested this vcard $conn->message($from, $body, $type);
$deliver = array_keys($vcard_request, $pl['from']);
// work through the array to generate a message if (isset($cmd[0])) {
print_r($pl); if ($cmd[0] == 'quit') {
$msg = ''; $conn->disconnect();
foreach($pl as $key => $item) { }
$msg .= "$key: ";
if(is_array($item)) { if ($cmd[0] == 'break') {
$msg .= "\n"; $conn->send('</end>');
foreach($item as $subkey => $subitem) { }
$msg .= " $subkey: $subitem\n";
} if ($cmd[0] == 'vcard') {
} else { if (!isset($cmd[1])) {
$msg .= "$item\n"; $cmd[1] = $conn->user;
} }
}
// deliver the vcard msg to everyone that requested that vcard // Take a note which user requested which vcard
foreach($deliver as $sendjid) { $vcard_request[$from] = $cmd[1];
// remove the note on requests as we send out the message // Request the vcard
unset($vcard_request[$sendjid]); $conn->getVCard($cmd[1]);
$conn->message($sendjid, $msg, 'chat'); }
} }
break; 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()); die($e->getMessage());
} }

View File

@ -1,43 +1,104 @@
<?php <?php
// activate full error reporting /**
//error_reporting(E_ALL & E_STRICT); * @file: XMPPHP Cli example BOSH
*
* @info: If this script doesn't work, are you running 64-bit PHP with < 5.2.6?
*/
include 'XMPPHP/BOSH.php'; /**
* Activate full error reporting
* error_reporting(E_ALL & E_STRICT);
*
* XMPPHP Log levels:
*
* LEVEL_ERROR = 0;
* LEVEL_WARNING = 1;
* LEVEL_INFO = 2;
* LEVEL_DEBUG = 3;
* LEVEL_VERBOSE = 4;
*/
#Use XMPPHP_Log::LEVEL_VERBOSE to get more logging for error reports require '../vendor/autoload.php';
#If this doesn't work, are you running 64-bit PHP with < 5.2.6?
$conn = new XMPPHP_BOSH('server.tld', 5280, 'username', 'password', 'xmpphp', 'server.tld', $printlog=true, $loglevel=XMPPHP_Log::LEVEL_VERBOSE); $conf = array(
'server' => '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(); $conn->autoSubscribe();
try { try {
$conn->connect('http://server.tld:5280/xmpp-httpbind'); $conn->connect('http://server.tld:5280/xmpp-httpbind');
while(!$conn->isDisconnected()) {
$payloads = $conn->processUntil(array('message', 'presence', 'end_stream', 'session_start')); while (!$conn->isDisconnected()) {
foreach($payloads as $event) { $events = array('message', 'presence', 'end_stream', 'session_start');
$pl = $event[1]; $payloads = $conn->processUntil($events);
switch($event[0]) {
case 'message': foreach ($payloads as $result) {
print "---------------------------------------------------------------------------------\n"; list($event, $data) = $result;
print "Message from: {$pl['from']}\n";
if($pl['subject']) print "Subject: {$pl['subject']}\n"; if (isset($data)) {
print $pl['body'] . "\n"; extract($data);
print "---------------------------------------------------------------------------------\n"; }
$conn->message($pl['from'], $body="Thanks for sending me \"{$pl['body']}\".", $type=$pl['type']);
if($pl['body'] == 'quit') $conn->disconnect(); switch ($event) {
if($pl['body'] == 'break') $conn->send("</end>");
break; case 'message':
case 'presence':
print "Presence: {$pl['from']} [{$pl['show']}] {$pl['status']}\n"; if (!$body) {
break; break;
case 'session_start': }
print "Session Start\n";
$conn->getRoster(); echo str_repeat('-', 80);
$conn->presence($status="Cheese!"); echo "Message from: $from";
break;
} 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('</end>');
}
}
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()); die($e->getMessage());
} }

View File

@ -1,20 +1,47 @@
<?php <?php
// activate full error reporting /**
//error_reporting(E_ALL & E_STRICT); * @file: XMPPHP Send message example
*
* @info: If this script doesn't work, are you running 64-bit PHP with < 5.2.6?
*/
/**
* Activate full error reporting
* error_reporting(E_ALL & E_STRICT);
*
* XMPPHP Log levels:
*
* LEVEL_ERROR = 0;
* LEVEL_WARNING = 1;
* LEVEL_INFO = 2;
* LEVEL_DEBUG = 3;
* LEVEL_VERBOSE = 4;
*/
include 'XMPPHP/XMPP.php'; require_once __DIR__.'/../vendor/autoload.php';
#Use XMPPHP_Log::LEVEL_VERBOSE to get more logging for error reports $conf = array(
#If this doesn't work, are you running 64-bit PHP with < 5.2.6? 'server' => 'talk.google.com',
$conn = new XMPPHP_XMPP('talk.google.com', 5222, 'username', 'password', 'xmpphp', 'gmail.com', $printlog=false, $loglevel=XMPPHP_Log::LEVEL_INFO); '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 { try {
$conn->connect(); $XMPP->connect();
$conn->processUntil('session_start'); $XMPP->processUntil('session_start', 10);
$conn->presence(); $XMPP->presence();
$conn->message('someguy@someserver.net', 'This is a test message!'); $XMPP->message('target.user@jabber.domain.com', 'Hello, how are you?', 'chat');
$conn->disconnect(); $XMPP->disconnect();
} catch(XMPPHP_Exception $e) { } catch (XMPPHP\Exception $e) {
die($e->getMessage()); die($e->getMessage());
} }

View File

@ -1,56 +1,117 @@
<?php <?php
/**
* @file: XMPPHP Cli example
*
* @info: If this script doesn't work, are you running 64-bit PHP with < 5.2.6?
*/
/**
* Activate full error reporting
* error_reporting(E_ALL & E_STRICT);
*
* XMPPHP Log levels:
*
* LEVEL_ERROR = 0;
* LEVEL_WARNING = 1;
* LEVEL_INFO = 2;
* LEVEL_DEBUG = 3;
* LEVEL_VERBOSE = 4;
*/
session_start(); session_start();
header('content-type', 'plain/text'); header('content-type', 'plain/text');
// activate full error reporting
//error_reporting(E_ALL & E_STRICT);
include 'XMPPHP/BOSH.php'; require '../vendor/autoload.php';
print "<pre>";
#Use XMPPHP_Log::LEVEL_VERBOSE to get more logging for error reports $conf = array(
#If this doesn't work, are you running 64-bit PHP with < 5.2.6? 'server' => 'talk.google.com',
$conn = new XMPPHP_BOSH('server.tld', 5280, 'user', 'password', 'xmpphp', 'server.tld', $printlog=true, $loglevel=XMPPHP_Log::LEVEL_INFO); '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(); $conn->autoSubscribe();
try { try {
if(isset($_SESSION['messages'])) { if (isset($_SESSION['messages'])) {
foreach($_SESSION['messages'] as $msg) { foreach ($_SESSION['messages'] as $message) {
print $msg; echo $message;
flush(); flush();
} }
} } else {
$conn->connect('http://server.tld:5280/xmpp-httpbind', 1, true); $_SESSION['messages'] = array();
#while(true) { }
$payloads = $conn->processUntil(array('message', 'presence', 'end_stream', 'session_start'));
foreach($payloads as $event) { $conn->connect('http://server.tld:5280/xmpp-httpbind', 1, true);
$pl = $event[1]; $events = array('message', 'presence', 'end_stream', 'session_start', 'vcard');
switch($event[0]) { $payloads = $conn->processUntil($events);
case 'message':
if(!isset($_SESSION['messages'])) $_SESSION['message'] = Array(); foreach ($payloads as $result) {
$msg = "---------------------------------------------------------------------------------\n{$pl['from']}: {$pl['body']}\n"; list($event, $data) = $result;
print $msg;
$_SESSION['messages'][] = $msg; if (isset($data)) {
flush(); extract($data);
$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("</end>"); switch ($event) {
break;
case 'presence': case 'message':
print "Presence: {$pl['from']} [{$pl['show']}] {$pl['status']}\n";
break; if (!$body) {
case 'session_start': break;
print "Session Start\n"; }
$conn->getRoster();
$conn->presence($status="Cheese!"); $cmd = explode(' ', $body);
break; $msg = str_repeat('-', 80);
} $msg .= "\nMessage from: $from\n";
}
#} if (isset($subject)) {
} catch(XMPPHP_Exception $e) { $msg .= "Subject: $subject\n";
}
$msg .= $body . "\n";
$msg .= str_repeat('-', 80);
echo "<pre>$msg</pre>";
if (isset($cmd[0])) {
if ($cmd[0] == 'quit') {
$conn->disconnect();
}
if ($cmd[0] == 'break') {
$conn->send('</end>');
}
}
$_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()); die($e->getMessage());
} }
$conn->saveSession(); $conn->saveSession();
print "</pre>"; echo '<img src="http://xmpp.org/images/xmpp.png" onload="window.location.reload()" />';
print "<img src='http://xmpp.org/images/xmpp.png' onload='window.location.reload()' />";
?>

View File

@ -1,31 +1,79 @@
<?php <?php
if (!defined('PHPUnit_MAIN_METHOD')) {
define('PHPUnit_MAIN_METHOD', 'AllTests::main'); /**
} * XMPPHP: The PHP XMPP Library
* Copyright (C) 2008 Nathanael C. Fritz
require_once 'XMPPHP/LogTest.php'; * This file is part of SleekXMPP.
require_once 'XMPPHP/XMLObjTest.php'; *
require_once 'XMPPHP/XMPPTest.php'; * XMPPHP is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
class AllTests * the Free Software Foundation; either version 2 of the License, or
{ * (at your option) any later version.
public static function main() *
{ * XMPPHP is distributed in the hope that it will be useful,
PHPUnit_TextUI_TestRunner::run(self::suite()); * but WITHOUT ANY WARRANTY; without even the implied warranty of
} * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
public static function suite() *
{ * You should have received a copy of the GNU General Public License
$suite = new PHPUnit_Framework_TestSuite(); * along with XMPPHP; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
$suite->addTestSuite('XMPPHP_LogTest'); *
$suite->addTestSuite('XMPPHP_XMLObjTest'); * @category xmpphp
$suite->addTestSuite('XMPPHP_XMPPTest'); * @package XMPPHP
* @author Nathanael C. Fritz <JID: fritzy@netflint.net>
return $suite; * @author Stephan Wentz <JID: stephan@jabber.wentz.it>
} * @author Michael Garvin <JID: gar@netflint.net>
} * @copyright 2008 Nathanael C. Fritz
*/
if (PHPUnit_MAIN_METHOD == 'AllTests::main') {
AllTests::main(); // 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 <JID: fritzy@netflint.net>
* @author Stephan Wentz <JID: stephan@jabber.wentz.it>
* @author Michael Garvin <JID: gar@netflint.net>
* @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();
}

View File

@ -1,162 +1,188 @@
<?php <?php
require_once dirname(dirname(dirname(__FILE__))) . '/XMPPHP/Log.php'; /**
* XMPPHP: The PHP XMPP Library
* Copyright (C) 2008 Nathanael C. Fritz
* This file is part of SleekXMPP.
*
* XMPPHP is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* XMPPHP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XMPPHP; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category xmpphp
* @package XMPPHP
* @author Nathanael C. Fritz <JID: fritzy@netflint.net>
* @author Stephan Wentz <JID: stephan@jabber.wentz.it>
* @author Michael Garvin <JID: gar@netflint.net>
* @copyright 2008 Nathanael C. Fritz
*/
/** XMPPHP_Log */
require_once CLASS_DIR . 'XMPPHP' . DIRECTORY_SEPARATOR . 'Log.php';
/**
* XMPPHP LogTest
*
* @package XMPPHP
* @author Nathanael C. Fritz <JID: fritzy@netflint.net>
* @author Stephan Wentz <JID: stephan@jabber.wentz.it>
* @author Michael Garvin <JID: gar@netflint.net>
* @copyright 2008 Nathanael C. Fritz
* @version $Id$
*/
class XMPPHP_LogTest extends PHPUnit_Framework_TestCase class XMPPHP_LogTest extends PHPUnit_Framework_TestCase
{ {
public function testPrintoutNoOutput() public function testPrintoutNoOutput()
{ {
$log = new XMPPHP_Log(); $log = new XMPPHP_Log();
$msg = 'I am a test log message'; $msg = 'I am a test log message';
ob_start(); ob_start();
$log->log('test'); $log->log('test');
$result = ob_get_clean(); $result = ob_get_clean();
$this->assertEquals('', $result); $this->assertEquals('', $result);
} }
public function testPrintoutOutput() public function testPrintoutOutput()
{ {
$log = new XMPPHP_Log(true); $log = new XMPPHP_Log(true);
$msg = 'I am a test log message'; $msg = 'I am a test log message';
ob_start(); ob_start();
$log->log($msg); $log->log($msg);
$result = ob_get_clean(); $result = ob_get_clean();
$this->assertContains($msg, $result); $this->assertContains($msg, $result);
} }
public function testPrintoutNoOutputWithDefaultLevel() public function testPrintoutNoOutputWithDefaultLevel()
{ {
$log = new XMPPHP_Log(true, XMPPHP_Log::LEVEL_ERROR); $log = new XMPPHP_Log(true, XMPPHP_Log::LEVEL_ERROR);
$msg = 'I am a test log message'; $msg = 'I am a test log message';
ob_start(); ob_start();
$log->log($msg); $log->log($msg);
$result = ob_get_clean(); $result = ob_get_clean();
$this->assertSame('', $result); $this->assertSame('', $result);
} }
public function testPrintoutOutputWithDefaultLevel() public function testPrintoutOutputWithDefaultLevel()
{ {
$log = new XMPPHP_Log(true, XMPPHP_Log::LEVEL_INFO); $log = new XMPPHP_Log(true, XMPPHP_Log::LEVEL_INFO);
$msg = 'I am a test log message'; $msg = 'I am a test log message';
ob_start(); ob_start();
$log->log($msg); $log->log($msg);
$result = ob_get_clean(); $result = ob_get_clean();
$this->assertContains($msg, $result); $this->assertContains($msg, $result);
} }
public function testPrintoutNoOutputWithCustomLevel() public function testPrintoutNoOutputWithCustomLevel()
{ {
$log = new XMPPHP_Log(true, XMPPHP_Log::LEVEL_INFO); $log = new XMPPHP_Log(true, XMPPHP_Log::LEVEL_INFO);
$msg = 'I am a test log message'; $msg = 'I am a test log message';
ob_start(); ob_start();
$log->log($msg, XMPPHP_Log::LEVEL_DEBUG); $log->log($msg, XMPPHP_Log::LEVEL_DEBUG);
$result = ob_get_clean(); $result = ob_get_clean();
$this->assertSame('', $result); $this->assertSame('', $result);
} }
public function testPrintoutOutputWithCustomLevel() public function testPrintoutOutputWithCustomLevel()
{ {
$log = new XMPPHP_Log(true, XMPPHP_Log::LEVEL_INFO); $log = new XMPPHP_Log(true, XMPPHP_Log::LEVEL_INFO);
$msg = 'I am a test log message'; $msg = 'I am a test log message';
ob_start(); ob_start();
$log->log($msg, XMPPHP_Log::LEVEL_INFO); $log->log($msg, XMPPHP_Log::LEVEL_INFO);
$result = ob_get_clean(); $result = ob_get_clean();
$this->assertContains($msg, $result); $this->assertContains($msg, $result);
} }
public function testExplicitPrintout() public function testExplicitPrintout()
{ {
$log = new XMPPHP_Log(false); $log = new XMPPHP_Log(false);
$msg = 'I am a test log message'; $msg = 'I am a test log message';
ob_start(); ob_start();
$log->log($msg); $log->log($msg);
$result = ob_get_clean(); $result = ob_get_clean();
$this->assertSame('', $result); $this->assertSame('', $result);
} }
public function testExplicitPrintoutResult() public function testExplicitPrintoutResult()
{ {
$log = new XMPPHP_Log(false); $log = new XMPPHP_Log(false);
$msg = 'I am a test log message'; $msg = 'I am a test log message';
ob_start(); ob_start();
$log->log($msg); $log->log($msg);
$result = ob_get_clean(); $result = ob_get_clean();
$this->assertSame('', $result); $this->assertSame('', $result);
ob_start(); ob_start();
$log->printout(); $log->printout();
$result = ob_get_clean(); $result = ob_get_clean();
$this->assertContains($msg, $result); $this->assertContains($msg, $result);
} }
public function testExplicitPrintoutClear() public function testExplicitPrintoutClear()
{ {
$log = new XMPPHP_Log(false); $log = new XMPPHP_Log(false);
$msg = 'I am a test log message'; $msg = 'I am a test log message';
ob_start(); ob_start();
$log->log($msg); $log->log($msg);
$result = ob_get_clean(); $result = ob_get_clean();
$this->assertSame('', $result); $this->assertSame('', $result);
ob_start(); ob_start();
$log->printout(); $log->printout();
$result = ob_get_clean(); $result = ob_get_clean();
$this->assertContains($msg, $result); $this->assertContains($msg, $result);
ob_start(); ob_start();
$log->printout(); $log->printout();
$result = ob_get_clean(); $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); $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);
}
} }

View File

@ -1,53 +1,78 @@
<?php <?php
require_once dirname(dirname(dirname(__FILE__))) . '/XMPPHP/XMLObj.php'; /**
* XMPPHP: The PHP XMPP Library
* Copyright (C) 2008 Nathanael C. Fritz
* This file is part of SleekXMPP.
*
* XMPPHP is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* XMPPHP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XMPPHP; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category xmpphp
* @package XMPPHP
* @author Nathanael C. Fritz <JID: fritzy@netflint.net>
* @author Stephan Wentz <JID: stephan@jabber.wentz.it>
* @author Michael Garvin <JID: gar@netflint.net>
* @copyright 2008 Nathanael C. Fritz
*/
/** XMPPHP_XMLObj */
require_once CLASS_DIR . 'XMPPHP' . DIRECTORY_SEPARATOR . 'XMLObj.php';
/**
* XMPPHP XMLObjectTest
*
* @package XMPPHP
* @author Nathanael C. Fritz <JID: fritzy@netflint.net>
* @author Stephan Wentz <JID: stephan@jabber.wentz.it>
* @author Michael Garvin <JID: gar@netflint.net>
* @copyright 2008 Nathanael C. Fritz
* @version $Id$
*/
class XMPPHP_XMLObjTest extends PHPUnit_Framework_TestCase class XMPPHP_XMLObjTest extends PHPUnit_Framework_TestCase
{ {
public function testToStringNameNamespace() public function testToStringNameNamespace()
{ {
$xmlobj = new XMPPHP_XMLObj('testname', 'testNameSpace'); $xmlobj = new XMPPHP_XMLObj('testname', 'testNameSpace');
$expected = '<testname xmlns="testNameSpace"></testname>';
$expected = "<testname xmlns='testNameSpace' ></testname>"; $result = $xmlobj->toString();
$result = $xmlobj->toString();
$this->assertSame($expected, $result); $this->assertSame($expected, $result);
} }
public function testToStringNameNamespaceAttr() public function testToStringNameNamespaceAttr()
{ {
$xmlobj = new XMPPHP_XMLObj('testName', 'testNameSpace', array('attr1'=>'valA', 'attr2'=>'valB')); $xmlobj = new XMPPHP_XMLObj('testName', 'testNameSpace', array('attr1' => 'valA', 'attr2' => 'valB'));
$expected = '<testname xmlns="testNameSpace" attr1="valA" attr2="valB"></testname>';
$expected = "<testname xmlns='testNameSpace' attr1='valA' attr2='valB' ></testname>"; $result = $xmlobj->toString();
$result = $xmlobj->toString();
$this->assertSame($expected, $result); $this->assertSame($expected, $result);
} }
public function testToStringNameNamespaceData() public function testToStringNameNamespaceData()
{ {
$xmlobj = new XMPPHP_XMLObj('testName', 'testNameSpace', array(), 'I am test data'); $xmlobj = new XMPPHP_XMLObj('testName', 'testNameSpace', array(), 'I am test data');
$expected = '<testname xmlns="testNameSpace">I am test data</testname>';
$expected = "<testname xmlns='testNameSpace' >I am test data</testname>"; $result = $xmlobj->toString();
$result = $xmlobj->toString();
$this->assertSame($expected, $result); $this->assertSame($expected, $result);
} }
public function testToStringNameNamespaceSub() public function testToStringNameNamespaceSub()
{ {
$xmlobj = new XMPPHP_XMLObj('testName', 'testNameSpace'); $xmlobj = new XMPPHP_XMLObj('testName', 'testNameSpace');
$sub1 = new XMPPHP_XMLObj('subName', 'subNameSpace'); $sub1 = new XMPPHP_XMLObj('subName', 'subNameSpace');
$xmlobj->subs = array($sub1); $xmlobj->subs = array($sub1);
$expected = '<testname xmlns="testNameSpace"><subname xmlns="subNameSpace"></subname></testname>';
$expected = "<testname xmlns='testNameSpace' ><subname xmlns='subNameSpace' ></subname></testname>"; $result = $xmlobj->toString();
$result = $xmlobj->toString();
$this->assertSame($expected, $result); $this->assertSame($expected, $result);
} }
} }

View File

@ -1,7 +1,45 @@
<?php <?php
require_once dirname(dirname(dirname(__FILE__))) . '/XMPPHP/XMPP.php'; /**
* XMPPHP: The PHP XMPP Library
* Copyright (C) 2008 Nathanael C. Fritz
* This file is part of SleekXMPP.
*
* XMPPHP is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* XMPPHP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XMPPHP; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category xmpphp
* @package XMPPHP
* @author Nathanael C. Fritz <JID: fritzy@netflint.net>
* @author Stephan Wentz <JID: stephan@jabber.wentz.it>
* @author Michael Garvin <JID: gar@netflint.net>
* @copyright 2008 Nathanael C. Fritz
*/
/** XMPPHP_XMPP */
require_once CLASS_DIR . 'XMPPHP' . DIRECTORY_SEPARATOR . 'XMPP.php';
/**
* XMPPHP XMPPTest
*
* @package XMPPHP
* @author Nathanael C. Fritz <JID: fritzy@netflint.net>
* @author Stephan Wentz <JID: stephan@jabber.wentz.it>
* @author Michael Garvin <JID: gar@netflint.net>
* @copyright 2008 Nathanael C. Fritz
* @version $Id$
*/
class XMPPHP_XMPPTest extends PHPUnit_Framework_TestCase class XMPPHP_XMPPTest extends PHPUnit_Framework_TestCase
{ {
public function testConnectException() public function testConnectException()
@ -14,12 +52,12 @@ class XMPPHP_XMPPTest extends PHPUnit_Framework_TestCase
$xmpp->presence(); $xmpp->presence();
$xmpp->message('stephan@jabber.wentz.it', 'This is a test message!'); $xmpp->message('stephan@jabber.wentz.it', 'This is a test message!');
$xmpp->disconnect(); $xmpp->disconnect();
} catch(XMPPHP_Exception $e) { } catch (XMPPHP_Exception $e) {
return; return;
} catch(Exception $e) { } catch (Exception $e) {
$this->fail('Unexpected Exception thrown: '.$e->getMessage()); $this->fail('Unexpected Exception thrown: '.$e->getMessage());
} }
$this->fail('Expected XMPPHP_Exception not thrown!'); $this->fail('Expected XMPPHP_Exception not thrown!');
} }
@ -33,12 +71,12 @@ class XMPPHP_XMPPTest extends PHPUnit_Framework_TestCase
$xmpp->presence(); $xmpp->presence();
$xmpp->message('stephan@jabber.wentz.it', 'This is a test message!'); $xmpp->message('stephan@jabber.wentz.it', 'This is a test message!');
$xmpp->disconnect(); $xmpp->disconnect();
} catch(XMPPHP_Exception $e) { } catch (XMPPHP_Exception $e) {
return; return;
} catch(Exception $e) { } catch (Exception $e) {
$this->fail('Unexpected Exception thrown: '.$e->getMessage()); $this->fail('Unexpected Exception thrown: '.$e->getMessage());
} }
$this->fail('Expected XMPPHP_Exception not thrown!'); $this->fail('Expected XMPPHP_Exception not thrown!');
} }
} }