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
/**
* XMPPHP: The PHP XMPP Library
* Copyright (C) 2008 Nathanael C. Fritz
@ -35,7 +34,7 @@ namespace XMPPHP;
use SimpleXMLElement;
/** XMPPHP_XMLStream */
require_once __DIR__ . "/XMPP.php";
require_once __DIR__ . DIRECTORY_SEPARATOR . 'XMPP.php';
/**
* XMPPHP BOSH
@ -51,7 +50,7 @@ require_once __DIR__ . "/XMPP.php";
class BOSH extends XMPP
{
/**
* @var integer
* @var int
*/
protected $rid;
@ -68,7 +67,7 @@ class BOSH extends XMPP
/**
* @var array
*/
protected $http_buffer = array();
protected $http_buffer = [];
/**
* @var string
@ -76,50 +75,58 @@ class BOSH extends XMPP
protected $session = false;
/**
* @var integer
* @var int
*/
protected $inactivity;
/**
* Connect
*
* @param $server
* @param $wait
* @param $session
* @throws Exception
* @throws Exception
*/
public function connect($server = null, $wait = '1', $session = false)
{
public function __construct(
string $host,
int $port,
string $user,
string $password,
string $resource,
?string $server = null,
bool $print_log = false,
?string $log_level = null
) {
parent::__construct($host, $port, $user, $password, $resource, $server, $print_log, $log_level);
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 : '';
$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;
}
}
/**
* 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->session = $session;
$this->session = $persistent;
$this->rid = 3001;
$this->sid = null;
$this->inactivity = 0;
if ($session) {
if ($persistent) {
$this->loadSession();
}
if (!$this->sid) {
$body = $this->__buildBody();
$body->addAttribute('hold', '1');
$body->addAttribute('to', $this->server);
$body->addAttribute('route', 'xmpp:' . $this->host . ':' . $this->port);
$body->addAttribute('secure', 'true');
$body->addAttribute('xmpp:version', '1.0', 'urn:xmpp:xbosh');
$body->addAttribute('wait', strval($wait));
$body->addAttribute('wait', strval($timeout));
$body->addAttribute('ack', '1');
$body->addAttribute('xmlns:xmpp', 'urn:xmpp:xbosh');
$buff = '<stream:stream xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams">';
@ -138,11 +145,9 @@ class BOSH extends XMPP
* Load session
*
*/
public function loadSession()
public function loadSession(): void
{
if ($this->session == 'ON_FILE') {
// Session not started so use session_file
$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;
if ($this->lat < $this->inactivity) {
if (isset($_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';
}
@ -200,17 +204,15 @@ class BOSH extends XMPP
/**
* Build body
*
* @param $sub
* @return SimpleXMLElement|string
* @param SimpleXMLElement|null $sub
* @return SimpleXMLElement
*/
public function __buildBody($sub = null)
private function __buildBody(?SimpleXMLElement $sub = null): SimpleXMLElement
{
$xml = '<body xmlns="http://jabber.org/protocol/httpbind" xmlns:xmpp="urn:xmpp:xbosh" />';
$xml = new SimpleXMLElement($xml);
$xml = new SimpleXMLElement('<body xmlns="http://jabber.org/protocol/httpbind" xmlns:xmpp="urn:xmpp:xbosh" />');
$xml->addAttribute('content', 'text/xml; charset=utf-8');
$xml->addAttribute('rid', $this->rid);
$this->rid++;
++$this->rid;
if ($this->sid) {
$xml->addAttribute('sid', $this->sid);
}
@ -218,7 +220,6 @@ class BOSH extends XMPP
$xml->addAttribute('xml:lang', 'en');
if ($sub !== null) {
// Ok, so simplexml is lame
$parent = dom_import_simplexml($xml);
$content = dom_import_simplexml($sub);
@ -233,21 +234,19 @@ class BOSH extends XMPP
/**
* Send body
*
* @param $body
* @param $recv
* @param SimpleXMLElement|null $body
* @param bool $recv
* @return bool|string
* @throws Exception
* @throws Exception
*/
public function __sendBody($body = null, $recv = true)
private function __sendBody(?SimpleXMLElement $body = null, bool $recv = true)
{
if (!$body) {
$body = $this->__buildBody();
}
$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();
curl_setopt($ch, CURLOPT_URL, $this->http_server);
@ -283,9 +282,8 @@ class BOSH extends XMPP
* @throws Exception
* @throws Exception
*/
public function __process($null1 = null, $null2 = null)
private function __process($null1 = null, $null2 = null)
{
if ($this->http_buffer) {
$this->__parseBuffer();
} else {
@ -298,17 +296,14 @@ class BOSH extends XMPP
return true;
}
public function __parseBuffer()
private function __parseBuffer()
{
while ($this->http_buffer) {
$idx = key($this->http_buffer);
$buffer = $this->http_buffer[$idx];
unset($this->http_buffer[$idx]);
if ($buffer) {
$xml = new SimpleXMLElement($buffer);
$children = $xml->xpath('child::node()');
@ -325,9 +320,8 @@ class BOSH extends XMPP
* Save session
*
*/
public function saveSession()
public function saveSession(): void
{
$_SESSION['XMPPHP_BOSH']['RID'] = (string)$this->rid;
$_SESSION['XMPPHP_BOSH']['SID'] = (string)$this->sid;
$_SESSION['XMPPHP_BOSH']['authed'] = (boolean)$this->authed;
@ -337,7 +331,6 @@ class BOSH extends XMPP
$_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);
@ -353,13 +346,10 @@ class BOSH extends XMPP
* Process
*
* @param $msg
* @param $null
*
* null param are not used and just to statify Strict Function Declaration
* @throws Exception
* @param int|null $_ unused
* @throws Exception
*/
public function send($msg, $null = null)
public function send($msg, ?int $_ = null)
{
$this->log->log('SEND: ' . $msg, Log::LEVEL_VERBOSE);
$msg = new SimpleXMLElement($msg);
@ -371,18 +361,17 @@ class BOSH extends XMPP
*
* @throws Exception
*/
public function reset()
public function reset(): void
{
$this->xml_depth = 0;
unset($this->xmlobj);
$this->xmlobj = array();
$this->xmlobj = [];
$this->setupParser();
$body = $this->__buildBody();
$body->addAttribute('to', $this->host);
$body->addAttribute('xmpp:restart', 'true', 'urn:xmpp:xbosh');
$buff = '<stream:stream xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams">';
$response = $this->__sendBody($body);
$this->__sendBody($body);
$this->been_reset = true;
xml_parse($this->parser, $buff, false);
}
@ -392,15 +381,14 @@ class BOSH extends XMPP
*
* @throws Exception
*/
public function disconnect()
public function disconnect(): void
{
parent::disconnect();
if ($this->session == 'ON_FILE') {
unlink($this->getSessionFile());
} else {
$keys = array('RID', 'SID', 'authed', 'basejid', 'fulljid', 'inactivity', 'lat');
$keys = ['RID', 'SID', 'authed', 'basejid', 'fulljid', 'inactivity', 'lat'];
foreach ($keys as $key) {
unset($_SESSION['XMPPHP_BOSH'][$key]);
}

View File

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

View File

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

View File

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

View File

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

View File

@ -1,5 +1,4 @@
<?php
/**
* XMPPHP: The PHP XMPP Library
* Copyright (C) 2008 Nathanael C. Fritz
@ -67,7 +66,7 @@ class XMLStream
*/
protected $buffer;
/**
* @var integer
* @var int
*/
protected $xml_depth = 0;
/**
@ -87,21 +86,21 @@ class XMLStream
*/
protected $stream_end = '</stream>';
/**
* @var boolean
* @var bool
*/
protected $disconnected = false;
/**
* @var boolean
* @var bool
*/
protected $sent_disconnect = false;
/**
* @var array
*/
protected $ns_map = array();
protected $ns_map = [];
/**
* @var array
*/
protected $current_ns = array();
protected $current_ns = [];
/**
* @var array
*/
@ -109,21 +108,21 @@ class XMLStream
/**
* @var array
*/
protected $nshandlers = array();
protected $nshandlers = [];
/**
* @var array
*/
protected $xpathhandlers = array();
protected $xpathhandlers = [];
/**
* @var array
*/
protected $idhandlers = array();
protected $idhandlers = [];
/**
* @var array
*/
protected $eventhandlers = array();
protected $eventhandlers = [];
/**
* @var integer
* @var int
*/
protected $lastid = 0;
/**
@ -145,21 +144,21 @@ class XMLStream
/**
* @var array
*/
protected $until_payload = array();
protected $until_payload = [];
/**
* @var Log
*/
protected $log;
/**
* @var boolean
* @var bool
*/
protected $reconnect = true;
/**
* @var boolean
* @var bool
*/
protected $been_reset = false;
/**
* @var boolean
* @var bool
*/
protected $is_server;
/**
@ -167,37 +166,42 @@ class XMLStream
*/
protected $last_send = 0;
/**
* @var boolean
* @var bool
*/
protected $use_ssl = false;
/**
* @var integer
* @var int
*/
protected $reconnectTimeout = 30;
/**
* Constructor
*
* @param string $host
* @param string $port
* @param boolean $printlog
* @param string $loglevel
* @param boolean $is_server
* @param string|null $host (optional)
* @param string|null $port (optional)
* @param bool $print_log (optional)
* @param string $log_level (optional)
* @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->is_server = $is_server;
$this->host = $host;
$this->port = $port;
$this->setupParser();
$this->log = new Log($printlog, $loglevel);
$this->log = new Log($print_log, $log_level);
}
/**
* Setup the XML parser
*/
public function setupParser()
public function setupParser(): void
{
$this->parser = xml_parser_create('UTF-8');
xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);
@ -210,6 +214,7 @@ class XMLStream
/**
* Destructor
* Cleanup connection
* @throws Exception
*/
public function __destruct()
{
@ -220,8 +225,9 @@ class XMLStream
/**
* Disconnect from XMPP Host
* @throws Exception
*/
public function disconnect()
public function disconnect(): void
{
$this->log->log("Disconnecting...", Log::LEVEL_VERBOSE);
if (false == (bool)$this->socket) {
@ -238,17 +244,16 @@ class XMLStream
* Send to socket
*
* @param string $msg
* @param null $timeout
* @param int|null $timeout
* @return bool|int
* @throws Exception
*/
public function send($msg, $timeout = NULL)
public function send(string $msg, ?int $timeout = null)
{
if (is_null($timeout)) {
$secs = NULL;
$usecs = NULL;
} else if ($timeout == 0) {
$secs = null;
$usecs = null;
} elseif ($timeout == 0) {
$secs = 0;
$usecs = 0;
} else {
@ -257,16 +262,16 @@ class XMLStream
$secs = floor(($maximum - $usecs) / 1000000);
}
$read = array();
$write = array($this->socket);
$except = array();
$read = [];
$write = [$this->socket];
$except = [];
$select = @stream_select($read, $write, $except, $secs, $usecs);
if ($select === False) {
if ($select === false) {
$this->log->log("ERROR sending message; reconnecting.");
$this->doReconnect();
# TODO: retry send here
// TODO: retry send here
return false;
} elseif ($select > 0) {
$this->log->log("Socket is ready; send it.", Log::LEVEL_VERBOSE);
@ -277,7 +282,7 @@ class XMLStream
$sentbytes = @fwrite($this->socket, $msg);
$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->doReconnect();
return false;
@ -294,7 +299,7 @@ class XMLStream
{
if (!$this->is_server) {
$this->log->log("Reconnecting ($this->reconnectTimeout)...", Log::LEVEL_WARNING);
$this->connect($this->reconnectTimeout, false, false);
$this->connect(false, false, $this->reconnectTimeout);
$this->reset();
$this->event('reconnect');
}
@ -303,16 +308,15 @@ class XMLStream
/**
* Connect to XMPP Host
*
* @param integer $timeout
* @param boolean $persistent
* @param boolean $sendinit
* @throws Exception
* @param bool $persistent (optional)
* @param bool $send_init (optional)
* @param int $timeout (optional)
* @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;
$starttime = time();
$start_time = time();
do {
$this->disconnected = false;
@ -322,21 +326,25 @@ class XMLStream
} 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);
$conn_type = 'tcp';
if ($this->use_ssl) {
$conn_type = 'ssl';
}
$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) {
$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);
} while (!$this->socket && (time() - $start_time) < $timeout);
if ($this->socket) {
stream_set_blocking($this->socket, 1);
if ($sendinit) $this->send($this->stream_start);
if ($send_init) {
$this->send($this->stream_start);
}
} else {
throw new Exception("Could not connect before timeout.");
}
@ -344,12 +352,13 @@ class XMLStream
/**
* Reset connection
* @throws Exception
*/
public function reset()
public function reset(): void
{
$this->xml_depth = 0;
unset($this->xmlobj);
$this->xmlobj = array();
$this->xmlobj = [];
$this->setupParser();
if (!$this->is_server) {
$this->send($this->stream_start);
@ -361,9 +370,9 @@ class XMLStream
* Event?
*
* @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);
foreach ($this->eventhandlers as $handler) {
@ -377,12 +386,12 @@ class XMLStream
foreach ($this->until as $key => $until) {
if (is_array($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])) {
$this->until_count[$key] = 0;
}
$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
*
* @param string|array $event
* @param integer $timeout
* @return string
* @param int $timeout (optional)
* @return array
* @throws Exception
*/
public function processUntil($event, $timeout = -1)
public function processUntil($event, int $timeout = -1): array
{
$start = time();
if (!is_array($event)) $event = array($event);
if (!is_array($event)) {
$event = array($event);
}
$this->until[] = $event;
end($this->until);
$event_key = key($this->until);
@ -414,7 +425,7 @@ class XMLStream
unset($this->until_count[$event_key]);
unset($this->until[$event_key]);
} else {
$payload = array();
$payload = [];
}
return $payload;
}
@ -428,21 +439,19 @@ class XMLStream
* @return bool
* @throws Exception
*/
private function __process($maximum = 5)
private function __process(int $maximum = 5): bool
{
$remaining = $maximum;
do {
$starttime = (microtime(true) * 1000000);
$read = array($this->socket);
$write = array();
$except = array();
$write = [];
$except = [];
if (is_null($maximum)) {
$secs = NULL;
$usecs = NULL;
} else if ($maximum == 0) {
$secs = null;
$usecs = null;
} elseif ($maximum == 0) {
$secs = 0;
$usecs = 0;
} else {
@ -456,10 +465,10 @@ class XMLStream
$this->doReconnect();
} else {
fclose($this->socket);
$this->socket = NULL;
$this->socket = null;
return false;
}
} else if ($updated > 0) {
} elseif ($updated > 0) {
# XXX: Is this big enough?
$buff = @fread($this->socket, 4096);
if (!$buff) {
@ -467,14 +476,14 @@ class XMLStream
$this->doReconnect();
} else {
fclose($this->socket);
$this->socket = NULL;
$this->socket = null;
return false;
}
}
$this->log->log("RECV: $buff", Log::LEVEL_VERBOSE);
xml_parse($this->parser, $buff, false);
} // Otherwise,
// $updated == 0 means no changes during timeout.
// $updated == 0 means no changes during timeout.
$endtime = (microtime(true) * 1000000);
$time_past = $endtime - $starttime;
@ -488,7 +497,7 @@ class XMLStream
*
* @return Log
*/
public function getLog()
public function getLog(): Log
{
return $this->log;
}
@ -496,9 +505,9 @@ class XMLStream
/**
* Get next ID
*
* @return integer
* @return int
*/
public function getId()
public function getId(): int
{
$this->lastid++;
return $this->lastid;
@ -508,7 +517,7 @@ class XMLStream
* Set SSL
* @param bool $use
*/
public function useSSL($use = true)
public function useSSL(bool $use = true): void
{
$this->use_ssl = $use;
}
@ -516,13 +525,13 @@ class XMLStream
/**
* Add ID Handler
*
* @param integer $id
* @param int $id
* @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 $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);
}
* @param string|null $obj
* @param int $depth
*
* public function addHandler(string $name, string $ns, string $pointer, ?string $obj = null, int $depth = 1): void
* {
* #TODO deprication warning
* $this->nshandlers[] = [$name, $ns, $pointer, $obj, $depth];
* }*/
/**
* Add XPath Handler
*
* @param string $xpath
* @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)) {
$ns_tags = $regs[0];
} else {
$ns_tags = array($xpath);
$ns_tags = [$xpath];
}
$xpath_array = [];
foreach ($ns_tags as $ns_tag) {
list($l, $r) = explode("}", $ns_tag);
if ($r != null) {
$xpart = array(substr($l, 1), $r);
$xpart = [substr($l, 1), $r];
} else {
$xpart = array(null, $l);
$xpart = [null, $l];
}
$xpath_array[] = $xpart;
}
$this->xpathhandlers[] = array($xpath_array, $pointer, $obj);
$this->xpathhandlers[] = [$xpath_array, $pointer, $obj];
}
/**
* Add Event Handler
*
* @param $name
* @param string $name
* @param string $pointer
* @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;
}
@ -586,9 +599,9 @@ class XMLStream
/**
* Are we are disconnected?
*
* @return boolean
* @return bool
*/
public function isDisconnected()
public function isDisconnected(): bool
{
return $this->disconnected;
}
@ -596,10 +609,11 @@ class XMLStream
/**
* Process
*
* @throws Exception
*/
public function process()
public function process(): void
{
$this->__process(NULL);
$this->__process(null);
}
/**
@ -609,10 +623,10 @@ class XMLStream
* @return string
* @throws Exception
*/
public function processTime($timeout = NULL)
public function processTime($timeout = null): string
{
if (is_null($timeout)) {
return $this->__process(NULL);
return $this->__process(null);
} else {
return $this->__process($timeout * 1000000);
}
@ -621,21 +635,21 @@ class XMLStream
/**
* Obsolete?
* @param $socket
*/
public function Xapply_socket($socket)
{
$this->socket = $socket;
}
*
* public function Xapply_socket($socket)
* {
* $this->socket = $socket;
* }*/
/**
* XML start callback
*
* @param resource $parser
* @param string resource $parser
* @param string $name
* @param $attr
* @param array $attr
* @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) {
$this->been_reset = false;
@ -646,7 +660,9 @@ class XMLStream
$this->current_ns[$this->xml_depth] = $attr['XMLNS'];
} else {
$this->current_ns[$this->xml_depth] = $this->current_ns[$this->xml_depth - 1];
if (!$this->current_ns[$this->xml_depth]) $this->current_ns[$this->xml_depth] = $this->default_ns;
if (!$this->current_ns[$this->xml_depth]) {
$this->current_ns[$this->xml_depth] = $this->default_ns;
}
}
$ns = $this->current_ns[$this->xml_depth];
foreach ($attr as $key => $value) {
@ -671,13 +687,13 @@ class XMLStream
/**
* XML end callback
*
* @param resource $parser
* @param string resource $parser
* @param string $name
* @throws Exception
* @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);
#print "$name\n";
@ -689,6 +705,7 @@ class XMLStream
if ($this->xml_depth == 1) {
#clean-up old objects
#$found = false; #FIXME This didn't appear to be in use --Gar
$searchxml = null;
foreach ($this->xpathhandlers as $handler) {
if (is_array($this->xmlobj) && array_key_exists(2, $this->xmlobj)) {
$searchxml = $this->xmlobj[2];
@ -703,7 +720,9 @@ class XMLStream
}
}
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);
$handler[2]->{$handler[1]}($this->xmlobj[2]);
}
@ -717,14 +736,18 @@ class XMLStream
$searchxml = $this->xmlobj[2];
}
if ($searchxml !== null and $searchxml->name == $handler[0] and ($searchxml->ns == $handler[1] or (!$handler[1] and $searchxml->ns == $this->default_ns))) {
if ($handler[3] === null) $handler[3] = $this;
if ($handler[3] === null) {
$handler[3] = $this;
}
$this->log->log("Calling {$handler[2]}", Log::LEVEL_DEBUG);
$handler[3]->{$handler[2]}($this->xmlobj[2]);
}
}
foreach ($this->idhandlers as $id => $handler) {
if (array_key_exists('id', $this->xmlobj[2]->attrs) and $this->xmlobj[2]->attrs['id'] == $id) {
if ($handler[1] === null) $handler[