Passed
Pull Request — master (#198)
by
unknown
03:01
created

authCheck::checkPermissions2()   F

Complexity

Conditions 41
Paths 381

Size

Total Lines 87
Code Lines 58

Duplication

Lines 31
Ratio 35.63 %

Importance

Changes 0
Metric Value
cc 41
eloc 58
nc 381
nop 0
dl 31
loc 87
rs 3.6496
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 $active;
38
    private $config;
39
    private $discord;
40
    private $logger;
41
    private $db;
42
    private $dbUser;
43
    private $dbPass;
44
    private $dbName;
45
    private $guildID;
46
    private $exempt;
47
    private $corpTickers;
48
    private $nameEnforce;
49
    private $standingsBased;
50
    private $apiKey;
51
    private $authGroups;
52
    private $alertChannel;
53
    private $nameCheck;
54
55
    /**
56
     * @param $config
57
     * @param $discord
58
     * @param $logger
59
     */
60
    public function init($config, $discord, $logger)
61
    {
62
        $this->active = true;
63
        $this->config = $config;
64
        $this->discord = $discord;
65
        $this->logger = $logger;
66
        $this->db = $config['database']['host'];
67
        $this->dbUser = $config['database']['user'];
68
        $this->dbPass = $config['database']['pass'];
69
        $this->dbName = $config['database']['database'];
70
        $this->guildID = $config['bot']['guild'];
71
        $this->exempt = $config['plugins']['auth']['exempt'];
72
        $this->corpTickers = $config['plugins']['auth']['corpTickers'];
73
        $this->nameEnforce = $config['plugins']['auth']['nameEnforce'];
74
        $this->standingsBased = $config['plugins']['auth']['standings']['enabled'];
75
        $this->apiKey = $config['eve']['apiKeys'];
76
        $this->authGroups = $config['plugins']['auth']['authGroups'];
77
        $this->alertChannel = $config['plugins']['auth']['alertChannel'];
78
        $this->nextCheck = 0;
79
80
        //Set name check to happen if corpTicker or nameEnforce is set
81
        if ($this->nameEnforce === 'true' || $this->corpTickers === 'true') {
82
            $this->nameCheck = 'true';
83
        }
84
85
        //check if cache has been set
86
        $permsChecked = getPermCache('permsLastChecked');
87
        $namesChecked = getPermCache('nextRename');
88
        if ($namesChecked === NULL) {
89
            setPermCache('nextRename', time());
90
        }
91
92
        //if not set set for now (30 minutes from now for role removal)
93
        if ($permsChecked === NULL) {
94
            setPermCache('permsLastChecked', time() - 1);
95
            setPermCache('authStateLastChecked', time() + 1);
96
        }
97
98
        // If config is outdated
99
        if (null === $this->authGroups) {
100
            $msg = '**Auth Failure:** Please update the bots config to the latest version.';
101
            queueMessage($msg, $this->alertChannel, $this->guildID);
102
            $this->logger->addInfo($msg);
103
            $this->active = false;
104
        }
105
106
    }
107
108
    public function tick()
109
    {
110
        // What was the servers last reported state
111
        $lastStatus = getPermCache('serverState');
112
        if ($this->active && $lastStatus === 'online') {
113
            $permsChecked = getPermCache('permsLastChecked');
114
            $stateChecked = getPermCache('authStateLastChecked');
115
            $namesChecked = getPermCache('nextRename');
116
            $standingsChecked = getPermCache('nextStandingsCheck');
117
118
            if ($permsChecked <= time()) {
119
                $this->logger->addInfo('AuthCheck: Checking for users who have left corp/alliance....');
120
                $this->checkPermissions2();
121
                $this->logger->addInfo('AuthCheck: Corp/alliance check complete.');
122
            }
123
124
            if ($stateChecked <= time()) {
125
                $this->logger->addInfo('AuthCheck: Checking for users who have been wrongly given roles....');
126
                $this->checkAuthState();
127
                $this->logger->addInfo('AuthCheck: Role check complete.');
128
            }
129
130
            if ($this->nameCheck === 'true' && $namesChecked <= time()) {
131
                $this->logger->addInfo('AuthCheck: Resetting player names....');
132
                $this->nameReset();
133
                $this->logger->addInfo('AuthCheck: Names reset.');
134
            }
135
136
            if ($this->standingsBased === 'true' && $standingsChecked <= time()) {
137
                $this->logger->addInfo('AuthCheck: Updating Standings');
138
                $this->standingsUpdate();
139
                $this->logger->addInfo('AuthCheck: Standings Updated');
140
            }
141
        }
142
    }
143
144
    /**
145
     * @return null
146
     */
147
148
    //Remove members who have roles but never authed
149
    private function checkPermissions2()
150
    {
151
        $rows = array();
0 ignored issues
show
Unused Code introduced by
$rows 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...
152
        $dbh = new PDO("mysql:host={$this->db};dbname={$this->dbName}", $this->dbUser, $this->dbPass);
153
        $rows = array_column($dbh->query('SELECT discordID, characterID, eveName, role FROM authUsers')->fetchAll(), null, 'discordID');
154
155
        //Set empty arrays
156
        $corpArray = array_column($this->authGroups, 'corpID');
157
        $allianceArray = array_column($this->authGroups, 'allianceID');
158
159
        foreach ($this->discord->guilds->get('id', $this->guildID)->members as $member) {
160
            $discordID = $member->getIdAttribute();
161
            $discordNick = $member->nick ?: $member->getUsernameAttribute();
162
            if ($member->getRolesAttribute()->isEmpty()) {
163
                continue;
164
            }
165
            if ($this->discord->id == $discordID) {
166
                continue;
167
            }
168
            $this->logger->addDebug("AuthCheck: Username: $discordNick");
169
            if (!isset($rows[$discordID])) {
170
                $this->logger->addInfo("AuthCheck: User [$discordNick] not found in database.");
171
                // remove user
172
                continue;
173
            }
174
            $charID = $rows[$discordID]['characterID'];
175
176
            // corporation membership check
177
            for ($i=0; $i<3; $i++) {
178
                $character = characterDetails($charID);
179
                //if (isset($character['corporation_id']) && in_array($character['corporation_id'], $corpArray))
0 ignored issues
show
Unused Code Comprehensibility introduced by
80% 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...
180
                if (!is_null($character))
181
                    break;
182
                //Postpone check if ESI is down to prevent timeouts
183 View Code Duplication
                if (isset($character['error']) && $character['error'] === 'The datasource tranquility is temporarily unavailable') {
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...
184
                    $this->logger->addInfo('AuthCheck: The datasource tranquility is temporarily unavailable, check canceled.');
185
                    $nextCheck = time() + 10800;
186
                    setPermCache('permsLastChecked', $nextCheck);
187
                    return;
188
                }
189
            }
190 View Code Duplication
            if (is_null($character) || isset($character['error'])) {
0 ignored issues
show
Bug introduced by
The variable $character 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...
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...
191
                $this->logger->addInfo('AuthCheck: characterDetails lookup failed.');
192
                continue;
193
            } elseif (isset($character['corporation_id']) && in_array($character['corporation_id'], $corpArray)) {
194
                continue; // user is in a valid corporation, stop checking
195
            }
196
197
            // alliance membership check
198
            for ($i=0; $i<3; $i++) {
199
                $corporationDetails = corpDetails($corporationID);
0 ignored issues
show
Bug introduced by
The variable $corporationID does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
200
                if (!is_null($corporationDetails))
201
                    break;
202
            }
203 View Code Duplication
            if (is_null($corporationDetails) || isset($corporationDetails['error'])) {
0 ignored issues
show
Bug introduced by
The variable $corporationDetails 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...
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...
204
                $this->logger->addInfo('AuthCheck: corpDetails lookup failed.');
205
                continue;
206
            } else if (isset($corporationDetails['alliance_id']) && in_array($corporationDetails['alliance_id'], $allianceArray)) {
207
                continue; // user is in a valid alliance, stop checking
208
            }
209
210
            //check if user authed based on standings
211
            $role = $rows[$discordID]['role'];
212
            $standings = null;
213 View Code Duplication
            if ($role === 'blue' || 'neut' || 'red') {
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...
214
                $allianceContacts = getContacts($allianceID);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $allianceContacts is correct as getContacts($allianceID) (which targets getContacts()) 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...
Bug introduced by
The variable $allianceID does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
215
                $corpContacts = getContacts($corporationID);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $corpContacts is correct as getContacts($corporationID) (which targets getContacts()) 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...
216
                if ($role === 'blue' && ((int) $allianceContacts['standing'] === 5 || 10 || (int) $corpContacts['standing'] === 5 || 10)) {
217
                    $standings = 1;
218
                }
219
                if ($role === 'red' && ((int) $allianceContacts['standing'] === -5 || -10 || (int) $corpContacts['standing'] === -5 || -10)) {
220
                    $standings = 1;
221
                }
222
                if ($role === 'neut' && ((int) $allianceContacts['standing'] === 0 || (int) $corpContacts['standing'] === 0 || (@(int) $allianceContacts['standings'] === null || '' && @(int) $corpContacts['standings'] === null || ''))) {
223
                    $standings = 1;
224
                }
225
            }
226
            if ($standings)
0 ignored issues
show
Bug Best Practice introduced by
The expression $standings of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
227
                continue; //keep the user based on standings
228
229
            // User failed all checks, deactivate user in database
230
            $sql = "UPDATE authUsers SET active='no' WHERE discordID='$discordID'";
231
            $this->logger->addInfo("AuthCheck: {$eveName} account has been deactivated as they are no longer in a correct corp/alliance.");
0 ignored issues
show
Bug introduced by
The variable $eveName does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
232
            $conn->query($sql);
0 ignored issues
show
Bug introduced by
The variable $conn does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
233
        }
234
        setPermCache('permsLastChecked', time() + 300);
235
    }
236
237
    /**
238
     * @return null
239
     */
240
241
    //Remove members who have roles but never authed
242
    private function checkPermissions()
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
243
    {
244
        //Get guild object
245
        $guild = $this->discord->guilds->get('id', $this->guildID);
246
247
        //Set empty arrays
248
        $corpArray = array();
249
        $allianceArray = array();
250
251
        //Set corp/ally id arrays
252
        foreach ($this->authGroups as $authGroup) {
253
            if ($authGroup['corpID'] !== 0) {
254
                $corpArray[] = $authGroup['corpID'];
255
            }
256
            if ($authGroup['allianceID'] !== 0) {
257
                $allianceArray[] = $authGroup['allianceID'];
258
            }
259
        }
260
261
        //Establish connection to mysql
262
        $conn = new mysqli($this->db, $this->dbUser, $this->dbPass, $this->dbName);
263
264
        $result = $conn->query("SELECT characterID, discordID, eveName, role FROM authUsers WHERE active='yes'");
265
        while ($row = $result->fetch_assoc()) {
266
            $charID = $row['characterID'];
267
            $discordID = $row['discordID'];
268
            $role = $row['role'];
269
            $eveName = $row['eveName'];
270
            //Check if member has roles
271
            //if ($guild->members->get('id', $discordID)->getRolesAttribute()->isEmpty()) {
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...
272
            if ($guild->members->fetch($discordID)->done(function ($r) { return $r->getRolesAttribute()->isEmpty(); })) {
273
                $this->logger->addInfo('AuthCheck: skipping user due to empty roles attribute.');
274
                continue;
275
            }
276
277
            $timeout = 0;
278
            do {
279
                //Auth things
280
                if ($timeout >= 3) {
281
                    $this->logger->addInfo("AuthCheck: ESI lookup failed $timeout times for character: $eveName");
282
                    continue 2; // skip this member and move on to the next one if ESI fails 3 time
283
                }
284
                $timeout++;
285
                $character = characterDetails($charID);
286
287
                //Postpone check if ESI is down to prevent timeouts
288 View Code Duplication
                if (isset($character['error']) && $character['error'] === 'The datasource tranquility is temporarily unavailable') {
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...
289
                    $this->logger->addInfo('AuthCheck: The datasource tranquility is temporarily unavailable, check canceled.');
290
                    $nextCheck = time() + 10800;
291
                    setPermCache('permsLastChecked', $nextCheck);
292
                    return;
293
                }
294
295
            } while (!isset($character['corporation_id']));
296
            $corporationID = $character['corporation_id'];
297
            if (in_array($corporationID, $corpArray))
298
                continue; // user is in a valid corp, stop checking
299
300
            $timeout = 0;
301
            do {
302
                if ($timeout >= 3) {
303
                    $this->logger->addInfo("AuthCheck: ESI lookup failed $timeout times for corporationID: $corporationID");
304
                    continue 2; // skip this member and move on to the next one if ESI fails 3 time
305
                }
306
                $timeout++;
307
                $corporationDetails = corpDetails($corporationID);
308
            } while (!isset($corporationDetails));
309
            if (isset($corporationDetails['alliance_id']) && in_array($corporationDetails['alliance_id'], $allianceArray))
310
                continue; // user is in a valid alliance, stop checking
311
312
            //check if user authed based on standings
313
            $standings = null;
314 View Code Duplication
            if ($role === 'blue' || 'neut' || 'red') {
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...
315
                $allianceContacts = getContacts($allianceID);
0 ignored issues
show
Bug introduced by
The variable $allianceID does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
Are you sure the assignment to $allianceContacts is correct as getContacts($allianceID) (which targets getContacts()) 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...
316
                $corpContacts = getContacts($corporationID);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $corpContacts is correct as getContacts($corporationID) (which targets getContacts()) 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...
317
                if ($role === 'blue' && ((int) $allianceContacts['standing'] === 5 || 10 || (int) $corpContacts['standing'] === 5 || 10)) {
318
                    $standings = 1;
319
                }
320
                if ($role === 'red' && ((int) $allianceContacts['standing'] === -5 || -10 || (int) $corpContacts['standing'] === -5 || -10)) {
321
                    $standings = 1;
322
                }
323
                if ($role === 'neut' && ((int) $allianceContacts['standing'] === 0 || (int) $corpContacts['standing'] === 0 || (@(int) $allianceContacts['standings'] === null || '' && @(int) $corpContacts['standings'] === null || ''))) {
324
                    $standings = 1;
325
                }
326
            }
327
            if ($standings)
0 ignored issues
show
Bug Best Practice introduced by
The expression $standings of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
328
                continue; //keep the user based on standings
329
330
            // User failed all checks, deactivate user in database
331
            $sql = "UPDATE authUsers SET active='no' WHERE discordID='$discordID'";
332
            $this->logger->addInfo("AuthCheck: {$eveName} account has been deactivated as they are no longer in a correct corp/alliance.");
333
            $conn->query($sql);
334
        }
335
        $nextCheck = time() + 10800;
336
        setPermCache('permsLastChecked', $nextCheck);
337
        return;
338
    }
339
340
    //Check user corp/alliance affiliation
341
342
343
    private function checkAuthState()
344
    {
345
346
        //Check if exempt roles are set
347
        if (null === $this->exempt) {
348
            $this->exempt = '0';
349
        }
350
351
        //Establish connection to mysql
352
        $conn = new mysqli($this->db, $this->dbUser, $this->dbPass, $this->dbName);
353
354
        //get bot ID so we don't remove out own roles
355
        $botID = $this->discord->id;
356
357
        //Get guild object
358
        $guild = $this->discord->guilds->get('id', $this->guildID);
359
360
        //Check to make sure guildID is set correctly
361
        if (null === $guild) {
362
            $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.');
363
            $nextCheck = time() + 7200;
364
            setPermCache('authLastChecked', $nextCheck);
365
            return null;
366
        }
367
368
        //create empty array to store names
369
        $removedRoles = array();
370
        $userCount = 0;
371
372
        //Perform check if roles were added without permission
373
        foreach ($guild->members as $member) {
374
            $id = $member->id;
375
            $username = $member->username;
376
            $roles = $member->roles;
377
378
            //Skip to next member if this user has no roles
379
            if (null === $roles) {
380
                continue;
381
            }
382
            $sql = "SELECT * FROM authUsers WHERE discordID='$id' AND active='yes'";
383
            $result = $conn->query($sql);
384
385
            //If they are NOT active in the db, check for roles to remove
386
            if ($result->num_rows === 0) {
387
                $userCount++;
388
                foreach ($roles as $role) {
389
                    if ($id !== $botID && !in_array($role->name, $this->exempt, true)) {
390
                        $member->removeRole($role);
391
                        $guild->members->save($member);
392
                        // Add users name to array
393
                        if (!in_array($username, $removedRoles)) {
394
                            $removedRoles[] = $username;
395
                        }
396
                    }
397
                }
398
            }
399
        }
400
        //Report removed users to log and channel
401
        $nameList = implode(', ', $removedRoles);
402
        if ($userCount > 0 && strlen($nameList) > 3 && null !== $nameList) {
403
            $msg = "Following users roles have been removed - {$nameList}";
404
            queueMessage($msg, $this->alertChannel, $this->guildID);
405
            $this->logger->addInfo("AuthCheck: Roles removed from {$nameList}");
406
        }
407
        //queue up next check
408
        $nextCheck = time() + 1800;
409
        setPermCache('authStateLastChecked', $nextCheck);
410
        return null;
411
    }
412
413
    private function nameReset()
414
    {
415
        //Get guild object
416
        $guild = $this->discord->guilds->get('id', $this->guildID);
417
418
        //Get name queue status
419
        $x = (int) getPermCache('nameQueueState');
420
421
        //Establish connection to mysql
422
        $conn = new mysqli($this->db, $this->dbUser, $this->dbPass, $this->dbName);
423
        $sql = "SELECT id FROM authUsers WHERE active='yes'";
424
        $count = $conn->query($sql);
425
        $rowAmount = round($count->num_rows / 2);
426
        if ($x === 1) {
427
            $sql = "SELECT characterID, discordID, eveName  FROM authUsers WHERE active='yes' ORDER BY id ASC LIMIT {$rowAmount} OFFSET {$rowAmount}";
428
            setPermCache('nameQueueState', 0);
429
        } else {
430
            $sql = "SELECT characterID, discordID, eveName  FROM authUsers WHERE active='yes' ORDER BY id ASC LIMIT {$rowAmount}";
431
            setPermCache('nameQueueState', 1);
432
        }
433
        $result = $conn->query($sql);
434
435
        if (@$result->num_rows >= 1) {
436
            while ($rows = $result->fetch_assoc()) {
437
                $charID = $rows['characterID'];
438
                $discordID = $rows['discordID'];
439
                $member = $guild->members->get('id', $discordID);
440
                $eveName = $rows['eveName'];
441
                //Check if member has roles
442
                if (null === @$member->roles) {
443
                    continue;
444
                }
445
446
                //Get current nickname
447
                $guild = $this->discord->guilds->get('id', $this->guildID);
448
                $member = $guild->members->get('id', $discordID);
449
                $nickName = $member->nick;
450
                $userName = $member->user->username;
451
                //If nick isn't set than make it username
452
                if ($nickName === '' || null === $nickName) {
453
                    $nickName = $userName;
454
                }
455
456
                //Check for bad tickers
457
                if (strpos($nickName, '[U]') !== false) {
458
                    $nickName = str_replace('[U]', '', $nickName);
459
                    queueRename($discordID, $nickName, $this->guildID);
460
                    continue;
461
                }
462
463
                //corp ticker
464
                if ($this->corpTickers === 'true') {
465
                    $timeout = 0;
466
                    $character = characterDetails($charID);
467
                    while (null === $character) { //try 10 times to pull characterDetails
468
                        if ($timeout > 9) {
469
                            continue;
470
                        }
471
                        else{
472
                            $character = characterDetails($charID);
473
                            $timeout++;
474
                        }
475
                    }
476
                    if (!array_key_exists('corporation_id', $character)) {
477
                        continue;
478
                    }
479
                    $corpInfo = getCorpInfo($character['corporation_id']);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $corpInfo is correct as getCorpInfo($character['corporation_id']) (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...
480
                    //Clean bad entries
481
                    if (@$corpInfo['corpTicker'] === 'U') {
482
                        deleteCorpInfo(@$corpInfo['corpID']);
483
                    }
484
                    $nick = null;
485 View Code Duplication
                    if (null !== @$corpInfo['corpTicker']) {
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...
486
                        $corpTicker = (string) $corpInfo['corpTicker'];
487
                        if ($this->nameEnforce === 'true') {
488
                            $nick = "[{$corpTicker}] {$eveName}";
489
                        } elseif ((string) $nickName === "[{$corpTicker}]") {
490
                            $nick = "[{$corpTicker}] {$userName}";
491
                        } elseif (strpos($nickName, $corpTicker) === false) {
492
                            $nick = "[{$corpTicker}] {$nickName}";
493
                        } elseif (strpos($nickName, $corpTicker) !== false) {
494
                            continue;
495
                        }
496
                        if ($nick !== $nickName) {
497
                            queueRename($discordID, $nick, $this->guildID);
498
                        }
499
                        continue;
500
                    }
501
                    $corporationDetails = corpDetails($character['corporation_id']);
502
                    if (null === $corporationDetails) {
503
                        continue;
504
                    }
505
                    $corpTicker = $corporationDetails['ticker'];
506
                    //Check for bad tickers (ESI ERROR?)
507
                    if (@$corpTicker === 'U') {
508
                        continue;
509
                    }
510
                    $corpName = (string) $corporationDetails['corporation_name'];
511 View Code Duplication
                    if (null !== $corpTicker) {
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...
512
                        if ($this->nameEnforce === 'true') {
513
                            $nick = "[{$corpTicker}] {$eveName}";
514
                        } elseif ((string) $nickName === "[{$corpTicker}]") {
515
                            $nick = "[{$corpTicker}] {$userName}";
516
                        } elseif (strpos($nickName, $corpTicker) === false) {
517
                            $nick = "[{$corpTicker}] {$nickName}";
518
                        } elseif (strpos($nickName, $corpTicker) !== false) {
519
                            continue;
520
                        }
521
                        if ($nick !== $nickName) {
522
                            queueRename($discordID, $nick, $this->guildID);
523
                            addCorpInfo($character['corporation_id'], $corpTicker, $corpName);
524
                        }
525
                        continue;
526
                    }
527
                    continue;
528
                }
529
                $nick = "{$eveName}";
530
                if ($nick !== $nickName) {
531
                    queueRename($discordID, $nick, $this->guildID);
532
                }
533
                continue;
534
            }
535
            $nextCheck = time() + 1800;
536
            setPermCache('nextRename', $nextCheck);
537
            return null;
538
        }
539
        $nextCheck = time() + 1800;
540
        setPermCache('nextRename', $nextCheck);
541
        return null;
542
543
    }
544
545
    private function standingsUpdate()
546
    {
547
        foreach ($this->apiKey as $apiKey) {
548
            if ((string) $apiKey['keyID'] === (string) $this->config['plugins']['auth']['standings']['apiKey']) {
549
                $url = "https://api.eveonline.com/char/ContactList.xml.aspx?keyID={$apiKey['keyID']}&vCode={$apiKey['vCode']}&characterID={$apiKey['characterID']}";
550
                $xml = makeApiRequest($url);
551
                if (empty($xml)) {
552
                    return null;
553
                }
554
                foreach ($xml->result->rowset as $contactType) {
555
                    if ((string) $contactType->attributes()->name === 'corporateContactList' || 'allianceContactList') {
556
                        foreach ($contactType->row as $contact) {
557
                            if (null !== $contact['contactID'] && $contact['contactName'] && $contact['standing']) {
558
                                addContactInfo($contact['contactID'], $contact['contactName'], $contact['standing']);
559
                            }
560
                        }
561
                    }
562
                }
563
            }
564
        }
565
        $nextCheck = time() + 86400;
566
        setPermCache('nextStandingsCheck', $nextCheck);
567
    }
568
}
569