Completed
Pull Request — master (#234)
by Дмитрий
07:45 queued 03:41
created

Connection::message()   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 4
dl 0
loc 22
rs 8.9197
eloc 14
c 1
b 1
f 0
nc 8
nop 5
1
<?php
2
namespace PHPDaemon\Clients\XMPP;
3
4
use PHPDaemon\Clients\XMPP\XMPPRoster;
5
use PHPDaemon\Core\Daemon;
6
use PHPDaemon\Core\Timer;
7
use PHPDaemon\Network\ClientConnection;
8
use PHPDaemon\Traits\EventHandlers;
9
use PHPDaemon\XMLStream\XMLStream;
10
11
/**
12
 * @package    NetworkClients
13
 * @subpackage XMPPClient
14
 * @author     Vasily Zorin <[email protected]>
15
 */
16
class Connection extends ClientConnection
17
{
18
19
    /**
20
     * @var boolean
21
     */
22
    public $use_encryption = false;
23
    
24
    /**
25
     * @var boolean
26
     */
27
    public $authorized;
28
    
29
    /**
30
     * @var integer
31
     */
32
    public $lastId = 0;
33
    
34
    /**
35
     * @var XMPPRoster
36
     */
37
    public $roster;
38
    
39
    /**
40
     * @var XMLStream
41
     */
42
    public $xml;
43
    
44
    /**
45
     * @var string
46
     */
47
    public $fulljid;
48
    
49
    /**
50
     * @var integer|string Timer ID
51
     */
52
    public $keepaliveTimer;
53
54
    /**
55
     * Get next ID
56
     * @return string
57
     */
58
    public function getId()
59
    {
60
        $id = ++$this->lastId;
61
        return dechex($id);
62
    }
63
64
    /**
65
     * Called when the connection is handshaked (at low-level), and peer is ready to recv. data
66
     * @return void
67
     */
68
    public function onReady()
69
    {
70
        $this->createXMLStream();
71
        $this->startXMLStream();
72
        $this->keepaliveTimer = setTimeout(function ($timer) {
0 ignored issues
show
Unused Code introduced by
The parameter $timer is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
73
            $this->ping();
74
        }, 1e6 * 30);
75
    }
76
77
    /**
78
     * Called when session finishes
79
     * @return void
80
     */
81
    public function onFinish()
82
    {
83
        parent::onFinish();
84
        $this->event('disconnect');
85
        if (isset($this->xml)) {
86
            $this->xml->finish();
87
        }
88
        unset($this->roster);
89
        if ($this->keepaliveTimer) {
90
            Timer::remove($this->keepaliveTimer);
91
        }
92
    }
93
94
    /**
95
     * @TODO DESCR
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
96
     * @param string $s
97
     */
98
    public function sendXML($s)
99
    {
100
        //Daemon::log(Debug::dump(['send', $s]));
0 ignored issues
show
Unused Code Comprehensibility introduced by
71% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
101
        $this->write($s);
102
    }
103
104
    /**
105
     * @TODO DESCR
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
106
     */
107
    public function startXMLStream()
108
    {
109
        $this->sendXML('<?xml version="1.0"?>' .
110
                       '<stream:stream xmlns:stream="http://etherx.jabber.org/streams" version="1.0" xmlns="jabber:client" to="' . $this->host . '" xml:lang="en" xmlns:xml="http://www.w3.org/XML/1998/namespace">'
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 212 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
111
        );
112
    }
113
114
    /**
115
     * @TODO DESCR
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
116
     * @param  string   $xml
117
     * @param  callable $cb
118
     * @callback $cb ( )
119
     * @return boolean
120
     */
121 View Code Duplication
    public function iqSet($xml, $cb)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
122
    {
123
        if (!isset($this->xml)) {
124
            return false;
125
        }
126
        $id = $this->getId();
127
        $this->xml->addIdHandler($id, $cb);
128
        $this->sendXML('<iq xmlns="jabber:client" type="set" id="' . $id . '">' . $xml . '</iq>');
129
        return true;
130
    }
131
132
    /**
133
     * @TODO DESCR
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
134
     * @param  string   $to
135
     * @param  string   $xml
136
     * @param  callable $cb
137
     * @callback $cb ( )
138
     * @return boolean
139
     */
140 View Code Duplication
    public function iqSetTo($to, $xml, $cb)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
141
    {
142
        if (!isset($this->xml)) {
143
            return false;
144
        }
145
        $id = $this->getId();
146
        $this->xml->addIdHandler($id, $cb);
147
        $this->sendXML('<iq xmlns="jabber:client" type="set" id="' . $id . '" to="' . htmlspecialchars($to) . '">' . $xml . '</iq>');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 133 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
148
        return true;
149
    }
150
151
    /**
152
     * @TODO DESCR
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
153
     * @param  string   $xml
154
     * @param  callable $cb
155
     * @callback $cb ( )
156
     * @return boolean
157
     */
158 View Code Duplication
    public function iqGet($xml, $cb)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
159
    {
160
        if (!isset($this->xml)) {
161
            return false;
162
        }
163
        $id = $this->getId();
164
        $this->xml->addIdHandler($id, $cb);
165
        $this->sendXML('<iq xmlns="jabber:client" type="get" id="' . $id . '">' . $xml . '</iq>');
166
        return true;
167
    }
168
169
    /**
170
     * @TODO DESCR
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
171
     * @param  string   $to
172
     * @param  string   $xml
173
     * @param  callable $cb
174
     * @callback $cb ( )
175
     * @return boolean
176
     */
177 View Code Duplication
    public function iqGetTo($to, $xml, $cb)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
178
    {
179
        if (!isset($this->xml)) {
180
            return false;
181
        }
182
        $id = $this->getId();
183
        $this->xml->addIdHandler($id, $cb);
184
        $this->sendXML('<iq xmlns="jabber:client" type="get" id="' . $id . '" to="' . htmlspecialchars($to) . '">' . $xml . '</iq>');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 133 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
185
        return true;
186
    }
187
188
    /**
189
     * @TODO DESCR
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
190
     * @param  string   $to
0 ignored issues
show
Documentation introduced by
Should the type for parameter $to not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
191
     * @param  callable $cb
0 ignored issues
show
Documentation introduced by
Should the type for parameter $cb not be callable|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
192
     * @callback $cb ( )
193
     * @return boolean
194
     */
195
    public function ping($to = null, $cb = null)
196
    {
197
        if (!isset($this->xml)) {
198
            return false;
199
        }
200
        if ($to === null) {
201
            $to = $this->host;
202
        }
203
        //Daemon::log('Sending ping to '.$to);
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
204
        return $this->iqGetTo($to, '<ping xmlns="urn:xmpp:ping"/>', $cb);
0 ignored issues
show
Bug introduced by
It seems like $cb defined by parameter $cb on line 195 can also be of type null; however, PHPDaemon\Clients\XMPP\Connection::iqGetTo() does only seem to accept callable, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
205
    }
206
207
    /**
208
     * @TODO DESCR
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
209
     * @param  string   $ns
210
     * @param  callable $cb
211
     * @callback $cb ( )
212
     * @return boolean
213
     */
214
    public function queryGet($ns, $cb)
215
    {
216
        return $this->iqGet('<query xmlns="' . $ns . '" />', $cb);
217
    }
218
219
    /**
220
     * @TODO DESCR
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
221
     * @param  string   $ns
222
     * @param  string   $xml
223
     * @param  callable $cb
224
     * @callback $cb ( )
225
     * @return boolean
226
     */
227
    public function querySet($ns, $xml, $cb)
228
    {
229
        return $this->iqSet('<query xmlns="' . $ns . '">' . $xml . '</query>', $cb);
230
    }
231
232
    /**
233
     * @TODO DESCR
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
234
     * @param  string   $to
235
     * @param  string   $ns
236
     * @param  string   $xml
237
     * @param  callable $cb
238
     * @callback $cb ( )
239
     * @return boolean
240
     */
241
    public function querySetTo($to, $ns, $xml, $cb)
242
    {
243
        return $this->iqSetTo($to, '<query xmlns="' . $ns . '">' . $xml . '</query>', $cb);
244
    }
245
246
    /**
247
     * @TODO DESCR
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
248
     */
249
    public function createXMLStream()
250
    {
251
        $this->xml = new XMLStream;
252
        $this->xml->setDefaultNS('jabber:client');
253
        $this->xml->addXPathHandler('{http://etherx.jabber.org/streams}features', function ($xml) {
254
            /** @var XMLStream $xml */
255
            if ($xml->hasSub('starttls') and $this->use_encryption) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
256
                $this->sendXML("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'><required /></starttls>");
257
            } elseif ($xml->hasSub('bind') and $this->authorized) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
258
                $id = $this->getId();
0 ignored issues
show
Unused Code introduced by
$id is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
259
                $this->iqSet('<bind xmlns="urn:ietf:params:xml:ns:xmpp-bind"><resource>' . $this->path . '</resource></bind>', function ($xml) {
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 144 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
260
                    if ($xml->attrs['type'] === 'result') {
261
                        $this->fulljid = $xml->sub('bind')->sub('jid')->data;
262
                        $jidarray      = explode('/', $this->fulljid);
263
                        $this->jid     = $jidarray[0];
0 ignored issues
show
Documentation introduced by
The property jid does not exist on object<PHPDaemon\Clients\XMPP\Connection>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
264
                    }
265
                    $this->iqSet('<session xmlns="urn:ietf:params:xml:ns:xmpp-session" />', function ($xml) {
0 ignored issues
show
Unused Code introduced by
The parameter $xml is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
266
                        $this->roster = new XMPPRoster($this);
267
                        if ($this->onConnected) {
268
                            $this->connected = true;
269
                            $this->onConnected->executeAll($this);
270
                            $this->onConnected = null;
271
                        }
272
                        $this->event('connected');
273
                    });
274
                });
275
            } else {
276
                if (mb_orig_strlen($this->password)) {
277
                    $this->sendXML("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>" . base64_encode("\x00" . $this->user . "\x00" . $this->password) . "</auth>");
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 181 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
278
                } else {
279
                    $this->sendXML("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='ANONYMOUS'/>");
280
                }
281
            }
282
        });
283
        $this->xml->addXPathHandler('{urn:ietf:params:xml:ns:xmpp-sasl}success', function ($xml) {
0 ignored issues
show
Unused Code introduced by
The parameter $xml is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
284
            $this->authorized = true;
285
            $this->xml->finish();
286
            $this->createXMLStream();
287
            $this->startXMLStream();
288
        });
289
        $this->xml->addXPathHandler('{urn:ietf:params:xml:ns:xmpp-sasl}failure', function ($xml) {
0 ignored issues
show
Unused Code introduced by
The parameter $xml is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
290
            if ($this->onConnected) {
291
                $this->connected = false;
292
                $func = $this->onConnected;
293
                $func($this);
294
                $this->onConnected = null;
295
            }
296
            $this->finish();
297
        });
298
        $this->xml->addXPathHandler('{urn:ietf:params:xml:ns:xmpp-tls}proceed', function ($xml) {
0 ignored issues
show
Unused Code introduced by
The parameter $xml is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
299
            Daemon::log("XMPPClient: TLS not supported.");
300
        });
301
        $this->xml->addXPathHandler('{jabber:client}message', function ($xml) {
302
            if (isset($xml->attrs['type'])) {
303
                $payload['type'] = $xml->attrs['type'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$payload was never initialized. Although not strictly required by PHP, it is generally a good practice to add $payload = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
304
            } else {
305
                $payload['type'] = 'chat';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$payload was never initialized. Although not strictly required by PHP, it is generally a good practice to add $payload = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
306
            }
307
            $payload['xml']  = $xml;
308
            $payload['from'] = $xml->attrs['from'];
309
            if ($xml->hasSub('body')) {
310
                $payload['body'] = $xml->sub('body')->data;
311
                $this->event('message', $payload);
312
            }
313
        });
314
    }
315
316
    /**
317
     * Send XMPP Message
318
     * @param string $to
319
     * @param string $body
320
     * @param string $type
321
     * @param string $subject
0 ignored issues
show
Documentation introduced by
Should the type for parameter $subject not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
322
     */
323
    public function message($to, $body, $type = 'chat', $subject = null, $payload = null)
324
    {
325
        if ($type === null) {
326
            $type = 'chat';
327
        }
328
329
        $to      = htmlspecialchars($to);
330
        $body    = htmlspecialchars($body);
331
        $subject = htmlspecialchars($subject);
332
333
        $out = '<message from="' . $this->fulljid . '" to="' . $to . '" type="' . $type . '">';
334
        if ($subject) {
335
            $out .= '<subject>' . $subject . '</subject>';
336
        }
337
        $out .= '<body>' . $body . '</body>';
338
        if ($payload) {
339
            $out .= $payload;
340
        }
341
        $out .= "</message>";
342
343
        $this->sendXML($out);
344
    }
345
346
    /**
347
     * Set Presence
348
     * @param string  $status
0 ignored issues
show
Documentation introduced by
Should the type for parameter $status not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
349
     * @param string  $show
350
     * @param string  $to
0 ignored issues
show
Documentation introduced by
Should the type for parameter $to not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
351
     * @param string  $type
352
     * @param integer $priority
353
     */
354
    public function presence($status = null, $show = 'available', $to = null, $type = 'available', $priority = 0)
355
    {
356
        if ($type === 'available') {
357
            $type = '';
358
        }
359
        $to     = htmlspecialchars($to);
360
        $status = htmlspecialchars($status);
361
        $show = htmlspecialchars($show);
362
        $type = htmlspecialchars($type);
363
        $priority = htmlspecialchars($priority);
364
        if ($show === 'unavailable') {
365
            $type = 'unavailable';
366
        }
367
368
        $out = "<presence";
369
        $out .= ' from="' . $this->fulljid . '"';
370
        if ($to) {
371
            $out .= ' to="' . $to . '"';
372
        }
373
        if ($type) {
374
            $out .= ' type="' . $type . '"';
375
        }
376
        $inner = '';
377
        if ($show !== 'available') {
378
            $inner .= "<show>$show</show>";
379
        }
380
        if ($status) {
381
            $inner .= "<status>$status</status>";
382
        }
383
        if ($priority) {
384
            $inner .= "<priority>$priority</priority>";
385
        }
386
        if ($inner === '') {
387
            $out .= "/>";
388
        } else {
389
            $out .= '>' . $inner . '</presence>';
390
        }
391
392
        $this->sendXML($out);
393
    }
394
395
    /**
396
     * @TODO DESCR
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
397
     * @param string   $jid
0 ignored issues
show
Documentation introduced by
Should the type for parameter $jid not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
398
     * @param callable $cb
399
     * @callback $cb ( )
400
     */
401
    public function getVCard($jid = null, $cb)
402
    {
403
        $id = $this->getId();
404
        $this->xml->addIdHandler($id, function ($xml) use ($cb) {
405
            $vcard    = [];
406
            $vcardXML = $xml->sub('vcard');
407
            foreach ($vcardXML->subs as $sub) {
408
                if ($sub->subs) {
409
                    $vcard[$sub->name] = [];
410
                    foreach ($sub->subs as $sub_child) {
411
                        $vcard[$sub->name][$sub_child->name] = $sub_child->data;
412
                    }
413
                } else {
414
                    $vcard[$sub->name] = $sub->data;
415
                }
416
            }
417
            $vcard['from'] = $xml->attrs['from'];
418
            $cb($vcard);
419
        });
420
        $id = htmlspecialchars($id);
421
        $jid = htmlspecialchars($jid);
422
        if ($jid) {
423
            $this->send('<iq type="get" id="' . $id . '" to="' . $jid . '"><vCard xmlns="vcard-temp" /></iq>');
0 ignored issues
show
Documentation Bug introduced by
The method send does not exist on object<PHPDaemon\Clients\XMPP\Connection>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
424
        } else {
425
            $this->send('<iq type="get" id="' . $id . '"><vCard xmlns="vcard-temp" /></iq>');
0 ignored issues
show
Documentation Bug introduced by
The method send does not exist on object<PHPDaemon\Clients\XMPP\Connection>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
426
        }
427
    }
428
429
    /**
430
     * Called when new data received
431
     * @return void
432
     */
433
    public function onRead()
434
    {
435
        Timer::setTimeout($this->keepaliveTimer);
436
        if (isset($this->xml)) {
437
            $this->xml->feed($this->readUnlimited());
438
        }
439
    }
440
}
441