Passed
Push — master ( fb6ce1...7c7d88 )
by Bob
02:59
created

evemails::init()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 2
eloc 15
c 2
b 1
f 0
nc 2
nop 3
dl 0
loc 19
rs 9.4285
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
use Discord\Discord;
26
use Discord\Parts\Channel\Channel;
27
use Discord\Parts\Channel\Message;
28
29
/**
30
 * Class corporationmails.
31
 *
32
 * @property  keyID
33
 * @property  vCode
34
 * @property  characterID
35
 */
36
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...
37
{
38
    /*
39
     * @var
40
     */
41
    public $config;
42
    /*
43
     * @var
44
     */
45
    public $discord;
46
    /*
47
     * @var
48
     */
49
    public $logger;
50
    /*
51
     * @var
52
     */
53
    public $nextCheck;
54
    /*
55
     * @var
56
     */
57
    public $toIDs;
58
    /*
59
     * @var
60
     */
61
    public $toDiscordChannel;
62
63
    /*
64
     * @var
65
     */
66
    public $newestMailID;
67
    /*
68
     * @var
69
     */
70
    public $maxID;
71
    /*
72
     * @var
73
     */
74
    public $keyCount;
75
    /*
76
     * @var
77
     */
78
    public $keys;
79
80
    /**
81
     * @param $config
82
     * @param $discord
83
     * @param $logger
84
     */
85
    public function init($config, $discord, $logger)
86
    {
87
        $this->config = $config;
88
        $this->discord = $discord;
89
        $this->logger = $logger;
90
        $this->toIDs = $config['plugins']['evemails']['fromIDs'];
91
        $this->toDiscordChannel = $config['plugins']['evemails']['channelID'];
92
        $this->newestMailID = getPermCache('newestCorpMailID');
93
        $this->maxID = 0;
94
        $this->keyID = $config['eve']['apiKeys']['user1']['keyID'];
0 ignored issues
show
Bug introduced by
The property keyID does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
95
        $this->vCode = $config['eve']['apiKeys']['user1']['vCode'];
0 ignored issues
show
Bug introduced by
The property vCode does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
96
        $this->characterID = $config['eve']['apiKeys']['user1']['characterID'];
0 ignored issues
show
Bug introduced by
The property characterID does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
97
        $this->nextCheck = 0;
98
        $lastCheck = getPermCache("mailLastChecked{$this->keyID}");
99
        if ($lastCheck == null) {
100
            // Schedule it for right now if first run
101
            setPermCache("mailLastChecked{$this->keyID}", time() - 5);
102
        }
103
    }
104
105
106 View Code Duplication
    public function tick()
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...
107
    {
108
        $lastChecked = getPermCache("mailLastChecked{$this->keyID}");
109
        $keyID = $this->keyID;
110
        $vCode = $this->vCode;
111
        $characterID = $this->characterID;
112
113
        if ($lastChecked <= time()) {
114
            $this->logger->addInfo("Checking API Key {$keyID} for new mail..");
115
            $this->checkMails($keyID, $vCode, $characterID);
116
        }
117
    }
118
119
    public function checkMails($keyID, $vCode, $characterID)
120
    {
121
        $updateMaxID = false;
0 ignored issues
show
Unused Code introduced by
$updateMaxID 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...
122
        $url = "https://api.eveonline.com/char/MailMessages.xml.aspx?keyID={$keyID}&vCode={$vCode}&characterID={$characterID}";
123
        $data = json_decode(json_encode(simplexml_load_string(downloadData($url), 'SimpleXMLElement', LIBXML_NOCDATA)), true);
124
        $data = $data['result']['rowset']['row'];
125
        $xml = makeApiRequest($url);
126
        $cached = $xml->cachedUntil[0];
127
        $baseUnix = strtotime($cached);
128
        $cacheClr = $baseUnix - 13500;
129 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...
130
            $weirdTime = time() + 1830;
131
            $cacheTimer = gmdate('Y-m-d H:i:s', $weirdTime);
132
            setPermCache("mailLastChecked{$keyID}", $weirdTime);
133
        } else {
134
            $cacheTimer = gmdate('Y-m-d H:i:s', $cacheClr);
135
            setPermCache("mailLastChecked{$keyID}", $cacheClr);
136
        }
137
138
        $mails = [];
139
        if (isset($data['@attributes'])) {
140
            $mails[] = $data['@attributes'];
141
        }
142
        // Sometimes there is only ONE notification, so.. yeah..
143
        if (count($data) > 1) {
144
            foreach ($data as $multiMail) {
145
                $mails[] = $multiMail['@attributes'];
146
            }
147
        }
148
149
        usort($mails, [$this, 'sortByDate']);
150
151
        foreach ($mails as $mail) {
152
            if (in_array($mail['toCorpOrAllianceID'], $this->toIDs) && $mail['messageID'] > $this->newestMailID) {
153
                $sentBy = $mail['senderName'];
154
                $title = $mail['title'];
155
                $sentDate = $mail['sentDate'];
156
                $url = "https://api.eveonline.com/char/MailBodies.xml.aspx?keyID={$keyID}&vCode={$vCode}&characterID={$characterID}&ids=".$mail['messageID'];
157
                $content = strip_tags(str_replace('<br>', "\n", json_decode(json_encode(simplexml_load_string(downloadData($url), 'SimpleXMLElement', LIBXML_NOCDATA)))->result->rowset->row));
158
159
                // Blank Content Check
160
                if ($content == '') {
161
                    return;
162
                }
163
164
                $messageSplit = str_split($content, 1850);
165
166
                // Stitch the mail together
167
                $msg = "**Mail By: **{$sentBy}\n";
168
                $msg .= "**Sent Date: **{$sentDate}\n";
169
                $msg .= "**Title: ** {$title}\n";
170
                $msg .= "**Content: **\n";
171
                $msg .= htmlspecialchars_decode(trim($messageSplit[0]));
172
                $msgLong = htmlspecialchars_decode(trim($messageSplit[1]));
173
174
                // Send the mails to the channel
175
                $channelID = $this->toDiscordChannel;
176
                $channel = Channel::find($channelID);
177
                $channel->sendMessage($msg, false);
178
                sleep(1); // Lets sleep for a second, so we don't rage spam
179
                if (strlen($content) > 1850) {
180
                    $channel->sendMessage($msgLong, false);
181
                }
182
183
                // Find the maxID so we don't spit this message out ever again
184
                $this->maxID = max($mail['messageID'], $this->maxID);
185
                $this->newestMailID = $this->maxID; //$mail["messageID"];
186
                $updateMaxID = true;
187
188
                // set the maxID
189
                if ($updateMaxID) {
190
                    setPermCache('newestCorpMailID', $this->maxID);
191
                }
192
            }
193
        }
194
        $this->logger->addInfo("Next Mail Check At: {$cacheTimer} EVE Time");
195
    }
196
197
    /**
198
     * @param $alpha
199
     * @param $bravo
200
     *
201
     * @return int
202
     */
203
    public function sortByDate($alpha, $bravo)
204
    {
205
        return strcmp($alpha['sentDate'], $bravo['sentDate']);
206
    }
207
208
209
    public function onMessage()
210
    {
211
    }
212
213
    /**
214
     * @return array
215
     */
216
    public function information()
217
    {
218
        return [
219
            'name'        => '',
220
            'trigger'     => [''],
221
            'information' => '',
222
        ];
223
    }
224
}
225