evemails::sortByDate()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
rs 10
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
use discord\discord;
27
28
/**
29
 * Class corporationmails
30
 * @property  keyID
31
 * @property  vCode
32
 * @property  characterID
33
 */
34
class evemails
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...
35
{
36
    public $config;
37
    public $discord;
38
    public $logger;
39
    private $nextCheck;
40
    private $toIDs;
41
    private $toDiscordChannel;
42
    private $newestMailID;
43
    private $maxID;
44
    private $apiKey;
45
    private $numberOfKeys;
46
    private $guild;
47
48
    /**
49
     * @param $config
50
     * @param $discord
51
     * @param $logger
52
     */
53
    public function init($config, $discord, $logger)
54
    {
55
        $this->config = $config;
56
        $this->discord = $discord;
57
        $this->logger = $logger;
58
        $this->toIDs = $config['plugins']['evemails']['fromIDs'];
59
        $this->toDiscordChannel = $config['plugins']['evemails']['channelID'];
60
        $this->newestMailID = getPermCache('newestCorpMailID');
61
        $this->maxID = 0;
62
        $this->apiKey = $config['eve']['apiKeys'];
63
        $this->guild = $config['bot']['guild'];
64
        $this->nextCheck = 0;
65
66
        //Get number of keys
67
        $x = 0;
68 View Code Duplication
        foreach ($this->apiKey as $apiKey) {
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...
69
            //Check if api is set
70
            if ($apiKey['keyID'] === '' || $apiKey['vCode'] === '' || $apiKey['characterID'] === null) {
71
                continue;
72
            }
73
            $x++;
74
        }
75
        $this->numberOfKeys = $x;
76
    }
77
78
    /**
79
     *
80
     */
81
    public function tick()
82
    {
83
        // What was the servers last reported state
84
        $lastStatus = getPermCache('serverState');
85
        if ($lastStatus === 'online') {
86
            foreach ($this->apiKey as $apiKey) {
87
                //Check if api is set
88
                if ($apiKey['keyID'] === '' || $apiKey['vCode'] === '' || $apiKey['characterID'] === null) {
89
                    continue;
90
                }
91
                //Get
92
                $lastChecked = getPermCache('mailLastChecked');
93
                if ($lastChecked <= time()) {
94
                    $lastCheckedAPI = getPermCache("mailLastChecked{$apiKey['keyID']}");
95
                    if ($lastCheckedAPI <= time()) {
96
                        $this->logger->addInfo("Mails: Checking API Key {$apiKey['keyID']} for new mail...");
97
                        $this->checkMails($apiKey['keyID'], $apiKey['vCode'], $apiKey['characterID']);
98
                    }
99
                }
100
            }
101
        }
102
    }
103
104
    private function checkMails($keyID, $vCode, $characterID)
105
    {
106
107
        $url = "https://api.eveonline.com/char/MailMessages.xml.aspx?keyID={$keyID}&vCode={$vCode}&characterID={$characterID}";
108
        $data = json_decode(json_encode(simplexml_load_string(downloadData($url), 'SimpleXMLElement', LIBXML_NOCDATA)), true);
109
        $xml = makeApiRequest($url);
110
        $cached = $xml->cachedUntil[0];
111
        $baseUnix = strtotime($cached);
112
        $cacheClr = $baseUnix - 13500;
113
114
        //Set timer for next key based on number of keys
115
        $nextKey = (1900 / (int)$this->numberOfKeys) + time();
116
        $nextKeyTime = gmdate('Y-m-d H:i:s', $nextKey);
117
        setPermCache('mailLastChecked', $nextKey);
118
119
        //Set cache timer for api key
120 View Code Duplication
        if ($cacheClr <= time()) {
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...
121
            $weirdTime = time() + 1830;
122
            setPermCache("mailLastChecked{$keyID}", $weirdTime);
123
        } else {
124
            setPermCache("mailLastChecked{$keyID}", $cacheClr);
125
        }
126
127
        // If there is no data, just quit..
128
        if (empty($data['result']['rowset']['row'])) {
129
            return null;
130
        }
131
        $data = $data['result']['rowset']['row'];
132
133
        $mails = array();
134
        if (isset($data['@attributes'])) {
135
            $mails[] = $data['@attributes'];
136
        }
137
        // Sometimes there is only ONE notification, so.. yeah..
138
        if (count($data) > 1) {
139
            foreach ($data as $multiMail) {
140
                $mails[] = $multiMail['@attributes'];
141
            }
142
        }
143
144
        usort($mails, array($this, 'sortByDate'));
145
146
        foreach ($mails as $mail) {
147
            if (in_array($mail['toCorpOrAllianceID'], $this->toIDs) && $mail['messageID'] > $this->newestMailID) {
148
                $sentBy = $mail['senderName'];
149
                $title = $mail['title'];
150
                $sentDate = $mail['sentDate'];
151
                $url = "https://api.eveonline.com/char/MailBodies.xml.aspx?keyID={$keyID}&vCode={$vCode}&characterID={$characterID}&ids=" . $mail['messageID'];
152
                $content = strip_tags(str_replace('<br>', "\n", json_decode(json_encode(simplexml_load_string(downloadData($url), 'SimpleXMLElement', LIBXML_NOCDATA)))->result->rowset->row));
153
154
                // Blank Content Check
155
                if ($content === '') {
156
                    return null;
157
                }
158
159
                $messageSplit = str_split($content, 1850);
160
161
                // Stitch the mail together
162
                $msg = "**------------------------------------**\n";
163
                $msg .= "**Mail By: **{$sentBy}\n";
164
                $msg .= "**Sent Date: **{$sentDate}\n";
165
                $msg .= "**Title: ** {$title}\n";
166
                $msg .= "**Content: **\n";
167
                $msg .= htmlspecialchars_decode(trim($messageSplit[0]), null);
168
                $msgLong = htmlspecialchars_decode(trim($messageSplit[1]), null);
169
170
                // Send the mails to the channel
171
                $channelID = $this->toDiscordChannel;
172
                queueMessage($msg, $channelID, $this->guild);
173
                $this->logger->addInfo('Mails: New mail queued');
174
                if (strlen($content) > 1850) {
175
                    queueMessage($msgLong, $channelID, $this->guild);
176
                }
177
178
                // Find the maxID so we don't spit this message out ever again
179
                $this->maxID = max($mail['messageID'], $this->maxID);
180
                $this->newestMailID = $this->maxID; //$mail["messageID"];
181
                $updateMaxID = true;
182
183
                // set the maxID
184
                if ($updateMaxID) {
185
                    setPermCache('newestCorpMailID', $this->maxID);
186
                }
187
            }
188
        }
189
        $this->logger->addInfo("Mails: Next Mail Check At: {$nextKeyTime} EVE Time");
190
    }
191
192
    /**
193
     * @param $alpha
194
     * @param $bravo
195
     * @return int
196
     */
197
    private function sortByDate($alpha, $bravo)
198
    {
199
        return strcmp($alpha['sentDate'], $bravo['sentDate']);
200
    }
201
}
202