Introduce PHP7 strict typing

This commit is contained in:
Diogo Cordeiro 2019-11-02 23:36:21 +00:00
parent 79239e8e2d
commit 57f33b4328
14 changed files with 586 additions and 547 deletions

View File

@ -1,5 +1,4 @@
<?php <?php
/** /**
* XMPPHP: The PHP XMPP Library * XMPPHP: The PHP XMPP Library
* Copyright (C) 2008 Nathanael C. Fritz * Copyright (C) 2008 Nathanael C. Fritz
@ -35,7 +34,7 @@ namespace XMPPHP;
use SimpleXMLElement; use SimpleXMLElement;
/** XMPPHP_XMLStream */ /** XMPPHP_XMLStream */
require_once __DIR__ . "/XMPP.php"; require_once __DIR__ . DIRECTORY_SEPARATOR . 'XMPP.php';
/** /**
* XMPPHP BOSH * XMPPHP BOSH
@ -51,7 +50,7 @@ require_once __DIR__ . "/XMPP.php";
class BOSH extends XMPP class BOSH extends XMPP
{ {
/** /**
* @var integer * @var int
*/ */
protected $rid; protected $rid;
@ -68,7 +67,7 @@ class BOSH extends XMPP
/** /**
* @var array * @var array
*/ */
protected $http_buffer = array(); protected $http_buffer = [];
/** /**
* @var string * @var string
@ -76,50 +75,58 @@ class BOSH extends XMPP
protected $session = false; protected $session = false;
/** /**
* @var integer * @var int
*/ */
protected $inactivity; protected $inactivity;
/** public function __construct(
* Connect string $host,
* int $port,
* @param $server string $user,
* @param $wait string $password,
* @param $session string $resource,
* @throws Exception ?string $server = null,
* @throws Exception bool $print_log = false,
*/ ?string $log_level = null
public function connect($server = null, $wait = '1', $session = false) ) {
{ parent::__construct($host, $port, $user, $password, $resource, $server, $print_log, $log_level);
if (is_null($server)) { if (is_null($server)) {
// If we aren't given the server http url, try and guess it // If we aren't given the server http url, try and guess it
$port_string = ($this->port AND $this->port != 80) ? ':' . $this->port : ''; $port_string = ($this->port and $this->port != 80) ? ':' . $this->port : '';
$this->http_server = 'http://' . $this->host . $port_string . '/http-bind/'; $this->http_server = 'http://' . $this->host . $port_string . '/http-bind/';
} else { } else {
$this->http_server = $server; $this->http_server = $server;
} }
}
/**
* Connect
*
* @param bool $persistent
* @param bool $send_init
* @param int $timeout
* @throws Exception
*/
public function connect(bool $persistent = false, bool $send_init = true, int $timeout = 30): void
{
$this->use_encryption = false; $this->use_encryption = false;
$this->session = $session; $this->session = $persistent;
$this->rid = 3001; $this->rid = 3001;
$this->sid = null; $this->sid = null;
$this->inactivity = 0; $this->inactivity = 0;
if ($session) { if ($persistent) {
$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->server); $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.0', 'urn:xmpp:xbosh'); $body->addAttribute('xmpp:version', '1.0', 'urn:xmpp:xbosh');
$body->addAttribute('wait', strval($wait)); $body->addAttribute('wait', strval($timeout));
$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">';
@ -138,11 +145,9 @@ class BOSH extends XMPP
* Load session * Load session
* *
*/ */
public function loadSession() public function loadSession(): void
{ {
if ($this->session == 'ON_FILE') { if ($this->session == 'ON_FILE') {
// Session not started so use session_file // Session not started so use session_file
$session_file = $this->getSessionFile(); $session_file = $this->getSessionFile();
@ -169,7 +174,6 @@ class BOSH extends XMPP
$this->lat = (time() - (isset($_SESSION['XMPPHP_BOSH']['lat']))) ? $_SESSION['XMPPHP_BOSH']['lat'] : 0; $this->lat = (time() - (isset($_SESSION['XMPPHP_BOSH']['lat']))) ? $_SESSION['XMPPHP_BOSH']['lat'] : 0;
if ($this->lat < $this->inactivity) { if ($this->lat < $this->inactivity) {
if (isset($_SESSION['XMPPHP_BOSH']['RID'])) { if (isset($_SESSION['XMPPHP_BOSH']['RID'])) {
$this->rid = $_SESSION['XMPPHP_BOSH']['RID']; $this->rid = $_SESSION['XMPPHP_BOSH']['RID'];
} }
@ -189,10 +193,10 @@ class BOSH extends XMPP
} }
/** /**
* Get the session file * Get the session file location
* *
*/ */
public function getSessionFile() public function getSessionFile(): string
{ {
return sys_get_temp_dir() . '/' . $this->user . '_' . $this->server . '_session'; return sys_get_temp_dir() . '/' . $this->user . '_' . $this->server . '_session';
} }
@ -200,17 +204,15 @@ class BOSH extends XMPP
/** /**
* Build body * Build body
* *
* @param $sub * @param SimpleXMLElement|null $sub
* @return SimpleXMLElement|string * @return SimpleXMLElement
*/ */
public function __buildBody($sub = null) private function __buildBody(?SimpleXMLElement $sub = null): SimpleXMLElement
{ {
$xml = new SimpleXMLElement('<body xmlns="http://jabber.org/protocol/httpbind" xmlns:xmpp="urn:xmpp:xbosh" />');
$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('content', 'text/xml; charset=utf-8');
$xml->addAttribute('rid', $this->rid); $xml->addAttribute('rid', $this->rid);
$this->rid++; ++$this->rid;
if ($this->sid) { if ($this->sid) {
$xml->addAttribute('sid', $this->sid); $xml->addAttribute('sid', $this->sid);
} }
@ -218,7 +220,6 @@ class BOSH extends XMPP
$xml->addAttribute('xml:lang', 'en'); $xml->addAttribute('xml:lang', 'en');
if ($sub !== null) { if ($sub !== null) {
// Ok, so simplexml is lame // Ok, so simplexml is lame
$parent = dom_import_simplexml($xml); $parent = dom_import_simplexml($xml);
$content = dom_import_simplexml($sub); $content = dom_import_simplexml($sub);
@ -233,21 +234,19 @@ class BOSH extends XMPP
/** /**
* Send body * Send body
* *
* @param $body * @param SimpleXMLElement|null $body
* @param $recv * @param bool $recv
* @return bool|string * @return bool|string
* @throws Exception * @throws Exception
* @throws Exception
*/ */
public function __sendBody($body = null, $recv = true) private function __sendBody(?SimpleXMLElement $body = null, bool $recv = true)
{ {
if (!$body) { if (!$body) {
$body = $this->__buildBody(); $body = $this->__buildBody();
} }
$output = ''; $output = '';
$header = array('Accept-Encoding: gzip, deflate', 'Content-Type: text/xml; charset=utf-8'); $header = ['Accept-Encoding: gzip, deflate', 'Content-Type: text/xml; charset=utf-8'];
$ch = curl_init(); $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->http_server); curl_setopt($ch, CURLOPT_URL, $this->http_server);
@ -283,9 +282,8 @@ class BOSH extends XMPP
* @throws Exception * @throws Exception
* @throws Exception * @throws Exception
*/ */
public function __process($null1 = null, $null2 = null) private function __process($null1 = null, $null2 = null)
{ {
if ($this->http_buffer) { if ($this->http_buffer) {
$this->__parseBuffer(); $this->__parseBuffer();
} else { } else {
@ -298,17 +296,14 @@ class BOSH extends XMPP
return true; return true;
} }
public function __parseBuffer() private 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()');
@ -325,9 +320,8 @@ class BOSH extends XMPP
* Save session * Save session
* *
*/ */
public function saveSession() public function saveSession(): void
{ {
$_SESSION['XMPPHP_BOSH']['RID'] = (string)$this->rid; $_SESSION['XMPPHP_BOSH']['RID'] = (string)$this->rid;
$_SESSION['XMPPHP_BOSH']['SID'] = (string)$this->sid; $_SESSION['XMPPHP_BOSH']['SID'] = (string)$this->sid;
$_SESSION['XMPPHP_BOSH']['authed'] = (boolean)$this->authed; $_SESSION['XMPPHP_BOSH']['authed'] = (boolean)$this->authed;
@ -337,7 +331,6 @@ class BOSH extends XMPP
$_SESSION['XMPPHP_BOSH']['lat'] = (string)time(); $_SESSION['XMPPHP_BOSH']['lat'] = (string)time();
if ($this->session == 'ON_FILE') { if ($this->session == 'ON_FILE') {
$session_file = $this->getSessionFile(); $session_file = $this->getSessionFile();
$session_file_fp = fopen($session_file, 'r'); $session_file_fp = fopen($session_file, 'r');
flock($session_file_fp, LOCK_EX); flock($session_file_fp, LOCK_EX);
@ -353,13 +346,10 @@ class BOSH extends XMPP
* Process * Process
* *
* @param $msg * @param $msg
* @param $null * @param int|null $_ unused
*
* null param are not used and just to statify Strict Function Declaration
* @throws Exception
* @throws Exception * @throws Exception
*/ */
public function send($msg, $null = null) public function send($msg, ?int $_ = null)
{ {
$this->log->log('SEND: ' . $msg, Log::LEVEL_VERBOSE); $this->log->log('SEND: ' . $msg, Log::LEVEL_VERBOSE);
$msg = new SimpleXMLElement($msg); $msg = new SimpleXMLElement($msg);
@ -371,18 +361,17 @@ class BOSH extends XMPP
* *
* @throws Exception * @throws Exception
*/ */
public function reset() public function reset(): void
{ {
$this->xml_depth = 0; $this->xml_depth = 0;
unset($this->xmlobj); unset($this->xmlobj);
$this->xmlobj = array(); $this->xmlobj = [];
$this->setupParser(); $this->setupParser();
$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); $this->__sendBody($body);
$this->been_reset = true; $this->been_reset = true;
xml_parse($this->parser, $buff, false); xml_parse($this->parser, $buff, false);
} }
@ -392,15 +381,14 @@ class BOSH extends XMPP
* *
* @throws Exception * @throws Exception
*/ */
public function disconnect() public function disconnect(): void
{ {
parent::disconnect(); parent::disconnect();
if ($this->session == 'ON_FILE') { if ($this->session == 'ON_FILE') {
unlink($this->getSessionFile()); unlink($this->getSessionFile());
} else { } else {
$keys = array('RID', 'SID', 'authed', 'basejid', 'fulljid', 'inactivity', 'lat'); $keys = ['RID', 'SID', 'authed', 'basejid', 'fulljid', 'inactivity', 'lat'];
foreach ($keys as $key) { foreach ($keys as $key) {
unset($_SESSION['XMPPHP_BOSH'][$key]); unset($_SESSION['XMPPHP_BOSH'][$key]);
} }

View File

@ -1,5 +1,4 @@
<?php <?php
/** /**
* XMPPHP: The PHP XMPP Library * XMPPHP: The PHP XMPP Library
* Copyright (C) 2008 Nathanael C. Fritz * Copyright (C) 2008 Nathanael C. Fritz

View File

@ -1,5 +1,4 @@
<?php <?php
/** /**
* XMPPHP: The PHP XMPP Library * XMPPHP: The PHP XMPP Library
* Copyright (C) 2008 Nathanael C. Fritz * Copyright (C) 2008 Nathanael C. Fritz
@ -53,20 +52,20 @@ class Log
/** /**
* @var array * @var array
*/ */
protected $data = array(); protected $data = [];
/** /**
* @var array * @var array
*/ */
protected $names = array('ERROR', 'WARNING', 'INFO', 'DEBUG', 'VERBOSE'); protected $names = ['ERROR', 'WARNING', 'INFO', 'DEBUG', 'VERBOSE'];
/** /**
* @var integer * @var int
*/ */
protected $runlevel; protected $runlevel;
/** /**
* @var boolean * @var bool
*/ */
protected $printout; protected $printout;
@ -74,11 +73,11 @@ class Log
* Constructor * Constructor
* *
* @param boolean $printout * @param boolean $printout
* @param int $runlevel * @param int $runlevel (optional)
*/ */
public function __construct($printout = false, $runlevel = self::LEVEL_INFO) public function __construct($printout = false, int $runlevel = self::LEVEL_INFO)
{ {
$this->printout = (boolean)$printout; $this->printout = (bool)$printout;
$this->runlevel = (int)$runlevel; $this->runlevel = (int)$runlevel;
} }
@ -87,18 +86,23 @@ class Log
* If printout in this instance is set to true, directly output the message * If printout in this instance is set to true, directly output the message
* *
* @param string $msg * @param string $msg
* @param integer $runlevel * @param int $runlevel (optional)
*/ */
public function log($msg, $runlevel = self::LEVEL_INFO) public function log($msg, $runlevel = self::LEVEL_INFO): void
{ {
$time = time(); $time = time();
#$this->data[] = array($this->runlevel, $msg, $time); //$this->data[] = [$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) /**
* @param string $msg
* @param int $runlevel
* @param int $time
*/
protected function writeLine(string $msg, int $runlevel, int $time): void
{ {
//echo date('Y-m-d H:i:s', $time)." [".$this->names[$runlevel]."]: ".$msg."\n"; //echo date('Y-m-d H:i:s', $time)." [".$this->names[$runlevel]."]: ".$msg."\n";
echo $time . " [" . $this->names[$runlevel] . "]: " . $msg . "\n"; echo $time . " [" . $this->names[$runlevel] . "]: " . $msg . "\n";
@ -109,10 +113,10 @@ class Log
* Output the complete log. * Output the complete log.
* Log will be cleared if $clear = true * Log will be cleared if $clear = true
* *
* @param boolean $clear * @param bool $clear
* @param integer $runlevel * @param int $runlevel
*/ */
public function printout($clear = true, $runlevel = null) public function printout(bool $clear = true, int $runlevel = null): void
{ {
if ($runlevel === null) { if ($runlevel === null) {
$runlevel = $this->runlevel; $runlevel = $this->runlevel;
@ -123,7 +127,7 @@ class Log
} }
} }
if ($clear) { if ($clear) {
$this->data = array(); $this->data = [];
} }
} }
} }

View File

@ -1,5 +1,4 @@
<?php <?php
/** /**
* XMPPHP: The PHP XMPP Library * XMPPHP: The PHP XMPP Library
* Copyright (C) 2008 Nathanael C. Fritz * Copyright (C) 2008 Nathanael C. Fritz
@ -49,70 +48,67 @@ class Roster
* 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 = [];
/** /**
* Constructor * Constructor
* @param array $roster_array * @param array $roster_array
*/ */
public function __construct($roster_array = array()) public function __construct($roster_array = [])
{ {
if ($this->verifyRoster($roster_array)) { if ($this->verifyRoster($roster_array)) {
$this->roster_array = $roster_array; //Allow for pre-population with existing roster $this->roster_array = $roster_array; //Allow for pre-population with existing roster
} else { } else {
$this->roster_array = array(); $this->roster_array = [];
} }
} }
/** /**
*
* Check that a given roster array is of a valid structure (empty is still valid) * Check that a given roster array is of a valid structure (empty is still valid)
* *
* @param array $roster_array * @param array $roster_array
* @return bool * @return bool true for valid, false otherwise
*/ */
protected function verifyRoster($roster_array) protected function verifyRoster(array $roster_array): bool
{ {
#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;
} }
/** /**
*
* Retrieve contact via jid * Retrieve contact via jid
* *
* @param string $jid * @param string $jid
* @return mixed * @return mixed|void
*/ */
public function getContact($jid) public function getContact(string $jid)
{ {
if ($this->isContact($jid)) { if ($this->isContact($jid)) {
return $this->roster_array[$jid]['contact']; return $this->roster_array[$jid]['contact'];
} }
return;
} }
/** /**
*
* 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 * @return bool
*/ */
public function isContact($jid) public function isContact(string $jid): bool
{ {
return (array_key_exists($jid, $this->roster_array)); return (array_key_exists($jid, $this->roster_array));
} }
/** /**
*
* Set presence * Set presence
* *
* @param string $presence * @param string $presence
* @param integer $priority * @param int $priority
* @param string $show * @param string $show
* @param string $status * @param string $status
*/ */
public function setPresence($presence, $priority, $show, $status) public function setPresence(string $presence, int $priority, string $show, string $status): void
{ {
$presence = explode('/', $presence, 2); $presence = explode('/', $presence, 2);
$jid = $presence[0]; $jid = $presence[0];
@ -121,7 +117,7 @@ class Roster
if (!$this->isContact($jid)) { if (!$this->isContact($jid)) {
$this->addContact($jid, 'not-in-roster'); $this->addContact($jid, 'not-in-roster');
} }
$this->roster_array[$jid]['presence'][$resource] = array('priority' => $priority, 'show' => $show, 'status' => $status); $this->roster_array[$jid]['presence'][$resource] = ['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]); unset($this->roster_array[$jid]['presence'][$resource]);
@ -129,54 +125,64 @@ class Roster
} }
/** /**
*
* Add given contact to roster * Add given contact to roster
* *
* @param string $jid * @param string $jid
* @param string $subscription * @param string $subscription
* @param string $name * @param string $name (optional)
* @param array $groups * @param array $groups (optional)
*/ */
public function addContact($jid, $subscription, $name = '', $groups = array()) public function addContact(string $jid, string $subscription, string $name = '', array $groups = []): void
{ {
$contact = array('jid' => $jid, 'subscription' => $subscription, 'name' => $name, 'groups' => $groups); $contact = ['jid' => $jid, 'subscription' => $subscription, 'name' => $name, 'groups' => $groups];
if ($this->isContact($jid)) { if ($this->isContact($jid)) {
$this->roster_array[$jid]['contact'] = $contact; $this->roster_array[$jid]['contact'] = $contact;
} else { } else {
$this->roster_array[$jid] = array('contact' => $contact); $this->roster_array[$jid] = ['contact' => $contact];
} }
} }
/* /**
* * Get presence
* Return best presence for jid
* *
* @param string $jid * @param string $jid
* @return array best presence for jid
*/ */
public function getPresence(string $jid): array
public function getPresence($jid)
{ {
$split = explode('/', $jid, 2); $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 = [
'resource' => '',
'active' => '',
'priority' => -129, //Priorities can only be -128 = 127
'show' => '',
'status' => ''
];
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;
$current['resource'] = $resource; $current['resource'] = $resource;
} }
} }
return $current; return $current;
} }
return [];
} }
/** /**
*
* Get roster * Get roster
* *
* @return array roster_array
*/ */
public function getRoster() public function getRoster(): array
{ {
return $this->roster_array; return $this->roster_array;
} }

View File

@ -63,14 +63,14 @@ class XMLObj
* *
* @var array * @var array
*/ */
public $attrs = array(); public $attrs = [];
/** /**
* Subs? * Subs?
* *
* @var array * @var array
*/ */
public $subs = array(); public $subs = [];
/** /**
* Node data * Node data
@ -83,11 +83,11 @@ class XMLObj
* Constructor * Constructor
* *
* @param string $name * @param string $name
* @param string $ns * @param string $ns (optional)
* @param array $attrs * @param array $attrs (optional)
* @param string $data * @param string $data (optional)
*/ */
public function __construct($name, $ns = '', $attrs = array(), $data = '') public function __construct(string $name, string $ns = '', array $attrs = [], string $data = '')
{ {
$this->name = strtolower($name); $this->name = strtolower($name);
$this->ns = $ns; $this->ns = $ns;
@ -102,9 +102,9 @@ class XMLObj
/** /**
* Dump this XML Object to output. * Dump this XML Object to output.
* *
* @param integer $depth * @param int $depth (optional)
*/ */
public function printObj($depth = 0) public function printObj(int $depth = 0): void
{ {
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";
@ -116,10 +116,10 @@ class XMLObj
/** /**
* Return this XML Object in xml notation * Return this XML Object in xml notation
* *
* @param string $str * @param string $str (optional)
* @return string * @return string
*/ */
public function toString($str = '') public function toString(string $str = ''): string
{ {
$str .= "<{$this->name} xmlns='{$this->ns}' "; $str .= "<{$this->name} xmlns='{$this->ns}' ";
foreach ($this->attrs as $key => $value) { foreach ($this->attrs as $key => $value) {
@ -141,10 +141,10 @@ class XMLObj
* Has this XML Object the given sub? * Has this XML Object the given sub?
* *
* @param string $name * @param string $name
* @param null $ns * @param string|null $ns
* @return boolean * @return bool
*/ */
public function hasSub($name, $ns = null) public function hasSub(string $name, ?string $ns = null): bool
{ {
foreach ($this->subs as $sub) { foreach ($this->subs as $sub) {
if (($name == "*" or $sub->name == $name) and ($ns == null or $sub->ns == $ns)) { if (($name == "*" or $sub->name == $name) and ($ns == null or $sub->ns == $ns)) {
@ -158,11 +158,11 @@ class XMLObj
* Return a sub * Return a sub
* *
* @param string $name * @param string $name
* @param string $attrs * @param array|null $attrs (optional)
* @param string $ns * @param string|null $ns (optional)
* @return mixed * @return mixed
*/ */
public function sub($name, $attrs = null, $ns = null) public function sub(string $name, ?array $attrs = null, ?string $ns = null)
{ {
#TODO attrs is ignored #TODO attrs is ignored
foreach ($this->subs as $sub) { foreach ($this->subs as $sub) {
@ -170,5 +170,6 @@ class XMLObj
return $sub; return $sub;
} }
} }
return null;
} }
} }

View File

@ -1,5 +1,4 @@
<?php <?php
/** /**
* XMPPHP: The PHP XMPP Library * XMPPHP: The PHP XMPP Library
* Copyright (C) 2008 Nathanael C. Fritz * Copyright (C) 2008 Nathanael C. Fritz
@ -67,7 +66,7 @@ class XMLStream
*/ */
protected $buffer; protected $buffer;
/** /**
* @var integer * @var int
*/ */
protected $xml_depth = 0; protected $xml_depth = 0;
/** /**
@ -87,21 +86,21 @@ class XMLStream
*/ */
protected $stream_end = '</stream>'; protected $stream_end = '</stream>';
/** /**
* @var boolean * @var bool
*/ */
protected $disconnected = false; protected $disconnected = false;
/** /**
* @var boolean * @var bool
*/ */
protected $sent_disconnect = false; protected $sent_disconnect = false;
/** /**
* @var array * @var array
*/ */
protected $ns_map = array(); protected $ns_map = [];
/** /**
* @var array * @var array
*/ */
protected $current_ns = array(); protected $current_ns = [];
/** /**
* @var array * @var array
*/ */
@ -109,21 +108,21 @@ class XMLStream
/** /**
* @var array * @var array
*/ */
protected $nshandlers = array(); protected $nshandlers = [];
/** /**
* @var array * @var array
*/ */
protected $xpathhandlers = array(); protected $xpathhandlers = [];
/** /**
* @var array * @var array
*/ */
protected $idhandlers = array(); protected $idhandlers = [];
/** /**
* @var array * @var array
*/ */
protected $eventhandlers = array(); protected $eventhandlers = [];
/** /**
* @var integer * @var int
*/ */
protected $lastid = 0; protected $lastid = 0;
/** /**
@ -145,21 +144,21 @@ class XMLStream
/** /**
* @var array * @var array
*/ */
protected $until_payload = array(); protected $until_payload = [];
/** /**
* @var Log * @var Log
*/ */
protected $log; protected $log;
/** /**
* @var boolean * @var bool
*/ */
protected $reconnect = true; protected $reconnect = true;
/** /**
* @var boolean * @var bool
*/ */
protected $been_reset = false; protected $been_reset = false;
/** /**
* @var boolean * @var bool
*/ */
protected $is_server; protected $is_server;
/** /**
@ -167,37 +166,42 @@ class XMLStream
*/ */
protected $last_send = 0; protected $last_send = 0;
/** /**
* @var boolean * @var bool
*/ */
protected $use_ssl = false; protected $use_ssl = false;
/** /**
* @var integer * @var int
*/ */
protected $reconnectTimeout = 30; protected $reconnectTimeout = 30;
/** /**
* Constructor * Constructor
* *
* @param string $host * @param string|null $host (optional)
* @param string $port * @param string|null $port (optional)
* @param boolean $printlog * @param bool $print_log (optional)
* @param string $loglevel * @param string $log_level (optional)
* @param boolean $is_server * @param bool $is_server (optional)
*/ */
public function __construct($host = null, $port = null, $printlog = false, $loglevel = null, $is_server = false) public function __construct(
{ ?string $host = null,
?string $port = null,
bool $print_log = false,
?string $log_level = null,
bool $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 Log($printlog, $loglevel); $this->log = new Log($print_log, $log_level);
} }
/** /**
* Setup the XML parser * Setup the XML parser
*/ */
public function setupParser() public function setupParser(): void
{ {
$this->parser = xml_parser_create('UTF-8'); $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_SKIP_WHITE, 1);
@ -210,6 +214,7 @@ class XMLStream
/** /**
* Destructor * Destructor
* Cleanup connection * Cleanup connection
* @throws Exception
*/ */
public function __destruct() public function __destruct()
{ {
@ -220,8 +225,9 @@ class XMLStream
/** /**
* Disconnect from XMPP Host * Disconnect from XMPP Host
* @throws Exception
*/ */
public function disconnect() public function disconnect(): void
{ {
$this->log->log("Disconnecting...", Log::LEVEL_VERBOSE); $this->log->log("Disconnecting...", Log::LEVEL_VERBOSE);
if (false == (bool)$this->socket) { if (false == (bool)$this->socket) {
@ -238,17 +244,16 @@ class XMLStream
* Send to socket * Send to socket
* *
* @param string $msg * @param string $msg
* @param null $timeout * @param int|null $timeout
* @return bool|int * @return bool|int
* @throws Exception * @throws Exception
*/ */
public function send($msg, $timeout = NULL) public function send(string $msg, ?int $timeout = null)
{ {
if (is_null($timeout)) { if (is_null($timeout)) {
$secs = NULL; $secs = null;
$usecs = NULL; $usecs = null;
} else if ($timeout == 0) { } elseif ($timeout == 0) {
$secs = 0; $secs = 0;
$usecs = 0; $usecs = 0;
} else { } else {
@ -257,16 +262,16 @@ class XMLStream
$secs = floor(($maximum - $usecs) / 1000000); $secs = floor(($maximum - $usecs) / 1000000);
} }
$read = array(); $read = [];
$write = array($this->socket); $write = [$this->socket];
$except = array(); $except = [];
$select = @stream_select($read, $write, $except, $secs, $usecs); $select = @stream_select($read, $write, $except, $secs, $usecs);
if ($select === False) { if ($select === false) {
$this->log->log("ERROR sending message; reconnecting."); $this->log->log("ERROR sending message; reconnecting.");
$this->doReconnect(); $this->doReconnect();
# TODO: retry send here // TODO: retry send here
return false; return false;
} elseif ($select > 0) { } elseif ($select > 0) {
$this->log->log("Socket is ready; send it.", Log::LEVEL_VERBOSE); $this->log->log("Socket is ready; send it.", Log::LEVEL_VERBOSE);
@ -277,7 +282,7 @@ class XMLStream
$sentbytes = @fwrite($this->socket, $msg); $sentbytes = @fwrite($this->socket, $msg);
$this->log->log("SENT: " . mb_substr($msg, 0, $sentbytes, '8bit'), Log::LEVEL_VERBOSE); $this->log->log("SENT: " . mb_substr($msg, 0, $sentbytes, '8bit'), Log::LEVEL_VERBOSE);
if ($sentbytes === FALSE) { if ($sentbytes === false) {
$this->log->log("ERROR sending message; reconnecting.", Log::LEVEL_ERROR); $this->log->log("ERROR sending message; reconnecting.", Log::LEVEL_ERROR);
$this->doReconnect(); $this->doReconnect();
return false; return false;
@ -294,7 +299,7 @@ class XMLStream
{ {
if (!$this->is_server) { if (!$this->is_server) {
$this->log->log("Reconnecting ($this->reconnectTimeout)...", Log::LEVEL_WARNING); $this->log->log("Reconnecting ($this->reconnectTimeout)...", Log::LEVEL_WARNING);
$this->connect($this->reconnectTimeout, false, false); $this->connect(false, false, $this->reconnectTimeout);
$this->reset(); $this->reset();
$this->event('reconnect'); $this->event('reconnect');
} }
@ -303,16 +308,15 @@ class XMLStream
/** /**
* Connect to XMPP Host * Connect to XMPP Host
* *
* @param integer $timeout * @param bool $persistent (optional)
* @param boolean $persistent * @param bool $send_init (optional)
* @param boolean $sendinit * @param int $timeout (optional)
* @throws Exception
* @throws Exception * @throws Exception
*/ */
public function connect($timeout = 30, $persistent = false, $sendinit = true) public function connect(bool $persistent = false, bool $send_init = true, int $timeout = 30): void
{ {
$this->sent_disconnect = false; $this->sent_disconnect = false;
$starttime = time(); $start_time = time();
do { do {
$this->disconnected = false; $this->disconnected = false;
@ -322,21 +326,25 @@ class XMLStream
} else { } else {
$conflag = STREAM_CLIENT_CONNECT; $conflag = STREAM_CLIENT_CONNECT;
} }
$conntype = 'tcp'; $conn_type = 'tcp';
if ($this->use_ssl) $conntype = 'ssl'; if ($this->use_ssl) {
$this->log->log("Connecting to $conntype://{$this->host}:{$this->port}"); $conn_type = 'ssl';
$this->socket = @stream_socket_client("$conntype://{$this->host}:{$this->port}", $errno, $errstr, $timeout, $conflag); }
$this->log->log("Connecting to $conn_type://{$this->host}:{$this->port}");
$this->socket = @stream_socket_client("$conn_type://{$this->host}:{$this->port}", $errno, $errstr, $timeout, $conflag);
if (!$this->socket) { if (!$this->socket) {
$this->log->log("Could not connect.", Log::LEVEL_ERROR); $this->log->log("Could not connect.", Log::LEVEL_ERROR);
$this->disconnected = true; $this->disconnected = true;
# Take it easy for a few seconds # Take it easy for a few seconds
sleep(min($timeout, 5)); sleep(min($timeout, 5));
} }
} while (!$this->socket && (time() - $starttime) < $timeout); } while (!$this->socket && (time() - $start_time) < $timeout);
if ($this->socket) { if ($this->socket) {
stream_set_blocking($this->socket, 1); stream_set_blocking($this->socket, 1);
if ($sendinit) $this->send($this->stream_start); if ($send_init) {
$this->send($this->stream_start);
}
} else { } else {
throw new Exception("Could not connect before timeout."); throw new Exception("Could not connect before timeout.");
} }
@ -344,12 +352,13 @@ class XMLStream
/** /**
* Reset connection * Reset connection
* @throws Exception
*/ */
public function reset() public function reset(): void
{ {
$this->xml_depth = 0; $this->xml_depth = 0;
unset($this->xmlobj); unset($this->xmlobj);
$this->xmlobj = array(); $this->xmlobj = [];
$this->setupParser(); $this->setupParser();
if (!$this->is_server) { if (!$this->is_server) {
$this->send($this->stream_start); $this->send($this->stream_start);
@ -361,9 +370,9 @@ class XMLStream
* Event? * Event?
* *
* @param string $name * @param string $name
* @param string $payload * @param array|null $payload
*/ */
public function event($name, $payload = null) public function event(string $name, ?array $payload = null): void
{ {
$this->log->log("EVENT: $name", Log::LEVEL_DEBUG); $this->log->log("EVENT: $name", Log::LEVEL_DEBUG);
foreach ($this->eventhandlers as $handler) { foreach ($this->eventhandlers as $handler) {
@ -377,12 +386,12 @@ class XMLStream
foreach ($this->until as $key => $until) { foreach ($this->until as $key => $until) {
if (is_array($until)) { if (is_array($until)) {
if (in_array($name, $until)) { if (in_array($name, $until)) {
$this->until_payload[$key][] = array($name, $payload); $this->until_payload[$key][] = [$name, $payload];
if (!isset($this->until_count[$key])) { if (!isset($this->until_count[$key])) {
$this->until_count[$key] = 0; $this->until_count[$key] = 0;
} }
$this->until_count[$key] += 1; $this->until_count[$key] += 1;
#$this->until[$key] = false; //$this->until[$key] = false;
} }
} }
} }
@ -392,14 +401,16 @@ class XMLStream
* Process until a specified event or a timeout occurs * Process until a specified event or a timeout occurs
* *
* @param string|array $event * @param string|array $event
* @param integer $timeout * @param int $timeout (optional)
* @return string * @return array
* @throws Exception * @throws Exception
*/ */
public function processUntil($event, $timeout = -1) public function processUntil($event, int $timeout = -1): array
{ {
$start = time(); $start = time();
if (!is_array($event)) $event = array($event); if (!is_array($event)) {
$event = array($event);
}
$this->until[] = $event; $this->until[] = $event;
end($this->until); end($this->until);
$event_key = key($this->until); $event_key = key($this->until);
@ -414,7 +425,7 @@ class XMLStream
unset($this->until_count[$event_key]); unset($this->until_count[$event_key]);
unset($this->until[$event_key]); unset($this->until[$event_key]);
} else { } else {
$payload = array(); $payload = [];
} }
return $payload; return $payload;
} }
@ -428,21 +439,19 @@ class XMLStream
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
private function __process(int $maximum = 5): bool
private function __process($maximum = 5)
{ {
$remaining = $maximum; $remaining = $maximum;
do { do {
$starttime = (microtime(true) * 1000000); $starttime = (microtime(true) * 1000000);
$read = array($this->socket); $read = array($this->socket);
$write = array(); $write = [];
$except = array(); $except = [];
if (is_null($maximum)) { if (is_null($maximum)) {
$secs = NULL; $secs = null;
$usecs = NULL; $usecs = null;
} else if ($maximum == 0) { } elseif ($maximum == 0) {
$secs = 0; $secs = 0;
$usecs = 0; $usecs = 0;
} else { } else {
@ -456,10 +465,10 @@ class XMLStream
$this->doReconnect(); $this->doReconnect();
} else { } else {
fclose($this->socket); fclose($this->socket);
$this->socket = NULL; $this->socket = null;
return false; return false;
} }
} else if ($updated > 0) { } elseif ($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) {
@ -467,14 +476,14 @@ class XMLStream
$this->doReconnect(); $this->doReconnect();
} else { } else {
fclose($this->socket); fclose($this->socket);
$this->socket = NULL; $this->socket = null;
return false; return false;
} }
} }
$this->log->log("RECV: $buff", Log::LEVEL_VERBOSE); $this->log->log("RECV: $buff", Log::LEVEL_VERBOSE);
xml_parse($this->parser, $buff, false); xml_parse($this->parser, $buff, false);
} // Otherwise, } // 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;
@ -488,7 +497,7 @@ class XMLStream
* *
* @return Log * @return Log
*/ */
public function getLog() public function getLog(): Log
{ {
return $this->log; return $this->log;
} }
@ -496,9 +505,9 @@ class XMLStream
/** /**
* Get next ID * Get next ID
* *
* @return integer * @return int
*/ */
public function getId() public function getId(): int
{ {
$this->lastid++; $this->lastid++;
return $this->lastid; return $this->lastid;
@ -508,7 +517,7 @@ class XMLStream
* Set SSL * Set SSL
* @param bool $use * @param bool $use
*/ */
public function useSSL($use = true) public function useSSL(bool $use = true): void
{ {
$this->use_ssl = $use; $this->use_ssl = $use;
} }
@ -516,13 +525,13 @@ class XMLStream
/** /**
* Add ID Handler * Add ID Handler
* *
* @param integer $id * @param int $id
* @param string $pointer * @param string $pointer
* @param string $obj * @param string|null $obj
*/ */
public function addIdHandler($id, $pointer, $obj = null) public function addIdHandler(int $id, string $pointer, ?string $obj = null): void
{ {
$this->idhandlers[$id] = array($pointer, $obj); $this->idhandlers[$id] = [$pointer, $obj];
} }
/** /**
@ -531,54 +540,58 @@ class XMLStream
* @param string $name * @param string $name
* @param string $ns * @param string $ns
* @param string $pointer * @param string $pointer
* @param string $obj * @param string|null $obj
* @param integer $depth * @param int $depth
*/ *
public function addHandler($name, $ns, $pointer, $obj = null, $depth = 1) * public function addHandler(string $name, string $ns, string $pointer, ?string $obj = null, int $depth = 1): void
{ * {
#TODO deprication warning * #TODO deprication warning
$this->nshandlers[] = array($name, $ns, $pointer, $obj, $depth); * $this->nshandlers[] = [$name, $ns, $pointer, $obj, $depth];
} * }*/
/** /**
* Add XPath Handler * Add XPath Handler
* *
* @param string $xpath * @param string $xpath
* @param string $pointer * @param string $pointer
* @param * @param string|null $obj
*/ */
public function addXPathHandler($xpath, $pointer, $obj = null) public function addXPathHandler(string $xpath, string $pointer, ?string $obj = null): void
{ {
if (preg_match_all("/\(?{[^\}]+}\)?(\/?)[^\/]+/", $xpath, $regs)) { if (preg_match_all("/\(?{[^\}]+}\)?(\/?)[^\/]+/", $xpath, $regs)) {
$ns_tags = $regs[0]; $ns_tags = $regs[0];
} else { } else {
$ns_tags = array($xpath); $ns_tags = [$xpath];
} }
$xpath_array = [];
foreach ($ns_tags as $ns_tag) { foreach ($ns_tags as $ns_tag) {
list($l, $r) = explode("}", $ns_tag); list($l, $r) = explode("}", $ns_tag);
if ($r != null) { if ($r != null) {
$xpart = array(substr($l, 1), $r); $xpart = [substr($l, 1), $r];
} else { } else {
$xpart = array(null, $l); $xpart = [null, $l];
} }
$xpath_array[] = $xpart; $xpath_array[] = $xpart;
} }
$this->xpathhandlers[] = array($xpath_array, $pointer, $obj); $this->xpathhandlers[] = [$xpath_array, $pointer, $obj];
} }
/** /**
* Add Event Handler * Add Event Handler
* *
* @param $name * @param string $name
* @param string $pointer * @param string $pointer
* @param string $obj * @param string $obj
*/ */
public function addEventHandler($name, $pointer, $obj) public function addEventHandler(string $name, string $pointer, string $obj)
{ {
$this->eventhandlers[] = array($name, $pointer, $obj); $this->eventhandlers[] = [$name, $pointer, $obj];
} }
public function setReconnectTimeout($timeout) /**
* @param int $timeout
*/
public function setReconnectTimeout(int $timeout): void
{ {
$this->reconnectTimeout = $timeout; $this->reconnectTimeout = $timeout;
} }
@ -586,9 +599,9 @@ class XMLStream
/** /**
* Are we are disconnected? * Are we are disconnected?
* *
* @return boolean * @return bool
*/ */
public function isDisconnected() public function isDisconnected(): bool
{ {
return $this->disconnected; return $this->disconnected;
} }
@ -596,10 +609,11 @@ class XMLStream
/** /**
* Process * Process
* *
* @throws Exception
*/ */
public function process() public function process(): void
{ {
$this->__process(NULL); $this->__process(null);
} }
/** /**
@ -609,10 +623,10 @@ class XMLStream
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
public function processTime($timeout = NULL) public function processTime($timeout = null): string
{ {
if (is_null($timeout)) { if (is_null($timeout)) {
return $this->__process(NULL); return $this->__process(null);
} else { } else {
return $this->__process($timeout * 1000000); return $this->__process($timeout * 1000000);
} }
@ -621,21 +635,21 @@ class XMLStream
/** /**
* Obsolete? * Obsolete?
* @param $socket * @param $socket
*/ *
public function Xapply_socket($socket) * public function Xapply_socket($socket)
{ * {
$this->socket = $socket; * $this->socket = $socket;
} * }*/
/** /**
* XML start callback * XML start callback
* *
* @param resource $parser * @param string resource $parser
* @param string $name * @param string $name
* @param $attr * @param array $attr
* @see xml_set_element_handler * @see xml_set_element_handler
*/ */
public function startXML($parser, $name, $attr) public function startXML(string $parser, string $name, array $attr): void
{ {
if ($this->been_reset) { if ($this->been_reset) {
$this->been_reset = false; $this->been_reset = false;
@ -646,7 +660,9 @@ class XMLStream
$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) {
@ -671,13 +687,13 @@ class XMLStream
/** /**
* XML end callback * XML end callback
* *
* @param resource $parser * @param string resource $parser
* @param string $name * @param string $name
* @throws Exception * @throws Exception
* @see xml_set_element_handler * @see xml_set_element_handler
* *
*/ */
public function endXML($parser, $name) public function endXML(string $parser, string $name): void
{ {
#$this->log->log("Ending $name", Log::LEVEL_DEBUG); #$this->log->log("Ending $name", Log::LEVEL_DEBUG);
#print "$name\n"; #print "$name\n";
@ -689,6 +705,7 @@ class XMLStream
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
$searchxml = null;
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];
@ -703,7 +720,9 @@ class XMLStream
} }
} }
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]}", 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]);
} }
@ -717,14 +736,18 @@ class XMLStream
$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]}", 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]);
@ -757,12 +780,12 @@ class XMLStream
/** /**
* XML character callback * XML character callback
* @param resource $parser * @param string resource $parser
* @param string $data * @param string $data
* @see xml_set_character_data_handler * @see xml_set_character_data_handler
* *
*/ */
public function charXML($parser, $data) public function charXML(string $parser, string $data): void
{ {
if (array_key_exists($this->xml_depth, $this->xmlobj)) { if (array_key_exists($this->xml_depth, $this->xmlobj)) {
$this->xmlobj[$this->xml_depth]->data .= $data; $this->xmlobj[$this->xml_depth]->data .= $data;
@ -771,8 +794,10 @@ class XMLStream
/** /**
* Read from socket * Read from socket
* @return bool Did read
* @throws Exception
*/ */
public function read() public function read(): bool
{ {
$buff = @fread($this->socket, 1024); $buff = @fread($this->socket, 1024);
if (!$buff) { if (!$buff) {
@ -785,19 +810,20 @@ class XMLStream
} }
$this->log->log("RECV: $buff", Log::LEVEL_VERBOSE); $this->log->log("RECV: $buff", Log::LEVEL_VERBOSE);
xml_parse($this->parser, $buff, false); xml_parse($this->parser, $buff, false);
return true;
} }
public function time() public function time(): float
{ {
list($usec, $sec) = explode(" ", microtime()); list($usec, $sec) = explode(" ", microtime());
return (float)$sec + (float)$usec; return (float)$sec + (float)$usec;
} }
public function readyToProcess() public function readyToProcess(): bool
{ {
$read = array($this->socket); $read = array($this->socket);
$write = array(); $write = [];
$except = array(); $except = [];
$updated = @stream_select($read, $write, $except, 0); $updated = @stream_select($read, $write, $except, 0);
return (($updated !== false) && ($updated > 0)); return (($updated !== false) && ($updated > 0));
} }

View File

@ -1,5 +1,4 @@
<?php <?php
/** /**
* XMPPHP: The PHP XMPP Library * XMPPHP: The PHP XMPP Library
* Copyright (C) 2008 Nathanael C. Fritz * Copyright (C) 2008 Nathanael C. Fritz
@ -59,7 +58,7 @@ class XMPP extends XMLStream
*/ */
public $user; public $user;
/** /**
* @var boolean * @var bool
*/ */
public $track_presence = true; public $track_presence = true;
/** /**
@ -83,16 +82,16 @@ class XMPP extends XMLStream
*/ */
protected $basejid; protected $basejid;
/** /**
* @var boolean * @var bool
*/ */
protected $authed = false; protected $authed = false;
protected $session_started = false; protected $session_started = false;
/** /**
* @var boolean * @var bool
*/ */
protected $auto_subscribe = false; protected $auto_subscribe = false;
/** /**
* @var boolean * @var bool
*/ */
protected $use_encryption = true; protected $use_encryption = true;
@ -105,12 +104,20 @@ class XMPP extends XMLStream
* @param string $password * @param string $password
* @param string $resource * @param string $resource
* @param string $server * @param string $server
* @param boolean $printlog * @param bool $print_log
* @param string $loglevel * @param string $log_level
*/ */
public function __construct($host, $port, $user, $password, $resource, $server = null, $printlog = false, $loglevel = null) public function __construct(
{ string $host,
parent::__construct($host, $port, $printlog, $loglevel); int $port,
string $user,
string $password,
string $resource,
?string $server = null,
bool $print_log = false,
?string $log_level = null
) {
parent::__construct($host, $port, $print_log, $log_level);
$this->user = $user; $this->user = $user;
$this->password = $password; $this->password = $password;
@ -140,9 +147,9 @@ class XMPP extends XMLStream
/** /**
* Turn encryption on/ff * Turn encryption on/ff
* *
* @param boolean $useEncryption * @param bool $useEncryption (optional)
*/ */
public function useEncryption($useEncryption = true) public function useEncryption(bool $useEncryption = true): void
{ {
$this->use_encryption = $useEncryption; $this->use_encryption = $useEncryption;
} }
@ -150,9 +157,9 @@ class XMPP extends XMLStream
/** /**
* Turn on auto-authorization of subscription requests. * Turn on auto-authorization of subscription requests.
* *
* @param boolean $autoSubscribe * @param bool $autoSubscribe (optional)
*/ */
public function autoSubscribe($autoSubscribe = true) public function autoSubscribe(bool $autoSubscribe = true): void
{ {
$this->auto_subscribe = $autoSubscribe; $this->auto_subscribe = $autoSubscribe;
} }
@ -162,12 +169,12 @@ class XMPP extends XMLStream
* *
* @param string $to * @param string $to
* @param string $body * @param string $body
* @param string $type * @param string $type (optional)
* @param string $subject * @param string|null $subject (optional)
* @param null $payload * @param string|null $payload (optional)
* @throws Exception * @throws Exception
*/ */
public function message($to, $body, $type = 'chat', $subject = null, $payload = null) public function message(string $to, string $body, string $type = 'chat', ?string $subject = null, ?string $payload = null): void
{ {
if ($this->disconnected) { if ($this->disconnected) {
throw new Exception('You need to connect first'); throw new Exception('You need to connect first');
@ -177,13 +184,13 @@ class XMPP extends XMLStream
$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>' : ''; $subject = ($subject) ? '<subject>' . $subject . '</subject>' : '';
$payload = ($payload) ? $payload : ''; $payload = ($payload) ? $payload : '';
$sprintf = '<message from="%s" to="%s" type="%s">%s<body>%s</body>%s</message>'; $sprintf = '<message from="%s" to="%s" type="%s">%s<body>%s</body>%s</message>';
$output = sprintf($sprintf, $this->fulljid, $to, $type, $subject, $body, $payload); $output = sprintf($sprintf, $this->fulljid, $to, $type, $subject, $body, $payload);
$this->send($output); $this->send($output);
} }
@ -197,7 +204,7 @@ class XMPP extends XMLStream
* @param null $priority * @param null $priority
* @throws Exception * @throws Exception
*/ */
public function presence($status = null, $show = 'available', $to = null, $type = 'available', $priority = null) public function presence($status = null, $show = 'available', $to = null, $type = 'available', $priority = null): void
{ {
if ($this->disconnected) { if ($this->disconnected) {
throw new Exception('You need to connect first'); throw new Exception('You need to connect first');
@ -242,8 +249,9 @@ class XMPP extends XMLStream
* Send Auth request * Send Auth request
* *
* @param string $jid * @param string $jid
* @throws Exception
*/ */
public function subscribe($jid) public function subscribe(string $jid): void
{ {
$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}' />");
@ -254,7 +262,7 @@ class XMPP extends XMLStream
* *
* @param string $xml * @param string $xml
*/ */
public function message_handler($xml) public function message_handler(string $xml): void
{ {
if (isset($xml->attrs['type'])) { if (isset($xml->attrs['type'])) {
$payload['type'] = $xml->attrs['type']; $payload['type'] = $xml->attrs['type'];
@ -273,8 +281,9 @@ class XMPP extends XMLStream
* Presence handler * Presence handler
* *
* @param string $xml * @param string $xml
* @throws Exception
*/ */
public function presence_handler($xml) public function presence_handler(string $xml): void
{ {
$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'];
@ -302,8 +311,9 @@ class XMPP extends XMLStream
/** /**
* Retrieves the roster * Retrieves the roster
* *
* @throws Exception
*/ */
public function getRoster() public function getRoster(): void
{ {
$id = $this->getID(); $id = $this->getID();
$this->send("<iq xmlns='jabber:client' type='get' id='$id'><query xmlns='jabber:iq:roster' /></iq>"); $this->send("<iq xmlns='jabber:client' type='get' id='$id'><query xmlns='jabber:iq:roster' /></iq>");
@ -311,9 +321,10 @@ class XMPP extends XMLStream
/** /**
* Retrieves the vcard * Retrieves the vcard
* @param null $jid * @param string|null $jid
* @throws Exception
*/ */
public function getVCard($jid = null) public function getVCard(?string $jid = null): void
{ {
$id = $this->getID(); $id = $this->getID();
$this->addIdHandler($id, 'vcard_get_handler'); $this->addIdHandler($id, 'vcard_get_handler');
@ -328,8 +339,9 @@ class XMPP extends XMLStream
* Features handler * Features handler
* *
* @param string $xml * @param string $xml
* @throws Exception
*/ */
protected function features_handler($xml) protected function features_handler(string $xml): void
{ {
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>");
@ -351,8 +363,9 @@ class XMPP extends XMLStream
* SASL success handler * SASL success handler
* *
* @param string $xml * @param string $xml
* @throws Exception
*/ */
protected function sasl_success_handler($xml) protected function sasl_success_handler(string $xml): void
{ {
$this->log->log("Auth success!"); $this->log->log("Auth success!");
$this->authed = true; $this->authed = true;
@ -365,7 +378,7 @@ class XMPP extends XMLStream
* @param string $xml * @param string $xml
* @throws Exception * @throws Exception
*/ */
protected function sasl_failure_handler($xml) protected function sasl_failure_handler(string $xml): void
{ {
$this->log->log("Auth failed!", Log::LEVEL_ERROR); $this->log->log("Auth failed!", Log::LEVEL_ERROR);
$this->disconnect(); $this->disconnect();
@ -377,8 +390,9 @@ class XMPP extends XMLStream
* Resource bind handler * Resource bind handler
* *
* @param string $xml * @param string $xml
* @throws Exception
*/ */
protected function resource_bind_handler($xml) protected function resource_bind_handler(string $xml): void
{ {
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);
@ -396,13 +410,15 @@ class XMPP extends XMLStream
* 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
* @throws Exception
*/ */
protected function roster_iq_handler($xml) protected function roster_iq_handler(string $xml): void
{ {
$status = "result"; $status = "result";
$xmlroster = $xml->sub('query'); $xmlroster = $xml->sub('query');
$contacts = [];
foreach ($xmlroster->subs as $item) { foreach ($xmlroster->subs as $item) {
$groups = array(); $groups = [];
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
@ -412,7 +428,7 @@ class XMPP extends XMLStream
$groups[] = $subitem->data; $groups[] = $subitem->data;
} }
} }
$contacts[] = array($jid, $subscription, $name, $groups); //Store for action if no errors happen $contacts[] = [$jid, $subscription, $name, $groups]; //Store for action if no errors happen
} else { } else {
$status = "error"; $status = "error";
} }
@ -432,7 +448,7 @@ class XMPP extends XMLStream
* *
* @param string $xml * @param string $xml
*/ */
protected function session_start_handler($xml) protected function session_start_handler(string $xml): void
{ {
$this->log->log("Session started"); $this->log->log("Session started");
$this->session_started = true; $this->session_started = true;
@ -443,8 +459,9 @@ class XMPP extends XMLStream
* TLS proceed handler * TLS proceed handler
* *
* @param string $xml * @param string $xml
* @throws Exception
*/ */
protected function tls_proceed_handler($xml) protected function tls_proceed_handler(string $xml): void
{ {
$this->log->log("Starting TLS encryption"); $this->log->log("Starting TLS encryption");
stream_socket_enable_crypto($this->socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); stream_socket_enable_crypto($this->socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
@ -456,14 +473,14 @@ class XMPP extends XMLStream
* *
* @param XMLObj $xml * @param XMLObj $xml
*/ */
protected function vcard_get_handler($xml) protected function vcard_get_handler(XMLObj $xml): void
{ {
$vcard_array = array(); $vcard_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
foreach ($vcard->subs as $sub) { foreach ($vcard->subs as $sub) {
if ($sub->subs) { if ($sub->subs) {
$vcard_array[$sub->name] = array(); $vcard_array[$sub->name] = [];
foreach ($sub->subs as $sub_child) { foreach ($sub->subs as $sub_child) {
$vcard_array[$sub->name][$sub_child->name] = $sub_child->data; $vcard_array[$sub->name][$sub_child->name] = $sub_child->data;
} }

View File

@ -1,49 +1,59 @@
{ {
"name": "diogocomposer/xmpphp", "name": "diogocomposer/xmpphp",
"description": "XMPP PHP Library", "description": "XMPP PHP Library",
"type": "library", "type": "library",
"keywords": ["jabber", "xmpphp", "xmpp"], "keywords": [
"license": "GPL-2.0+", "jabber",
"authors": [ "xmpphp",
{ "xmpp"
"name": "Nathan Fritz", ],
"email": "fritzy@netflint.net" "license": "GPL-2.0+",
}, "authors": [
{ {
"name": "Stephan Wentz", "name": "Nathan Fritz",
"email": "stephan@wentz.it" "email": "fritzy@netflint.net"
},
{
"name": "Christian Weiske",
"email": "cweiske@cweiske.de"
},
{
"name": "Vito Tafuni",
"email": "vitotafuni@gmail.com"
},
{
"name": "Ivan Borzenkov",
"email": "ivan.borzenkov@gmail.com"
},
{
"name": "bandroidx",
"email": "bandroidx@gmail.com"
},
{
"name": "BirknerAlex",
"email": "alex.birkner@gmail.com"
},
{
"name": "Diogo Cordeiro",
"email": "diogo@fc.up.pt"
}
],
"autoload": {
"psr-4": { "XMPPHP\\": "XMPPHP" }
}, },
"require": { {
"php": "^7.3.0", "name": "Stephan Wentz",
"ext-mbstring": "*", "email": "stephan@wentz.it"
"ext-xml": "*" },
{
"name": "Christian Weiske",
"email": "cweiske@cweiske.de"
},
{
"name": "Vito Tafuni",
"email": "vitotafuni@gmail.com"
},
{
"name": "Ivan Borzenkov",
"email": "ivan.borzenkov@gmail.com"
},
{
"name": "bandroidx",
"email": "bandroidx@gmail.com"
},
{
"name": "BirknerAlex",
"email": "alex.birkner@gmail.com"
},
{
"name": "Diogo Cordeiro",
"email": "diogo@fc.up.pt"
} }
],
"autoload": {
"psr-4": {
"XMPPHP\\": "XMPPHP"
}
},
"require": {
"php": "^7.3.0",
"ext-mbstring": "*",
"ext-xml": "*",
"ext-simplexml": "*",
"ext-dom": "*",
"ext-curl": "*",
"ext-openssl": "*"
}
} }

View File

@ -1,5 +1,4 @@
<?php <?php
/** /**
* @file: XMPPHP Cli example * @file: XMPPHP Cli example
* *
@ -19,18 +18,16 @@
* LEVEL_VERBOSE = 4; * LEVEL_VERBOSE = 4;
*/ */
require '../vendor/autoload.php'; $conf = [
'server' => 'im.server.tld',
$conf = array( 'port' => 5222,
'server' => 'talk.google.com', 'username' => 'username',
'port' => 5222, 'password' => 'password',
'username' => 'username', 'proto' => 'xmpphp',
'password' => 'password', 'domain' => 'domain.net',
'proto' => 'xmpphp', 'printlog' => true,
'domain' => 'gmail.com', 'loglevel' => XMPPHP\Log::LEVEL_VERBOSE,
'printlog' => true, ];
'loglevel' => XMPPHP\Log::LEVEL_VERBOSE,
);
// Easy and simple for access to variables with their names // Easy and simple for access to variables with their names
extract($conf); extract($conf);
@ -38,13 +35,13 @@ extract($conf);
$conn = new XMPPHP\XMPP($server, $port, $username, $password, $proto, $domain, $printlog, $loglevel); $conn = new XMPPHP\XMPP($server, $port, $username, $password, $proto, $domain, $printlog, $loglevel);
$conn->autoSubscribe(); $conn->autoSubscribe();
$vcard_request = array(); $vcard_request = [];
try { try {
$conn->connect(); $conn->connect();
while (!$conn->isDisconnected()) { while (!$conn->isDisconnected()) {
$events = array('message', 'presence', 'end_stream', 'session_start', 'vcard'); $events = ['message', 'presence', 'end_stream', 'session_start', 'vcard'];
$payloads = $conn->processUntil($events); $payloads = $conn->processUntil($events);
foreach ($payloads as $result) { foreach ($payloads as $result) {
@ -56,84 +53,84 @@ try {
switch ($event) { switch ($event) {
case 'message': case 'message':
if (!$body) { if (!$body) {
break; break;
} }
echo str_repeat('-', 80); echo str_repeat('-', 80);
echo "Message from: $from"; echo "Message from: $from";
if (isset($subject)) { if (isset($subject)) {
echo "Subject: $subject"; echo "Subject: $subject";
} }
echo $body; echo $body;
echo str_repeat('-', 80); echo str_repeat('-', 80);
$cmd = explode(' ', $body); $cmd = explode(' ', $body);
$body = "Mi no entender! '$body'"; $body = "Mi no entender! '$body'";
$conn->message($from, $body, $type); $conn->message($from, $body, $type);
if (isset($cmd[0])) { if (isset($cmd[0])) {
if ($cmd[0] == 'quit') { if ($cmd[0] == 'quit') {
$conn->disconnect(); $conn->disconnect();
} }
if ($cmd[0] == 'break') { if ($cmd[0] == 'break') {
$conn->send('</end>'); $conn->send('</end>');
} }
if ($cmd[0] == 'vcard') { if ($cmd[0] == 'vcard') {
if (!isset($cmd[1])) { if (!isset($cmd[1])) {
$cmd[1] = $conn->user; $cmd[1] = $conn->user;
} }
// Take a note which user requested which vcard // Take a note which user requested which vcard
$vcard_request[$from] = $cmd[1]; $vcard_request[$from] = $cmd[1];
// Request the vcard // Request the vcard
$conn->getVCard($cmd[1]); $conn->getVCard($cmd[1]);
} }
} }
break; break;
case 'presence': case 'presence':
echo "Presence: $from [$show] $status\n"; echo "Presence: $from [$show] $status\n";
break; break;
case 'session_start': case 'session_start':
echo "Session start\n"; echo "Session start\n";
$conn->getRoster(); $conn->getRoster();
$conn->presence('Quasar!'); $conn->presence('Quasar!');
break; break;
case 'vcard': case 'vcard':
$deliver = array_keys($vcard_request, $from); $deliver = array_keys($vcard_request, $from);
$msg = ''; $msg = '';
foreach ($data as $key => $item) { foreach ($data as $key => $item) {
$msg .= $key . ': '; $msg .= $key . ': ';
if (is_array($item)) { if (is_array($item)) {
$msg .= "\n"; $msg .= "\n";
foreach ($item as $subkey => $subitem) { foreach ($item as $subkey => $subitem) {
$msg .= ' ' . $subkey . ':' . $subitem . "\n"; $msg .= ' ' . $subkey . ':' . $subitem . "\n";
} }
} else { } else {
$msg .= $item . "\n"; $msg .= $item . "\n";
} }
} }
foreach ($deliver as $sendjid) { foreach ($deliver as $sendjid) {
unset($vcard_request[$sendjid]); unset($vcard_request[$sendjid]);
$conn->message($sendjid, $msg, 'chat'); $conn->message($sendjid, $msg, 'chat');
} }
break; break;
} }
} }
} }
} catch (XMPPHP\Exception $e) { } catch (XMPPHP\Exception $e) {

View File

@ -1,5 +1,4 @@
<?php <?php
/** /**
* @file: XMPPHP Cli example BOSH * @file: XMPPHP Cli example BOSH
* *
@ -19,30 +18,28 @@
* LEVEL_VERBOSE = 4; * LEVEL_VERBOSE = 4;
*/ */
require '../vendor/autoload.php'; $conf = [
'host' => 'server.tld',
$conf = array( 'port' => 5280,
'server' => 'server.tld', 'username' => 'username',
'port' => 5280, 'password' => 'password',
'username' => 'username', 'resource' => 'xmpphp',
'password' => 'password', 'server' => 'http://server.tld:5280/xmpp-httpbind',
'proto' => 'xmpphp', 'print_log' => true,
'domain' => 'server.tld', 'log_level' => XMPPHP\Log::LEVEL_VERBOSE,
'printlog' => true, ];
'loglevel' => XMPPHP\Log::LEVEL_VERBOSE,
);
// Easy and simple for access to variables with their names // Easy and simple for access to variables with their names
extract($conf); extract($conf);
$conn = new XMPPHP\BOSH($server, $port, $username, $password, $proto, $domain, $printlog, $loglevel); $conn = new XMPPHP\BOSH($host, $port, $username, $password, $proto, $server, $print_log, $log_level);
$conn->autoSubscribe(); $conn->autoSubscribe();
try { try {
$conn->connect('http://server.tld:5280/xmpp-httpbind'); $conn->connect();
while (!$conn->isDisconnected()) { while (!$conn->isDisconnected()) {
$events = array('message', 'presence', 'end_stream', 'session_start'); $events = ['message', 'presence', 'end_stream', 'session_start'];
$payloads = $conn->processUntil($events); $payloads = $conn->processUntil($events);
foreach ($payloads as $result) { foreach ($payloads as $result) {
@ -54,49 +51,49 @@ try {
switch ($event) { switch ($event) {
case 'message': case 'message':
if (!$body) { if (!$body) {
break; break;
} }
echo str_repeat('-', 80); echo str_repeat('-', 80);
echo "Message from: $from"; echo "Message from: $from";
if (isset($subject)) { if (isset($subject)) {
echo "Subject: $subject"; echo "Subject: $subject";
} }
echo $body; echo $body;
echo str_repeat('-', 80); echo str_repeat('-', 80);
$cmd = explode(' ', $body); $cmd = explode(' ', $body);
$body = "Mi no entender! '$body'"; $body = "Mi no entender! '$body'";
$conn->message($from, $body, $type); $conn->message($from, $body, $type);
if (isset($cmd[0])) { if (isset($cmd[0])) {
if ($cmd[0] == 'quit') { if ($cmd[0] == 'quit') {
$conn->disconnect(); $conn->disconnect();
} }
if ($cmd[0] == 'break') { if ($cmd[0] == 'break') {
$conn->send('</end>'); $conn->send('</end>');
} }
} }
break; break;
case 'presence': case 'presence':
echo "Presence: $from [$show] $status\n"; echo "Presence: $from [$show] $status\n";
break; break;
case 'session_start': case 'session_start':
echo "Session start\n"; echo "Session start\n";
$conn->getRoster(); $conn->getRoster();
$conn->presence('Quasar!'); $conn->presence('Quasar!');
break; break;
} }
} }
} }
} catch (XMPPHP\Exception $e) { } catch (XMPPHP\Exception $e) {

View File

@ -1,5 +1,4 @@
<?php <?php
/** /**
* @file: XMPPHP Send message example * @file: XMPPHP Send message example
* *
@ -18,18 +17,16 @@
* LEVEL_VERBOSE = 4; * LEVEL_VERBOSE = 4;
*/ */
require_once __DIR__.'/../vendor/autoload.php'; $conf = [
'server' => 'jabber.domain.com',
$conf = array( 'port' => 5222,
'server' => 'talk.google.com', 'username' => 'username',
'port' => 5222, 'password' => 'password',
'username' => 'username', 'proto' => 'xmpphp',
'password' => 'password', 'domain' => 'domain.net',
'proto' => 'xmpphp', 'printlog' => true,
'domain' => 'gmail.com', 'loglevel' => XMPPHP\Log::LEVEL_VERBOSE,
'printlog' => true, ];
'loglevel' => XMPPHP\Log::LEVEL_VERBOSE,
);
// Easy and simple for access to variables with their names // Easy and simple for access to variables with their names
extract($conf); extract($conf);

View File

@ -1,5 +1,4 @@
<?php <?php
/** /**
* @file: XMPPHP Cli example * @file: XMPPHP Cli example
* *
@ -22,18 +21,16 @@
session_start(); session_start();
header('content-type', 'plain/text'); header('content-type', 'plain/text');
require '../vendor/autoload.php'; $conf = [
'server' => 'talk.google.com',
$conf = array( 'port' => 5222,
'server' => 'talk.google.com', 'username' => 'username',
'port' => 5222, 'password' => 'password',
'username' => 'username', 'proto' => 'xmpphp',
'password' => 'password', 'domain' => 'gmail.com',
'proto' => 'xmpphp', 'printlog' => true,
'domain' => 'gmail.com', 'loglevel' => XMPPHP\Log::LEVEL_VERBOSE,
'printlog' => true, ];
'loglevel' => XMPPHP\Log::LEVEL_VERBOSE,
);
// Easy and simple for access to variables with their names // Easy and simple for access to variables with their names
extract($conf); extract($conf);
@ -48,11 +45,11 @@ try {
flush(); flush();
} }
} else { } else {
$_SESSION['messages'] = array(); $_SESSION['messages'] = [];
} }
$conn->connect('http://server.tld:5280/xmpp-httpbind', 1, true); $conn->connect();
$events = array('message', 'presence', 'end_stream', 'session_start', 'vcard'); $events = ['message', 'presence', 'end_stream', 'session_start', 'vcard'];
$payloads = $conn->processUntil($events); $payloads = $conn->processUntil($events);
foreach ($payloads as $result) { foreach ($payloads as $result) {
@ -64,49 +61,49 @@ try {
switch ($event) { switch ($event) {
case 'message': case 'message':
if (!$body) { if (!$body) {
break; break;
}
$cmd = explode(' ', $body);
$msg = str_repeat('-', 80);
$msg .= "\nMessage from: $from\n";
if (isset($subject)) {
$msg .= "Subject: $subject\n";
}
$msg .= $body . "\n";
$msg .= str_repeat('-', 80);
echo "<pre>$msg</pre>";
if (isset($cmd[0])) {
if ($cmd[0] == 'quit') {
$conn->disconnect();
}
if ($cmd[0] == 'break') {
$conn->send('</end>');
}
}
$_SESSION['messages'][] = $msg;
flush();
break;
case 'presence':
echo "Presence: $from [$show] $status\n";
break;
case 'session_start':
echo "Session start\n";
$conn->getRoster();
$conn->presence('Quasar!');
break;
} }
$cmd = explode(' ', $body);
$msg = str_repeat('-', 80);
$msg .= "\nMessage from: $from\n";
if (isset($subject)) {
$msg .= "Subject: $subject\n";
}
$msg .= $body . "\n";
$msg .= str_repeat('-', 80);
echo "<pre>$msg</pre>";
if (isset($cmd[0])) {
if ($cmd[0] == 'quit') {
$conn->disconnect();
}
if ($cmd[0] == 'break') {
$conn->send('</end>');
}
}
$_SESSION['messages'][] = $msg;
flush();
break;
case 'presence':
echo "Presence: $from [$show] $status\n";
break;
case 'session_start':
echo "Session start\n";
$conn->getRoster();
$conn->presence('Quasar!');
break;
}
} }
} catch (XMPPHP\Exception $e) { } catch (XMPPHP\Exception $e) {
die($e->getMessage()); die($e->getMessage());

View File

@ -44,35 +44,35 @@ class XMPPHP_XMLObjTest extends PHPUnit_Framework_TestCase
{ {
public function testToStringNameNamespace() public function testToStringNameNamespace()
{ {
$xmlobj = new XMPPHP_XMLObj('testname', 'testNameSpace'); $xmlobj = new XMPPHP_XMLObj('testname', 'testNameSpace');
$expected = '<testname xmlns="testNameSpace"></testname>'; $expected = '<testname xmlns="testNameSpace"></testname>';
$result = $xmlobj->toString(); $result = $xmlobj->toString();
$this->assertSame($expected, $result); $this->assertSame($expected, $result);
} }
public function testToStringNameNamespaceAttr() public function testToStringNameNamespaceAttr()
{ {
$xmlobj = new XMPPHP_XMLObj('testName', 'testNameSpace', array('attr1' => 'valA', 'attr2' => 'valB')); $xmlobj = new XMPPHP_XMLObj('testName', 'testNameSpace', ['attr1' => 'valA', 'attr2' => 'valB']);
$expected = '<testname xmlns="testNameSpace" attr1="valA" attr2="valB"></testname>'; $expected = '<testname xmlns="testNameSpace" attr1="valA" attr2="valB"></testname>';
$result = $xmlobj->toString(); $result = $xmlobj->toString();
$this->assertSame($expected, $result); $this->assertSame($expected, $result);
} }
public function testToStringNameNamespaceData() public function testToStringNameNamespaceData()
{ {
$xmlobj = new XMPPHP_XMLObj('testName', 'testNameSpace', array(), 'I am test data'); $xmlobj = new XMPPHP_XMLObj('testName', 'testNameSpace', [], 'I am test data');
$expected = '<testname xmlns="testNameSpace">I am test data</testname>'; $expected = '<testname xmlns="testNameSpace">I am test data</testname>';
$result = $xmlobj->toString(); $result = $xmlobj->toString();
$this->assertSame($expected, $result); $this->assertSame($expected, $result);
} }
public function testToStringNameNamespaceSub() public function testToStringNameNamespaceSub()
{ {
$xmlobj = new XMPPHP_XMLObj('testName', 'testNameSpace'); $xmlobj = new XMPPHP_XMLObj('testName', 'testNameSpace');
$sub1 = new XMPPHP_XMLObj('subName', 'subNameSpace'); $sub1 = new XMPPHP_XMLObj('subName', 'subNameSpace');
$xmlobj->subs = array($sub1); $xmlobj->subs = [$sub1];
$expected = '<testname xmlns="testNameSpace"><subname xmlns="subNameSpace"></subname></testname>'; $expected = '<testname xmlns="testNameSpace"><subname xmlns="subNameSpace"></subname></testname>';
$result = $xmlobj->toString(); $result = $xmlobj->toString();
$this->assertSame($expected, $result); $this->assertSame($expected, $result);
} }
} }

View File

@ -55,7 +55,7 @@ class XMPPHP_XMPPTest extends PHPUnit_Framework_TestCase
} catch (XMPPHP_Exception $e) { } catch (XMPPHP_Exception $e) {
return; return;
} catch (Exception $e) { } catch (Exception $e) {
$this->fail('Unexpected Exception thrown: '.$e->getMessage()); $this->fail('Unexpected Exception thrown: ' . $e->getMessage());
} }
$this->fail('Expected XMPPHP_Exception not thrown!'); $this->fail('Expected XMPPHP_Exception not thrown!');
@ -74,7 +74,7 @@ class XMPPHP_XMPPTest extends PHPUnit_Framework_TestCase
} catch (XMPPHP_Exception $e) { } catch (XMPPHP_Exception $e) {
return; return;
} catch (Exception $e) { } catch (Exception $e) {
$this->fail('Unexpected Exception thrown: '.$e->getMessage()); $this->fail('Unexpected Exception thrown: ' . $e->getMessage());
} }
$this->fail('Expected XMPPHP_Exception not thrown!'); $this->fail('Expected XMPPHP_Exception not thrown!');