Completed
Push — class-eventloop ( 5bf25d...85cff1 )
by Vasily
06:25
created

XMPPRoster::getPresence()   C

Complexity

Conditions 8
Paths 4

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 8
eloc 16
c 2
b 1
f 0
nc 4
nop 1
dl 0
loc 23
rs 6.1403
1
<?php
2
namespace PHPDaemon\Clients\XMPP;
3
4
use PHPDaemon\Traits\EventHandlers;
5
6
class XMPPRoster
7
{
8
    use EventHandlers;
9
    use \PHPDaemon\Traits\ClassWatchdog;
10
    use \PHPDaemon\Traits\StaticObjectWatchdog;
11
12
    /**
13
     * @var Connection
14
     */
15
    public $xmpp;
16
17
    /**
18
     * @var array
19
     */
20
    public $roster_array = [];
21
22
    /**
23
     * @var boolean
24
     */
25
    public $track_presence = true;
26
27
    /**
28
     * @var boolean
29
     */
30
    public $auto_subscribe = true;
31
32
    /**
33
     * @var string
34
     */
35
    public $ns = 'jabber:iq:roster';
36
37
    /**
38
     * Constructor
39
     * @param Connection $xmpp
40
     */
41
    public function __construct($xmpp)
42
    {
43
        $this->xmpp = $xmpp;
44
45
        $this->xmpp->xml->addXPathHandler('{jabber:client}presence', function ($xml) {
46
            $payload = [];
47
            $payload['type'] = (isset($xml->attrs['type'])) ? $xml->attrs['type'] : 'available';
48
            $payload['show'] = (isset($xml->sub('show')->data)) ? $xml->sub('show')->data : $payload['type'];
49
            $payload['from'] = $xml->attrs['from'];
50
            $payload['status'] = (isset($xml->sub('status')->data)) ? $xml->sub('status')->data : '';
51
            $payload['priority'] = (isset($xml->sub('priority')->data)) ? intval($xml->sub('priority')->data) : 0;
52
            $payload['xml'] = $xml;
53
            if (($payload['from'] === $this->xmpp->fulljid) && $payload['type'] === 'unavailable') {
54
                $this->xmpp->finish();
55
            }
56
            if ($this->track_presence) {
57
                $this->setPresence($payload['from'], $payload['priority'], $payload['show'], $payload['status']);
58
            }
59
            //Daemon::log("Presence: {$payload['from']} [{$payload['show']}] {$payload['status']}");
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% 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...
60
            if (array_key_exists('type', $xml->attrs) and $xml->attrs['type'] === 'subscribe') {
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...
61
                if ($this->auto_subscribe) {
62
                    $this->xmpp->sendXML("<presence type='subscribed' to='{$xml->attrs['from']}' from='{$this->xmpp->fulljid}' />");
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 132 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...
63
                    $this->xmpp->sendXML("<presence type='subscribe' to='{$xml->attrs['from']}' from='{$this->xmpp->fulljid}' />");
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 131 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...
64
                }
65
                $this->event('subscription_requested', $payload);
66
            } elseif (array_key_exists('type', $xml->attrs) and $xml->attrs['type'] === 'subscribed') {
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...
67
                $this->event('subscription_accepted', $payload);
68
            } else {
69
                $this->event('presence', $payload);
70
            }
71
        });
72
        $this->fetch();
73
    }
74
75
    /**
76
     * @TODO
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...
77
     * @param  string $xml
78
     * @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...
79
     * @callback $cb ( )
80
     */
81
    public function rosterSet($xml, $cb = null)
82
    {
83
        $this->xmpp->querySetTo($this->xmpp->fulljid, $this->ns, $xml, $cb);
0 ignored issues
show
Bug introduced by
It seems like $cb defined by parameter $cb on line 81 can also be of type null; however, PHPDaemon\Clients\XMPP\Connection::querySetTo() 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...
84
    }
85
86
    /**
87
     * @TODO
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...
88
     * @param  string $jid
89
     * @param  string $type
90
     * @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...
91
     * @callback $cb ( )
92
     */
93
    public function setSubscription($jid, $type, $cb = null)
94
    {
95
        $this->rosterSet('<item jid="' . htmlspecialchars($jid) . '" subscription="' . htmlspecialchars($type) . '" />',
96
            $cb);
97
    }
98
99
    /**
100
     * @TODO
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...
101
     * @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...
102
     * @callback $cb ( )
103
     */
104
    public function fetch($cb = null)
105
    {
106
        $this->xmpp->queryGet($this->ns, function ($xml) use ($cb) {
107
            $status = "result";
108
            $xmlroster = $xml->sub('query');
109
            $contacts = [];
110
            foreach ($xmlroster->subs as $item) {
111
                $groups = [];
112
                if ($item->name === 'item') {
113
                    $jid = $item->attrs['jid']; //REQUIRED
114
                    $name = isset($item->attrs['name']) ? $item->attrs['name'] : ''; //MAY
115
                    $subscription = $item->attrs['subscription'];
116
                    foreach ($item->subs as $subitem) {
117
                        if ($subitem->name === 'group') {
118
                            $groups[] = $subitem->data;
119
                        }
120
                    }
121
                    $contacts[] = [$jid, $subscription, $name, $groups]; //Store for action if no errors happen
122
                } else {
123
                    $status = 'error';
124
                }
125
            }
126
            if ($status === 'result') { //No errors, add contacts
127
                foreach ($contacts as $contact) {
128
                    $this->_addContact($contact[0], $contact[1], $contact[2], $contact[3]);
129
                }
130
            }
131
            if ($xml->attrs['type'] === 'set') {
132
                $this->xmpp->sendXML('<iq type="reply" id="' . $xml->attrs['id'] . '" to="' . $xml->attrs['from'] . '" />');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 124 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...
133
            }
134
            if ($cb) {
135
                $cb($status);
136
            }
137
        });
138
    }
139
140
    /**
141
     * Add given contact to roster
142
     * @param string $jid
143
     * @param string $subscription
144
     * @param string $name
145
     * @param array $groups
146
     */
147
    public function _addContact($jid, $subscription, $name = '', $groups = [])
148
    {
149
        $contact = ['jid' => $jid, 'subscription' => $subscription, 'name' => $name, 'groups' => $groups];
150
        if ($this->isContact($jid)) {
151
            $this->roster_array[$jid]['contact'] = $contact;
152
        } else {
153
            $this->roster_array[$jid] = ['contact' => $contact];
154
        }
155
    }
156
157
    /**
158
     * Retrieve contact via jid
159
     * @param  string $jid
160
     * @return array|null
161
     */
162
    public function getContact($jid)
163
    {
164
        if ($this->isContact($jid)) {
165
            return $this->roster_array[$jid]['contact'];
166
        }
167
        return null;
168
    }
169
170
    /**
171
     * Discover if a contact exists in the roster via jid
172
     * @param  string $jid
173
     * @return boolean
174
     */
175
    public function isContact($jid)
176
    {
177
        return array_key_exists($jid, $this->roster_array);
178
    }
179
180
    /**
181
     * Set presence
182
     * @param string $presence
183
     * @param integer $priority
184
     * @param string $show
185
     * @param string $status
186
     */
187
    public function setPresence($presence, $priority, $show, $status)
188
    {
189
        list($jid, $resource) = explode('/', $presence . '/');
190
        if ($show !== 'unavailable') {
191
            if (!$this->isContact($jid)) {
192
                $this->_addContact($jid, 'not-in-roster');
193
            }
194
            $this->roster_array[$jid]['presence'][$resource] = [
195
                'priority' => $priority,
196
                'show' => $show,
197
                'status' => $status
198
            ];
199
        } else { //Nuke unavailable resources to save memory
200
            unset($this->roster_array[$jid]['resource'][$resource]);
201
        }
202
    }
203
204
    /**
205
     * Return best presence for jid
206
     * @param  string $jid
207
     * @return array|false
208
     */
209
    public function getPresence($jid)
210
    {
211
        $split = split("/", $jid);
212
        $jid = $split[0];
213
        if (!$this->isContact($jid)) {
214
            return false;
215
        }
216
        $current = [
217
            'resource' => '',
218
            'active' => '',
219
            'priority' => -129,
220
            'show' => '',
221
            'status' => ''
222
        ]; //Priorities can only be -128 = 127
223
        foreach ($this->roster_array[$jid]['presence'] as $resource => $presence) {
224
            //Highest available priority or just highest priority
225
            if ($presence['priority'] > $current['priority'] && (($presence['show'] === 'chat' || $presence['show'] === 'available') or ($current['show'] !== 'chat' or $current['show'] !== 'available'))) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or 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...
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 205 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...
226
                $current = $presence;
227
                $current['resource'] = $resource;
228
            }
229
        }
230
        return $current;
231
    }
232
}
233