Passed
Branch master (f30628)
by
unknown
02:34
created

authCheck   B

Complexity

Total Complexity 47

Size/Duplication

Total Lines 352
Duplicated Lines 6.25 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
dl 22
loc 352
rs 8.439
c 0
b 0
f 0
wmc 47
lcom 1
cbo 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
B init() 0 31 3
A information() 0 8 1
B tick() 0 28 6
C checkPermissions() 7 76 13
C checkAuthState() 8 79 14
C nameReset() 7 71 10

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like authCheck often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use authCheck, and based on these observations, apply Extract Interface, too.

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
     * @var
35
     */
36
    var $config;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $config.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
37
    /**
38
     * @var
39
     */
40
    var $db;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $db.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
41
    var $dbUser;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $dbUser.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
42
    var $dbPass;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $dbPass.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
43
    var $dbName;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $dbName.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
44
    var $guildID;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $guildID.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
45
    var $corpTickers;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $corpTickers.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
46
    var $authGroups;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $authGroups.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
47
    var $exempt;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $exempt.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
48
    var $alertChannel;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $alertChannel.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
49
    var $guild;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $guild.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
50
    var $nameEnforce;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $nameEnforce.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
51
    /**
52
     * @var
53
     */
54
    var $discord;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $discord.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
55
    /**
56
     * @var
57
     */
58
    var $channelConfig;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $channelConfig.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
59
    /**
60
     * @var int
61
     */
62
    var $lastCheck = 0;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $lastCheck.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
63
    /**
64
     * @var
65
     */
66
    var $logger;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $logger.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
67
68
    /**
69
     * @param $config
70
     * @param $discord
71
     * @param $logger
72
     */
73
    function init($config, $discord, $logger)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
74
    {
75
        $this->config = $config;
76
        $this->discord = $discord;
77
        $this->logger = $logger;
78
        $this->db = $config["database"]["host"];
79
        $this->dbUser = $config["database"]["user"];
80
        $this->dbPass = $config["database"]["pass"];
81
        $this->dbName = $config["database"]["database"];
82
        $this->guildID = $config["bot"]["guild"];
83
        $this->exempt = $config["plugins"]["auth"]["exempt"];
84
        $this->corpTickers = $config["plugins"]["auth"]["corpTickers"];
85
        $this->nameEnforce = $config["plugins"]["auth"]["nameEnforce"];
86
        $this->authGroups = $config["plugins"]["auth"]["authGroups"];
87
        $this->alertChannel = $config["plugins"]["auth"]["alertChannel"];
88
        $this->guild = $config["bot"]["guild"];
89
        $this->nextCheck = 0;
90
91
        //check if cache has been set
92
        $permsChecked = getPermCache("permsLastChecked");
93
        $namesChecked = getPermCache("nameStateLastChecked");
94
        if ($namesChecked == NULL) {
95
            setPermCache("nameStateLastChecked", time());
96
        }
97
98
        //if not set set for now (30 minutes from now for role removal)
99
        if ($permsChecked == NULL) {
100
            setPermCache("permsLastChecked", time() - 5);
101
            setPermCache("authStateLastChecked", time() + 7200);
102
        }
103
    }
104
105
    /**
106
     * @return array
107
     */
108
    function information()
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
109
    {
110
        return array(
111
            "name" => "",
112
            "trigger" => array(),
113
            "information" => ""
114
        );
115
    }
116
117
    function tick()
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
118
    {
119
        // What was the servers last reported state
120
        $lastStatus = getPermCache("serverState");
121
        if ($lastStatus == "online") {
122
            $permsChecked = getPermCache("permsLastChecked");
123
            $stateChecked = getPermCache("authStateLastChecked");
124
            $namesChecked = getPermCache("nameStateLastChecked");
125
126
            if ($permsChecked <= time()) {
127
                $this->logger->addInfo("AuthCheck: Checking for users who have left corp/alliance....");
128
                $this->checkPermissions();
129
                $this->logger->addInfo("AuthCheck: Corp/alliance check complete.");
130
            }
131
132
            if ($stateChecked <= time()) {
133
                $this->logger->addInfo("AuthCheck: Checking for users who have been wrongly given roles....");
134
                $this->checkAuthState();
135
                $this->logger->addInfo("AuthCheck: Role check complete.");
136
            }
137
138
            if ($this->nameEnforce == "true" && $namesChecked <= time()) {
139
                $this->logger->addInfo("AuthCheck: Resetting player names....");
140
                $this->nameReset();
141
                $this->logger->addInfo("AuthCheck: Names reset.");
142
            }
143
        }
144
    }
145
146
    /**
147
     * @return null
148
     */
149
150
    //Remove members who have roles but never authed
151
    function checkPermissions()
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
152
    {
153
        //Get guild object
154
        $guild = $this->discord->guilds->get('id', $this->guildID);
155
156
        //Establish connection to mysql
157
        $conn = new mysqli($this->db, $this->dbUser, $this->dbPass, $this->dbName);
158
159
        $sql = "SELECT characterID, discordID, eveName FROM authUsers WHERE active='yes'";
160
161
        $result = $conn->query($sql);
162
163
        //Set empty arrays
164
        $corpArray = array();
165
        $allianceArray = array();
166
167
        // If config is outdated
168 View Code Duplication
        if (is_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...
169
            $msg = "**Auth Failure:** Please update the bots config to the latest version.";
170
            queueMessage($msg, $this->alertChannel, $this->guild);
171
            $nextCheck = time() + 10800;
172
            setPermCache("permsLastChecked", $nextCheck);
173
            return null;
174
        }
175
176
        //Set corp/ally id arrays
177
        foreach ($this->authGroups as $authGroup) {
178
            if ($authGroup["corpID"] != 0) {
179
                array_push($corpArray, (int)$authGroup["corpID"]);
180
            }
181
            if ($authGroup["allianceID"] != 0) {
182
                array_push($allianceArray, (int)$authGroup["allianceID"]);
183
            }
184
        }
185
186
        if ($result->num_rows >= 1) {
187
            while ($rows = $result->fetch_assoc()) {
188
                $charID = $rows['characterID'];
189
                $discordID = $rows['discordID'];
190
                $member = $guild->members->get("id", $discordID);
191
                $eveName = $rows['eveName'];
192
                //Check if member has roles
193
                if (is_null($member->roles)) {
194
                    continue;
195
                }
196
197
                //Get ingame affiliations
198
                $url = "https://api.eveonline.com/eve/CharacterAffiliation.xml.aspx?ids=$charID";
199
                $xml = makeApiRequest($url);
200
                // Stop the process if the api is throwing an error
201
                if (is_null($xml)) {
202
                    $this->logger->addInfo("{$eveName} cannot be authed, API issues detected.");
203
                    return null;
204
                }
205
206
                //Auth things
207
                if ($xml->result->rowset->row[0]) {
208
                    foreach ($xml->result->rowset->row as $character) {
209
                        if (!in_array((int)$character->attributes()->allianceID, $allianceArray) && !in_array((int)$character->attributes()->corporationID, $corpArray)) {
210
                            // Deactivate user in database
211
                            $sql = "UPDATE authUsers SET active='no' WHERE discordID='$discordID'";
212
                            $this->logger->addInfo("AuthCheck: {$eveName} account has been deactivated as they are no longer in a correct corp/alliance.");
213
                            $conn->query($sql);
214
                            continue;
215
                        }
216
                    }
217
                }
218
            }
219
            $nextCheck = time() + 10800;
220
            setPermCache("permsLastChecked", $nextCheck);
221
            return null;
222
        }
223
        $nextCheck = time() + 10800;
224
        setPermCache("permsLastChecked", $nextCheck);
225
        return null;
226
    }
227
228
    //Check user corp/alliance affiliation
229
230
231
    function checkAuthState()
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
232
    {
233
234
        //Check if exempt roles are set
235
        if (is_null($this->exempt)) {
236
            $this->exempt = "0";
237
        }
238
239
        // If config is outdated
240 View Code Duplication
        if (is_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...
241
            $msg = "**Auth Failure:** Please update the bots config to the latest version.";
242
            queueMessage($msg, $this->alertChannel, $this->guild);
243
            //queue up next check
244
            $nextCheck = time() + 1800;
245
            setPermCache("authStateLastChecked", $nextCheck);
246
            return null;
247
        }
248
249
        //Establish connection to mysql
250
        $conn = new mysqli($this->db, $this->dbUser, $this->dbPass, $this->dbName);
251
252
        //get bot ID so we don't remove out own roles
253
        $botID = $this->discord->id;
254
255
        //Get guild object
256
        $guild = $this->discord->guilds->get('id', $this->guildID);
257
258
        //Check to make sure guildID is set correctly
259
        if (is_null($guild)) {
260
            $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.");
261
            $nextCheck = time() + 7200;
262
            setPermCache("authLastChecked", $nextCheck);
263
            return null;
264
        }
265
266
        //create empty array to store names
267
        $removedRoles = array();
268
        $userCount = 0;
269
270
        //Perform check if roles were added without permission
271
        foreach ($guild->members as $member) {
272
            $id = $member->id;
273
            $username = $member->username;
274
            $roles = $member->roles;
275
276
            //Skip to next member if this user has no roles
277
            if (is_null($roles)) {
278
                continue;
279
            }
280
            $sql = "SELECT * FROM authUsers WHERE discordID='$id' AND active='yes'";
281
            $result = $conn->query($sql);
282
283
            //If they are NOT active in the db, check for roles to remove
284
            if ($result->num_rows == 0) {
285
                $userCount++;
286
                foreach ($roles as $role) {
287
                    if (!isset($role->name)) {
288
                        if ($id != $botID && !in_array($role->name, $this->exempt, true)) {
289
                            $member->removeRole($role);
290
                            $guild->members->save($member);
291
                            // Add users name to array
292
                            array_push($removedRoles, $username);
293
                        }
294
                    }
295
                }
296
            }
297
        }
298
        //Report removed users to log and channel
299
        $nameList = implode(", ", $removedRoles);
300
        if ($userCount > 0 && strlen($nameList) > 3 && !is_null($nameList)) {
301
            $msg = "Following users roles have been removed - {$nameList}";
302
            queueMessage($msg, $this->alertChannel, $this->guild);
303
            $this->logger->addInfo("AuthCheck: Roles removed from {$nameList}");
304
        }
305
        //queue up next check
306
        $nextCheck = time() + 1800;
307
        setPermCache("authStateLastChecked", $nextCheck);
308
        return null;
309
    }
310
311
    function nameReset()
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
312
    {
313
        //Get guild object
314
        $guild = $this->discord->guilds->get('id', $this->guildID);
315
316
        //Establish connection to mysql
317
        $conn = new mysqli($this->db, $this->dbUser, $this->dbPass, $this->dbName);
318
319
        $sql = "SELECT characterID, discordID, eveName FROM authUsers WHERE active='yes'";
320
321
        $result = $conn->query($sql);
322
323
        // If config is outdated
324 View Code Duplication
        if (is_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...
325
            $msg = "**Auth Failure:** Please update the bots config to the latest version.";
326
            queueMessage($msg, $this->alertChannel, $this->guild);
327
            $nextCheck = time() + 10800;
328
            setPermCache("permsLastChecked", $nextCheck);
329
            return null;
330
        }
331
332
        if ($result->num_rows >= 1) {
333
            while ($rows = $result->fetch_assoc()) {
334
                $charID = $rows['characterID'];
335
                $discordID = $rows['discordID'];
336
                $member = $guild->members->get("id", $discordID);
337
                $eveName = $rows['eveName'];
338
                //Check if member has roles
339
                if (is_null($member->roles)) {
340
                    continue;
341
                }
342
343
                //Get ingame affiliations
344
                $url = "https://api.eveonline.com/eve/CharacterAffiliation.xml.aspx?ids=$charID";
345
                $xml = makeApiRequest($url);
346
                // Stop the process if the api is throwing an error
347
                if (is_null($xml)) {
348
                    $this->logger->addInfo("{$eveName} cannot be authed, API issues detected.");
349
                    return null;
350
                }
351
352
                //Perform name check if true
353
354
                if ($xml->result->rowset->row[0]) {
355
                    foreach ($xml->result->rowset->row as $character) {
356
                        if ($this->corpTickers == "true") {
357
                            $url = "https://api.eveonline.com/corp/CorporationSheet.xml.aspx?corporationID={$character->attributes()->corporationID}";
358
                            $xml = makeApiRequest($url);
359
                            $corpTicker = "";
360
                            foreach ($xml->result as $corporation) {
361
                                $corpTicker = $corporation->ticker;
362
                            }
363
                            $nick = "[{$corpTicker}] {$eveName}";
364
                            queueRename($discordID, $nick, $this->guildID);
365
                            continue;
366
                        }
367
                        $nick = "{$eveName}";
368
                        queueRename($discordID, $nick, $this->guildID);
369
                        continue;
370
                    }
371
                }
372
            }
373
            $nextCheck = time() + 43200;
374
            setPermCache("nameStateLastChecked", $nextCheck);
375
            return null;
376
        }
377
        $nextCheck = time() + 43200;
378
        setPermCache("nameStateLastChecked", $nextCheck);
379
        return null;
380
381
    }
382
}
383