123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854 |
- <?php
- namespace XMPPHP;
- require_once __DIR__ . DIRECTORY_SEPARATOR . 'Exception.php';
- require_once __DIR__ . DIRECTORY_SEPARATOR . 'XMLObj.php';
- require_once __DIR__ . DIRECTORY_SEPARATOR . 'Log.php';
- class XMLStream
- {
-
- protected $socket;
-
- protected $parser;
-
- protected $buffer;
-
- protected $xml_depth = 0;
-
- protected $host;
-
- protected $port;
-
- protected $stream_start = '<stream>';
-
- protected $stream_end = '</stream>';
-
- protected $disconnected = false;
-
- protected $sent_disconnect = false;
-
- protected $ns_map = [];
-
- protected $current_ns = [];
-
- protected $xmlobj = null;
-
- protected $nshandlers = [];
-
- protected $xpathhandlers = [];
-
- protected $idhandlers = [];
-
- protected $eventhandlers = [];
-
- protected $lastid = 0;
-
- protected $default_ns;
-
- protected $until = [];
-
- protected $until_count = [];
-
- protected $until_happened = false;
-
- protected $until_payload = [];
-
- protected $log;
-
- protected $reconnect = true;
-
- protected $been_reset = false;
-
- protected $is_server;
-
- protected $last_send = 0;
-
- protected $use_ssl = false;
-
- protected $reconnectTimeout = 30;
-
- 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($print_log, $log_level);
- }
-
- public function setupParser(): void
- {
- $this->parser = xml_parser_create('UTF-8');
- xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);
- xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
- xml_set_object($this->parser, $this);
- xml_set_element_handler($this->parser, 'startXML', 'endXML');
- xml_set_character_data_handler($this->parser, 'charXML');
- }
-
- public function __destruct()
- {
- if (!$this->disconnected && $this->socket) {
- $this->disconnect();
- }
- }
-
- public function disconnect(): void
- {
- $this->log->log("Disconnecting...", Log::LEVEL_VERBOSE);
- if (false == (bool)$this->socket) {
- return;
- }
- $this->reconnect = false;
- $this->send($this->stream_end);
- $this->sent_disconnect = true;
- $this->processUntil('end_stream', 5);
- $this->disconnected = true;
- }
-
- public function send(string $msg, ?int $timeout = null)
- {
- if (is_null($timeout)) {
- $secs = null;
- $usecs = null;
- } elseif ($timeout == 0) {
- $secs = 0;
- $usecs = 0;
- } else {
- $maximum = $timeout * 1000000;
- $usecs = $maximum % 1000000;
- $secs = floor(($maximum - $usecs) / 1000000);
- }
- $read = [];
- $write = [$this->socket];
- $except = [];
- $select = @stream_select($read, $write, $except, $secs, $usecs);
- if ($select === false) {
- $this->log->log("ERROR sending message; reconnecting.");
- $this->doReconnect();
-
- return false;
- } elseif ($select > 0) {
- $this->log->log("Socket is ready; send it.", Log::LEVEL_VERBOSE);
- } else {
- $this->log->log("Socket is not ready; break.", Log::LEVEL_ERROR);
- return false;
- }
- $sentbytes = @fwrite($this->socket, $msg);
- $this->log->log("SENT: " . mb_substr($msg, 0, $sentbytes, '8bit'), Log::LEVEL_VERBOSE);
- if ($sentbytes === false) {
- $this->log->log("ERROR sending message; reconnecting.", Log::LEVEL_ERROR);
- $this->doReconnect();
- return false;
- }
- $this->log->log("Successfully sent $sentbytes bytes.", Log::LEVEL_VERBOSE);
- return $sentbytes;
- }
-
- public function doReconnect()
- {
- if (!$this->is_server) {
- $this->log->log("Reconnecting ($this->reconnectTimeout)...", Log::LEVEL_WARNING);
- $this->connect(false, false, $this->reconnectTimeout);
- $this->reset();
- $this->event('reconnect');
- }
- }
-
- public function connect(bool $persistent = false, bool $send_init = true, int $timeout = 30): void
- {
- $this->sent_disconnect = false;
- $start_time = time();
- do {
- $this->disconnected = false;
- $this->sent_disconnect = false;
- if ($persistent) {
- $conflag = STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT;
- } else {
- $conflag = STREAM_CLIENT_CONNECT;
- }
- $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;
-
- sleep(min($timeout, 5));
- }
- } while (!$this->socket && (time() - $start_time) < $timeout);
- if ($this->socket) {
- stream_set_blocking($this->socket, 1);
- if ($send_init) {
- $this->send($this->stream_start);
- }
- } else {
- throw new Exception("Could not connect before timeout.");
- }
- }
-
- public function reset(): void
- {
- $this->xml_depth = 0;
- unset($this->xmlobj);
- $this->xmlobj = [];
- $this->setupParser();
- if (!$this->is_server) {
- $this->send($this->stream_start);
- }
- $this->been_reset = true;
- }
-
- public function event(string $name, ?array $payload = null): void
- {
- $this->log->log("EVENT: {$name}", Log::LEVEL_DEBUG);
- foreach ($this->eventhandlers as $handler) {
- if ($handler[0] === $name) {
- call_user_func_array($handler[1], [&$payload]);
- }
- }
- foreach ($this->until as $key => $until) {
- if (is_array($until)) {
- if (in_array($name, $until)) {
- $this->until_payload[$key][] = [$name, $payload];
- if (!isset($this->until_count[$key])) {
- $this->until_count[$key] = 0;
- }
- $this->until_count[$key] += 1;
-
- }
- }
- }
- }
-
- public function processUntil($event, int $timeout = -1): array
- {
- $start = time();
- if (!is_array($event)) {
- $event = array($event);
- }
- $this->until[] = $event;
- end($this->until);
- $event_key = key($this->until);
- reset($this->until);
- $this->until_count[$event_key] = 0;
- while (!$this->disconnected and $this->until_count[$event_key] < 1 and (time() - $start < $timeout or $timeout == -1)) {
- $this->__process();
- }
- if (array_key_exists($event_key, $this->until_payload)) {
- $payload = $this->until_payload[$event_key];
- unset($this->until_payload[$event_key]);
- unset($this->until_count[$event_key]);
- unset($this->until[$event_key]);
- } else {
- $payload = [];
- }
- return $payload;
- }
-
- private function __process(int $maximum = 5): bool
- {
- $remaining = $maximum;
- do {
- $starttime = (microtime(true) * 1000000);
- $read = array($this->socket);
- $write = [];
- $except = [];
- if (is_null($maximum)) {
- $secs = null;
- $usecs = null;
- } elseif ($maximum == 0) {
- $secs = 0;
- $usecs = 0;
- } else {
- $usecs = $remaining % 1000000;
- $secs = floor(($remaining - $usecs) / 1000000);
- }
- $updated = @stream_select($read, $write, $except, $secs, $usecs);
- if ($updated === false) {
- $this->log->log("Error on stream_select()", Log::LEVEL_VERBOSE);
- if ($this->reconnect) {
- $this->doReconnect();
- } else {
- fclose($this->socket);
- $this->socket = null;
- return false;
- }
- } elseif ($updated > 0) {
-
- $buff = @fread($this->socket, 4096);
- if (!$buff) {
- if ($this->reconnect) {
- $this->doReconnect();
- } else {
- fclose($this->socket);
- $this->socket = null;
- return false;
- }
- }
- $this->log->log("RECV: $buff", Log::LEVEL_VERBOSE);
- xml_parse($this->parser, $buff, false);
- }
-
- $endtime = (microtime(true) * 1000000);
- $time_past = $endtime - $starttime;
- $remaining = $remaining - $time_past;
- } while (is_null($maximum) || $remaining > 0);
- return true;
- }
-
- public function getLog(): Log
- {
- return $this->log;
- }
-
- public function getId(): string
- {
- ++$this->lastid;
- return (string) $this->lastid;
- }
-
- public function useSSL(bool $use = true): void
- {
- $this->use_ssl = $use;
- }
-
- protected function ensureHandler($pointer, $obj = false): callable
- {
- $handler = $pointer;
- if (is_string($pointer)) {
- if (is_object($obj)) {
- $handler = [$obj, $pointer];
- } elseif (is_null($obj)) {
-
- $handler = [$this, $pointer];
- }
- }
- if (!is_callable($handler)) {
- throw new \InvalidArgumentException(
- 'Cannot compose a proper callable'
- );
- }
- return $handler;
- }
-
- public function addIdHandler(string $id, $pointer, $obj = null): void
- {
- $this->idhandlers[$id] = [$this->ensureHandler($pointer, $obj)];
- }
-
-
- public function addXPathHandler(string $xpath, $pointer, $obj = null): void
- {
- if (preg_match_all('/\/?(\{[^\}]+\})?[^\/]+/', $xpath, $regs)) {
- $tag = $regs[0];
- } else {
- $tag = [$xpath];
- }
- $xpath_array = [];
- foreach ($tag as $t) {
- $t = ltrim($t, '/');
- preg_match('/(\{([^\}]+)\})?(.*)/', $t, $regs);
- $xpath_array[] = [$regs[2], $regs[3]];
- }
- $this->xpathhandlers[] = [$xpath_array, $this->ensureHandler($pointer, $obj)];
- }
-
- public function addEventHandler(string $name, $pointer, $obj = null): void
- {
- $this->eventhandlers[] = [$name, $this->ensureHandler($pointer, $obj)];
- }
-
- public function setReconnectTimeout(int $timeout): void
- {
- $this->reconnectTimeout = $timeout;
- }
-
- public function isDisconnected(): bool
- {
- return $this->disconnected;
- }
-
- public function process(): void
- {
- $this->__process(null);
- }
-
- public function processTime($timeout = null): string
- {
- if (is_null($timeout)) {
- return $this->__process(null);
- } else {
- return $this->__process($timeout * 1000000);
- }
- }
-
-
- public function startXML($parser, string $name, array $attr): void
- {
- if ($this->been_reset) {
- $this->been_reset = false;
- $this->xml_depth = 0;
- }
- $this->xml_depth++;
- if (array_key_exists('XMLNS', $attr)) {
- $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;
- }
- }
- $ns = $this->current_ns[$this->xml_depth];
- foreach ($attr as $key => $value) {
- if (strstr($key, ":")) {
- $key = explode(':', $key);
- $key = $key[1];
- $this->ns_map[$key] = $value;
- }
- }
- if (!strstr($name, ":") === false) {
- $name = explode(':', $name);
- $ns = $this->ns_map[$name[0]];
- $name = $name[1];
- }
- $obj = new XMLObj($name, $ns, $attr);
- if ($this->xml_depth > 1) {
- $this->xmlobj[$this->xml_depth - 1]->subs[] = $obj;
- }
- $this->xmlobj[$this->xml_depth] = $obj;
- }
-
- public function endXML($parser, string $name): void
- {
-
-
- if ($this->been_reset) {
- $this->been_reset = false;
- $this->xml_depth = 0;
- }
- $this->xml_depth--;
- if ($this->xml_depth == 1) {
-
-
- $searchxml = null;
- foreach ($this->xpathhandlers as $handler) {
- if (is_array($this->xmlobj) && array_key_exists(2, $this->xmlobj)) {
- $searchxml = $this->xmlobj[2];
- $nstag = array_shift($handler[0]);
- if (($nstag[0] == null or $searchxml->ns == $nstag[0]) and ($nstag[1] == "*" or $nstag[1] == $searchxml->name)) {
- foreach ($handler[0] as $nstag) {
- if ($searchxml !== null and $searchxml->hasSub($nstag[1], $ns = $nstag[0])) {
- $searchxml = $searchxml->sub($nstag[1], $ns = $nstag[0]);
- } else {
- $searchxml = null;
- break;
- }
- }
- if (!is_null($searchxml)) {
- call_user_func_array($handler[1], [&$this->xmlobj[2]]);
- }
- }
- }
- }
- foreach ($this->nshandlers as $handler) {
- if ($handler[4] != 1 and array_key_exists(2, $this->xmlobj) and $this->xmlobj[2]->hasSub($handler[0])) {
- $searchxml = $this->xmlobj[2]->sub($handler[0]);
- } elseif (is_array($this->xmlobj) and array_key_exists(2, $this->xmlobj)) {
- $searchxml = $this->xmlobj[2];
- }
- if (
- !is_null($searchxml)
- && $searchxml->name === $handler[0]
- && (
- (!$handler[1] && $searchxml->ns === $this->default_ns)
- || $searchxml->ns === $handler[1]
- )
- ) {
- call_user_func_array($handler[2], [&$this->xmlobj[2]]);
- }
- }
- foreach ($this->idhandlers as $id => $handler) {
- if (
- array_key_exists(2, $this->xmlobj)
- && array_key_exists('id', $this->xmlobj[2]->attrs)
- && $this->xmlobj[2]->attrs['id'] === (string) $id
- ) {
- call_user_func_array($handler[0], [&$this->xmlobj[2]]);
-
- unset($this->idhandlers[$id]);
- break;
- }
- }
- if (is_array($this->xmlobj)) {
- $this->xmlobj = array_slice($this->xmlobj, 0, 1);
- if (isset($this->xmlobj[0]) && $this->xmlobj[0] instanceof XMLObj) {
- $this->xmlobj[0]->subs = null;
- }
- }
- unset($this->xmlobj[2]);
- }
- if ($this->xml_depth == 0 and !$this->been_reset) {
- if (!$this->disconnected) {
- if (!$this->sent_disconnect) {
- $this->send($this->stream_end);
- }
- $this->disconnected = true;
- $this->sent_disconnect = true;
- fclose($this->socket);
- if ($this->reconnect) {
- $this->doReconnect();
- }
- }
- $this->event('end_stream');
- }
- }
-
- public function charXML($parser, string $data): void
- {
- if (array_key_exists($this->xml_depth, $this->xmlobj)) {
- $this->xmlobj[$this->xml_depth]->data .= $data;
- }
- }
-
- public function read(): bool
- {
- $buff = @fread($this->socket, 1024);
- if (!$buff) {
- if ($this->reconnect) {
- $this->doReconnect();
- } else {
- fclose($this->socket);
- return false;
- }
- }
- $this->log->log("RECV: $buff", Log::LEVEL_VERBOSE);
- xml_parse($this->parser, $buff, false);
- return true;
- }
- public function time(): float
- {
- list($usec, $sec) = explode(" ", microtime());
- return (float)$sec + (float)$usec;
- }
- public function readyToProcess(): bool
- {
- $read = array($this->socket);
- $write = [];
- $except = [];
- $updated = @stream_select($read, $write, $except, 0);
- return (($updated !== false) && ($updated > 0));
- }
- }
|