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-04-21 01:23:50 +01:00
parent a59c439b46
commit 3290227b50
13 changed files with 2262 additions and 2024 deletions

View File

@ -525,7 +525,7 @@ abstract class ImPlugin extends Plugin
{ {
// If we don't require CLI mode, or if we do and GNUSOCIAL_CLI _is_ set, then connect the transports // If we don't require CLI mode, or if we do and GNUSOCIAL_CLI _is_ set, then connect the transports
// This check is made mostly because some IM plugins can't deliver to transports unless they // This check is made mostly because some IM plugins can't deliver to transports unless they
// have continously running daemons (such as XMPP) and we can't have that over HTTP requests. // have continuously running daemons (such as XMPP) and we can't have that over HTTP requests.
if (!$this->requires_cli || defined('GNUSOCIAL_CLI')) { if (!$this->requires_cli || defined('GNUSOCIAL_CLI')) {
$manager->connect($this->transport . '-in', new ImReceiverQueueHandler($this), 'im'); $manager->connect($this->transport . '-in', new ImReceiverQueueHandler($this), 'im');
$manager->connect($this->transport, new ImQueueHandler($this)); $manager->connect($this->transport, new ImQueueHandler($this));

View File

@ -5,7 +5,7 @@
* *
* Send and receive notices using the XMPP network * Send and receive notices using the XMPP network
* *
* PHP version 5 * PHP version 7
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by * it under the terms of the GNU Affero General Public License as published by
@ -57,22 +57,66 @@ class XmppPlugin extends ImPlugin
public $transport = 'xmpp'; public $transport = 'xmpp';
function getDisplayName(){ function getDisplayName()
{
// TRANS: Plugin display name. // TRANS: Plugin display name.
return _m('XMPP/Jabber'); return _m('XMPP/Jabber');
} }
function daemonScreenname()
{
$ret = $this->user . '@' . $this->server;
if ($this->resource) {
return $ret . '/' . $this->resource;
} else {
return $ret;
}
}
function validate($screenname)
{
return $this->validateBaseJid($screenname, common_config('email', 'check_domain'));
}
/**
* Checks whether a string is a syntactically valid base Jabber ID (JID).
* A base JID won't include a resource specifier on the end; since we
* take it off when reading input we can't really use them reliably
* to direct outgoing messages yet (sorry guys!)
*
* Note that a bare domain can be a valid JID.
*
* @param string $jid string to check
* @param bool $check_domain whether we should validate that domain...
*
* @return boolean whether the string is a valid JID
*/
protected function validateBaseJid($jid, $check_domain = false)
{
try {
$parts = $this->splitJid($jid);
if ($check_domain) {
if (!$this->checkDomain($parts['domain'])) {
return false;
}
}
return ($parts['resource'] === null); // missing; empty ain't kosher
} catch (Exception $e) {
return false;
}
}
/** /**
* Splits a Jabber ID (JID) into node, domain, and resource portions. * Splits a Jabber ID (JID) into node, domain, and resource portions.
* *
* Based on validation routine submitted by: * Based on validation routine submitted by:
* @copyright 2009 Patrick Georgi <patrick@georgi-clan.de>
* @license Licensed under ISC-L, which is compatible with everything else that keeps the copyright notice intact.
*
* @param string $jid string to check * @param string $jid string to check
* *
* @return array with "node", "domain", and "resource" indices * @return array with "node", "domain", and "resource" indices
* @throws Exception if input is not valid * @throws Exception if input is not valid
* @license Licensed under ISC-L, which is compatible with everything else that keeps the copyright notice intact.
*
* @copyright 2009 Patrick Georgi <patrick@georgi-clan.de>
*/ */
protected function splitJid($jid) protected function splitJid($jid)
{ {
@ -109,10 +153,9 @@ class XmppPlugin extends ImPlugin
$parts = explode("/", $jid, 2); $parts = explode("/", $jid, 2);
if (count($parts) > 1) { if (count($parts) > 1) {
$resource = $parts[1]; $resource = $parts[1];
if ($resource == '') { // if ($resource == '') then
// Warning: empty resource isn't legit. // Warning: empty resource isn't legit.
// But if we're normalizing, we may as well take it... // But if we're normalizing, we may as well take it...
}
} else { } else {
$resource = null; $resource = null;
} }
@ -139,10 +182,10 @@ class XmppPlugin extends ImPlugin
// TRANS: Exception thrown when using too long a Jabber ID (>1023). // TRANS: Exception thrown when using too long a Jabber ID (>1023).
throw new Exception(_m('Invalid JID: node too long.')); throw new Exception(_m('Invalid JID: node too long.'));
} }
if (preg_match("/[".$nodeprepchars."]/u", $node)) { if (preg_match("/[" . $nodeprepchars . "]/u", $node)) {
// TRANS: Exception thrown when using an invalid Jabber ID. // TRANS: Exception thrown when using an invalid Jabber ID.
// TRANS: %s is the invalid Jabber ID. // TRANS: %s is the invalid Jabber ID.
throw new Exception(sprintf(_m('Invalid JID node "%s".'),$node)); throw new Exception(sprintf(_m('Invalid JID node "%s".'), $node));
} }
} }
@ -153,7 +196,7 @@ class XmppPlugin extends ImPlugin
if (!common_valid_domain($domain)) { if (!common_valid_domain($domain)) {
// TRANS: Exception thrown when using an invalid Jabber domain name. // TRANS: Exception thrown when using an invalid Jabber domain name.
// TRANS: %s is the invalid domain name. // TRANS: %s is the invalid domain name.
throw new Exception(sprintf(_m('Invalid JID domain name "%s".'),$domain)); throw new Exception(sprintf(_m('Invalid JID domain name "%s".'), $domain));
} }
if ($resource !== null) { if ($resource !== null) {
@ -161,10 +204,10 @@ class XmppPlugin extends ImPlugin
// TRANS: Exception thrown when using too long a resource (>1023). // TRANS: Exception thrown when using too long a resource (>1023).
throw new Exception("Invalid JID: resource too long."); throw new Exception("Invalid JID: resource too long.");
} }
if (preg_match("/[".$chars."]/u", $resource)) { if (preg_match("/[" . $chars . "]/u", $resource)) {
// TRANS: Exception thrown when using an invalid Jabber resource. // TRANS: Exception thrown when using an invalid Jabber resource.
// TRANS: %s is the invalid resource. // TRANS: %s is the invalid resource.
throw new Exception(sprintf(_m('Invalid JID resource "%s".'),$resource)); throw new Exception(sprintf(_m('Invalid JID resource "%s".'), $resource));
} }
} }
@ -173,84 +216,10 @@ class XmppPlugin extends ImPlugin
'resource' => $resource); 'resource' => $resource);
} }
/**
* Checks whether a string is a syntactically valid Jabber ID (JID),
* either with or without a resource.
*
* Note that a bare domain can be a valid JID.
*
* @param string $jid string to check
* @param bool $check_domain whether we should validate that domain...
*
* @return boolean whether the string is a valid JID
*/
protected function validateFullJid($jid, $check_domain=false)
{
try {
$parts = $this->splitJid($jid);
if ($check_domain) {
if (!$this->checkDomain($parts['domain'])) {
return false;
}
}
return $parts['resource'] !== ''; // missing or present; empty ain't kosher
} catch (Exception $e) {
return false;
}
}
/**
* Checks whether a string is a syntactically valid base Jabber ID (JID).
* A base JID won't include a resource specifier on the end; since we
* take it off when reading input we can't really use them reliably
* to direct outgoing messages yet (sorry guys!)
*
* Note that a bare domain can be a valid JID.
*
* @param string $jid string to check
* @param bool $check_domain whether we should validate that domain...
*
* @return boolean whether the string is a valid JID
*/
protected function validateBaseJid($jid, $check_domain=false)
{
try {
$parts = $this->splitJid($jid);
if ($check_domain) {
if (!$this->checkDomain($parts['domain'])) {
return false;
}
}
return ($parts['resource'] === null); // missing; empty ain't kosher
} catch (Exception $e) {
return false;
}
}
/**
* Normalizes a Jabber ID for comparison, dropping the resource component if any.
*
* @param string $jid JID to check
* @param bool $check_domain if true, reject if the domain isn't findable
*
* @return string an equivalent JID in normalized (lowercase) form
*/
function normalize($jid)
{
try {
$parts = $this->splitJid($jid);
if ($parts['node'] !== null) {
return $parts['node'] . '@' . $parts['domain'];
} else {
return $parts['domain'];
}
} catch (Exception $e) {
return null;
}
}
/** /**
* Check if this domain's got some legit DNS record * Check if this domain's got some legit DNS record
* @param $domain
* @return bool
*/ */
protected function checkDomain($domain) protected function checkDomain($domain)
{ {
@ -263,22 +232,6 @@ class XmppPlugin extends ImPlugin
return false; return false;
} }
function daemonScreenname()
{
$ret = $this->user . '@' . $this->server;
if($this->resource)
{
return $ret . '/' . $this->resource;
}else{
return $ret;
}
}
function validate($screenname)
{
return $this->validateBaseJid($screenname, common_config('email', 'check_domain'));
}
/** /**
* Load related modules when needed * Load related modules when needed
* *
@ -289,12 +242,9 @@ class XmppPlugin extends ImPlugin
function onAutoload($cls) function onAutoload($cls)
{ {
$dir = dirname(__FILE__); switch ($cls) {
switch ($cls)
{
case 'XMPPHP_XMPP': case 'XMPPHP_XMPP':
require_once $dir . '/extlib/XMPPHP/XMPP.php'; require_once __DIR__ . '/extlib/XMPPHP/XMPP.php';
return false; return false;
} }
@ -313,6 +263,47 @@ class XmppPlugin extends ImPlugin
$this->queuedConnection()->message($screenname, $body, 'chat'); $this->queuedConnection()->message($screenname, $body, 'chat');
} }
/**
* Build a queue-proxied XMPP interface object. Any outgoing messages
* will be run back through us for enqueing rather than sent directly.
*
* @return QueuedXMPP
* @throws Exception if server settings are invalid.
*/
function queuedConnection()
{
if (!isset($this->server)) {
// TRANS: Exception thrown when the plugin configuration is incorrect.
throw new Exception(_m('You must specify a server in the configuration.'));
}
if (!isset($this->port)) {
// TRANS: Exception thrown when the plugin configuration is incorrect.
throw new Exception(_m('You must specify a port in the configuration.'));
}
if (!isset($this->user)) {
// TRANS: Exception thrown when the plugin configuration is incorrect.
throw new Exception(_m('You must specify a user in the configuration.'));
}
if (!isset($this->password)) {
// TRANS: Exception thrown when the plugin configuration is incorrect.
throw new Exception(_m('You must specify a password in the configuration.'));
}
return new QueuedXMPP($this, $this->host ?
$this->host :
$this->server,
$this->port,
$this->user,
$this->password,
$this->resource,
$this->server,
$this->debug ?
true : false,
$this->debug ?
\XMPPHP\Log::LEVEL_VERBOSE : null
);
}
function sendNotice($screenname, Notice $notice) function sendNotice($screenname, Notice $notice)
{ {
try { try {
@ -329,7 +320,6 @@ class XmppPlugin extends ImPlugin
/** /**
* extra information for XMPP messages, as defined by Twitter * extra information for XMPP messages, as defined by Twitter
* *
* @param Profile $profile Profile of the sending user
* @param Notice $notice Notice being sent * @param Notice $notice Notice being sent
* *
* @return string Extra information (Atom, HTML, addresses) in string format * @return string Extra information (Atom, HTML, addresses) in string format
@ -351,23 +341,18 @@ class XmppPlugin extends ImPlugin
$xs->text(" => "); $xs->text(" => ");
$xs->element('a', array('href' => $orig_profurl), $orig_profile->nickname); $xs->element('a', array('href' => $orig_profurl), $orig_profile->nickname);
$xs->text(": "); $xs->text(": ");
} catch (InvalidUrlException $e) {
$xs->text(sprintf(' => %s', $orig_profile->nickname));
} catch (NoParentNoticeException $e) { } catch (NoParentNoticeException $e) {
$xs->text(": "); $xs->text(": ");
} catch (NoResultException $e) {
// Parent notice was probably deleted.
$xs->text(": ");
} }
// FIXME: Why do we replace \t with ''? is it just to make it pretty? shouldn't whitespace be handled well...? // FIXME: Why do we replace \t with ''? is it just to make it pretty? shouldn't whitespace be handled well...?
$xs->raw(str_replace("\t", "", $notice->getRendered())); $xs->raw(str_replace("\t", "", $notice->getRendered()));
$xs->text(" "); $xs->text(" ");
$xs->element('a', array( $xs->element('a', array(
'href'=>common_local_url('conversation', 'href' => common_local_url('conversation',
array('id' => $notice->conversation)).'#notice-'.$notice->id), array('id' => $notice->conversation)) . '#notice-' . $notice->id),
// TRANS: Link description to notice in conversation. // TRANS: Link description to notice in conversation.
// TRANS: %s is a notice ID. // TRANS: %s is a notice ID.
sprintf(_m('[%u]'),$notice->id)); sprintf(_m('[%u]'), $notice->id));
$xs->elementEnd('body'); $xs->elementEnd('body');
$xs->elementEnd('html'); $xs->elementEnd('html');
@ -381,7 +366,7 @@ class XmppPlugin extends ImPlugin
$from = $this->normalize($pl['from']); $from = $this->normalize($pl['from']);
if ($pl['type'] != 'chat') { if ($pl['type'] != 'chat') {
$this->log(LOG_WARNING, "Ignoring message of type ".$pl['type']." from $from: " . $pl['xml']->toString()); $this->log(LOG_WARNING, "Ignoring message of type " . $pl['type'] . " from $from: " . $pl['xml']->toString());
return true; return true;
} }
@ -396,43 +381,23 @@ class XmppPlugin extends ImPlugin
} }
/** /**
* Build a queue-proxied XMPP interface object. Any outgoing messages * Normalizes a Jabber ID for comparison, dropping the resource component if any.
* will be run back through us for enqueing rather than sent directly.
* *
* @return QueuedXMPP * @param string $jid JID to check
* @throws Exception if server settings are invalid. * @return string an equivalent JID in normalized (lowercase) form
*/ */
function queuedConnection(){ function normalize($jid)
if(!isset($this->server)){ {
// TRANS: Exception thrown when the plugin configuration is incorrect. try {
throw new Exception(_m('You must specify a server in the configuration.')); $parts = $this->splitJid($jid);
if ($parts['node'] !== null) {
return $parts['node'] . '@' . $parts['domain'];
} else {
return $parts['domain'];
} }
if(!isset($this->port)){ } catch (Exception $e) {
// TRANS: Exception thrown when the plugin configuration is incorrect. return null;
throw new Exception(_m('You must specify a port in the configuration.'));
} }
if(!isset($this->user)){
// TRANS: Exception thrown when the plugin configuration is incorrect.
throw new Exception(_m('You must specify a user in the configuration.'));
}
if(!isset($this->password)){
// TRANS: Exception thrown when the plugin configuration is incorrect.
throw new Exception(_m('You must specify a password in the configuration.'));
}
return new QueuedXMPP($this, $this->host ?
$this->host :
$this->server,
$this->port,
$this->user,
$this->password,
$this->resource,
$this->server,
$this->debug ?
true : false,
$this->debug ?
XMPPHP_Log::LEVEL_VERBOSE : null
);
} }
/** /**
@ -444,10 +409,10 @@ class XmppPlugin extends ImPlugin
*/ */
function onGetValidDaemons(&$daemons) function onGetValidDaemons(&$daemons)
{ {
if( isset($this->server) && if (isset($this->server) &&
isset($this->port) && isset($this->port) &&
isset($this->user) && isset($this->user) &&
isset($this->password) ){ isset($this->password)) {
array_push( array_push(
$daemons, $daemons,
@ -459,7 +424,6 @@ class XmppPlugin extends ImPlugin
return true; return true;
} }
function onPluginVersion(array &$versions) function onPluginVersion(array &$versions)
{ {
$versions[] = array('name' => 'XMPP', $versions[] = array('name' => 'XMPP',
@ -471,5 +435,31 @@ class XmppPlugin extends ImPlugin
_m('The XMPP plugin allows users to send and receive notices over the XMPP/Jabber network.')); _m('The XMPP plugin allows users to send and receive notices over the XMPP/Jabber network.'));
return true; return true;
} }
/**
* Checks whether a string is a syntactically valid Jabber ID (JID),
* either with or without a resource.
*
* Note that a bare domain can be a valid JID.
*
* @param string $jid string to check
* @param bool $check_domain whether we should validate that domain...
*
* @return boolean whether the string is a valid JID
*/
protected function validateFullJid($jid, $check_domain = false)
{
try {
$parts = $this->splitJid($jid);
if ($check_domain) {
if (!$this->checkDomain($parts['domain'])) {
return false;
}
}
return $parts['resource'] !== ''; // missing or present; empty ain't kosher
} catch (Exception $e) {
return false;
}
}
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* XMPPHP: The PHP XMPP Library * XMPPHP: The PHP XMPP Library
* Copyright (C) 2008 Nathanael C. Fritz * Copyright (C) 2008 Nathanael C. Fritz
@ -23,16 +24,23 @@
* @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 dirname(__FILE__) . "/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>
@ -40,149 +48,362 @@ require_once dirname(__FILE__) . "/XMPP.php";
* @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;
/**
* @var string
*/
protected $sid; protected $sid;
/**
* @var string
*/
protected $http_server; protected $http_server;
protected $http_buffer = Array();
/**
* @var array
*/
protected $http_buffer = array();
/**
* @var string
*/
protected $session = false; protected $session = false;
public function connect($server, $wait='1', $session=false) { /**
* @var integer
*/
protected $inactivity;
/**
* Connect
*
* @param $server
* @param $wait
* @param $session
* @throws Exception
* @throws Exception
*/
public function connect($server = null, $wait = '1', $session = false)
{
if (is_null($server)) {
// If we aren't given the server http url, try and guess it
$port_string = ($this->port AND $this->port != 80) ? ':' . $this->port : '';
$this->http_server = 'http://' . $this->host . $port_string . '/http-bind/';
} else {
$this->http_server = $server; $this->http_server = $server;
}
$this->use_encryption = false; $this->use_encryption = false;
$this->session = $session; $this->session = $session;
$this->rid = 3001; $this->rid = 3001;
$this->sid = null; $this->sid = null;
if($session) $this->inactivity = 0;
{
if ($session) {
$this->loadSession(); $this->loadSession();
} }
if(!$this->sid) {
if (!$this->sid) {
$body = $this->__buildBody(); $body = $this->__buildBody();
$body->addAttribute('hold','1'); $body->addAttribute('hold', '1');
$body->addAttribute('to', $this->host); $body->addAttribute('to', $this->server);
$body->addAttribute('route', "xmpp:{$this->host}:{$this->port}"); $body->addAttribute('route', 'xmpp:' . $this->host . ':' . $this->port);
$body->addAttribute('secure','true'); $body->addAttribute('secure', 'true');
$body->addAttribute('xmpp:version','1.6', 'urn:xmpp:xbosh'); $body->addAttribute('xmpp:version', '1.0', 'urn:xmpp:xbosh');
$body->addAttribute('wait', strval($wait)); $body->addAttribute('wait', strval($wait));
$body->addAttribute('ack','1'); $body->addAttribute('ack', '1');
$body->addAttribute('xmlns:xmpp','urn:xmpp:xbosh'); $body->addAttribute('xmlns:xmpp', 'urn:xmpp:xbosh');
$buff = "<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'>"; $buff = '<stream:stream xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams">';
xml_parse($this->parser, $buff, false); xml_parse($this->parser, $buff, false);
$response = $this->__sendBody($body); $response = $this->__sendBody($body);
$rxml = new SimpleXMLElement($response); $rxml = new SimpleXMLElement($response);
$this->sid = $rxml['sid']; $this->sid = $rxml['sid'];
$this->inactivity = $rxml['inactivity'];
} else { } else {
$buff = "<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'>"; $buff = '<stream:stream xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams">';
xml_parse($this->parser, $buff, false); xml_parse($this->parser, $buff, false);
} }
} }
public function __sendBody($body=null, $recv=true) { /**
if(!$body) { * 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(); $body = $this->__buildBody();
} }
$ch = curl_init($this->http_server);
$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_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body->asXML()); curl_setopt($ch, CURLOPT_POSTFIELDS, $body->asXML());
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 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_HTTPHEADER, $header );
curl_setopt($ch, CURLOPT_VERBOSE, 0); curl_setopt($ch, CURLOPT_VERBOSE, 0);
$output = '';
if($recv) { if ($recv) {
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch); $output = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) != '200') {
throw new Exception('Wrong response from server!');
}
$this->http_buffer[] = $output; $this->http_buffer[] = $output;
} }
curl_close($ch); curl_close($ch);
return $output; return $output;
} }
public function __buildBody($sub=null) { /**
$xml = new SimpleXMLElement("<body xmlns='http://jabber.org/protocol/httpbind' xmlns:xmpp='urn:xmpp:xbosh' />"); * Process
$xml->addAttribute('content', 'text/xml; charset=utf-8'); *
$xml->addAttribute('rid', $this->rid); * @param $null1
$this->rid += 1; * @param $null2
if($this->sid) $xml->addAttribute('sid', $this->sid); *
#if($this->sid) $xml->addAttribute('xmlns', 'http://jabber.org/protocol/httpbind'); * null params are not used and just to statify Strict Function Declaration
$xml->addAttribute('xml:lang', 'en'); * @return bool
if($sub) { // ok, so simplexml is lame * @throws Exception
$p = dom_import_simplexml($xml); * @throws Exception
$c = dom_import_simplexml($sub); */
$cn = $p->ownerDocument->importNode($c, true); public function __process($null1 = null, $null2 = null)
$p->appendChild($cn); {
$xml = simplexml_import_dom($p);
}
return $xml;
}
public function __process() { if ($this->http_buffer) {
if($this->http_buffer) {
$this->__parseBuffer(); $this->__parseBuffer();
} else { } else {
$this->__sendBody(); $this->__sendBody();
$this->__parseBuffer(); $this->__parseBuffer();
} }
$this->saveSession();
return true;
} }
public function __parseBuffer() { public function __parseBuffer()
{
while ($this->http_buffer) { while ($this->http_buffer) {
$idx = key($this->http_buffer); $idx = key($this->http_buffer);
$buffer = $this->http_buffer[$idx]; $buffer = $this->http_buffer[$idx];
unset($this->http_buffer[$idx]); unset($this->http_buffer[$idx]);
if($buffer) {
if ($buffer) {
$xml = new SimpleXMLElement($buffer); $xml = new SimpleXMLElement($buffer);
$children = $xml->xpath('child::node()'); $children = $xml->xpath('child::node()');
foreach ($children as $child) { foreach ($children as $child) {
$buff = $child->asXML(); $buff = $child->asXML();
$this->log->log("RECV: $buff", XMPPHP_Log::LEVEL_VERBOSE); $this->log->log('RECV: ' . $buff, Log::LEVEL_VERBOSE);
xml_parse($this->parser, $buff, false); xml_parse($this->parser, $buff, false);
} }
} }
} }
} }
public function send($msg) { /**
$this->log->log("SEND: $msg", XMPPHP_Log::LEVEL_VERBOSE); * Save session
$msg = new SimpleXMLElement($msg); *
#$msg->addAttribute('xmlns', 'jabber:client'); */
$this->__sendBody($this->__buildBody($msg), true); public function saveSession()
#$this->__parseBuffer(); {
$_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);
}
} }
public function reset() { /**
* 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; $this->xml_depth = 0;
unset($this->xmlobj); unset($this->xmlobj);
$this->xmlobj = array(); $this->xmlobj = array();
$this->setupParser(); $this->setupParser();
#$this->send($this->stream_start);
$body = $this->__buildBody(); $body = $this->__buildBody();
$body->addAttribute('to', $this->host); $body->addAttribute('to', $this->host);
$body->addAttribute('xmpp:restart', 'true', 'urn:xmpp:xbosh'); $body->addAttribute('xmpp:restart', 'true', 'urn:xmpp:xbosh');
$buff = "<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'>"; $buff = '<stream:stream xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams">';
$response = $this->__sendBody($body); $response = $this->__sendBody($body);
$this->been_reset = true; $this->been_reset = true;
xml_parse($this->parser, $buff, false); xml_parse($this->parser, $buff, false);
} }
public function loadSession() { /**
if(isset($_SESSION['XMPPHP_BOSH_RID'])) $this->rid = $_SESSION['XMPPHP_BOSH_RID']; * Disconnect
if(isset($_SESSION['XMPPHP_BOSH_SID'])) $this->sid = $_SESSION['XMPPHP_BOSH_SID']; *
if(isset($_SESSION['XMPPHP_BOSH_authed'])) $this->authed = $_SESSION['XMPPHP_BOSH_authed']; * @throws Exception
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 disconnect()
} {
public function saveSession() { parent::disconnect();
$_SESSION['XMPPHP_BOSH_RID'] = (string) $this->rid;
$_SESSION['XMPPHP_BOSH_SID'] = (string) $this->sid; if ($this->session == 'ON_FILE') {
$_SESSION['XMPPHP_BOSH_authed'] = (boolean) $this->authed; unlink($this->getSessionFile());
$_SESSION['XMPPHP_BOSH_jid'] = (string) $this->jid; } else {
$_SESSION['XMPPHP_BOSH_fulljid'] = (string) $this->fulljid; $keys = array('RID', 'SID', 'authed', 'basejid', 'fulljid', 'inactivity', 'lat');
foreach ($keys as $key) {
unset($_SESSION['XMPPHP_BOSH'][$key]);
}
}
} }
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* XMPPHP: The PHP XMPP Library * XMPPHP: The PHP XMPP Library
* Copyright (C) 2008 Nathanael C. Fritz * Copyright (C) 2008 Nathanael C. Fritz
@ -23,13 +24,19 @@
* @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>
@ -37,5 +44,6 @@
* @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,4 +1,5 @@
<?php <?php
/** /**
* XMPPHP: The PHP XMPP Library * XMPPHP: The PHP XMPP Library
* Copyright (C) 2008 Nathanael C. Fritz * Copyright (C) 2008 Nathanael C. Fritz
@ -23,9 +24,14 @@
* @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
* *
@ -36,8 +42,8 @@
* @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;
@ -68,9 +74,10 @@ class XMPPHP_Log {
* Constructor * Constructor
* *
* @param boolean $printout * @param boolean $printout
* @param string $runlevel * @param int $runlevel
*/ */
public function __construct($printout = false, $runlevel = self::LEVEL_INFO) { public function __construct($printout = false, $runlevel = self::LEVEL_INFO)
{
$this->printout = (boolean)$printout; $this->printout = (boolean)$printout;
$this->runlevel = (int)$runlevel; $this->runlevel = (int)$runlevel;
} }
@ -82,14 +89,22 @@ class XMPPHP_Log {
* @param string $msg * @param string $msg
* @param integer $runlevel * @param integer $runlevel
*/ */
public function log($msg, $runlevel = self::LEVEL_INFO) { public function log($msg, $runlevel = self::LEVEL_INFO)
{
$time = time(); $time = time();
#$this->data[] = array($this->runlevel, $msg, $time); #$this->data[] = array($this->runlevel, $msg, $time);
if($this->printout and $runlevel <= $this->runlevel) { if ($this->printout and $runlevel <= $this->runlevel) {
$this->writeLine($msg, $runlevel, $time); $this->writeLine($msg, $runlevel, $time);
} }
} }
protected function writeLine($msg, $runlevel, $time)
{
//echo date('Y-m-d H:i:s', $time)." [".$this->names[$runlevel]."]: ".$msg."\n";
echo $time . " [" . $this->names[$runlevel] . "]: " . $msg . "\n";
flush();
}
/** /**
* Output the complete log. * Output the complete log.
* Log will be cleared if $clear = true * Log will be cleared if $clear = true
@ -97,23 +112,18 @@ class XMPPHP_Log {
* @param boolean $clear * @param boolean $clear
* @param integer $runlevel * @param integer $runlevel
*/ */
public function printout($clear = true, $runlevel = null) { public function printout($clear = true, $runlevel = null)
if($runlevel === null) { {
if ($runlevel === null) {
$runlevel = $this->runlevel; $runlevel = $this->runlevel;
} }
foreach($this->data as $data) { foreach ($this->data as $data) {
if($runlevel <= $data[0]) { if ($runlevel <= $data[0]) {
$this->writeLine($data[1], $runlevel, $data[2]); $this->writeLine($data[1], $runlevel, $data[2]);
} }
} }
if($clear) { if ($clear) {
$this->data = array(); $this->data = array();
} }
} }
protected function writeLine($msg, $runlevel, $time) {
//echo date('Y-m-d H:i:s', $time)." [".$this->names[$runlevel]."]: ".$msg."\n";
echo $time." [".$this->names[$runlevel]."]: ".$msg."\n";
flush();
}
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* XMPPHP: The PHP XMPP Library * XMPPHP: The PHP XMPP Library
* Copyright (C) 2008 Nathanael C. Fritz * Copyright (C) 2008 Nathanael C. Fritz
@ -23,13 +24,17 @@
* @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>
@ -37,21 +42,23 @@
* @copyright 2008 Nathanael C. Fritz * @copyright 2008 Nathanael C. Fritz
* @version $Id$ * @version $Id$
*/ */
class Roster
class Roster { {
/** /**
* Roster array, handles contacts and presence. Indexed by jid. * Roster array, handles contacts and presence. Indexed by jid.
* Contains array with potentially two indexes 'contact' and 'presence' * Contains array with potentially two indexes 'contact' and 'presence'
* @var array * @var array
*/ */
protected $roster_array = array(); protected $roster_array = array();
/** /**
* Constructor * Constructor
* * @param array $roster_array
*/ */
public function __construct($roster_array = array()) { public function __construct($roster_array = array())
{
if ($this->verifyRoster($roster_array)) { if ($this->verifyRoster($roster_array)) {
$this->roster_array = $roster_array; //Allow for prepopulation with existing roster $this->roster_array = $roster_array; //Allow for pre-population with existing roster
} else { } else {
$this->roster_array = array(); $this->roster_array = array();
} }
@ -62,28 +69,12 @@ class Roster {
* 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) { protected function verifyRoster($roster_array)
{
#TODO once we know *what* a valid roster array looks like #TODO once we know *what* a valid roster array looks like
return True; return true;
}
/**
*
* Add given contact to roster
*
* @param string $jid
* @param string $subscription
* @param string $name
* @param array $groups
*/
public function addContact($jid, $subscription, $name='', $groups=array()) {
$contact = array('jid' => $jid, 'subscription' => $subscription, 'name' => $name, 'groups' => $groups);
if ($this->isContact($jid)) {
$this->roster_array[$jid]['contact'] = $contact;
} else {
$this->roster_array[$jid] = array('contact' => $contact);
}
} }
/** /**
@ -91,8 +82,10 @@ class Roster {
* Retrieve contact via jid * Retrieve contact via jid
* *
* @param string $jid * @param string $jid
* @return mixed
*/ */
public function getContact($jid) { public function getContact($jid)
{
if ($this->isContact($jid)) { if ($this->isContact($jid)) {
return $this->roster_array[$jid]['contact']; return $this->roster_array[$jid]['contact'];
} }
@ -103,8 +96,10 @@ class Roster {
* Discover if a contact exists in the roster via jid * Discover if a contact exists in the roster via jid
* *
* @param string $jid * @param string $jid
* @return bool
*/ */
public function isContact($jid) { public function isContact($jid)
{
return (array_key_exists($jid, $this->roster_array)); return (array_key_exists($jid, $this->roster_array));
} }
@ -117,10 +112,11 @@ class Roster {
* @param string $show * @param string $show
* @param string $status * @param string $status
*/ */
public function setPresence($presence, $priority, $show, $status) { public function setPresence($presence, $priority, $show, $status)
$parts = explode('/', $presence); {
$jid = $parts[0]; $presence = explode('/', $presence, 2);
$resource = isset($parts[1]) ? $parts[1] : ''; // apparently we can do '' as an associative array index $jid = $presence[0];
$resource = isset($presence[1]) ? $presence[1] : '';
if ($show != 'unavailable') { if ($show != 'unavailable') {
if (!$this->isContact($jid)) { if (!$this->isContact($jid)) {
$this->addContact($jid, 'not-in-roster'); $this->addContact($jid, 'not-in-roster');
@ -128,6 +124,26 @@ class Roster {
$this->roster_array[$jid]['presence'][$resource] = array('priority' => $priority, 'show' => $show, 'status' => $status); $this->roster_array[$jid]['presence'][$resource] = array('priority' => $priority, 'show' => $show, 'status' => $status);
} else { //Nuke unavailable resources to save memory } else { //Nuke unavailable resources to save memory
unset($this->roster_array[$jid]['resource'][$resource]); unset($this->roster_array[$jid]['resource'][$resource]);
unset($this->roster_array[$jid]['presence'][$resource]);
}
}
/**
*
* Add given contact to roster
*
* @param string $jid
* @param string $subscription
* @param string $name
* @param array $groups
*/
public function addContact($jid, $subscription, $name = '', $groups = array())
{
$contact = array('jid' => $jid, 'subscription' => $subscription, 'name' => $name, 'groups' => $groups);
if ($this->isContact($jid)) {
$this->roster_array[$jid]['contact'] = $contact;
} else {
$this->roster_array[$jid] = array('contact' => $contact);
} }
} }
@ -137,12 +153,14 @@ class Roster {
* *
* @param string $jid * @param string $jid
*/ */
public function getPresence($jid) {
$split = explode("/", $jid); public function getPresence($jid)
{
$split = explode('/', $jid, 2);
$jid = $split[0]; $jid = $split[0];
if($this->isContact($jid)) { if ($this->isContact($jid)) {
$current = array('resource' => '', 'active' => '', 'priority' => -129, 'show' => '', 'status' => ''); //Priorities can only be -128 = 127 $current = array('resource' => '', 'active' => '', 'priority' => -129, 'show' => '', 'status' => ''); //Priorities can only be -128 = 127
foreach($this->roster_array[$jid]['presence'] as $resource => $presence) { foreach ($this->roster_array[$jid]['presence'] as $resource => $presence) {
//Highest available priority or just highest priority //Highest available priority or just highest priority
if ($presence['priority'] > $current['priority'] and (($presence['show'] == "chat" or $presence['show'] == "available") or ($current['show'] != "chat" or $current['show'] != "available"))) { if ($presence['priority'] > $current['priority'] and (($presence['show'] == "chat" or $presence['show'] == "available") or ($current['show'] != "chat" or $current['show'] != "available"))) {
$current = $presence; $current = $presence;
@ -152,13 +170,14 @@ class Roster {
return $current; return $current;
} }
} }
/** /**
* *
* Get roster * Get roster
* *
*/ */
public function getRoster() { public function getRoster()
{
return $this->roster_array; return $this->roster_array;
} }
} }
?>

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* XMPPHP: The PHP XMPP Library * XMPPHP: The PHP XMPP Library
* Copyright (C) 2008 Nathanael C. Fritz * Copyright (C) 2008 Nathanael C. Fritz
@ -23,13 +24,17 @@
* @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>
@ -37,7 +42,8 @@
* @copyright 2008 Nathanael C. Fritz * @copyright 2008 Nathanael C. Fritz
* @version $Id$ * @version $Id$
*/ */
class XMPPHP_XMLObj { class XMLObj
{
/** /**
* Tag name * Tag name
* *
@ -81,11 +87,12 @@ class XMPPHP_XMLObj {
* @param array $attrs * @param array $attrs
* @param string $data * @param string $data
*/ */
public function __construct($name, $ns = '', $attrs = array(), $data = '') { public function __construct($name, $ns = '', $attrs = array(), $data = '')
{
$this->name = strtolower($name); $this->name = strtolower($name);
$this->ns = $ns; $this->ns = $ns;
if(is_array($attrs) && count($attrs)) { if (is_array($attrs) && count($attrs)) {
foreach($attrs as $key => $value) { foreach ($attrs as $key => $value) {
$this->attrs[strtolower($key)] = $value; $this->attrs[strtolower($key)] = $value;
} }
} }
@ -97,10 +104,11 @@ class XMPPHP_XMLObj {
* *
* @param integer $depth * @param integer $depth
*/ */
public function printObj($depth = 0) { public function printObj($depth = 0)
{
print str_repeat("\t", $depth) . $this->name . " " . $this->ns . ' ' . $this->data; print str_repeat("\t", $depth) . $this->name . " " . $this->ns . ' ' . $this->data;
print "\n"; print "\n";
foreach($this->subs as $sub) { foreach ($this->subs as $sub) {
$sub->printObj($depth + 1); $sub->printObj($depth + 1);
} }
} }
@ -109,17 +117,19 @@ class XMPPHP_XMLObj {
* Return this XML Object in xml notation * Return this XML Object in xml notation
* *
* @param string $str * @param string $str
* @return string
*/ */
public function toString($str = '') { public function toString($str = '')
{
$str .= "<{$this->name} xmlns='{$this->ns}' "; $str .= "<{$this->name} xmlns='{$this->ns}' ";
foreach($this->attrs as $key => $value) { foreach ($this->attrs as $key => $value) {
if($key != 'xmlns') { if ($key != 'xmlns') {
$value = htmlspecialchars($value); $value = htmlspecialchars($value);
$str .= "$key='$value' "; $str .= "$key='$value' ";
} }
} }
$str .= ">"; $str .= ">";
foreach($this->subs as $sub) { foreach ($this->subs as $sub) {
$str .= $sub->toString(); $str .= $sub->toString();
} }
$body = htmlspecialchars($this->data); $body = htmlspecialchars($this->data);
@ -131,11 +141,15 @@ class XMPPHP_XMLObj {
* Has this XML Object the given sub? * Has this XML Object the given sub?
* *
* @param string $name * @param string $name
* @param null $ns
* @return boolean * @return boolean
*/ */
public function hasSub($name, $ns = null) { 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; foreach ($this->subs as $sub) {
if (($name == "*" or $sub->name == $name) and ($ns == null or $sub->ns == $ns)) {
return true;
}
} }
return false; return false;
} }
@ -146,11 +160,13 @@ class XMPPHP_XMLObj {
* @param string $name * @param string $name
* @param string $attrs * @param string $attrs
* @param string $ns * @param string $ns
* @return mixed
*/ */
public function sub($name, $attrs = null, $ns = null) { public function sub($name, $attrs = null, $ns = null)
{
#TODO attrs is ignored #TODO attrs is ignored
foreach($this->subs as $sub) { foreach ($this->subs as $sub) {
if($sub->name == $name and ($ns == null or $sub->ns == $ns)) { if ($sub->name == $name and ($ns == null or $sub->ns == $ns)) {
return $sub; return $sub;
} }
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* XMPPHP: The PHP XMPP Library * XMPPHP: The PHP XMPP Library
* Copyright (C) 2008 Nathanael C. Fritz * Copyright (C) 2008 Nathanael C. Fritz
@ -23,22 +24,27 @@
* @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
*/ */
/** XMPPHP_Exception */ namespace XMPPHP;
/** Exception */
require_once __DIR__ . DIRECTORY_SEPARATOR . 'Exception.php'; require_once __DIR__ . DIRECTORY_SEPARATOR . 'Exception.php';
/** XMPPHP_XMLObj */ /** XMLObj */
require_once __DIR__ . DIRECTORY_SEPARATOR . 'XMLObj.php'; require_once __DIR__ . DIRECTORY_SEPARATOR . 'XMLObj.php';
/** XMPPHP_Log */ /** Log */
require_once __DIR__ . DIRECTORY_SEPARATOR . 'Log.php'; require_once __DIR__ . DIRECTORY_SEPARATOR . 'Log.php';
/** /**
* XMPPHP XML Stream * XMPPHP XMLStream
* *
* @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>
@ -46,7 +52,8 @@ require_once __DIR__ . DIRECTORY_SEPARATOR . 'Log.php';
* @copyright 2008 Nathanael C. Fritz * @copyright 2008 Nathanael C. Fritz
* @version $Id$ * @version $Id$
*/ */
class XMPPHP_XMLStream { class XMLStream
{
/** /**
* @var resource * @var resource
*/ */
@ -140,7 +147,7 @@ class XMPPHP_XMLStream {
*/ */
protected $until_payload = array(); protected $until_payload = array();
/** /**
* @var XMPPHP_Log * @var Log
*/ */
protected $log; protected $log;
/** /**
@ -177,179 +184,47 @@ class XMPPHP_XMLStream {
* @param string $loglevel * @param string $loglevel
* @param boolean $is_server * @param boolean $is_server
*/ */
public function __construct($host = null, $port = null, $printlog = false, $loglevel = null, $is_server = false) { public function __construct($host = null, $port = null, $printlog = false, $loglevel = null, $is_server = false)
{
$this->reconnect = !$is_server; $this->reconnect = !$is_server;
$this->is_server = $is_server; $this->is_server = $is_server;
$this->host = $host; $this->host = $host;
$this->port = $port; $this->port = $port;
$this->setupParser(); $this->setupParser();
$this->log = new XMPPHP_Log($printlog, $loglevel); $this->log = new Log($printlog, $loglevel);
}
/**
* Setup the XML parser
*/
public function setupParser()
{
$this->parser = xml_parser_create('UTF-8');
xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);
xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
xml_set_object($this->parser, $this);
xml_set_element_handler($this->parser, 'startXML', 'endXML');
xml_set_character_data_handler($this->parser, 'charXML');
} }
/** /**
* Destructor * Destructor
* Cleanup connection * Cleanup connection
*/ */
public function __destruct() { public function __destruct()
if(!$this->disconnected && $this->socket) { {
if (!$this->disconnected && $this->socket) {
$this->disconnect(); $this->disconnect();
} }
} }
/**
* Return the log instance
*
* @return XMPPHP_Log
*/
public function getLog() {
return $this->log;
}
/**
* Get next ID
*
* @return integer
*/
public function getId() {
$this->lastid++;
return $this->lastid;
}
/**
* Set SSL
*
* @return integer
*/
public function useSSL($use=true) {
$this->use_ssl = $use;
}
/**
* Add ID Handler
*
* @param integer $id
* @param string $pointer
* @param string $obj
*/
public function addIdHandler($id, $pointer, $obj = null) {
$this->idhandlers[$id] = array($pointer, $obj);
}
/**
* Add Handler
*
* @param string $name
* @param string $ns
* @param string $pointer
* @param string $obj
* @param integer $depth
*/
public function addHandler($name, $ns, $pointer, $obj = null, $depth = 1) {
#TODO deprication warning
$this->nshandlers[] = array($name,$ns,$pointer,$obj, $depth);
}
/**
* Add XPath Handler
*
* @param string $xpath
* @param string $pointer
* @param
*/
public function addXPathHandler($xpath, $pointer, $obj = null) {
if (preg_match_all("/\(?{[^\}]+}\)?(\/?)[^\/]+/", $xpath, $regs)) {
$ns_tags = $regs[0];
} else {
$ns_tags = array($xpath);
}
foreach($ns_tags as $ns_tag) {
list($l, $r) = explode("}", $ns_tag);
if ($r != null) {
$xpart = array(substr($l, 1), $r);
} else {
$xpart = array(null, $l);
}
$xpath_array[] = $xpart;
}
$this->xpathhandlers[] = array($xpath_array, $pointer, $obj);
}
/**
* Add Event Handler
*
* @param integer $id
* @param string $pointer
* @param string $obj
*/
public function addEventHandler($name, $pointer, $obj) {
$this->eventhandlers[] = array($name, $pointer, $obj);
}
/**
* Connect to XMPP Host
*
* @param integer $timeout
* @param boolean $persistent
* @param boolean $sendinit
*/
public function connect($timeout = 30, $persistent = false, $sendinit = true) {
$this->sent_disconnect = false;
$starttime = time();
do {
$this->disconnected = false;
$this->sent_disconnect = false;
if($persistent) {
$conflag = STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT;
} else {
$conflag = STREAM_CLIENT_CONNECT;
}
$conntype = 'tcp';
if($this->use_ssl) $conntype = 'ssl';
$this->log->log("Connecting to $conntype://{$this->host}:{$this->port}");
try {
$this->socket = @stream_socket_client("$conntype://{$this->host}:{$this->port}", $errno, $errstr, $timeout, $conflag);
} catch (Exception $e) {
throw new XMPPHP_Exception($e->getMessage());
}
if(!$this->socket) {
$this->log->log("Could not connect.", XMPPHP_Log::LEVEL_ERROR);
$this->disconnected = true;
# Take it easy for a few seconds
sleep(min($timeout, 5));
}
} while (!$this->socket && (time() - $starttime) < $timeout);
if ($this->socket) {
stream_set_blocking($this->socket, 1);
if($sendinit) $this->send($this->stream_start);
} else {
throw new XMPPHP_Exception("Could not connect before timeout.");
}
}
/**
* Reconnect XMPP Host
*/
public function doReconnect() {
if(!$this->is_server) {
$this->log->log("Reconnecting ($this->reconnectTimeout)...", XMPPHP_Log::LEVEL_WARNING);
$this->connect($this->reconnectTimeout, false, false);
$this->reset();
$this->event('reconnect');
}
}
public function setReconnectTimeout($timeout) {
$this->reconnectTimeout = $timeout;
}
/** /**
* Disconnect from XMPP Host * Disconnect from XMPP Host
*/ */
public function disconnect() { public function disconnect()
$this->log->log("Disconnecting...", XMPPHP_Log::LEVEL_VERBOSE); {
if(false == (bool) $this->socket) { $this->log->log("Disconnecting...", Log::LEVEL_VERBOSE);
if (false == (bool)$this->socket) {
return; return;
} }
$this->reconnect = false; $this->reconnect = false;
@ -360,12 +235,188 @@ class XMPPHP_XMLStream {
} }
/** /**
* Are we are disconnected? * Send to socket
* *
* @return boolean * @param string $msg
* @param null $timeout
* @return bool|int
* @throws Exception
*/ */
public function isDisconnected() { public function send($msg, $timeout = NULL)
return $this->disconnected; {
if (is_null($timeout)) {
$secs = NULL;
$usecs = NULL;
} else if ($timeout == 0) {
$secs = 0;
$usecs = 0;
} else {
$maximum = $timeout * 1000000;
$usecs = $maximum % 1000000;
$secs = floor(($maximum - $usecs) / 1000000);
}
$read = array();
$write = array($this->socket);
$except = array();
$select = @stream_select($read, $write, $except, $secs, $usecs);
if ($select === False) {
$this->log->log("ERROR sending message; reconnecting.");
$this->doReconnect();
# TODO: retry send here
return false;
} elseif ($select > 0) {
$this->log->log("Socket is ready; send it.", Log::LEVEL_VERBOSE);
} else {
$this->log->log("Socket is not ready; break.", Log::LEVEL_ERROR);
return false;
}
$sentbytes = @fwrite($this->socket, $msg);
$this->log->log("SENT: " . mb_substr($msg, 0, $sentbytes, '8bit'), Log::LEVEL_VERBOSE);
if ($sentbytes === FALSE) {
$this->log->log("ERROR sending message; reconnecting.", Log::LEVEL_ERROR);
$this->doReconnect();
return false;
}
$this->log->log("Successfully sent $sentbytes bytes.", Log::LEVEL_VERBOSE);
return $sentbytes;
}
/**
* Reconnect XMPP Host
* @throws Exception
*/
public function doReconnect()
{
if (!$this->is_server) {
$this->log->log("Reconnecting ($this->reconnectTimeout)...", Log::LEVEL_WARNING);
$this->connect($this->reconnectTimeout, false, false);
$this->reset();
$this->event('reconnect');
}
}
/**
* Connect to XMPP Host
*
* @param integer $timeout
* @param boolean $persistent
* @param boolean $sendinit
* @throws Exception
* @throws Exception
*/
public function connect($timeout = 30, $persistent = false, $sendinit = true)
{
$this->sent_disconnect = false;
$starttime = time();
do {
$this->disconnected = false;
$this->sent_disconnect = false;
if ($persistent) {
$conflag = STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT;
} else {
$conflag = STREAM_CLIENT_CONNECT;
}
$conntype = 'tcp';
if ($this->use_ssl) $conntype = 'ssl';
$this->log->log("Connecting to $conntype://{$this->host}:{$this->port}");
$this->socket = @stream_socket_client("$conntype://{$this->host}:{$this->port}", $errno, $errstr, $timeout, $conflag);
if (!$this->socket) {
$this->log->log("Could not connect.", Log::LEVEL_ERROR);
$this->disconnected = true;
# Take it easy for a few seconds
sleep(min($timeout, 5));
}
} while (!$this->socket && (time() - $starttime) < $timeout);
if ($this->socket) {
stream_set_blocking($this->socket, 1);
if ($sendinit) $this->send($this->stream_start);
} else {
throw new Exception("Could not connect before timeout.");
}
}
/**
* Reset connection
*/
public function reset()
{
$this->xml_depth = 0;
unset($this->xmlobj);
$this->xmlobj = array();
$this->setupParser();
if (!$this->is_server) {
$this->send($this->stream_start);
}
$this->been_reset = true;
}
/**
* Event?
*
* @param string $name
* @param string $payload
*/
public function event($name, $payload = null)
{
$this->log->log("EVENT: $name", Log::LEVEL_DEBUG);
foreach ($this->eventhandlers as $handler) {
if ($name == $handler[0]) {
if ($handler[2] === null) {
$handler[2] = $this;
}
$handler[2]->{$handler[1]}($payload);
}
}
foreach ($this->until as $key => $until) {
if (is_array($until)) {
if (in_array($name, $until)) {
$this->until_payload[$key][] = array($name, $payload);
if (!isset($this->until_count[$key])) {
$this->until_count[$key] = 0;
}
$this->until_count[$key] += 1;
#$this->until[$key] = false;
}
}
}
}
/**
* Process until a specified event or a timeout occurs
*
* @param string|array $event
* @param integer $timeout
* @return string
* @throws Exception
*/
public function processUntil($event, $timeout = -1)
{
$start = time();
if (!is_array($event)) $event = array($event);
$this->until[] = $event;
end($this->until);
$event_key = key($this->until);
reset($this->until);
$this->until_count[$event_key] = 0;
while (!$this->disconnected and $this->until_count[$event_key] < 1 and (time() - $start < $timeout or $timeout == -1)) {
$this->__process();
}
if (array_key_exists($event_key, $this->until_payload)) {
$payload = $this->until_payload[$event_key];
unset($this->until_payload[$event_key]);
unset($this->until_count[$event_key]);
unset($this->until[$event_key]);
} else {
$payload = array();
}
return $payload;
} }
/** /**
@ -373,9 +424,13 @@ class XMPPHP_XMLStream {
* 0 -> only read if data is immediately ready * 0 -> only read if data is immediately ready
* NULL -> wait forever and ever * NULL -> wait forever and ever
* integer -> process for this amount of time * integer -> process for this amount of time
* @param int $maximum
* @return bool
* @throws Exception
*/ */
private function __process($maximum=5) { private function __process($maximum = 5)
{
$remaining = $maximum; $remaining = $maximum;
@ -396,7 +451,7 @@ class XMPPHP_XMLStream {
} }
$updated = @stream_select($read, $write, $except, $secs, $usecs); $updated = @stream_select($read, $write, $except, $secs, $usecs);
if ($updated === false) { if ($updated === false) {
$this->log->log("Error on stream_select()", XMPPHP_Log::LEVEL_VERBOSE); $this->log->log("Error on stream_select()", Log::LEVEL_VERBOSE);
if ($this->reconnect) { if ($this->reconnect) {
$this->doReconnect(); $this->doReconnect();
} else { } else {
@ -407,8 +462,8 @@ class XMPPHP_XMLStream {
} else if ($updated > 0) { } else if ($updated > 0) {
# XXX: Is this big enough? # XXX: Is this big enough?
$buff = @fread($this->socket, 4096); $buff = @fread($this->socket, 4096);
if(!$buff) { if (!$buff) {
if($this->reconnect) { if ($this->reconnect) {
$this->doReconnect(); $this->doReconnect();
} else { } else {
fclose($this->socket); fclose($this->socket);
@ -416,24 +471,134 @@ class XMPPHP_XMLStream {
return false; return false;
} }
} }
$this->log->log("RECV: $buff", XMPPHP_Log::LEVEL_VERBOSE); $this->log->log("RECV: $buff", Log::LEVEL_VERBOSE);
xml_parse($this->parser, $buff, false); xml_parse($this->parser, $buff, false);
} else { } // Otherwise,
# $updated == 0 means no changes during timeout. // $updated == 0 means no changes during timeout.
}
$endtime = (microtime(true)*1000000); $endtime = (microtime(true) * 1000000);
$time_past = $endtime - $starttime; $time_past = $endtime - $starttime;
$remaining = $remaining - $time_past; $remaining = $remaining - $time_past;
} while (is_null($maximum) || $remaining > 0); } while (is_null($maximum) || $remaining > 0);
return true; return true;
} }
/**
* Return the log instance
*
* @return Log
*/
public function getLog()
{
return $this->log;
}
/**
* Get next ID
*
* @return integer
*/
public function getId()
{
$this->lastid++;
return $this->lastid;
}
/**
* Set SSL
* @param bool $use
*/
public function useSSL($use = true)
{
$this->use_ssl = $use;
}
/**
* Add ID Handler
*
* @param integer $id
* @param string $pointer
* @param string $obj
*/
public function addIdHandler($id, $pointer, $obj = null)
{
$this->idhandlers[$id] = array($pointer, $obj);
}
/**
* Add Handler
*
* @param string $name
* @param string $ns
* @param string $pointer
* @param string $obj
* @param integer $depth
*/
public function addHandler($name, $ns, $pointer, $obj = null, $depth = 1)
{
#TODO deprication warning
$this->nshandlers[] = array($name, $ns, $pointer, $obj, $depth);
}
/**
* Add XPath Handler
*
* @param string $xpath
* @param string $pointer
* @param
*/
public function addXPathHandler($xpath, $pointer, $obj = null)
{
if (preg_match_all("/\(?{[^\}]+}\)?(\/?)[^\/]+/", $xpath, $regs)) {
$ns_tags = $regs[0];
} else {
$ns_tags = array($xpath);
}
foreach ($ns_tags as $ns_tag) {
list($l, $r) = explode("}", $ns_tag);
if ($r != null) {
$xpart = array(substr($l, 1), $r);
} else {
$xpart = array(null, $l);
}
$xpath_array[] = $xpart;
}
$this->xpathhandlers[] = array($xpath_array, $pointer, $obj);
}
/**
* Add Event Handler
*
* @param $name
* @param string $pointer
* @param string $obj
*/
public function addEventHandler($name, $pointer, $obj)
{
$this->eventhandlers[] = array($name, $pointer, $obj);
}
public function setReconnectTimeout($timeout)
{
$this->reconnectTimeout = $timeout;
}
/**
* Are we are disconnected?
*
* @return boolean
*/
public function isDisconnected()
{
return $this->disconnected;
}
/** /**
* Process * Process
* *
* @return string
*/ */
public function process() { public function process()
{
$this->__process(NULL); $this->__process(NULL);
} }
@ -442,8 +607,10 @@ class XMPPHP_XMLStream {
* *
* @param integer $timeout * @param integer $timeout
* @return string * @return string
* @throws Exception
*/ */
public function processTime($timeout=NULL) { public function processTime($timeout = NULL)
{
if (is_null($timeout)) { if (is_null($timeout)) {
return $this->__process(NULL); return $this->__process(NULL);
} else { } else {
@ -451,79 +618,51 @@ class XMPPHP_XMLStream {
} }
} }
/**
* Process until a specified event or a timeout occurs
*
* @param string|array $event
* @param integer $timeout
* @return string
*/
public function processUntil($event, $timeout=-1) {
$start = time();
if(!is_array($event)) $event = array($event);
$this->until[] = $event;
end($this->until);
$event_key = key($this->until);
reset($this->until);
$this->until_count[$event_key] = 0;
$updated = '';
while(!$this->disconnected and $this->until_count[$event_key] < 1 and (time() - $start < $timeout or $timeout == -1)) {
$this->__process();
}
if(array_key_exists($event_key, $this->until_payload)) {
$payload = $this->until_payload[$event_key];
unset($this->until_payload[$event_key]);
unset($this->until_count[$event_key]);
unset($this->until[$event_key]);
} else {
$payload = array();
}
return $payload;
}
/** /**
* Obsolete? * Obsolete?
* @param $socket
*/ */
public function Xapply_socket($socket) { public function Xapply_socket($socket)
{
$this->socket = $socket; $this->socket = $socket;
} }
/** /**
* XML start callback * XML start callback
* *
* @see xml_set_element_handler
*
* @param resource $parser * @param resource $parser
* @param string $name * @param string $name
* @param $attr
* @see xml_set_element_handler
*/ */
public function startXML($parser, $name, $attr) { public function startXML($parser, $name, $attr)
if($this->been_reset) { {
if ($this->been_reset) {
$this->been_reset = false; $this->been_reset = false;
$this->xml_depth = 0; $this->xml_depth = 0;
} }
$this->xml_depth++; $this->xml_depth++;
if(array_key_exists('XMLNS', $attr)) { if (array_key_exists('XMLNS', $attr)) {
$this->current_ns[$this->xml_depth] = $attr['XMLNS']; $this->current_ns[$this->xml_depth] = $attr['XMLNS'];
} else { } else {
$this->current_ns[$this->xml_depth] = $this->current_ns[$this->xml_depth - 1]; $this->current_ns[$this->xml_depth] = $this->current_ns[$this->xml_depth - 1];
if(!$this->current_ns[$this->xml_depth]) $this->current_ns[$this->xml_depth] = $this->default_ns; if (!$this->current_ns[$this->xml_depth]) $this->current_ns[$this->xml_depth] = $this->default_ns;
} }
$ns = $this->current_ns[$this->xml_depth]; $ns = $this->current_ns[$this->xml_depth];
foreach($attr as $key => $value) { foreach ($attr as $key => $value) {
if(strstr($key, ":")) { if (strstr($key, ":")) {
$key = explode(':', $key); $key = explode(':', $key);
$key = $key[1]; $key = $key[1];
$this->ns_map[$key] = $value; $this->ns_map[$key] = $value;
} }
} }
if(!strstr($name, ":") === false) if (!strstr($name, ":") === false) {
{
$name = explode(':', $name); $name = explode(':', $name);
$ns = $this->ns_map[$name[0]]; $ns = $this->ns_map[$name[0]];
$name = $name[1]; $name = $name[1];
} }
$obj = new XMPPHP_XMLObj($name, $ns, $attr); $obj = new XMLObj($name, $ns, $attr);
if($this->xml_depth > 1) { if ($this->xml_depth > 1) {
$this->xmlobj[$this->xml_depth - 1]->subs[] = $obj; $this->xmlobj[$this->xml_depth - 1]->subs[] = $obj;
} }
$this->xmlobj[$this->xml_depth] = $obj; $this->xmlobj[$this->xml_depth] = $obj;
@ -532,81 +671,83 @@ class XMPPHP_XMLStream {
/** /**
* XML end callback * XML end callback
* *
* @see xml_set_element_handler
*
* @param resource $parser * @param resource $parser
* @param string $name * @param string $name
* @throws Exception
* @see xml_set_element_handler
*
*/ */
public function endXML($parser, $name) { public function endXML($parser, $name)
#$this->log->log("Ending $name", XMPPHP_Log::LEVEL_DEBUG); {
#$this->log->log("Ending $name", Log::LEVEL_DEBUG);
#print "$name\n"; #print "$name\n";
if($this->been_reset) { if ($this->been_reset) {
$this->been_reset = false; $this->been_reset = false;
$this->xml_depth = 0; $this->xml_depth = 0;
} }
$this->xml_depth--; $this->xml_depth--;
if($this->xml_depth == 1) { if ($this->xml_depth == 1) {
#clean-up old objects #clean-up old objects
#$found = false; #FIXME This didn't appear to be in use --Gar #$found = false; #FIXME This didn't appear to be in use --Gar
foreach($this->xpathhandlers as $handler) { foreach ($this->xpathhandlers as $handler) {
if (is_array($this->xmlobj) && array_key_exists(2, $this->xmlobj)) { if (is_array($this->xmlobj) && array_key_exists(2, $this->xmlobj)) {
$searchxml = $this->xmlobj[2]; $searchxml = $this->xmlobj[2];
$nstag = array_shift($handler[0]); $nstag = array_shift($handler[0]);
if (($nstag[0] == null or $searchxml->ns == $nstag[0]) and ($nstag[1] == "*" or $nstag[1] == $searchxml->name)) { if (($nstag[0] == null or $searchxml->ns == $nstag[0]) and ($nstag[1] == "*" or $nstag[1] == $searchxml->name)) {
foreach($handler[0] as $nstag) { foreach ($handler[0] as $nstag) {
if ($searchxml !== null and $searchxml->hasSub($nstag[1], $ns=$nstag[0])) { if ($searchxml !== null and $searchxml->hasSub($nstag[1], $ns = $nstag[0])) {
$searchxml = $searchxml->sub($nstag[1], $ns=$nstag[0]); $searchxml = $searchxml->sub($nstag[1], $ns = $nstag[0]);
} else { } else {
$searchxml = null; $searchxml = null;
break; break;
} }
} }
if ($searchxml !== null) { if ($searchxml !== null) {
if($handler[2] === null) $handler[2] = $this; if ($handler[2] === null) $handler[2] = $this;
$this->log->log("Calling {$handler[1]}", XMPPHP_Log::LEVEL_DEBUG); $this->log->log("Calling {$handler[1]}", Log::LEVEL_DEBUG);
$handler[2]->{$handler[1]}($this->xmlobj[2]); $handler[2]->{$handler[1]}($this->xmlobj[2]);
} }
} }
} }
} }
foreach($this->nshandlers as $handler) { foreach ($this->nshandlers as $handler) {
if($handler[4] != 1 and array_key_exists(2, $this->xmlobj) and $this->xmlobj[2]->hasSub($handler[0])) { if ($handler[4] != 1 and array_key_exists(2, $this->xmlobj) and $this->xmlobj[2]->hasSub($handler[0])) {
$searchxml = $this->xmlobj[2]->sub($handler[0]); $searchxml = $this->xmlobj[2]->sub($handler[0]);
} elseif(is_array($this->xmlobj) and array_key_exists(2, $this->xmlobj)) { } elseif (is_array($this->xmlobj) and array_key_exists(2, $this->xmlobj)) {
$searchxml = $this->xmlobj[2]; $searchxml = $this->xmlobj[2];
} }
if($searchxml !== null and $searchxml->name == $handler[0] and ($searchxml->ns == $handler[1] or (!$handler[1] and $searchxml->ns == $this->default_ns))) { if ($searchxml !== null and $searchxml->name == $handler[0] and ($searchxml->ns == $handler[1] or (!$handler[1] and $searchxml->ns == $this->default_ns))) {
if($handler[3] === null) $handler[3] = $this; if ($handler[3] === null) $handler[3] = $this;
$this->log->log("Calling {$handler[2]}", XMPPHP_Log::LEVEL_DEBUG); $this->log->log("Calling {$handler[2]}", Log::LEVEL_DEBUG);
$handler[3]->{$handler[2]}($this->xmlobj[2]); $handler[3]->{$handler[2]}($this->xmlobj[2]);
} }
} }
foreach($this->idhandlers as $id => $handler) { foreach ($this->idhandlers as $id => $handler) {
if(array_key_exists('id', $this->xmlobj[2]->attrs) and $this->xmlobj[2]->attrs['id'] == $id) { if (array_key_exists('id', $this->xmlobj[2]->attrs) and $this->xmlobj[2]->attrs['id'] == $id) {
if($handler[1] === null) $handler[1] = $this; if ($handler[1] === null) $handler[1] = $this;
$handler[1]->{$handler[0]}($this->xmlobj[2]); $handler[1]->{$handler[0]}($this->xmlobj[2]);
#id handlers are only used once #id handlers are only used once
unset($this->idhandlers[$id]); unset($this->idhandlers[$id]);
break; break;
} }
} }
if(is_array($this->xmlobj)) { if (is_array($this->xmlobj)) {
$this->xmlobj = array_slice($this->xmlobj, 0, 1); $this->xmlobj = array_slice($this->xmlobj, 0, 1);
if(isset($this->xmlobj[0]) && $this->xmlobj[0] instanceof XMPPHP_XMLObj) { if (isset($this->xmlobj[0]) && $this->xmlobj[0] instanceof XMLObj) {
$this->xmlobj[0]->subs = null; $this->xmlobj[0]->subs = null;
} }
} }
unset($this->xmlobj[2]); unset($this->xmlobj[2]);
} }
if($this->xml_depth == 0 and !$this->been_reset) { if ($this->xml_depth == 0 and !$this->been_reset) {
if(!$this->disconnected) { if (!$this->disconnected) {
if(!$this->sent_disconnect) { if (!$this->sent_disconnect) {
$this->send($this->stream_end); $this->send($this->stream_end);
} }
$this->disconnected = true; $this->disconnected = true;
$this->sent_disconnect = true; $this->sent_disconnect = true;
fclose($this->socket); fclose($this->socket);
if($this->reconnect) { if ($this->reconnect) {
$this->doReconnect(); $this->doReconnect();
} }
} }
@ -616,144 +757,44 @@ class XMPPHP_XMLStream {
/** /**
* XML character callback * XML character callback
* @see xml_set_character_data_handler
*
* @param resource $parser * @param resource $parser
* @param string $data * @param string $data
*/ * @see xml_set_character_data_handler
public function charXML($parser, $data) {
if(array_key_exists($this->xml_depth, $this->xmlobj)) {
$this->xmlobj[$this->xml_depth]->data .= $data;
}
}
/**
* Event?
* *
* @param string $name
* @param string $payload
*/ */
public function event($name, $payload = null) { public function charXML($parser, $data)
$this->log->log("EVENT: $name", XMPPHP_Log::LEVEL_DEBUG); {
foreach($this->eventhandlers as $handler) { if (array_key_exists($this->xml_depth, $this->xmlobj)) {
if($name == $handler[0]) { $this->xmlobj[$this->xml_depth]->data .= $data;
if($handler[2] === null) {
$handler[2] = $this;
}
$handler[2]->{$handler[1]}($payload);
}
}
foreach($this->until as $key => $until) {
if(is_array($until)) {
if(in_array($name, $until)) {
$this->until_payload[$key][] = array($name, $payload);
if(!isset($this->until_count[$key])) {
$this->until_count[$key] = 0;
}
$this->until_count[$key] += 1;
#$this->until[$key] = false;
}
}
} }
} }
/** /**
* Read from socket * Read from socket
*/ */
public function read() { public function read()
{
$buff = @fread($this->socket, 1024); $buff = @fread($this->socket, 1024);
if(!$buff) { if (!$buff) {
if($this->reconnect) { if ($this->reconnect) {
$this->doReconnect(); $this->doReconnect();
} else { } else {
fclose($this->socket); fclose($this->socket);
return false; return false;
} }
} }
$this->log->log("RECV: $buff", XMPPHP_Log::LEVEL_VERBOSE); $this->log->log("RECV: $buff", Log::LEVEL_VERBOSE);
xml_parse($this->parser, $buff, false); xml_parse($this->parser, $buff, false);
} }
/** public function time()
* Send to socket {
*
* @param string $msg
*/
public function send($msg, $timeout=NULL) {
if (is_null($timeout)) {
$secs = NULL;
$usecs = NULL;
} else if ($timeout == 0) {
$secs = 0;
$usecs = 0;
} else {
$maximum = $timeout * 1000000;
$usecs = $maximum % 1000000;
$secs = floor(($maximum - $usecs) / 1000000);
}
$read = array();
$write = array($this->socket);
$except = array();
$select = @stream_select($read, $write, $except, $secs, $usecs);
if($select === False) {
$this->log->log("ERROR sending message; reconnecting.");
$this->doReconnect();
# TODO: retry send here
return false;
} elseif ($select > 0) {
$this->log->log("Socket is ready; send it.", XMPPHP_Log::LEVEL_VERBOSE);
} else {
$this->log->log("Socket is not ready; break.", XMPPHP_Log::LEVEL_ERROR);
return false;
}
$sentbytes = @fwrite($this->socket, $msg);
$this->log->log("SENT: " . mb_substr($msg, 0, $sentbytes, '8bit'), XMPPHP_Log::LEVEL_VERBOSE);
if($sentbytes === FALSE) {
$this->log->log("ERROR sending message; reconnecting.", XMPPHP_Log::LEVEL_ERROR);
$this->doReconnect();
return false;
}
$this->log->log("Successfully sent $sentbytes bytes.", XMPPHP_Log::LEVEL_VERBOSE);
return $sentbytes;
}
public function time() {
list($usec, $sec) = explode(" ", microtime()); list($usec, $sec) = explode(" ", microtime());
return (float)$sec + (float)$usec; return (float)$sec + (float)$usec;
} }
/** public function readyToProcess()
* Reset connection {
*/
public function reset() {
$this->xml_depth = 0;
unset($this->xmlobj);
$this->xmlobj = array();
$this->setupParser();
if(!$this->is_server) {
$this->send($this->stream_start);
}
$this->been_reset = true;
}
/**
* Setup the XML parser
*/
public function setupParser() {
$this->parser = xml_parser_create('UTF-8');
xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);
xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
xml_set_object($this->parser, $this);
xml_set_element_handler($this->parser, 'startXML', 'endXML');
xml_set_character_data_handler($this->parser, 'charXML');
}
public function readyToProcess() {
$read = array($this->socket); $read = array($this->socket);
$write = array(); $write = array();
$except = array(); $except = array();

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* XMPPHP: The PHP XMPP Library * XMPPHP: The PHP XMPP Library
* Copyright (C) 2008 Nathanael C. Fritz * Copyright (C) 2008 Nathanael C. Fritz
@ -23,17 +24,22 @@
* @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 dirname(__FILE__) . "/XMLStream.php"; require_once __DIR__ . DIRECTORY_SEPARATOR . 'XMLStream.php';
require_once dirname(__FILE__) . "/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>
@ -41,7 +47,8 @@ require_once dirname(__FILE__) . "/Roster.php";
* @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
*/ */
@ -51,53 +58,44 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
* @var string * @var string
*/ */
public $user; public $user;
/**
* @var boolean
*/
public $track_presence = true;
/**
* @var object
*/
public $roster;
/** /**
* @var string * @var string
*/ */
protected $password; protected $password;
/** /**
* @var string * @var string
*/ */
protected $resource; protected $resource;
/** /**
* @var string * @var string
*/ */
protected $fulljid; protected $fulljid;
/** /**
* @var string * @var string
*/ */
protected $basejid; protected $basejid;
/** /**
* @var boolean * @var boolean
*/ */
protected $authed = false; protected $authed = false;
protected $session_started = false; protected $session_started = false;
/** /**
* @var boolean * @var boolean
*/ */
protected $auto_subscribe = false; 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;
/** /**
* Constructor * Constructor
* *
@ -110,13 +108,17 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
* @param boolean $printlog * @param boolean $printlog
* @param string $loglevel * @param string $loglevel
*/ */
public function __construct($host, $port, $user, $password, $resource, $server = null, $printlog = false, $loglevel = null) { public function __construct($host, $port, $user, $password, $resource, $server = null, $printlog = false, $loglevel = null)
{
parent::__construct($host, $port, $printlog, $loglevel); parent::__construct($host, $port, $printlog, $loglevel);
$this->user = $user; $this->user = $user;
$this->password = $password; $this->password = $password;
$this->resource = $resource; $this->resource = $resource;
if(!$server) $server = $host; if (!$server) {
$server = $host;
}
$this->server = $server;
$this->basejid = $this->user . '@' . $this->host; $this->basejid = $this->user . '@' . $this->host;
$this->roster = new Roster(); $this->roster = new Roster();
@ -140,7 +142,8 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
* *
* @param boolean $useEncryption * @param boolean $useEncryption
*/ */
public function useEncryption($useEncryption = true) { public function useEncryption($useEncryption = true)
{
$this->use_encryption = $useEncryption; $this->use_encryption = $useEncryption;
} }
@ -149,7 +152,8 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
* *
* @param boolean $autoSubscribe * @param boolean $autoSubscribe
*/ */
public function autoSubscribe($autoSubscribe = true) { public function autoSubscribe($autoSubscribe = true)
{
$this->auto_subscribe = $autoSubscribe; $this->auto_subscribe = $autoSubscribe;
} }
@ -160,24 +164,27 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
* @param string $body * @param string $body
* @param string $type * @param string $type
* @param string $subject * @param string $subject
* @param null $payload
* @throws Exception
*/ */
public function message($to, $body, $type = 'chat', $subject = null, $payload = null) { public function message($to, $body, $type = 'chat', $subject = null, $payload = null)
if(is_null($type))
{ {
if ($this->disconnected) {
throw new Exception('You need to connect first');
}
if (empty($type)) {
$type = 'chat'; $type = 'chat';
} }
$to = htmlspecialchars($to); $to = htmlspecialchars($to);
$body = htmlspecialchars($body); $body = htmlspecialchars($body);
$subject = htmlspecialchars($subject); $subject = htmlspecialchars($subject);
$subject = ($subject) ? '<subject>' . $subject . '</subject>' : '';
$out = "<message from=\"{$this->fulljid}\" to=\"$to\" type='$type'>"; $payload = ($payload) ? $payload : '';
if($subject) $out .= "<subject>$subject</subject>"; $sprintf = '<message from="%s" to="%s" type="%s">%s<body>%s</body>%s</message>';
$out .= "<body>$body</body>"; $output = sprintf($sprintf, $this->fulljid, $to, $type, $subject, $body, $payload);
if($payload) $out .= $payload; $this->send($output);
$out .= "</message>";
$this->send($out);
} }
/** /**
@ -186,34 +193,58 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
* @param string $status * @param string $status
* @param string $show * @param string $show
* @param string $to * @param string $to
* @param string $type
* @param null $priority
* @throws Exception
*/ */
public function presence($status = null, $show = 'available', $to = null, $type='available', $priority=0) { public function presence($status = null, $show = 'available', $to = null, $type = 'available', $priority = null)
if($type == 'available') $type = ''; {
if ($this->disconnected) {
throw new Exception('You need to connect first');
}
if ($type == 'available') {
$type = '';
}
$to = htmlspecialchars($to); $to = htmlspecialchars($to);
$status = htmlspecialchars($status); $status = htmlspecialchars($status);
if($show == 'unavailable') $type = 'unavailable'; if ($show == 'unavailable') {
$type = 'unavailable';
}
$out = "<presence"; $out = "<presence";
if($to) $out .= " to=\"$to\""; if ($to) {
if($type) $out .= " type='$type'"; $out .= " to=\"$to\"";
if($show == 'available' and !$status) { }
if ($type) {
$out .= " type='$type'";
}
if ($show == 'available' and !$status and $priority !== null) {
$out .= "/>"; $out .= "/>";
} else { } else {
$out .= ">"; $out .= ">";
if($show != 'available') $out .= "<show>$show</show>"; if ($show != 'available') {
if($status) $out .= "<status>$status</status>"; $out .= "<show>$show</show>";
if($priority) $out .= "<priority>$priority</priority>"; }
if ($status) {
$out .= "<status>$status</status>";
}
if ($priority !== null) {
$out .= "<priority>$priority</priority>";
}
$out .= "</presence>"; $out .= "</presence>";
} }
$this->send($out); $this->send($out);
} }
/** /**
* Send Auth request * Send Auth request
* *
* @param string $jid * @param string $jid
*/ */
public function subscribe($jid) { public function subscribe($jid)
{
$this->send("<presence type='subscribe' to='{$jid}' from='{$this->fulljid}' />"); $this->send("<presence type='subscribe' to='{$jid}' from='{$this->fulljid}' />");
#$this->send("<presence type='subscribed' to='{$jid}' from='{$this->fulljid}' />"); #$this->send("<presence type='subscribed' to='{$jid}' from='{$this->fulljid}' />");
} }
@ -223,16 +254,18 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
* *
* @param string $xml * @param string $xml
*/ */
public function message_handler($xml) { public function message_handler($xml)
if(isset($xml->attrs['type'])) { {
if (isset($xml->attrs['type'])) {
$payload['type'] = $xml->attrs['type']; $payload['type'] = $xml->attrs['type'];
} else { } else {
$payload['type'] = 'chat'; $payload['type'] = 'chat';
} }
$body = $xml->sub('body');
$payload['from'] = $xml->attrs['from']; $payload['from'] = $xml->attrs['from'];
$payload['body'] = $xml->sub('body')->data; $payload['body'] = is_object($body) ? $body->data : false; // $xml->sub('body')->data;
$payload['xml'] = $xml; $payload['xml'] = $xml;
$this->log->log("Message: {$xml->sub('body')->data}", XMPPHP_Log::LEVEL_DEBUG); $this->log->log("Message: {$payload['body']}", Log::LEVEL_DEBUG);
$this->event('message', $payload); $this->event('message', $payload);
} }
@ -241,39 +274,66 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
* *
* @param string $xml * @param string $xml
*/ */
public function presence_handler($xml) { public function presence_handler($xml)
{
$payload['type'] = (isset($xml->attrs['type'])) ? $xml->attrs['type'] : 'available'; $payload['type'] = (isset($xml->attrs['type'])) ? $xml->attrs['type'] : 'available';
$payload['show'] = (isset($xml->sub('show')->data)) ? $xml->sub('show')->data : $payload['type']; $payload['show'] = (isset($xml->sub('show')->data)) ? $xml->sub('show')->data : $payload['type'];
$payload['from'] = $xml->attrs['from']; $payload['from'] = $xml->attrs['from'];
$payload['status'] = (isset($xml->sub('status')->data)) ? $xml->sub('status')->data : ''; $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['priority'] = (isset($xml->sub('priority')->data)) ? intval($xml->sub('priority')->data) : 0;
$payload['xml'] = $xml; $payload['xml'] = $xml;
if($this->track_presence) { if ($this->track_presence) {
$this->roster->setPresence($payload['from'], $payload['priority'], $payload['show'], $payload['status']); $this->roster->setPresence($payload['from'], $payload['priority'], $payload['show'], $payload['status']);
} }
$this->log->log("Presence: {$payload['from']} [{$payload['show']}] {$payload['status']}", XMPPHP_Log::LEVEL_DEBUG); $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 (array_key_exists('type', $xml->attrs) and $xml->attrs['type'] == 'subscribe') {
if($this->auto_subscribe) { if ($this->auto_subscribe) {
$this->send("<presence type='subscribed' to='{$xml->attrs['from']}' from='{$this->fulljid}' />"); $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->send("<presence type='subscribe' to='{$xml->attrs['from']}' from='{$this->fulljid}' />");
} }
$this->event('subscription_requested', $payload); $this->event('subscription_requested', $payload);
} elseif(array_key_exists('type', $xml->attrs) and $xml->attrs['type'] == 'subscribed') { } elseif (array_key_exists('type', $xml->attrs) and $xml->attrs['type'] == 'subscribed') {
$this->event('subscription_accepted', $payload); $this->event('subscription_accepted', $payload);
} else { } else {
$this->event('presence', $payload); $this->event('presence', $payload);
} }
} }
/**
* Retrieves the roster
*
*/
public function getRoster()
{
$id = $this->getID();
$this->send("<iq xmlns='jabber:client' type='get' id='$id'><query xmlns='jabber:iq:roster' /></iq>");
}
/**
* Retrieves the vcard
* @param null $jid
*/
public function getVCard($jid = null)
{
$id = $this->getID();
$this->addIdHandler($id, 'vcard_get_handler');
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 * Features handler
* *
* @param string $xml * @param string $xml
*/ */
protected function features_handler($xml) { protected function features_handler($xml)
if($xml->hasSub('starttls') and $this->use_encryption) { {
if ($xml->hasSub('starttls') and $this->use_encryption) {
$this->send("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'><required /></starttls>"); $this->send("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'><required /></starttls>");
} elseif($xml->hasSub('bind') and $this->authed) { } elseif ($xml->hasSub('bind') and $this->authed) {
$id = $this->getId(); $id = $this->getId();
$this->addIdHandler($id, 'resource_bind_handler'); $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>"); $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>");
@ -292,7 +352,8 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
* *
* @param string $xml * @param string $xml
*/ */
protected function sasl_success_handler($xml) { protected function sasl_success_handler($xml)
{
$this->log->log("Auth success!"); $this->log->log("Auth success!");
$this->authed = true; $this->authed = true;
$this->reset(); $this->reset();
@ -302,12 +363,14 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
* SASL feature handler * SASL feature handler
* *
* @param string $xml * @param string $xml
* @throws Exception
*/ */
protected function sasl_failure_handler($xml) { protected function sasl_failure_handler($xml)
$this->log->log("Auth failed!", XMPPHP_Log::LEVEL_ERROR); {
$this->log->log("Auth failed!", Log::LEVEL_ERROR);
$this->disconnect(); $this->disconnect();
throw new XMPPHP_Exception('Auth failed!'); throw new Exception('Auth failed!');
} }
/** /**
@ -315,11 +378,12 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
* *
* @param string $xml * @param string $xml
*/ */
protected function resource_bind_handler($xml) { protected function resource_bind_handler($xml)
if($xml->attrs['type'] == 'result') { {
if ($xml->attrs['type'] == 'result') {
$this->log->log("Bound to " . $xml->sub('bind')->sub('jid')->data); $this->log->log("Bound to " . $xml->sub('bind')->sub('jid')->data);
$this->fulljid = $xml->sub('bind')->sub('jid')->data; $this->fulljid = $xml->sub('bind')->sub('jid')->data;
$jidarray = explode('/',$this->fulljid); $jidarray = explode('/', $this->fulljid);
$this->jid = $jidarray[0]; $this->jid = $jidarray[0];
} }
$id = $this->getId(); $id = $this->getId();
@ -327,31 +391,23 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
$this->send("<iq xmlns='jabber:client' type='set' id='$id'><session xmlns='urn:ietf:params:xml:ns:xmpp-session' /></iq>"); $this->send("<iq xmlns='jabber:client' type='set' id='$id'><session xmlns='urn:ietf:params:xml:ns:xmpp-session' /></iq>");
} }
/**
* Retrieves the roster
*
*/
public function getRoster() {
$id = $this->getID();
$this->send("<iq xmlns='jabber:client' type='get' id='$id'><query xmlns='jabber:iq:roster' /></iq>");
}
/** /**
* Roster iq handler * Roster iq handler
* Gets all packets matching XPath "iq/{jabber:iq:roster}query' * Gets all packets matching XPath "iq/{jabber:iq:roster}query'
* *
* @param string $xml * @param string $xml
*/ */
protected function roster_iq_handler($xml) { protected function roster_iq_handler($xml)
{
$status = "result"; $status = "result";
$xmlroster = $xml->sub('query'); $xmlroster = $xml->sub('query');
foreach($xmlroster->subs as $item) { foreach ($xmlroster->subs as $item) {
$groups = array(); $groups = array();
if ($item->name == 'item') { if ($item->name == 'item') {
$jid = $item->attrs['jid']; //REQUIRED $jid = $item->attrs['jid']; //REQUIRED
$name = $item->attrs['name']; //MAY $name = $item->attrs['name']; //MAY
$subscription = $item->attrs['subscription']; $subscription = $item->attrs['subscription'];
foreach($item->subs as $subitem) { foreach ($item->subs as $subitem) {
if ($subitem->name == 'group') { if ($subitem->name == 'group') {
$groups[] = $subitem->data; $groups[] = $subitem->data;
} }
@ -362,7 +418,7 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
} }
} }
if ($status == "result") { //No errors, add contacts if ($status == "result") { //No errors, add contacts
foreach($contacts as $contact) { foreach ($contacts as $contact) {
$this->roster->addContact($contact[0], $contact[1], $contact[2], $contact[3]); $this->roster->addContact($contact[0], $contact[1], $contact[2], $contact[3]);
} }
} }
@ -376,7 +432,8 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
* *
* @param string $xml * @param string $xml
*/ */
protected function session_start_handler($xml) { protected function session_start_handler($xml)
{
$this->log->log("Session started"); $this->log->log("Session started");
$this->session_started = true; $this->session_started = true;
$this->event('session_start'); $this->event('session_start');
@ -387,32 +444,20 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
* *
* @param string $xml * @param string $xml
*/ */
protected function tls_proceed_handler($xml) { protected function tls_proceed_handler($xml)
{
$this->log->log("Starting TLS encryption"); $this->log->log("Starting TLS encryption");
stream_socket_enable_crypto($this->socket, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT); stream_socket_enable_crypto($this->socket, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
$this->reset(); $this->reset();
} }
/**
* Retrieves the vcard
*
*/
public function getVCard($jid = Null) {
$id = $this->getID();
$this->addIdHandler($id, 'vcard_get_handler');
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>");
}
}
/** /**
* VCard retrieval handler * VCard retrieval handler
* *
* @param XML Object $xml * @param XMLObj $xml
*/ */
protected function vcard_get_handler($xml) { protected function vcard_get_handler($xml)
{
$vcard_array = array(); $vcard_array = array();
$vcard = $xml->sub('vcard'); $vcard = $xml->sub('vcard');
// go through all of the sub elements and add them to the vcard array // go through all of the sub elements and add them to the 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');
}
}
}
?>

View File

@ -4,7 +4,7 @@
* *
* Queue-mediated proxy class for outgoing XMPP messages. * Queue-mediated proxy class for outgoing XMPP messages.
* *
* PHP version 5 * PHP version 7
* *
* LICENCE: This program is free software: you can redistribute it and/or modify * LICENCE: This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by * it under the terms of the GNU Affero General Public License as published by
@ -31,7 +31,11 @@ if (!defined('STATUSNET') && !defined('LACONICA')) {
exit(1); exit(1);
} }
class QueuedXMPP extends XMPPHP_XMPP require_once dirname(__DIR__) . '/extlib/XMPPHP/XMPP.php';
use XMPPHP\XMPP;
class QueuedXMPP extends XMPP
{ {
/** /**
* Reference to the XmppPlugin object we're hooked up to. * Reference to the XmppPlugin object we're hooked up to.
@ -76,15 +80,21 @@ class QueuedXMPP extends XMPPHP_XMPP
* to a real XMPP connection. * to a real XMPP connection.
* *
* @param string $msg * @param string $msg
* @param null $timeout
*/ */
public function send($msg, $timeout=NULL) public function send($msg, $timeout = NULL)
{ {
$this->plugin->enqueueOutgoingRaw($msg); @$this->plugin->enqueueOutgoingRaw($msg);
} }
//@{ //@{
/** /**
* Stream i/o functions disabled; only do output * Stream i/o functions disabled; only do output
* @param int $timeout
* @param bool $persistent
* @param bool $sendinit
* @throws Exception
*/ */
public function connect($timeout = 30, $persistent = false, $sendinit = true) public function connect($timeout = 30, $persistent = false, $sendinit = true)
{ {
@ -104,7 +114,7 @@ class QueuedXMPP extends XMPPHP_XMPP
throw new Exception('Cannot read stream from fake XMPP.'); throw new Exception('Cannot read stream from fake XMPP.');
} }
public function processUntil($event, $timeout=-1) public function processUntil($event, $timeout = -1)
{ {
// No i18n needed. Test message. // No i18n needed. Test message.
throw new Exception('Cannot read stream from fake XMPP.'); throw new Exception('Cannot read stream from fake XMPP.');

View File

@ -5,7 +5,7 @@
* *
* Send and receive notices using the Jabber network * Send and receive notices using the Jabber network
* *
* PHP version 5 * PHP version 7
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by * it under the terms of the GNU Affero General Public License as published by
@ -34,7 +34,11 @@ if (!defined('STATUSNET')) {
exit(1); exit(1);
} }
class SharingXMPP extends XMPPHP_XMPP require_once dirname(__DIR__) . '/extlib/XMPPHP/XMPP.php';
use XMPPHP\XMPP;
class SharingXMPP extends XMPP
{ {
function getSocket() function getSocket()
{ {

View File

@ -17,7 +17,11 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); } if (!defined('STATUSNET') && !defined('LACONICA')) {
exit(1);
}
use XMPPHP\Log;
/** /**
* XMPP background connection manager for XMPP-using queue handlers, * XMPP background connection manager for XMPP-using queue handlers,
@ -31,28 +35,86 @@ if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
*/ */
class XmppManager extends ImManager class XmppManager extends ImManager
{ {
const PING_INTERVAL = 120;
public $conn = null;
protected $lastping = null; protected $lastping = null;
protected $pingid = null; protected $pingid = null;
public $conn = null;
const PING_INTERVAL = 120;
/** /**
* Initialize connection to server. * Initialize connection to server.
* @param $master
* @return boolean true on success * @return boolean true on success
*/ */
public function start($master) public function start($master)
{ {
if(parent::start($master)) if (parent::start($master)) {
{
$this->connect(); $this->connect();
return true; return true;
}else{ } else {
return false; return false;
} }
} }
function connect()
{
if (!$this->conn || $this->conn->isDisconnected()) {
$resource = 'queue' . posix_getpid();
$this->conn = new SharingXMPP($this->plugin->host ?
$this->plugin->host :
$this->plugin->server,
$this->plugin->port,
$this->plugin->user,
$this->plugin->password,
$this->plugin->resource,
$this->plugin->server,
$this->plugin->debug ?
true : false,
$this->plugin->debug ?
Log::LEVEL_VERBOSE : null
);
if (!$this->conn) {
return false;
}
$this->conn->addEventHandler('message', 'handle_xmpp_message', $this);
$this->conn->addEventHandler('reconnect', 'handle_xmpp_reconnect', $this);
$this->conn->setReconnectTimeout(600);
$this->conn->autoSubscribe();
$this->conn->useEncryption($this->plugin->encryption);
$this->conn->connect(true);
$this->conn->processUntil('session_start');
// TRANS: Presence announcement for XMPP.
$this->send_presence(_m('Send me a message to post a notice'), 'available', null, 'available', 100);
}
return $this->conn;
}
/**
* sends a presence stanza on the XMPP network
*
* @param string $status current status, free-form string
* @param string $show structured status value
* @param string $to recipient of presence, null for general
* @param string $type type of status message, related to $show
* @param int $priority priority of the presence
*
* @return boolean success value
*/
function send_presence($status, $show = 'available', $to = null,
$type = 'available', $priority = null)
{
$this->connect();
if (!$this->conn || $this->conn->isDisconnected()) {
return false;
}
$this->conn->presence($status, $show, $to, $type, $priority);
return true;
}
function send_raw_message($data) function send_raw_message($data)
{ {
$this->connect(); $this->connect();
@ -80,14 +142,9 @@ class XmppManager extends ImManager
public function handleInput($socket) public function handleInput($socket)
{ {
// Process the queue for as long as needed // Process the queue for as long as needed
try {
common_log(LOG_DEBUG, "Servicing the XMPP queue."); common_log(LOG_DEBUG, "Servicing the XMPP queue.");
$this->stats('xmpp_process'); $this->stats('xmpp_process');
$this->conn->processTime(0); $this->conn->processTime(0);
} catch (XMPPHP_Exception $e) {
common_log(LOG_ERR, "Got an XMPPHP_Exception: " . $e->getMessage());
die($e->getMessage());
}
} }
/** /**
@ -99,9 +156,9 @@ class XmppManager extends ImManager
public function getSockets() public function getSockets()
{ {
$this->connect(); $this->connect();
if($this->conn){ if ($this->conn) {
return array($this->conn->getSocket()); return array($this->conn->getSocket());
}else{ } else {
return array(); return array();
} }
} }
@ -112,62 +169,16 @@ class XmppManager extends ImManager
* *
* Side effect: kills process on exception from XMPP library. * Side effect: kills process on exception from XMPP library.
* *
* @param int $timeout
* @todo FIXME: non-dying error handling * @todo FIXME: non-dying error handling
*/ */
public function idle($timeout=0) public function idle($timeout = 0)
{ {
$now = time(); $now = time();
if (empty($this->lastping) || $now - $this->lastping > self::PING_INTERVAL) { if (empty($this->lastping) || $now - $this->lastping > self::PING_INTERVAL) {
try {
$this->send_ping(); $this->send_ping();
} catch (XMPPHP_Exception $e) {
common_log(LOG_ERR, "Got an XMPPHP_Exception: " . $e->getMessage());
die($e->getMessage());
} }
} }
}
function connect()
{
if (!$this->conn || $this->conn->isDisconnected()) {
$resource = 'queue' . posix_getpid();
$this->conn = new SharingXMPP($this->plugin->host ?
$this->plugin->host :
$this->plugin->server,
$this->plugin->port,
$this->plugin->user,
$this->plugin->password,
$this->plugin->resource,
$this->plugin->server,
$this->plugin->debug ?
true : false,
$this->plugin->debug ?
XMPPHP_Log::LEVEL_VERBOSE : null
);
if (!$this->conn) {
return false;
}
$this->conn->addEventHandler('message', 'handle_xmpp_message', $this);
$this->conn->addEventHandler('reconnect', 'handle_xmpp_reconnect', $this);
$this->conn->setReconnectTimeout(600);
$this->conn->autoSubscribe();
$this->conn->useEncryption($this->plugin->encryption);
try {
$this->conn->connect(true); // true = persistent connection
} catch (XMPPHP_Exception $e) {
common_log(LOG_ERR, $e->getMessage());
return false;
}
$this->conn->processUntil('session_start');
// TRANS: Presence announcement for XMPP.
$this->send_presence(_m('Send me a message to post a notice'), 'available', null, 'available', 100);
}
return $this->conn;
}
function send_ping() function send_ping()
{ {
@ -207,29 +218,6 @@ class XmppManager extends ImManager
$this->send_presence(_m('Send me a message to post a notice'), 'available', null, 'available', 100); $this->send_presence(_m('Send me a message to post a notice'), 'available', null, 'available', 100);
} }
/**
* sends a presence stanza on the XMPP network
*
* @param string $status current status, free-form string
* @param string $show structured status value
* @param string $to recipient of presence, null for general
* @param string $type type of status message, related to $show
* @param int $priority priority of the presence
*
* @return boolean success value
*/
function send_presence($status, $show='available', $to=null,
$type = 'available', $priority=null)
{
$this->connect();
if (!$this->conn || $this->conn->isDisconnected()) {
return false;
}
$this->conn->presence($status, $show, $to, $type, $priority);
return true;
}
/** /**
* sends a "special" presence stanza on the XMPP network * sends a "special" presence stanza on the XMPP network
* *
@ -243,7 +231,7 @@ class XmppManager extends ImManager
* @see send_presence() * @see send_presence()
*/ */
function special_presence($type, $to=null, $show=null, $status=null) function special_presence($type, $to = null, $show = null, $status = null)
{ {
// @todo FIXME: why use this instead of send_presence()? // @todo FIXME: why use this instead of send_presence()?
$this->connect(); $this->connect();