GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — develop ( 05d2a6...198a02 )
by Dane
03:13
created

DatabaseRepository::add()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 49
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 49
rs 8.7972
c 0
b 0
f 0
cc 4
eloc 34
nc 4
nop 1
1
<?php
2
/**
3
 * Pterodactyl - Panel
4
 * Copyright (c) 2015 - 2017 Dane Everitt <[email protected]>.
5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7
 * of this software and associated documentation files (the "Software"), to deal
8
 * in the Software without restriction, including without limitation the rights
9
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
 * copies of the Software, and to permit persons to whom the Software is
11
 * furnished to do so, subject to the following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included in all
14
 * copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
 * SOFTWARE.
23
 */
24
25
namespace Pterodactyl\Repositories;
26
27
use DB;
28
use Crypt;
29
use Config;
30
use Validator;
31
use Pterodactyl\Models\Server;
32
use Pterodactyl\Models\Database;
33
use Pterodactyl\Models\DatabaseHost;
34
use Pterodactyl\Exceptions\DisplayException;
35
use Pterodactyl\Exceptions\DisplayValidationException;
36
37
class DatabaseRepository
38
{
39
    /**
40
     * Adds a new database to a specified database host server.
41
     *
42
     * @param  int   $id
43
     * @param  array $data
44
     * @return \Pterodactyl\Models\Database
45
     *
46
     * @throws \Pterodactyl\Exceptions\DisplayException
47
     * @throws \Pterodactyl\Exceptions\DisplayValidationException
48
     */
49
    public function create($id, array $data)
0 ignored issues
show
Unused Code introduced by
The parameter $id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
50
    {
51
        $server = Server::findOrFail($server);
0 ignored issues
show
Bug introduced by
The variable $server seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
52
53
        $validator = Validator::make($data, [
54
            'host' => 'required|exists:database_servers,id',
55
            'database' => 'required|regex:/^\w{1,100}$/',
56
            'connection' => 'required|regex:/^[0-9%.]{1,15}$/',
57
        ]);
58
59
        if ($validator->fails()) {
60
            throw new DisplayValidationException(json_encode($validator->errors()));
61
        }
62
63
        $host = DatabaseHost::findOrFail($data['host']);
64
        DB::beginTransaction();
65
66
        try {
67
            $database = Models\Database::firstOrNew([
68
                'server_id' => $server->id,
69
                'database_host_id' => $data['host'],
70
                'database' => sprintf('s%d_%s', $server->id, $data['database']),
71
            ]);
72
73
            if ($database->exists) {
74
                throw new DisplayException('A database with those details already exists in the system.');
75
            }
76
77
            $database->username = sprintf('s%d_%s', $server->id, str_random(10));
78
            $database->remote = $data['connection'];
79
            $database->password = Crypt::encrypt(str_random(20));
80
81
            $database->save();
82
        } catch (\Exception $ex) {
83
            DB::rollBack();
84
            throw $ex;
85
        }
86
87
        Config::set('database.connections.dynamic', [
88
            'driver' => 'mysql',
89
            'host' => $host->host,
90
            'port' => $host->port,
91
            'database' => 'mysql',
92
            'username' => $host->username,
93
            'password' => Crypt::decrypt($host->password),
94
            'charset'   => 'utf8',
95
            'collation' => 'utf8_unicode_ci',
96
        ]);
97
98
        try {
99
            DB::connection('dynamic')->statement(sprintf('CREATE DATABASE IF NOT EXISTS `%s`', $database->database));
100
            DB::connection('dynamic')->statement(sprintf(
101
                'CREATE USER `%s`@`%s` IDENTIFIED BY \'%s\'',
102
                $database->username, $database->remote, Crypt::decrypt($database->password)
103
            ));
104
            DB::connection('dynamic')->statement(sprintf(
105
                'GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER, INDEX ON `%s`.* TO `%s`@`%s`',
106
                $database->database, $database->username, $database->remote
107
            ));
108
109
            DB::connection('dynamic')->statement('FLUSH PRIVILEGES');
110
111
            // Save Everything
112
            DB::commit();
113
114
            return $database;
115
        } catch (\Exception $ex) {
116
            try {
117
                DB::connection('dynamic')->statement(sprintf('DROP DATABASE IF EXISTS `%s`', $database->database));
118
                DB::connection('dynamic')->statement(sprintf('DROP USER IF EXISTS `%s`@`%s`', $database->username, $database->remote));
119
                DB::connection('dynamic')->statement('FLUSH PRIVILEGES');
120
            } catch (\Exception $ex) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
121
            }
122
123
            DB::rollBack();
124
            throw $ex;
125
        }
126
    }
127
128
    /**
129
     * Updates the password for a given database.
130
     *
131
     * @param  int    $id
132
     * @param  string $password
133
     * @return void
134
     */
135
    public function password($id, $password)
136
    {
137
        $database = Models\Database::with('host')->findOrFail($id);
138
139
        DB::transaction(function () use ($database, $password) {
140
            $database->password = Crypt::encrypt($password);
141
142
            Config::set('database.connections.dynamic', [
143
                'driver' => 'mysql',
144
                'host' => $database->host->host,
145
                'port' => $database->host->port,
146
                'database' => 'mysql',
147
                'username' => $database->host->username,
148
                'password' => Crypt::decrypt($database->host->password),
149
                'charset'   => 'utf8',
150
                'collation' => 'utf8_unicode_ci',
151
            ]);
152
153
            DB::connection('dynamic')->statement(sprintf(
154
                'SET PASSWORD FOR `%s`@`%s` = PASSWORD(\'%s\')',
155
                $database->username, $database->remote, $password
156
            ));
157
158
            $database->save();
159
        });
160
    }
161
162
    /**
163
     * Drops a database from the associated database host.
164
     *
165
     * @param  int $id
166
     * @return void
167
     */
168
    public function drop($id)
169
    {
170
        $database = Database::with('host')->findOrFail($id);
0 ignored issues
show
Bug introduced by
The method findOrFail does only exist in Illuminate\Database\Eloquent\Builder, but not in Illuminate\Database\Eloquent\Model.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
171
172
        DB::transaction(function () use ($database) {
173
            Config::set('database.connections.dynamic', [
174
                'driver' => 'mysql',
175
                'host' => $database->host->host,
176
                'port' => $database->host->port,
177
                'database' => 'mysql',
178
                'username' => $database->host->username,
179
                'password' => Crypt::decrypt($database->host->password),
180
                'charset'   => 'utf8',
181
                'collation' => 'utf8_unicode_ci',
182
            ]);
183
184
            DB::connection('dynamic')->statement(sprintf('DROP DATABASE IF EXISTS `%s`', $database->database));
185
            DB::connection('dynamic')->statement(sprintf('DROP USER IF EXISTS `%s`@`%s`', $database->username, $database->remote));
186
            DB::connection('dynamic')->statement('FLUSH PRIVILEGES');
187
188
            $database->delete();
189
        });
190
    }
191
192
    /**
193
     * Deletes a database host from the system if it has no associated databases.
194
     *
195
     * @param  int $server
0 ignored issues
show
Bug introduced by
There is no parameter named $server. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
196
     * @return void
197
     *
198
     * @throws \Pterodactyl\Exceptions\DisplayException
199
     */
200
    public function delete($id)
201
    {
202
        $host = DatabaseHost::withCount('databases')->findOrFail($id);
203
204
        if ($host->databases_count > 0) {
205
            throw new DisplayException('You cannot delete a database host that has active databases attached to it.');
206
        }
207
208
        $host->delete();
209
    }
210
211
    /**
212
     * Adds a new Database Host to the system.
213
     *
214
     * @param  array $data
215
     * @return \Pterodactyl\Models\DatabaseHost
216
     *
217
     * @throws \Pterodactyl\Exceptions\DisplayValidationException
218
     */
219
    public function add(array $data)
220
    {
221
        if (isset($data['host'])) {
222
            $data['host'] = gethostbyname($data['host']);
223
        }
224
225
        $validator = Validator::make($data, [
226
            'name' => 'required|string|max:255',
227
            'host' => 'required|ip|unique:database_hosts,host',
228
            'port' => 'required|numeric|between:1,65535',
229
            'username' => 'required|string|max:32',
230
            'password' => 'required|string',
231
            'node_id' => 'sometimes|required|exists:nodes,id',
232
        ]);
233
234
        if ($validator->fails()) {
235
            throw new DisplayValidationException(json_encode($validator->errors()));
236
        }
237
238
        return DB::transaction(function () use ($data) {
239
            Config::set('database.connections.dynamic', [
240
                'driver' => 'mysql',
241
                'host' => $data['host'],
242
                'port' => $data['port'],
243
                'database' => 'mysql',
244
                'username' => $data['username'],
245
                'password' => $data['password'],
246
                'charset'   => 'utf8',
247
                'collation' => 'utf8_unicode_ci',
248
            ]);
249
250
            // Allows us to check that we can connect to things.
251
            DB::connection('dynamic')->select('SELECT 1 FROM dual');
252
253
            $host = new DatabaseHost;
254
            $host->password = Crypt::encrypt($data['password']);
0 ignored issues
show
Documentation introduced by
The property password does not exist on object<Pterodactyl\Models\DatabaseHost>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
255
256
            $host->fill([
257
                'name' => $data['name'],
258
                'host' => $data['host'],
259
                'port' => $data['port'],
260
                'username' => $data['username'],
261
                'max_databases' => null,
262
                'node_id' => (isset($data['node_id'])) ? $data['node_id'] : null,
263
            ])->save();
264
265
            return $host;
266
        });
267
    }
268
269
    /**
270
     * Updates a Database Host on the system.
271
     *
272
     * @param  int   $id
273
     * @param  array $data
274
     * @return \Pterodactyl\Models\DatabaseHost
275
     *
276
     * @throws \Pterodactyl\Exceptions\DisplayValidationException
277
     */
278
    public function update($id, array $data)
279
    {
280
        $host = DatabaseHost::findOrFail($id);
281
282
        if (isset($data['host'])) {
283
            $data['host'] = gethostbyname($data['host']);
284
        }
285
286
        $validator = Validator::make($data, [
287
            'name' => 'sometimes|required|string|max:255',
288
            'host' => 'sometimes|required|ip|unique:database_hosts,host,' . $host->id,
289
            'port' => 'sometimes|required|numeric|between:1,65535',
290
            'username' => 'sometimes|required|string|max:32',
291
            'password' => 'sometimes|required|string',
292
            'node_id' => 'sometimes|required|exists:nodes,id',
293
        ]);
294
295
        if ($validator->fails()) {
296
            throw new DisplayValidationException(json_encode($validator->errors()));
297
        }
298
299
        return DB::transaction(function () use ($data, $host) {
300
            if (isset($data['password'])) {
301
                $host->password = Crypt::encrypt($data['password']);
302
            }
303
            $host->fill($data)->save();
304
305
            // Check that we can still connect with these details.
306
            Config::set('database.connections.dynamic', [
307
                'driver' => 'mysql',
308
                'host' => $host->host,
309
                'port' => $host->port,
310
                'database' => 'mysql',
311
                'username' => $host->username,
312
                'password' => Crypt::decrypt($host->password),
313
                'charset'   => 'utf8',
314
                'collation' => 'utf8_unicode_ci',
315
            ]);
316
317
            // Allows us to check that we can connect to things.
318
            DB::connection('dynamic')->select('SELECT 1 FROM dual');
319
320
            return $host;
321
        });
322
    }
323
}
324