Passed
Branch master (29155b)
by
unknown
03:29
created

src/plugins/onTick/authCheck.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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
32
{
33
    /**
34
     * @var
35
     */
36
    var $config;
37
    /**
38
     * @var
39
     */
40
    var $db;
41
    var $dbUser;
42
    var $dbPass;
43
    var $dbName;
44
    var $id;
45
    var $allyID;
46
    var $corpID;
47
    var $exempt;
48
    var $alertChannel;
49
    /**
50
     * @var
51
     */
52
    var $discord;
53
    /**
54
     * @var
55
     */
56
    var $channelConfig;
57
    /**
58
     * @var int
59
     */
60
    var $lastCheck = 0;
61
    /**
62
     * @var
63
     */
64
    var $logger;
65
66
    /**
67
     * @param $config
68
     * @param $discord
69
     * @param $logger
70
     */
71
    function init($config, $discord, $logger)
72
    {
73
        $this->config = $config;
74
        $this->discord = $discord;
75
        $this->logger = $logger;
76
        $this->db = $config["database"]["host"];
77
        $this->dbUser = $config["database"]["user"];
78
        $this->dbPass = $config["database"]["pass"];
79
        $this->dbName = $config["database"]["database"];
80
        $this->id = $config["bot"]["guild"];
81
        $this->allyID = $config["plugins"]["auth"]["allianceID"];
82
        $this->corpID = $config["plugins"]["auth"]["corpID"];
83
        $this->exempt = $config["plugins"]["auth"]["exempt"];
84
        $this->alertChannel = $config["plugins"]["auth"]["alertChannel"];
85
        $this->nextCheck = 0;
86
87
        //check if cache has been set
88
        $permsChecked = getPermCache("permsLastChecked");
89
90
        //if not set set for now (30 minutes from now for role removal)
91
        if ($permsChecked == NULL) {
92
            setPermCache("permsLastChecked", time() - 5);
93
            setPermCache("authStateLastChecked", time() + 7200);
94
        }
95
    }
96
97
    /**
98
     * @return array
99
     */
100
    function information()
101
    {
102
        return array(
103
            "name" => "",
104
            "trigger" => array(),
105
            "information" => ""
106
        );
107
    }
108
109
    function tick()
110
    {
111
        $permsChecked = getPermCache("permsLastChecked");
112
        $stateChecked = getPermCache("authStateLastChecked");
113
114
        if ($permsChecked <= time()) {
115
            $this->logger->addInfo("AuthCheck: Checking for users who have left corp/alliance....");
116
            $this->checkPermissions();
117
            $this->logger->addInfo("AuthCheck: Corp/alliance check complete.");
118
        }
119
120
        if ($stateChecked <= time()) {
121
            $this->logger->addInfo("AuthCheck: Checking for users who have been wrongly given roles....");
122
            $this->checkAuthState();
123
            $this->logger->addInfo("AuthCheck: Role check complete.");
124
        }
125
    }
126
127
    /**
128
     * @return null
129
     */
130
131
    //Remove members who have roles but never authed
132
    function checkPermissions()
133
    {
134
        //Get guild object
135
        $guild = $this->discord->guilds->get('id', $this->id);
136
137
        //Establish connection to mysql
138
        $conn = new mysqli($this->db, $this->dbUser, $this->dbPass, $this->dbName);
139
140
        $sql = "SELECT characterID, discordID, eveName FROM authUsers WHERE active='yes'";
141
142
        $result = $conn->query($sql);
143
144
        if ($result->num_rows >= 1) {
145
            while ($rows = $result->fetch_assoc()) {
146
                $charID = $rows['characterID'];
147
                $discordID = $rows['discordID'];
148
                $member = $guild->members->get("id", $discordID);
149
                $eveName = $rows['eveName'];
150
                if (is_null($member->roles)) {
151
                    continue;
152
                }
153
154
                if ($this->config["plugins"]["auth"]["nameEnforce"] == "true" && !is_null($member)) {
155
                    $nick = $eveName;
156
                    $member->setNickname($nick);
157
                }
158
159
                $url = "https://api.eveonline.com/eve/CharacterAffiliation.xml.aspx?ids=$charID";
160
                $xml = makeApiRequest($url);
161
                // Stop the process if the api is throwing an error
162
                if (is_null($xml)) {
163
                    $this->logger->addInfo("{$eveName} cannot be authed, API issues detected.");
164
                    return null;
165
                }
166
                if ($xml->result->rowset->row[0]) {
167
                    foreach ($xml->result->rowset->row as $character) {
168
                        if ($character->attributes()->allianceID != $this->allyID && $character->attributes()->corporationID != $this->corpID) {
169
                            // Deactivate user in database
170
                            $sql = "UPDATE authUsers SET active='no' WHERE discordID='$discordID'";
171
                            $this->logger->addInfo("AuthCheck: {$eveName} account has been deactivated as they are no longer in the correct corp/alliance.");
172
                            $conn->query($sql);
173
                        }
174
                    }
175
                }
176
            }
177
            $nextCheck = time() + 10800;
178
            setPermCache("permsLastChecked", $nextCheck);
179
            return null;
180
        }
181
        $nextCheck = time() + 10800;
182
        setPermCache("permsLastChecked", $nextCheck);
183
        return null;
184
    }
185
186
    //Check user corp/alliance affiliation
187
188
189
    function checkAuthState()
190
    {
191
192
        //Check if exempt roles are set
193
        if (is_null($this->exempt)) {
194
            $this->exempt = "0";
195
        }
196
197
        //Establish connection to mysql
198
        $conn = new mysqli($this->db, $this->dbUser, $this->dbPass, $this->dbName);
199
200
        //get bot ID so we don't remove out own roles
201
        $botID = $this->discord->id;
202
203
        //Get guild object
204
        $guild = $this->discord->guilds->get('id', $this->id);
205
206
        //Check to make sure guildID is set correctly
207
        if (is_null($guild)) {
208
            $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.");
209
            $nextCheck = time() + 7200;
210
            setPermCache("authLastChecked", $nextCheck);
211
            return null;
212
        }
213
214
        //Perform check if roles were added without permission
215
        foreach ($guild->members as $member) {
216
            $id = $member->id;
217
            $username = $member->username;
218
            $roles = $member->roles;
219
220
            //Skip to next member if this user has no roles
221
            if (is_null($roles)) {
222
                continue;
223
            }
224
            $sql = "SELECT * FROM authUsers WHERE discordID='$id' AND active='yes'";
225
            $result = $conn->query($sql);
226
227
            //If they are NOT active in the db, check for roles to remove
228
            if ($result->num_rows == 0) {
229
                foreach ($roles as $role) {
230
                    if (!isset($role->name)) {
231
                        if ($id != $botID && !in_array($role->name, $this->exempt, true)) {
232
                            $member->removeRole($role);
233
                            $guild->members->save($member);
234
                            // Send the info to the channel
235
                            $msg = "{$username} has been removed from the {$role->name} role.";
0 ignored issues
show
$msg 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...
236
                            //queueMessage($msg, $this->alertChannel, $this->guild);
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
237
                            $this->logger->addInfo("AuthCheck: {$username} has been removed from the {$role->name} role.");
238
                        }
239
                    }
240
                }
241
            }
242
        }
243
        $nextCheck = time() + 1800;
244
        setPermCache("authStateLastChecked", $nextCheck);
245
        return null;
246
    }
247
}
248