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
Pull Request — develop (#286)
by Dane
03:00
created

NodesController::getIndex()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
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\Http\Controllers\Admin;
26
27
use DB;
28
use Log;
29
use Alert;
30
use Carbon;
31
use Validator;
32
use Pterodactyl\Models;
33
use Illuminate\Http\Request;
34
use Pterodactyl\Exceptions\DisplayException;
35
use Pterodactyl\Http\Controllers\Controller;
36
use Pterodactyl\Repositories\NodeRepository;
37
use Pterodactyl\Exceptions\DisplayValidationException;
38
39
class NodesController extends Controller
40
{
41
    /**
42
     * Controller Constructor.
43
     */
44
    public function __construct()
45
    {
46
        //
47
    }
48
49
    public function getScript(Request $request, $id)
0 ignored issues
show
Unused Code introduced by
The parameter $request 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
        return response()->view('admin.nodes.remote.deploy', [
52
            'node' => Models\Node::findOrFail($id),
53
        ])->header('Content-Type', 'text/plain');
54
    }
55
56
    public function getIndex(Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request 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...
57
    {
58
        return view('admin.nodes.index', [
59
            'nodes' => Models\Node::with('location')->withCount('servers')->paginate(20),
0 ignored issues
show
Bug introduced by
The method withCount 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...
60
        ]);
61
    }
62
63
    public function getNew(Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request 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...
64
    {
65
        if (! Models\Location::all()->count()) {
66
            Alert::warning('You must add a location before you can add a new node.')->flash();
67
68
            return redirect()->route('admin.locations');
69
        }
70
71
        return view('admin.nodes.new', [
72
            'locations' => Models\Location::all(),
73
        ]);
74
    }
75
76
    public function postNew(Request $request)
77
    {
78
        try {
79
            $repo = new NodeRepository;
80
            $node = $repo->create($request->only([
81
                'name',
82
                'location',
83
                'public',
84
                'fqdn',
85
                'scheme',
86
                'memory',
87
                'memory_overallocate',
88
                'disk',
89
                'disk_overallocate',
90
                'daemonBase',
91
                'daemonSFTP',
92
                'daemonListen',
93
            ]));
94
            Alert::success('Successfully created new node that can be configured automatically on your remote machine by visiting the configuration tab. <strong>Before you can add any servers you need to first assign some IP addresses and ports.</strong>')->flash();
95
96
            return redirect()->route('admin.nodes.view', [
97
                'id' => $node->id,
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<Pterodactyl\Models\Node>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read 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.");
        }
    }

}

If the property has read access only, you can use the @property-read 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...
98
                'tab' => 'tab_allocation',
99
            ]);
100
        } catch (DisplayValidationException $e) {
101
            return redirect()->route('admin.nodes.new')->withErrors(json_decode($e->getMessage()))->withInput();
102
        } catch (DisplayException $e) {
103
            Alert::danger($e->getMessage())->flash();
104
        } catch (\Exception $e) {
105
            Log::error($e);
106
            Alert::danger('An unhandled exception occured while attempting to add this node. Please try again.')->flash();
107
        }
108
109
        return redirect()->route('admin.nodes.new')->withInput();
110
    }
111
112
    public function getView(Request $request, $id)
0 ignored issues
show
Unused Code introduced by
The parameter $request 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...
113
    {
114
        $node = Models\Node::with(
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...
115
            'servers.user',
116
            'servers.service',
117
            'servers.allocations',
118
            'location'
119
        )->findOrFail($id);
120
        $node->setRelation('allocations', $node->allocations()->paginate(40));
121
122
        return view('admin.nodes.view', [
123
            'node' => $node,
124
            'stats' => Models\Server::select(DB::raw('SUM(memory) as memory, SUM(disk) as disk'))->where('node_id', $node->id)->first(),
125
            'locations' => Models\Location::all(),
126
        ]);
127
    }
128
129
    public function postView(Request $request, $id)
130
    {
131
        try {
132
            $node = new NodeRepository;
133
            $node->update($id, $request->only([
134
                'name',
135
                'location',
136
                'public',
137
                'fqdn',
138
                'scheme',
139
                'memory',
140
                'memory_overallocate',
141
                'disk',
142
                'disk_overallocate',
143
                'upload_size',
144
                'daemonBase',
145
                'daemonSFTP',
146
                'daemonListen',
147
                'reset_secret',
148
            ]));
149
            Alert::success('Successfully update this node\'s information. If you changed any daemon settings you will need to restart it now.')->flash();
150
151
            return redirect()->route('admin.nodes.view', [
152
                'id' => $id,
153
                'tab' => 'tab_settings',
154
            ]);
155
        } catch (DisplayValidationException $e) {
156
            return redirect()->route('admin.nodes.view', $id)->withErrors(json_decode($e->getMessage()))->withInput();
157
        } catch (DisplayException $e) {
158
            Alert::danger($e->getMessage())->flash();
159
        } catch (\Exception $e) {
160
            Log::error($e);
161
            Alert::danger('An unhandled exception occured while attempting to edit this node. Please try again.')->flash();
162
        }
163
164
        return redirect()->route('admin.nodes.view', [
165
            'id' => $id,
166
            'tab' => 'tab_settings',
167
        ])->withInput();
168
    }
169
170
    public function deallocateSingle(Request $request, $node, $allocation)
0 ignored issues
show
Unused Code introduced by
The parameter $request 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...
171
    {
172
        $query = Models\Allocation::where('node', $node)->whereNull('assigned_to')->where('id', $allocation)->delete();
173
        if ((int) $query === 0) {
174
            return response()->json([
175
                'error' => 'Unable to find an allocation matching those details to delete.',
176
            ], 400);
177
        }
178
179
        return response('', 204);
180
    }
181
182
    public function deallocateBlock(Request $request, $node)
183
    {
184
        $query = Models\Allocation::where('node', $node)->whereNull('assigned_to')->where('ip', $request->input('ip'))->delete();
185
        if ((int) $query === 0) {
186
            Alert::danger('There was an error while attempting to delete allocations on that IP.')->flash();
187
188
            return redirect()->route('admin.nodes.view', [
189
                'id' => $node,
190
                'tab' => 'tab_allocations',
191
            ]);
192
        }
193
        Alert::success('Deleted all unallocated ports for <code>' . $request->input('ip') . '</code>.')->flash();
194
195
        return redirect()->route('admin.nodes.view', [
196
            'id' => $node,
197
            'tab' => 'tab_allocation',
198
        ]);
199
    }
200
201
    public function setAlias(Request $request, $node)
0 ignored issues
show
Unused Code introduced by
The parameter $node 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...
202
    {
203
        if (! $request->input('allocation')) {
204
            return response('Missing required parameters.', 422);
205
        }
206
207
        try {
208
            $update = Models\Allocation::findOrFail($request->input('allocation'));
209
            $update->ip_alias = (empty($request->input('alias'))) ? null : $request->input('alias');
210
            $update->save();
211
212
            return response('', 204);
213
        } catch (\Exception $ex) {
214
            throw $ex;
215
        }
216
    }
217
218
    public function getAllocationsJson(Request $request, $id)
0 ignored issues
show
Unused Code introduced by
The parameter $request 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...
219
    {
220
        $allocations = Models\Allocation::select('ip')->where('node', $id)->groupBy('ip')->get();
221
222
        return response()->json($allocations);
223
    }
224
225
    public function postAllocations(Request $request, $id)
226
    {
227
        $validator = Validator::make($request->all(), [
228
            'allocate_ip.*' => 'required|string',
229
            'allocate_port.*' => 'required',
230
        ]);
231
232
        if ($validator->fails()) {
233
            return redirect()->route('admin.nodes.view', [
234
                'id' => $id,
235
                'tab' => 'tab_allocation',
236
            ])->withErrors($validator->errors())->withInput();
237
        }
238
239
        $processedData = [];
240
        foreach ($request->input('allocate_ip') as $ip) {
0 ignored issues
show
Bug introduced by
The expression $request->input('allocate_ip') of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
241
            if (! array_key_exists($ip, $processedData)) {
242
                $processedData[$ip] = [];
243
            }
244
        }
245
246
        foreach ($request->input('allocate_port') as $portid => $ports) {
0 ignored issues
show
Bug introduced by
The expression $request->input('allocate_port') of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
247
            if (array_key_exists($portid, $request->input('allocate_ip'))) {
248
                $json = json_decode($ports);
249
                if (json_last_error() === 0 && ! empty($json)) {
250
                    foreach ($json as &$parsed) {
251
                        array_push($processedData[$request->input('allocate_ip')[$portid]], $parsed->value);
252
                    }
253
                }
254
            }
255
        }
256
257
        try {
258
            $node = new NodeRepository;
259
            $node->addAllocations($id, $processedData);
260
            Alert::success('Successfully added new allocations to this node.')->flash();
261
        } catch (DisplayException $e) {
262
            Alert::danger($e->getMessage())->flash();
263
        } catch (\Exception $e) {
264
            Log::error($e);
265
            Alert::danger('An unhandled exception occured while attempting to add allocations this node. Please try again.')->flash();
266
        } finally {
267
            return redirect()->route('admin.nodes.view', [
268
                'id' => $id,
269
                'tab' => 'tab_allocation',
270
            ]);
271
        }
272
    }
273
274 View Code Duplication
    public function deleteNode(Request $request, $id)
0 ignored issues
show
Unused Code introduced by
The parameter $request 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...
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...
275
    {
276
        try {
277
            $repo = new NodeRepository;
278
            $repo->delete($id);
279
            Alert::success('Successfully deleted the requested node from the panel.')->flash();
280
281
            return redirect()->route('admin.nodes');
282
        } catch (DisplayException $e) {
283
            Alert::danger($e->getMessage())->flash();
284
        } catch (\Exception $e) {
285
            Log::error($e);
286
            Alert::danger('An unhandled exception occured while attempting to delete this node. Please try again.')->flash();
287
        }
288
289
        return redirect()->route('admin.nodes.view', [
290
            'id' => $id,
291
            'tab' => 'tab_delete',
292
        ]);
293
    }
294
295
    public function getConfigurationToken(Request $request, $id)
0 ignored issues
show
Unused Code introduced by
The parameter $request 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...
296
    {
297
        // Check if Node exists. Will lead to 404 if not.
298
        Models\Node::findOrFail($id);
299
300
        // Create a token
301
        $token = new Models\NodeConfigurationToken();
302
        $token->node = $id;
0 ignored issues
show
Documentation introduced by
The property node does not exist on object<Pterodactyl\Models\NodeConfigurationToken>. 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...
303
        $token->token = str_random(32);
0 ignored issues
show
Documentation introduced by
The property token does not exist on object<Pterodactyl\Models\NodeConfigurationToken>. 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...
304
        $token->expires_at = Carbon::now()->addMinutes(5); // Expire in 5 Minutes
0 ignored issues
show
Documentation introduced by
The property expires_at does not exist on object<Pterodactyl\Models\NodeConfigurationToken>. 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...
305
        $token->save();
306
307
        $token_response = [
308
            'token' => $token->token,
0 ignored issues
show
Documentation introduced by
The property token does not exist on object<Pterodactyl\Models\NodeConfigurationToken>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read 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.");
        }
    }

}

If the property has read access only, you can use the @property-read 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...
309
            'expires_at' => $token->expires_at->toDateTimeString(),
0 ignored issues
show
Documentation introduced by
The property expires_at does not exist on object<Pterodactyl\Models\NodeConfigurationToken>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read 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.");
        }
    }

}

If the property has read access only, you can use the @property-read 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...
310
        ];
311
312
        return response()->json($token_response, 200);
313
    }
314
}
315