Passed
Branch master (5e0a66)
by
unknown
03:07
created

authCheck::removeRoles()   B

Complexity

Conditions 7
Paths 10

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 14
nc 10
nop 1
dl 0
loc 21
rs 7.551
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 $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
    private $dbusers;
55
    private $characterCache;
56
    private $corpCache;
57
58
    /**
59
     * @param $config
60
     * @param $discord
61
     * @param $logger
62
     */
63
    public function init($config, $discord, $logger)
64
    {
65
        $this->active = true;
66
        $this->config = $config;
67
        $this->discord = $discord;
68
        $this->logger = $logger;
69
        $this->db = $config['database']['host'];
70
        $this->dbUser = $config['database']['user'];
71
        $this->dbPass = $config['database']['pass'];
72
        $this->dbName = $config['database']['database'];
73
        $this->guildID = $config['bot']['guild'];
74
        $this->exempt = $config['plugins']['auth']['exempt'];
75
        $this->corpTickers = $config['plugins']['auth']['corpTickers'];
76
        $this->nameEnforce = $config['plugins']['auth']['nameEnforce'];
77
        $this->standingsBased = $config['plugins']['auth']['standings']['enabled'];
78
        $this->apiKey = $config['eve']['apiKeys'];
79
        $this->authGroups = $config['plugins']['auth']['authGroups'];
80
        $this->alertChannel = $config['plugins']['auth']['alertChannel'];
81
        $this->nextCheck = 0;
82
        $this->characterCache = array();
83
        $this->corpCache = array();
84
85
        //Set name check to happen if corpTicker or nameEnforce is set
86
        if ($this->nameEnforce === 'true' || $this->corpTickers === 'true') {
87
            $this->nameCheck = true;
88
        }
89
90
        //check if cache has been set
91
        $permsChecked = getPermCache('permsLastChecked');
92
        $namesChecked = getPermCache('nextRename');
93
        if ($namesChecked === NULL) {
94
            setPermCache('nextRename', time());
95
        }
96
97
        //if not set set for now (30 minutes from now for role removal)
98
        if ($permsChecked === NULL) {
99
            setPermCache('permsLastChecked', time() - 1);
100
        }
101
102
        // If config is outdated
103
        if (null === $this->authGroups) {
104
            $msg = '**Auth Failure:** Please update the bots config to the latest version.';
105
            queueMessage($msg, $this->alertChannel, $this->guildID);
106
            $this->logger->addInfo($msg);
107
            $this->active = false;
108
        }
109
110
        // Load database users
111
        $dbh = new PDO("mysql:host={$this->db};dbname={$this->dbName}", $this->dbUser, $this->dbPass);
112
        $this->dbusers = array_column($dbh->query("SELECT discordID, characterID, eveName, role FROM authUsers where active='yes'")->fetchAll(), null, 'discordID');
113
    }
114
115
    public function tick()
116
    {
117
        // What was the servers last reported state
118
        $lastStatus = getPermCache('serverState');
119
        if ($this->active && $lastStatus === 'online') {
120
            $permsChecked = getPermCache('permsLastChecked');
121
            $standingsChecked = getPermCache('nextStandingsCheck');
122
123
            if ($permsChecked <= time()) {
124
                $this->logger->addInfo('AuthCheck: Checking for users who have left corp/alliance....');
125
                $this->checkPermissions();
126
                $this->logger->addInfo('AuthCheck: Corp/alliance check complete.');
127
            }
128
129
            if ($this->standingsBased === 'true' && $standingsChecked <= time()) {
130
                $this->logger->addInfo('AuthCheck: Updating Standings');
131
                $this->standingsUpdate();
132
                $this->logger->addInfo('AuthCheck: Standings Updated');
133
            }
134
        }
135
    }
136
137
    // remove user roles
138
    private function removeRoles($member)
139
    {
140
        $discordNick = $member->nick ?: $member->user->username;
141
        $roleRemoved = false;
142
        if (!is_null($member->roles)) {
143
            if (!isset($this->dbusers[$member->id])) {
144
                foreach ($member->roles as $role) {
145
                    if (!in_array($role->name, $this->exempt, true)) {
146
                        $roleRemoved = true;
147
                        $member->removeRole($role);
148
                        $this->discord->guilds->get('id', $this->guildID)->members->save($member);
149
                    }
150
                }
151
            }
152
            if ($roleRemoved) {
153
                $this->logger->addInfo("AuthCheck: Roles removed from $discordNick");
154
                $msg = "Discord roles removed from $discordNick";
155
                queueMessage($msg, $this->alertChannel, $this->guildID);
156
            }
157
        }
158
    }
159
160 View Code Duplication
    private function getCharacterDetails($charID, $retries = 3)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
161
    {
162
        if (isset($this->characterCache[$charID])) {
163
            return $this->characterCache[$charID];
164
        }
165
        $character = null;
166
        for ($i = 0; $i < $retries; $i++) {
167
            $character = characterDetails($charID);
168
            if (!is_null($character)) {
169
                break;
170
            }
171
        }
172
        if (!$character || isset($character['error'])) {
173
            $this->logger->addInfo('AuthCheck: characterDetails lookup failed.');
174
            $msg = isset($character['error']) ? $character['error'] : 'characterDetails lookup failed';
175
            throw new Exception($msg);
176
        }
177
        $this->characterCache[$charID] = $character;
178
        return $character;
179
    }
180
181 View Code Duplication
    private function getCorpDetails($corpID, $retries = 3)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
182
    {
183
        if (isset($this->corpCache[$corpID])) {
184
            return $this->corpCache[$corpID];
185
        }
186
        $corporationDetails = null;
187
        for ($i = 0; $i < $retries; $i++) {
188
            $corporationDetails = corpDetails($corpID);
189
            if (!is_null($corporationDetails)) {
190
                break;
191
            }
192
        }
193
        if (!$corporationDetails || isset($corporationDetails['error'])) {
194
            $this->logger->addInfo('AuthCheck: corpDetails lookup failed.');
195
            $msg = isset($corporationDetails['error']) ? $corporationDetails['error'] : 'corpDetails lookup failed';
196
            throw new Exception($msg);
197
        }
198
        $this->corpCache[$corpID] = $corporationDetails;
199
        return $corporationDetails;
200
    }
201
202 View Code Duplication
    private function isMemberInValidCorp($member)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
203
    {
204
        $corpArray = array_column($this->authGroups, 'corpID');
205
        $discordID = $member->id;
206
        $discordNick = $member->nick ?: $member->user->username;
207
        $return = false;
208
        if (isset($this->dbusers[$discordID])) {
209
            $character = $this->getCharacterDetails($this->dbusers[$discordID]['characterID']);
210
            $return = in_array($character['corporation_id'], $corpArray);
211
        } else {
212
            $this->logger->addInfo("AuthCheck: User [$discordNick] not found in database.");
213
        }
214
        return $return;
215
    }
216
217 View Code Duplication
    private function isMemberInValidAlliance($member)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
218
    {
219
        $allianceArray = array_column($this->authGroups, 'allianceID');
220
        $discordID = $member->id;
221
        $discordNick = $member->nick ?: $member->user->username;
222
        $return = false;
223
        // get charID
224
        if (isset($this->dbusers[$discordID])) {
225
            $character = $this->getCharacterDetails($this->dbusers[$discordID]['characterID']);
226
            $corp = $this->getCorpDetails($character['corporation_id']);
227
            $return = in_array($corp['alliance_id'], $allianceArray);
228
        } else {
229
            $this->logger->addInfo("AuthCheck: User [$discordNick] not found in database.");
230
        }
231
        return $return;
232
    }
233
234
    private function isMemberCorpOrAllianceContact($member) {
235
        $return = false;
236
        $discordID = $member->id;
237
        if (isset($this->dbusers[$discordID])) {
238
            $role = $this->dbusers[$discordID]['role'];
239
            if ($role === 'blue' || 'neut' || 'red') {
240
                $character = $this->getCharacterDetails($this->dbusers[$discordID]['characterID']);
241
                $corporationDetails = $this->getCorpDetails($character['corporation_id']);
242
                $allianceContacts = getContacts($corporationDetails['alliance_id']);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $allianceContacts is correct as getContacts($corporationDetails['alliance_id']) (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...
243
                $corpContacts = getContacts($character['corporation_id']);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $corpContacts is correct as getContacts($character['corporation_id']) (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...
244
                if ($role === 'blue' && ((int) $allianceContacts['standing'] === 5 || 10 || (int) $corpContacts['standing'] === 5 || 10)) {
245
                    $return = true;
246
                }
247
                if ($role === 'red' && ((int) $allianceContacts['standing'] === -5 || -10 || (int) $corpContacts['standing'] === -5 || -10)) {
248
                    $return = true;
249
                }
250
                if ($role === 'neut' && ((int) $allianceContacts['standing'] === 0 || (int) $corpContacts['standing'] === 0 || (@(int) $allianceContacts['standings'] === null || '' && @(int) $corpContacts['standings'] === null || ''))) {
251
                    $return = true;
252
                }
253
            }
254
        }
255
        return $return;
256
    }
257
258
    private function deactivateMember($member)
259
    {
260
        $discordID = $member->id;
261
        $discordNick = $member->nick ?: $member->user->username;
262
        $dbh = new PDO("mysql:host={$this->db};dbname={$this->dbName}", $this->dbUser, $this->dbPass);
263
        $sql = "UPDATE authUsers SET active='no' WHERE discordID='$discordID'";
264
        $dbh->query($sql);
265
        $this->removeRoles($member);
266
        $this->logger->addInfo("AuthCheck: {$discordNick} account has been deactivated as they are no longer in a correct corp/alliance.");
267
    }
268
269
    private function resetMemberNick($member)
270
    {
271
        $discordID = $member->id;
272
        $discordNick = $member->nick ?: $member->user->username;
273
        if (!isset($this->dbusers[$discordID])) {
274
            return false;
275
        }
276
        $character = $this->getCharacterDetails($this->dbusers[$discordID]['characterID']); 
277
        $corpTicker = '';
278
        if ($this->corpTickers === 'true') {
279
            $corporationDetails = $this->getCorpDetails($character['corporation_id']);
280
            if ($corporationDetails && isset($corporationDetails['ticker']) && $corporationDetails['ticker'] !== 'U') {
281
                $corpTicker = "[{$corporationDetails['ticker']}] ";
282
            }
283
        }
284
        if ($this->nameEnforce) {
285
            $newNick = $corpTicker . $this->dbusers[$discordID]['eveName'];
286
        } else {
287
            $newNick = $corpTicker . $discordNick;
288
        }
289
        if ($newNick !== $discordNick) {
290
            queueRename($discordID, $newNick, $this->guildID);
291
        }
292
    }
293
294
    /**
295
     * @return null
296
     */
297
298
    //Check user corp/alliance affiliation
299
    //Remove members who have roles but never authed
300
    private function checkPermissions()
301
    {
302
        $this->characterCache = array();
303
        $this->corpCache = array();
304
        foreach ($this->discord->guilds->get('id', $this->guildID)->members as $member) {
305
            $discordNick = $member->nick ?: $member->user->username;
306
            if ($this->discord->id == $member->id || $member->getRolesAttribute()->isEmpty()) {
307
                continue;
308
            }
309
            $this->logger->addDebug("AuthCheck: Username: $discordNick");
310
            try {
311
                if (!($this->isMemberInValidCorp($member) || $this->isMemberInValidAlliance($member) || $this->isMemberCorpOrAllianceContact($member))) {
312
                    $this->deactivateMember($member);
313
                }
314
                if ($this->nameCheck) {
315
                    $this->resetMemberNick($member);
316
                }
317
            } catch (Exception $e) {
318
                $this->logger->addError("AuthCheck: " . $e->getMessage());
319
                if ($e->getMessage() == 'The datasource tranquility is temporarily unavailable') {
320
                    return;
321
                }
322
            }
323
        }
324
        setPermCache('permsLastChecked', time() + 1800);
325
    }
326
327
    private function standingsUpdate()
328
    {
329
        foreach ($this->apiKey as $apiKey) {
330
            if ((string) $apiKey['keyID'] === (string) $this->config['plugins']['auth']['standings']['apiKey']) {
331
                $url = "https://api.eveonline.com/char/ContactList.xml.aspx?keyID={$apiKey['keyID']}&vCode={$apiKey['vCode']}&characterID={$apiKey['characterID']}";
332
                $xml = makeApiRequest($url);
333
                if (empty($xml)) {
334
                    return null;
335
                }
336
                foreach ($xml->result->rowset as $contactType) {
337
                    if ((string) $contactType->attributes()->name === 'corporateContactList' || 'allianceContactList') {
338
                        foreach ($contactType->row as $contact) {
339
                            if (null !== $contact['contactID'] && $contact['contactName'] && $contact['standing']) {
340
                                addContactInfo($contact['contactID'], $contact['contactName'], $contact['standing']);
341
                            }
342
                        }
343
                    }
344
                }
345
            }
346
        }
347
        $nextCheck = time() + 86400;
348
        setPermCache('nextStandingsCheck', $nextCheck);
349
    }
350
}
351