From 57f33b4328aa764f8dc35bda6cb6a5736a40d9ba Mon Sep 17 00:00:00 2001 From: Diogo Cordeiro Date: Sat, 2 Nov 2019 23:36:21 +0000 Subject: [PATCH] Introduce PHP7 strict typing --- XMPPHP/BOSH.php | 116 +++++------ XMPPHP/Exception.php | 1 - XMPPHP/Log.php | 36 ++-- XMPPHP/Roster.php | 68 ++++--- XMPPHP/XMLObj.php | 33 +-- XMPPHP/XMLStream.php | 282 ++++++++++++++------------ XMPPHP/XMPP.php | 97 +++++---- composer.json | 100 +++++---- examples/cli_longrun_example.php | 147 +++++++------- examples/cli_longrun_example_bosh.php | 93 ++++----- examples/sendmessage_example.php | 23 +-- examples/webclient_example.php | 111 +++++----- tests/XMPPHP/XMLObjTest.php | 22 +- tests/XMPPHP/XMPPTest.php | 4 +- 14 files changed, 586 insertions(+), 547 deletions(-) diff --git a/XMPPHP/BOSH.php b/XMPPHP/BOSH.php index 140ff7c..bfc313f 100644 --- a/XMPPHP/BOSH.php +++ b/XMPPHP/BOSH.php @@ -1,5 +1,4 @@ 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 = ''; @@ -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 = ''; - $xml = new SimpleXMLElement($xml); + $xml = new SimpleXMLElement(''); $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 = ''; - $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]); } diff --git a/XMPPHP/Exception.php b/XMPPHP/Exception.php index 525bdd9..1595e81 100644 --- a/XMPPHP/Exception.php +++ b/XMPPHP/Exception.php @@ -1,5 +1,4 @@ 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 = []; } } } diff --git a/XMPPHP/Roster.php b/XMPPHP/Roster.php index 799c549..91bac21 100644 --- a/XMPPHP/Roster.php +++ b/XMPPHP/Roster.php @@ -1,5 +1,4 @@ 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; } diff --git a/XMPPHP/XMLObj.php b/XMPPHP/XMLObj.php index de359ae..33b53e8 100644 --- a/XMPPHP/XMLObj.php +++ b/XMPPHP/XMLObj.php @@ -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; } } diff --git a/XMPPHP/XMLStream.php b/XMPPHP/XMLStream.php index 615e7ca..80a5073 100644 --- a/XMPPHP/XMLStream.php +++ b/XMPPHP/XMLStream.php @@ -1,5 +1,4 @@ '; /** - * @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[1] = $this; + if ($handler[1] === null) { + $handler[1] = $this; + } $handler[1]->{$handler[0]}($this->xmlobj[2]); #id handlers are only used once unset($this->idhandlers[$id]); @@ -757,12 +780,12 @@ class XMLStream /** * XML character callback - * @param resource $parser + * @param string resource $parser * @param string $data * @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)) { $this->xmlobj[$this->xml_depth]->data .= $data; @@ -771,8 +794,10 @@ class XMLStream /** * Read from socket + * @return bool Did read + * @throws Exception */ - public function read() + public function read(): bool { $buff = @fread($this->socket, 1024); if (!$buff) { @@ -785,19 +810,20 @@ class XMLStream } $this->log->log("RECV: $buff", Log::LEVEL_VERBOSE); xml_parse($this->parser, $buff, false); + return true; } - public function time() + public function time(): float { list($usec, $sec) = explode(" ", microtime()); return (float)$sec + (float)$usec; } - public function readyToProcess() + public function readyToProcess(): bool { $read = array($this->socket); - $write = array(); - $except = array(); + $write = []; + $except = []; $updated = @stream_select($read, $write, $except, 0); return (($updated !== false) && ($updated > 0)); } diff --git a/XMPPHP/XMPP.php b/XMPPHP/XMPP.php index fbbe13f..b1362c6 100644 --- a/XMPPHP/XMPP.php +++ b/XMPPHP/XMPP.php @@ -1,5 +1,4 @@ user = $user; $this->password = $password; @@ -140,9 +147,9 @@ class XMPP extends XMLStream /** * 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; } @@ -150,9 +157,9 @@ class XMPP extends XMLStream /** * 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; } @@ -162,12 +169,12 @@ class XMPP extends XMLStream * * @param string $to * @param string $body - * @param string $type - * @param string $subject - * @param null $payload + * @param string $type (optional) + * @param string|null $subject (optional) + * @param string|null $payload (optional) * @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) { throw new Exception('You need to connect first'); @@ -177,13 +184,13 @@ class XMPP extends XMLStream $type = 'chat'; } - $to = htmlspecialchars($to); - $body = htmlspecialchars($body); + $to = htmlspecialchars($to); + $body = htmlspecialchars($body); $subject = htmlspecialchars($subject); $subject = ($subject) ? '' . $subject . '' : ''; $payload = ($payload) ? $payload : ''; $sprintf = '%s%s%s'; - $output = sprintf($sprintf, $this->fulljid, $to, $type, $subject, $body, $payload); + $output = sprintf($sprintf, $this->fulljid, $to, $type, $subject, $body, $payload); $this->send($output); } @@ -197,7 +204,7 @@ class XMPP extends XMLStream * @param null $priority * @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) { throw new Exception('You need to connect first'); @@ -242,8 +249,9 @@ class XMPP extends XMLStream * Send Auth request * * @param string $jid + * @throws Exception */ - public function subscribe($jid) + public function subscribe(string $jid): void { $this->send(""); #$this->send(""); @@ -254,7 +262,7 @@ class XMPP extends XMLStream * * @param string $xml */ - public function message_handler($xml) + public function message_handler(string $xml): void { if (isset($xml->attrs['type'])) { $payload['type'] = $xml->attrs['type']; @@ -273,8 +281,9 @@ class XMPP extends XMLStream * Presence handler * * @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['show'] = (isset($xml->sub('show')->data)) ? $xml->sub('show')->data : $payload['type']; @@ -302,8 +311,9 @@ class XMPP extends XMLStream /** * Retrieves the roster * + * @throws Exception */ - public function getRoster() + public function getRoster(): void { $id = $this->getID(); $this->send(""); @@ -311,9 +321,10 @@ class XMPP extends XMLStream /** * 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(); $this->addIdHandler($id, 'vcard_get_handler'); @@ -328,8 +339,9 @@ class XMPP extends XMLStream * Features handler * * @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) { $this->send(""); @@ -351,8 +363,9 @@ class XMPP extends XMLStream * SASL success handler * * @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->authed = true; @@ -365,7 +378,7 @@ class XMPP extends XMLStream * @param string $xml * @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->disconnect(); @@ -377,8 +390,9 @@ class XMPP extends XMLStream * Resource bind handler * * @param string $xml + * @throws Exception */ - protected function resource_bind_handler($xml) + protected function resource_bind_handler(string $xml): void { if ($xml->attrs['type'] == 'result') { $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' * * @param string $xml + * @throws Exception */ - protected function roster_iq_handler($xml) + protected function roster_iq_handler(string $xml): void { $status = "result"; $xmlroster = $xml->sub('query'); + $contacts = []; foreach ($xmlroster->subs as $item) { - $groups = array(); + $groups = []; if ($item->name == 'item') { $jid = $item->attrs['jid']; //REQUIRED $name = $item->attrs['name']; //MAY @@ -412,7 +428,7 @@ class XMPP extends XMLStream $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 { $status = "error"; } @@ -432,7 +448,7 @@ class XMPP extends XMLStream * * @param string $xml */ - protected function session_start_handler($xml) + protected function session_start_handler(string $xml): void { $this->log->log("Session started"); $this->session_started = true; @@ -443,8 +459,9 @@ class XMPP extends XMLStream * TLS proceed handler * * @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"); stream_socket_enable_crypto($this->socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); @@ -456,14 +473,14 @@ class XMPP extends XMLStream * * @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'); // go through all of the sub elements and add them to the vcard array foreach ($vcard->subs as $sub) { if ($sub->subs) { - $vcard_array[$sub->name] = array(); + $vcard_array[$sub->name] = []; foreach ($sub->subs as $sub_child) { $vcard_array[$sub->name][$sub_child->name] = $sub_child->data; } diff --git a/composer.json b/composer.json index 3e879b3..163b5cb 100644 --- a/composer.json +++ b/composer.json @@ -1,49 +1,59 @@ { - "name": "diogocomposer/xmpphp", - "description": "XMPP PHP Library", - "type": "library", - "keywords": ["jabber", "xmpphp", "xmpp"], - "license": "GPL-2.0+", - "authors": [ - { - "name": "Nathan Fritz", - "email": "fritzy@netflint.net" - }, - { - "name": "Stephan Wentz", - "email": "stephan@wentz.it" - }, - { - "name": "Christian Weiske", - "email": "cweiske@cweiske.de" - }, - { - "name": "Vito Tafuni", - "email": "vitotafuni@gmail.com" - }, - { - "name": "Ivan Borzenkov", - "email": "ivan.borzenkov@gmail.com" - }, - { - "name": "bandroidx", - "email": "bandroidx@gmail.com" - }, - { - "name": "BirknerAlex", - "email": "alex.birkner@gmail.com" - }, - { - "name": "Diogo Cordeiro", - "email": "diogo@fc.up.pt" - } - ], - "autoload": { - "psr-4": { "XMPPHP\\": "XMPPHP" } + "name": "diogocomposer/xmpphp", + "description": "XMPP PHP Library", + "type": "library", + "keywords": [ + "jabber", + "xmpphp", + "xmpp" + ], + "license": "GPL-2.0+", + "authors": [ + { + "name": "Nathan Fritz", + "email": "fritzy@netflint.net" }, - "require": { - "php": "^7.3.0", - "ext-mbstring": "*", - "ext-xml": "*" + { + "name": "Stephan Wentz", + "email": "stephan@wentz.it" + }, + { + "name": "Christian Weiske", + "email": "cweiske@cweiske.de" + }, + { + "name": "Vito Tafuni", + "email": "vitotafuni@gmail.com" + }, + { + "name": "Ivan Borzenkov", + "email": "ivan.borzenkov@gmail.com" + }, + { + "name": "bandroidx", + "email": "bandroidx@gmail.com" + }, + { + "name": "BirknerAlex", + "email": "alex.birkner@gmail.com" + }, + { + "name": "Diogo Cordeiro", + "email": "diogo@fc.up.pt" } + ], + "autoload": { + "psr-4": { + "XMPPHP\\": "XMPPHP" + } + }, + "require": { + "php": "^7.3.0", + "ext-mbstring": "*", + "ext-xml": "*", + "ext-simplexml": "*", + "ext-dom": "*", + "ext-curl": "*", + "ext-openssl": "*" + } } diff --git a/examples/cli_longrun_example.php b/examples/cli_longrun_example.php index c997264..9564bdc 100644 --- a/examples/cli_longrun_example.php +++ b/examples/cli_longrun_example.php @@ -1,5 +1,4 @@ 'talk.google.com', - 'port' => 5222, - 'username' => 'username', - 'password' => 'password', - 'proto' => 'xmpphp', - 'domain' => 'gmail.com', - 'printlog' => true, - 'loglevel' => XMPPHP\Log::LEVEL_VERBOSE, -); +$conf = [ + 'server' => 'im.server.tld', + 'port' => 5222, + 'username' => 'username', + 'password' => 'password', + 'proto' => 'xmpphp', + 'domain' => 'domain.net', + 'printlog' => true, + 'loglevel' => XMPPHP\Log::LEVEL_VERBOSE, +]; // Easy and simple for access to variables with their names extract($conf); @@ -38,13 +35,13 @@ extract($conf); $conn = new XMPPHP\XMPP($server, $port, $username, $password, $proto, $domain, $printlog, $loglevel); $conn->autoSubscribe(); -$vcard_request = array(); +$vcard_request = []; try { $conn->connect(); while (!$conn->isDisconnected()) { - $events = array('message', 'presence', 'end_stream', 'session_start', 'vcard'); + $events = ['message', 'presence', 'end_stream', 'session_start', 'vcard']; $payloads = $conn->processUntil($events); foreach ($payloads as $result) { @@ -56,84 +53,84 @@ try { switch ($event) { - case 'message': + case 'message': - if (!$body) { - break; - } + if (!$body) { + break; + } - echo str_repeat('-', 80); - echo "Message from: $from"; + echo str_repeat('-', 80); + echo "Message from: $from"; - if (isset($subject)) { - echo "Subject: $subject"; - } + if (isset($subject)) { + echo "Subject: $subject"; + } - echo $body; - echo str_repeat('-', 80); + echo $body; + echo str_repeat('-', 80); - $cmd = explode(' ', $body); - $body = "Mi no entender! '$body'"; - $conn->message($from, $body, $type); + $cmd = explode(' ', $body); + $body = "Mi no entender! '$body'"; + $conn->message($from, $body, $type); - if (isset($cmd[0])) { - if ($cmd[0] == 'quit') { - $conn->disconnect(); - } + if (isset($cmd[0])) { + if ($cmd[0] == 'quit') { + $conn->disconnect(); + } - if ($cmd[0] == 'break') { - $conn->send(''); - } + if ($cmd[0] == 'break') { + $conn->send(''); + } - if ($cmd[0] == 'vcard') { - if (!isset($cmd[1])) { - $cmd[1] = $conn->user; - } + if ($cmd[0] == 'vcard') { + if (!isset($cmd[1])) { + $cmd[1] = $conn->user; + } - // Take a note which user requested which vcard - $vcard_request[$from] = $cmd[1]; - // Request the vcard - $conn->getVCard($cmd[1]); - } - } - break; + // Take a note which user requested which vcard + $vcard_request[$from] = $cmd[1]; + // Request the vcard + $conn->getVCard($cmd[1]); + } + } + break; - case 'presence': + case 'presence': - echo "Presence: $from [$show] $status\n"; - break; + echo "Presence: $from [$show] $status\n"; + break; - case 'session_start': + case 'session_start': - echo "Session start\n"; - $conn->getRoster(); - $conn->presence('Quasar!'); - break; + echo "Session start\n"; + $conn->getRoster(); + $conn->presence('Quasar!'); + break; - case 'vcard': + case 'vcard': - $deliver = array_keys($vcard_request, $from); - $msg = ''; + $deliver = array_keys($vcard_request, $from); + $msg = ''; - foreach ($data as $key => $item) { - $msg .= $key . ': '; + foreach ($data as $key => $item) { + $msg .= $key . ': '; - if (is_array($item)) { - $msg .= "\n"; - foreach ($item as $subkey => $subitem) { - $msg .= ' ' . $subkey . ':' . $subitem . "\n"; - } - } else { - $msg .= $item . "\n"; - } - } + if (is_array($item)) { + $msg .= "\n"; + foreach ($item as $subkey => $subitem) { + $msg .= ' ' . $subkey . ':' . $subitem . "\n"; + } + } else { + $msg .= $item . "\n"; + } + } - foreach ($deliver as $sendjid) { - unset($vcard_request[$sendjid]); - $conn->message($sendjid, $msg, 'chat'); - } - break; - } + foreach ($deliver as $sendjid) { + unset($vcard_request[$sendjid]); + $conn->message($sendjid, $msg, 'chat'); + } + break; + } } } } catch (XMPPHP\Exception $e) { diff --git a/examples/cli_longrun_example_bosh.php b/examples/cli_longrun_example_bosh.php index 5a93e75..892ac52 100644 --- a/examples/cli_longrun_example_bosh.php +++ b/examples/cli_longrun_example_bosh.php @@ -1,5 +1,4 @@ 'server.tld', - 'port' => 5280, - 'username' => 'username', - 'password' => 'password', - 'proto' => 'xmpphp', - 'domain' => 'server.tld', - 'printlog' => true, - 'loglevel' => XMPPHP\Log::LEVEL_VERBOSE, -); +$conf = [ + 'host' => 'server.tld', + 'port' => 5280, + 'username' => 'username', + 'password' => 'password', + 'resource' => 'xmpphp', + 'server' => 'http://server.tld:5280/xmpp-httpbind', + 'print_log' => true, + 'log_level' => XMPPHP\Log::LEVEL_VERBOSE, +]; // Easy and simple for access to variables with their names extract($conf); -$conn = new XMPPHP\BOSH($server, $port, $username, $password, $proto, $domain, $printlog, $loglevel); +$conn = new XMPPHP\BOSH($host, $port, $username, $password, $proto, $server, $print_log, $log_level); $conn->autoSubscribe(); try { - $conn->connect('http://server.tld:5280/xmpp-httpbind'); + $conn->connect(); while (!$conn->isDisconnected()) { - $events = array('message', 'presence', 'end_stream', 'session_start'); + $events = ['message', 'presence', 'end_stream', 'session_start']; $payloads = $conn->processUntil($events); foreach ($payloads as $result) { @@ -54,49 +51,49 @@ try { switch ($event) { - case 'message': + case 'message': - if (!$body) { - break; - } + if (!$body) { + break; + } - echo str_repeat('-', 80); - echo "Message from: $from"; + echo str_repeat('-', 80); + echo "Message from: $from"; - if (isset($subject)) { - echo "Subject: $subject"; - } + if (isset($subject)) { + echo "Subject: $subject"; + } - echo $body; - echo str_repeat('-', 80); + echo $body; + echo str_repeat('-', 80); - $cmd = explode(' ', $body); - $body = "Mi no entender! '$body'"; - $conn->message($from, $body, $type); + $cmd = explode(' ', $body); + $body = "Mi no entender! '$body'"; + $conn->message($from, $body, $type); - if (isset($cmd[0])) { - if ($cmd[0] == 'quit') { - $conn->disconnect(); - } + if (isset($cmd[0])) { + if ($cmd[0] == 'quit') { + $conn->disconnect(); + } - if ($cmd[0] == 'break') { - $conn->send(''); - } - } - break; + if ($cmd[0] == 'break') { + $conn->send(''); + } + } + break; - case 'presence': + case 'presence': - echo "Presence: $from [$show] $status\n"; - break; + echo "Presence: $from [$show] $status\n"; + break; - case 'session_start': + case 'session_start': - echo "Session start\n"; - $conn->getRoster(); - $conn->presence('Quasar!'); - break; - } + echo "Session start\n"; + $conn->getRoster(); + $conn->presence('Quasar!'); + break; + } } } } catch (XMPPHP\Exception $e) { diff --git a/examples/sendmessage_example.php b/examples/sendmessage_example.php index b71290d..89a0ea4 100644 --- a/examples/sendmessage_example.php +++ b/examples/sendmessage_example.php @@ -1,5 +1,4 @@ 'talk.google.com', - 'port' => 5222, - 'username' => 'username', - 'password' => 'password', - 'proto' => 'xmpphp', - 'domain' => 'gmail.com', - 'printlog' => true, - 'loglevel' => XMPPHP\Log::LEVEL_VERBOSE, -); +$conf = [ + 'server' => 'jabber.domain.com', + 'port' => 5222, + 'username' => 'username', + 'password' => 'password', + 'proto' => 'xmpphp', + 'domain' => 'domain.net', + 'printlog' => true, + 'loglevel' => XMPPHP\Log::LEVEL_VERBOSE, +]; // Easy and simple for access to variables with their names extract($conf); diff --git a/examples/webclient_example.php b/examples/webclient_example.php index 147281d..4fc3584 100644 --- a/examples/webclient_example.php +++ b/examples/webclient_example.php @@ -1,5 +1,4 @@ 'talk.google.com', - 'port' => 5222, - 'username' => 'username', - 'password' => 'password', - 'proto' => 'xmpphp', - 'domain' => 'gmail.com', - 'printlog' => true, - 'loglevel' => XMPPHP\Log::LEVEL_VERBOSE, -); +$conf = [ + 'server' => 'talk.google.com', + 'port' => 5222, + 'username' => 'username', + 'password' => 'password', + 'proto' => 'xmpphp', + 'domain' => 'gmail.com', + 'printlog' => true, + 'loglevel' => XMPPHP\Log::LEVEL_VERBOSE, +]; // Easy and simple for access to variables with their names extract($conf); @@ -48,11 +45,11 @@ try { flush(); } } else { - $_SESSION['messages'] = array(); + $_SESSION['messages'] = []; } - $conn->connect('http://server.tld:5280/xmpp-httpbind', 1, true); - $events = array('message', 'presence', 'end_stream', 'session_start', 'vcard'); + $conn->connect(); + $events = ['message', 'presence', 'end_stream', 'session_start', 'vcard']; $payloads = $conn->processUntil($events); foreach ($payloads as $result) { @@ -64,49 +61,49 @@ try { switch ($event) { - case 'message': + case 'message': - if (!$body) { - break; + if (!$body) { + break; + } + + $cmd = explode(' ', $body); + $msg = str_repeat('-', 80); + $msg .= "\nMessage from: $from\n"; + + if (isset($subject)) { + $msg .= "Subject: $subject\n"; + } + + $msg .= $body . "\n"; + $msg .= str_repeat('-', 80); + echo "
$msg
"; + + if (isset($cmd[0])) { + if ($cmd[0] == 'quit') { + $conn->disconnect(); + } + + if ($cmd[0] == 'break') { + $conn->send(''); + } + } + $_SESSION['messages'][] = $msg; + flush(); + break; + + case 'presence': + + echo "Presence: $from [$show] $status\n"; + break; + + case 'session_start': + + echo "Session start\n"; + $conn->getRoster(); + $conn->presence('Quasar!'); + break; } - - $cmd = explode(' ', $body); - $msg = str_repeat('-', 80); - $msg .= "\nMessage from: $from\n"; - - if (isset($subject)) { - $msg .= "Subject: $subject\n"; - } - - $msg .= $body . "\n"; - $msg .= str_repeat('-', 80); - echo "
$msg
"; - - if (isset($cmd[0])) { - if ($cmd[0] == 'quit') { - $conn->disconnect(); - } - - if ($cmd[0] == 'break') { - $conn->send(''); - } - } - $_SESSION['messages'][] = $msg; - flush(); - break; - - case 'presence': - - echo "Presence: $from [$show] $status\n"; - break; - - case 'session_start': - - echo "Session start\n"; - $conn->getRoster(); - $conn->presence('Quasar!'); - break; - } } } catch (XMPPHP\Exception $e) { die($e->getMessage()); diff --git a/tests/XMPPHP/XMLObjTest.php b/tests/XMPPHP/XMLObjTest.php index f4f2e09..83bcdb9 100755 --- a/tests/XMPPHP/XMLObjTest.php +++ b/tests/XMPPHP/XMLObjTest.php @@ -44,35 +44,35 @@ class XMPPHP_XMLObjTest extends PHPUnit_Framework_TestCase { public function testToStringNameNamespace() { - $xmlobj = new XMPPHP_XMLObj('testname', 'testNameSpace'); + $xmlobj = new XMPPHP_XMLObj('testname', 'testNameSpace'); $expected = ''; - $result = $xmlobj->toString(); + $result = $xmlobj->toString(); $this->assertSame($expected, $result); } 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 = ''; - $result = $xmlobj->toString(); + $result = $xmlobj->toString(); $this->assertSame($expected, $result); } 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 = 'I am test data'; - $result = $xmlobj->toString(); + $result = $xmlobj->toString(); $this->assertSame($expected, $result); } public function testToStringNameNamespaceSub() { - $xmlobj = new XMPPHP_XMLObj('testName', 'testNameSpace'); - $sub1 = new XMPPHP_XMLObj('subName', 'subNameSpace'); - $xmlobj->subs = array($sub1); - $expected = ''; - $result = $xmlobj->toString(); + $xmlobj = new XMPPHP_XMLObj('testName', 'testNameSpace'); + $sub1 = new XMPPHP_XMLObj('subName', 'subNameSpace'); + $xmlobj->subs = [$sub1]; + $expected = ''; + $result = $xmlobj->toString(); $this->assertSame($expected, $result); } } diff --git a/tests/XMPPHP/XMPPTest.php b/tests/XMPPHP/XMPPTest.php index b77a1b9..371f0d2 100755 --- a/tests/XMPPHP/XMPPTest.php +++ b/tests/XMPPHP/XMPPTest.php @@ -55,7 +55,7 @@ class XMPPHP_XMPPTest extends PHPUnit_Framework_TestCase } catch (XMPPHP_Exception $e) { return; } catch (Exception $e) { - $this->fail('Unexpected Exception thrown: '.$e->getMessage()); + $this->fail('Unexpected Exception thrown: ' . $e->getMessage()); } $this->fail('Expected XMPPHP_Exception not thrown!'); @@ -74,7 +74,7 @@ class XMPPHP_XMPPTest extends PHPUnit_Framework_TestCase } catch (XMPPHP_Exception $e) { return; } catch (Exception $e) { - $this->fail('Unexpected Exception thrown: '.$e->getMessage()); + $this->fail('Unexpected Exception thrown: ' . $e->getMessage()); } $this->fail('Expected XMPPHP_Exception not thrown!');