Passed
Pull Request — master (#100)
by Bob
17:47
created

authCheck::tick()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 28
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 18
nc 9
nop 0
dl 0
loc 28
rs 8.439
c 0
b 0
f 0
1
<?php
2
/**
3
 * The MIT License (MIT)
4
 *
5
 * Copyright (c) 2016 Robert Sardinia
6
 *
7
 * Permission is hereby granted, free of charge, to any person obtaining a copy
8
 * of this software and associated documentation files (the "Software"), to deal
9
 * in the Software without restriction, including without limitation the rights
10
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
 * copies of the Software, and to permit persons to whom the Software is
12
 * furnished to do so, subject to the following conditions:
13
 *
14
 * The above copyright notice and this permission notice shall be included in all
15
 * copies or substantial portions of the Software.
16
 *
17
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
 * SOFTWARE.
24
 */
25
26
27
/**
28
 * Class fileAuthCheck
29
 * @property int nextCheck
30
 */
31
class authCheck
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
32
{
33
34
    /**
35
     * @var
36
     */
37
    private $config;
38
    private $db;
39
    private $dbUser;
40
    private $dbPass;
41
    private $dbName;
42
    private $guildID;
43
    private $corpTickers;
44
    private $authGroups;
45
    private $exempt;
46
    private $alertChannel;
47
    private $guild;
48
    private $nameEnforce;
49
    private $nameCheck;
50
    private $discord;
51
    private $logger;
52
53
    /**
54
     * @param $config
55
     * @param $discord
56
     * @param $logger
57
     */
58
    public function init($config, $discord, $logger)
59
    {
60
        $this->config = $config;
61
        $this->discord = $discord;
62
        $this->logger = $logger;
63
        $this->db = $config['database']['host'];
64
        $this->dbUser = $config['database']['user'];
65
        $this->dbPass = $config['database']['pass'];
66
        $this->dbName = $config['database']['database'];
67
        $this->guildID = $config['bot']['guild'];
68
        $this->exempt = $config['plugins']['auth']['exempt'];
69
        $this->corpTickers = $config['plugins']['auth']['corpTickers'];
70
        $this->nameEnforce = $config['plugins']['auth']['nameEnforce'];
71
        $this->authGroups = $config['plugins']['auth']['authGroups'];
72
        $this->alertChannel = $config['plugins']['auth']['alertChannel'];
73
        $this->guild = $config['bot']['guild'];
74
        $this->nextCheck = 0;
75
76
        //Set name check to happen if corpTicker or nameEnforce is set
77
        if ($this->nameEnforce === 'true' || $this->corpTickers === 'true') {
78
            $this->nameCheck = 'true';
79
        }
80
81
        //check if cache has been set
82
        $permsChecked = getPermCache('permsLastChecked');
83
        $namesChecked = getPermCache('nextRename');
84
        if ($namesChecked === NULL) {
85
            setPermCache('nextRename', time());
86
        }
87
88
        //if not set set for now (30 minutes from now for role removal)
89
        if ($permsChecked === NULL) {
90
            setPermCache('permsLastChecked', time() - 5);
91
            setPermCache('authStateLastChecked', time() + 7200);
92
        }
93
    }
94
95
    public function tick()
96
    {
97
        // What was the servers last reported state
98
        $lastStatus = getPermCache('serverState');
99
        if ($lastStatus === 'online') {
100
            $permsChecked = getPermCache('permsLastChecked');
101
            $stateChecked = getPermCache('authStateLastChecked');
102
            $namesChecked = getPermCache('nextRename');
103
104
            if ($permsChecked <= time()) {
105
                $this->logger->addInfo('AuthCheck: Checking for users who have left corp/alliance....');
106
                $this->checkPermissions();
107
                $this->logger->addInfo('AuthCheck: Corp/alliance check complete.');
108
            }
109
110
            if ($stateChecked <= time()) {
111
                $this->logger->addInfo('AuthCheck: Checking for users who have been wrongly given roles....');
112
                $this->checkAuthState();
113
                $this->logger->addInfo('AuthCheck: Role check complete.');
114
            }
115
116
            if ($this->nameCheck === 'true' && $namesChecked <= time()) {
117
                $this->logger->addInfo('AuthCheck: Resetting player names....');
118
                $this->nameReset();
119
                $this->logger->addInfo('AuthCheck: Names reset.');
120
            }
121
        }
122
    }
123
124
    /**
125
     * @return null
126
     */
127
128
    //Remove members who have roles but never authed
129
    private function checkPermissions()
130
    {
131
        //Get guild object
132
        $guild = $this->discord->guilds->get('id', $this->guildID);
133
134
        //Establish connection to mysql
135
        $conn = new mysqli($this->db, $this->dbUser, $this->dbPass, $this->dbName);
136
137
        $sql = "SELECT characterID, discordID, eveName FROM authUsers WHERE active='yes'";
138
139
        $result = $conn->query($sql);
140
141
        //Set empty arrays
142
        $corpArray = array();
143
        $allianceArray = array();
144
145
        // If config is outdated
146 View Code Duplication
        if (null === $this->authGroups) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
147
            $msg = '**Auth Failure:** Please update the bots config to the latest version.';
148
            queueMessage($msg, $this->alertChannel, $this->guild);
149
            $nextCheck = time() + 10800;
150
            setPermCache('permsLastChecked', $nextCheck);
151
            return null;
152
        }
153
154
        //Set corp/ally id arrays
155
        foreach ($this->authGroups as $authGroup) {
156
            if ($authGroup['corpID'] !== 0) {
157
                $corpArray[] = (int)$authGroup['corpID'];
158
            }
159
            if ($authGroup['allianceID'] !== 0) {
160
                $allianceArray[] = (int)$authGroup['allianceID'];
161
            }
162
        }
163
164
        if ($result->num_rows >= 1) {
165
            while ($rows = $result->fetch_assoc()) {
166
                $charID = $rows['characterID'];
167
                $discordID = $rows['discordID'];
168
                $member = $guild->members->get('id', $discordID);
169
                $eveName = $rows['eveName'];
170
                //Check if member has roles
171
                if (null === @$member->roles) {
172
                    continue;
173
                }
174
175
                //Get ingame affiliations
176
                $url = "https://api.eveonline.com/eve/CharacterAffiliation.xml.aspx?ids=$charID";
177
                $xml = makeApiRequest($url);
178
                // Stop the process if the api is throwing an error
179
                if (null === $xml) {
180
                    $this->logger->addInfo("{$eveName} cannot be authed, API issues detected.");
181
                    return null;
182
                }
183
184
                //Auth things
185
                if ($xml->result->rowset->row[0]) {
186
                    foreach ($xml->result->rowset->row as $character) {
187
                        if (!in_array((int) $character->attributes()->allianceID, $allianceArray) && !in_array((int) $character->attributes()->corporationID, $corpArray)) {
188
                            // Deactivate user in database
189
                            $sql = "UPDATE authUsers SET active='no' WHERE discordID='$discordID'";
190
                            $this->logger->addInfo("AuthCheck: {$eveName} account has been deactivated as they are no longer in a correct corp/alliance.");
191
                            $conn->query($sql);
192
                            continue;
193
                        }
194
                    }
195
                }
196
            }
197
            $nextCheck = time() + 10800;
198
            setPermCache('permsLastChecked', $nextCheck);
199
            return null;
200
        }
201
        $nextCheck = time() + 10800;
202
        setPermCache('permsLastChecked', $nextCheck);
203
        return null;
204
    }
205
206
    //Check user corp/alliance affiliation
207
208
209
    private function checkAuthState()
210
    {
211
212
        //Check if exempt roles are set
213
        if (null === $this->exempt) {
214
            $this->exempt = '0';
215
        }
216
217
        // If config is outdated
218 View Code Duplication
        if (null === $this->authGroups) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
219
            $msg = '**Auth Failure:** Please update the bots config to the latest version.';
220
            queueMessage($msg, $this->alertChannel, $this->guild);
221
            //queue up next check
222
            $nextCheck = time() + 1800;
223
            setPermCache('authStateLastChecked', $nextCheck);
224
            return null;
225
        }
226
227
        //Establish connection to mysql
228
        $conn = new mysqli($this->db, $this->dbUser, $this->dbPass, $this->dbName);
229
230
        //get bot ID so we don't remove out own roles
231
        $botID = $this->discord->id;
232
233
        //Get guild object
234
        $guild = $this->discord->guilds->get('id', $this->guildID);
235
236
        //Check to make sure guildID is set correctly
237
        if (null === $guild) {
238
            $this->logger->addError('Config Error: Ensure the guild entry in the config is the guildID (aka serverID) for the main server that the bot is in.');
239
            $nextCheck = time() + 7200;
240
            setPermCache('authLastChecked', $nextCheck);
241
            return null;
242
        }
243
244
        //create empty array to store names
245
        $removedRoles = array();
246
        $userCount = 0;
247
248
        //Perform check if roles were added without permission
249
        foreach ($guild->members as $member) {
250
            $id = $member->id;
251
            $username = $member->username;
252
            $roles = $member->roles;
253
254
            //Skip to next member if this user has no roles
255
            if (null === $roles) {
256
                continue;
257
            }
258
            $sql = "SELECT * FROM authUsers WHERE discordID='$id' AND active='yes'";
259
            $result = $conn->query($sql);
260
261
            //If they are NOT active in the db, check for roles to remove
262
            if ($result->num_rows === 0) {
263
                $userCount++;
264
                foreach ($roles as $role) {
265
                    if (!isset($role->name)) {
266
                        if ($id !== $botID && !in_array($role->name, $this->exempt, true)) {
267
                            $member->removeRole($role);
268
                            $guild->members->save($member);
269
                            // Add users name to array
270
                            $removedRoles[] = $username;
271
                        }
272
                    }
273
                }
274
            }
275
        }
276
        //Report removed users to log and channel
277
        $nameList = implode(', ', $removedRoles);
278
        if ($userCount > 0 && strlen($nameList) > 3 && null !== $nameList) {
279
            $msg = "Following users roles have been removed - {$nameList}";
280
            queueMessage($msg, $this->alertChannel, $this->guild);
281
            $this->logger->addInfo("AuthCheck: Roles removed from {$nameList}");
282
        }
283
        //queue up next check
284
        $nextCheck = time() + 1800;
285
        setPermCache('authStateLastChecked', $nextCheck);
286
        return null;
287
    }
288
289
    private function nameReset()
290
    {
291
        //Get guild object
292
        $guild = $this->discord->guilds->get('id', $this->guildID);
293
294
        //Get name queue status
295
        $x = (int)getPermCache('nameQueueState');
296
297
        //Establish connection to mysql
298
        $conn = new mysqli($this->db, $this->dbUser, $this->dbPass, $this->dbName);
299
        $sql = "SELECT id FROM authUsers WHERE active='yes'";
300
        $count = $conn->query($sql);
301
        $rowAmount = $count->num_rows / 2;
302
        if ($x == 1) {
303
            $sql = "SELECT characterID, discordID, eveName  FROM authUsers WHERE active='yes' ORDER BY id ASC LIMIT {$rowAmount} OFFSET {$rowAmount}";
304
            setPermCache('nameQueueState', 0);
305
        } else {
306
            $sql = "SELECT characterID, discordID, eveName  FROM authUsers WHERE active='yes' ORDER BY id ASC LIMIT {$rowAmount}";
307
            setPermCache('nameQueueState', 1);
308
        }
309
        $result = $conn->query($sql);
310
311
        // If config is outdated
312 View Code Duplication
        if (null === $this->authGroups) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
313
            $msg = '**Auth Failure:** Please update the bots config to the latest version.';
314
            queueMessage($msg, $this->alertChannel, $this->guild);
315
            $nextCheck = time() + 1800;
316
            setPermCache('nextRename', $nextCheck);
317
            return null;
318
        }
319
320
        if (@$result->num_rows >= 1) {
321
            while ($rows = $result->fetch_assoc()) {
322
                $charID = $rows['characterID'];
323
                $discordID = $rows['discordID'];
324
                $member = $guild->members->get('id', $discordID);
325
                $eveName = $rows['eveName'];
326
                //Check if member has roles
327
                if (null === $member->roles) {
328
                    continue;
329
                }
330
331
                //Get current nickname
332
                $guild = $this->discord->guilds->get('id', $this->guildID);
333
                $member = $guild->members->get('id', $discordID);
334
                $nickName = $member->nick;
335
                $userName = $member->user->username;
336
                //If nick isn't set than make it username
337
                if ($nickName == '' || null === $nickName) {
338
                    $nickName = $userName;
339
                }
340
341
                //Get ingame affiliations
342
                if ($this->corpTickers === 'true') {
343
                    $url = "https://api.eveonline.com/eve/CharacterAffiliation.xml.aspx?ids=$charID";
344
                    $xml = makeApiRequest($url);
345
                    // Stop the process if the api is throwing an error
346
                    if (null === $xml) {
347
                        $this->logger->addInfo("{$eveName} cannot be authed, API issues detected.");
348
                        return null;
349
                    }
350
                    if ($xml->result->rowset->row[0]) {
351
                        foreach ($xml->result->rowset->row as $character) {
352
                            $corpInfo = getCorpInfo($character->attributes()->corporationID);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $corpInfo is correct as getCorpInfo($character->...butes()->corporationID) (which targets getCorpInfo()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
353
                            if (null !== $corpInfo) {
354
                                $corpTicker = (string)$corpInfo['corpTicker'];
355 View Code Duplication
                                if ($this->nameEnforce === 'true') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
356
                                    $nick = "[{$corpTicker}] {$eveName}";
357
                                } elseif ((string)$nickName === "[{$corpTicker}]") {
358
                                    $nick = "[{$corpTicker}] {$userName}";
359
                                } elseif (strpos($nickName, $corpTicker) == false) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing strpos($nickName, $corpTicker) of type integer to the boolean false. If you are specifically checking for 0, consider using something more explicit like === 0 instead.
Loading history...
360
                                    $nick = "[{$corpTicker}] {$nickName}";
361
                                } elseif (strpos($nickName, $corpTicker) !== false) {
362
                                    $nick = "{$nickName}";
363
                                    continue;
364
                                }
365
                                if ($nick != $nickName) {
366
                                    queueRename($discordID, $nick, $this->guildID);
0 ignored issues
show
Bug introduced by
The variable $nick does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
367
                                }
368
                                continue;
369
                            }
370
                            $url = "https://api.eveonline.com/corp/CorporationSheet.xml.aspx?corporationID={$character->attributes()->corporationID}";
371
                            $xml = makeApiRequest($url);
372
                            $corpTicker = '';
373
                            $corpName = '';
374
                            foreach ($xml->result as $corporation) {
375
                                $corpTicker = $corporation->ticker;
376
                                $corpName = $corporation->corporationName;
377
                            }
378 View Code Duplication
                            if ($this->nameEnforce === 'true') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
379
                                $nick = "[{$corpTicker}] {$eveName}";
380
                            } elseif ((string)$nickName === "[{$corpTicker}]") {
381
                                $nick = "[{$corpTicker}] {$userName}";
382
                            } elseif (strpos($nickName, $corpTicker) == false) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing strpos($nickName, $corpTicker) of type integer to the boolean false. If you are specifically checking for 0, consider using something more explicit like === 0 instead.
Loading history...
383
                                $nick = "[{$corpTicker}] {$nickName}";
384
                            } elseif (strpos($nickName, $corpTicker) !== false) {
385
                                $nick = "{$nickName}";
386
                                continue;
387
                            }
388
                            if ($nick !== $nickName) {
389
                                queueRename($discordID, $nick, $this->guildID);
390
                            }
391
                            addCorpInfo($character->attributes()->corporationID, $corpTicker, $corpName);
392
                            continue;
393
                        }
394
                    }
395
                }
396
                $nick = "{$eveName}";
397
                if ($nick !== $nickName && $this->corpTickers !== 'true') {
398
                    queueRename($discordID, $nick, $this->guildID);
399
                }
400
                continue;
401
            }
402
            $nextCheck = time() + 1800;
403
            setPermCache('nextRename', $nextCheck);
404
            return null;
405
        }
406
        $nextCheck = time() + 1800;
407
        setPermCache('nextRename', $nextCheck);
408
        return null;
409
410
    }
411
}
412