Completed
Push — master ( aaaac1...dad4ee )
by Klochok
05:34
created

ServerController::behaviors()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 30
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1.2963

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 30
ccs 1
cts 3
cp 0.3333
rs 8.8571
cc 1
eloc 22
nc 1
nop 0
crap 1.2963
1
<?php
2
/**
3
 * Server module for HiPanel.
4
 *
5
 * @link      https://github.com/hiqdev/hipanel-module-server
6
 * @package   hipanel-module-server
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hipanel\modules\server\controllers;
12
13
use hipanel\actions\Action;
14
use hipanel\actions\ComboSearchAction;
15
use hipanel\actions\IndexAction;
16
use hipanel\actions\PrepareBulkAction;
17
use hipanel\actions\ProxyAction;
18
use hipanel\actions\RedirectAction;
19
use hipanel\actions\RenderAction;
20
use hipanel\actions\RenderJsonAction;
21
use hipanel\actions\RequestStateAction;
22
use hipanel\actions\SmartDeleteAction;
23
use hipanel\actions\SmartPerformAction;
24
use hipanel\actions\SmartUpdateAction;
25
use hipanel\actions\ValidateFormAction;
26
use hipanel\actions\ViewAction;
27
use hipanel\base\CrudController;
28
use hipanel\filters\EasyAccessControl;
29
use hipanel\models\Ref;
30
use hipanel\modules\finance\models\Tariff;
31
use hipanel\modules\server\cart\ServerRenewProduct;
32
use hipanel\modules\server\helpers\ServerHelper;
33
use hipanel\modules\server\models\HardwareSettings;
34
use hipanel\modules\server\models\MonitoringSettings;
35
use hipanel\modules\server\models\Osimage;
36
use hipanel\modules\server\models\Server;
37
use hipanel\modules\server\models\ServerUseSearch;
38
use hipanel\modules\server\models\SoftwareSettings;
39
use hipanel\modules\server\widgets\ResourceConsumption;
40
use hipanel\modules\server\widgets\TrafficConsumption;
41
use hiqdev\hiart\ResponseErrorException;
42
use hiqdev\yii2\cart\actions\AddToCartAction;
43
use Yii;
44
use yii\base\Event;
45
use yii\filters\AccessControl;
46
use yii\filters\VerbFilter;
47
use yii\helpers\ArrayHelper;
48
use yii\web\NotFoundHttpException;
49
use yii\web\Response;
50
51
class ServerController extends CrudController
52
{
53
    public function behaviors()
54
    {
55
        return array_merge(parent::behaviors(), [
0 ignored issues
show
Bug Best Practice introduced by
The return type of return array_merge(paren...' => 'server.read')))); (array<*,array>) is incompatible with the return type of the parent method hipanel\base\Controller::behaviors of type array[].

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
56
            'server-actions-verb' => [
57
                'class' => VerbFilter::class,
58
                'actions' => [
59
                    'reboot' => ['post'],
60
                    'reset' => ['post'],
61
                    'shutdown' => ['post'],
62
                    'power-off' => ['post'],
63
                    'power-on' => ['post'],
64
                    'reset-password' => ['post'],
65
                    'enable-block' => ['post'],
66
                    'disable-block' => ['post'],
67
                    'refuse' => ['post'],
68
                    'flush-switch-graphs' => ['post'],
69
                ],
70
            ],
71
            [
72
                'class' => EasyAccessControl::class,
73
                'actions' => [
74
                    'monitoring-settings' => 'support',
75
                    'software-settings' => 'support',
76
                    'hardware-settings' => 'support',
77
                    'delete' => 'server.delete',
78
                    '*' => 'server.read',
79
                ],
80
            ],
81
        ]);
82 1
    }
83
84 1
    public function actions()
85 1
    {
86
        return array_merge(parent::actions(), [
87
            'index' => [
88 1
                'class' => IndexAction::class,
89
                'findOptions' => ['with_requests' => true, 'with_discounts' => true],
90
                'on beforePerform' => function (Event $event) {
91
                    /** @var \hipanel\actions\SearchAction $action */
92
                    $action = $event->sender;
93
                    $dataProvider = $action->getDataProvider();
94
                    $dataProvider->query->joinWith(['ips', 'bindings']);
95
96
                    $dataProvider->query
97
                        ->andWhere(['with_ips' => 1])
98
                        ->andWhere(['with_requests' => 1])
99
                        ->andWhere(['with_discounts' => 1])
100 1
                        ->andWhere(['with_bindings' => 1])
101
                        ->select(['*']);
102
                },
103
                'filterStorageMap' => [
104
                    'name_like' => 'server.server.name',
105
                    'ips' => 'hosting.ip.ip_in',
106
                    'state' => 'server.server.state',
107
                    'client_id' => 'client.client.id',
108
                    'seller_id' => 'client.client.seller_id',
109
                ],
110
            ],
111
            'search' => [
112
                'class' => ComboSearchAction::class,
113
            ],
114 1
            'hardware-settings' => [
115 1
                'class' => SmartUpdateAction::class,
116 1
                'success' => Yii::t('hipanel:server', 'Hardware properties was changed'),
117 1
                'view' => 'hardwareSettings',
118
                'scenario' => 'default',
119 View Code Duplication
                'on beforeFetch' => function (Event $event) {
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...
120
                    /** @var \hipanel\actions\SearchAction $action */
121
                    $action = $event->sender;
122
                    $dataProvider = $action->getDataProvider();
123 1
                    $dataProvider->query->joinWith(['hardwareSettings']);
124 1
                    $dataProvider->query->andWhere(['with_hardwareSettings' => 1])->select(['*']);
125
                },
126
                'on beforeLoad' => function (Event $event) {
127
                    /** @var Action $action */
128
                    $action = $event->sender;
129 1
130
                    $action->collection->setModel(HardwareSettings::class);
131
                },
132
                'POST html' => [
133
                    'save' => true,
134 1
                    'success' => [
135
                        'class' => RedirectAction::class,
136
                        'url' => function () {
137
                            $server = Yii::$app->request->post('HardwareSettings');
138 1
139
                            return ['@server/view', 'id' => $server['id']];
140
                        },
141
                    ],
142
                ],
143
            ],
144 1
            'software-settings' => [
145 1
                'class' => SmartUpdateAction::class,
146 1
                'success' => Yii::t('hipanel:server', 'Software properties was changed'),
147 1
                'view' => 'softwareSettings',
148
                'scenario' => 'default',
149 View Code Duplication
                'on beforeFetch' => function (Event $event) {
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...
150
                    /** @var \hipanel\actions\SearchAction $action */
151
                    $action = $event->sender;
152
                    $dataProvider = $action->getDataProvider();
153 1
                    $dataProvider->query->joinWith(['softwareSettings']);
154 1
                    $dataProvider->query->andWhere(['with_softwareSettings' => 1])->select(['*']);
155
                },
156
                'on beforeLoad' => function (Event $event) {
157
                    /** @var Action $action */
158
                    $action = $event->sender;
159 1
160
                    $action->collection->setModel(SoftwareSettings::class);
161
                },
162
                'POST html' => [
163
                    'save' => true,
164 1
                    'success' => [
165
                        'class' => RedirectAction::class,
166
                        'url' => function () {
167
                            $server = Yii::$app->request->post('SoftwareSettings');
168 1
169
                            return ['@server/view', 'id' => $server['id']];
170
                        },
171
                    ],
172
                ],
173
            ],
174 1
            'monitoring-settings' => [
175 1
                'class' => SmartUpdateAction::class,
176 1
                'success' => Yii::t('hipanel:server', 'Monitoring properties was changed'),
177 1
                'view' => 'monitoringSettings',
178
                'scenario' => 'default',
179 View Code Duplication
                'on beforeFetch' => function (Event $event) {
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...
180
                    /** @var \hipanel\actions\SearchAction $action */
181
                    $action = $event->sender;
182
                    $dataProvider = $action->getDataProvider();
183
                    $dataProvider->query->joinWith(['monitoringSettings']);
184 1
                    $dataProvider->query
185 1
                        ->andWhere(['with_monitoringSettings' => 1])->select(['*']);
186
                },
187
                'on beforeLoad' => function (Event $event) {
188
                    /** @var Action $action */
189
                    $action = $event->sender;
190 1
191 1
                    $action->collection->setModel(MonitoringSettings::class);
192
                },
193
                'data' => function ($action) {
194
                    return [
195 1
                        'nicMediaOptions' => $action->controller->getFullFromRef('type,nic_media'),
196
                    ];
197
                },
198
                'POST html' => [
199
                    'save' => true,
200 1
                    'success' => [
201
                        'class' => RedirectAction::class,
202
                        'url' => function () {
203
                            $server = Yii::$app->request->post('MonitoringSettings');
204 1
205
                            return ['@server/view', 'id' => $server['id']];
206
                        },
207
                    ],
208
                ],
209
            ],
210 1
            'view' => [
211
                'class' => ViewAction::class,
212
                'on beforePerform' => function (Event $event) {
213
                    /** @var \hipanel\actions\SearchAction $action */
214
                    $action = $event->sender;
215
                    $dataProvider = $action->getDataProvider();
216
                    $dataProvider->query->joinWith(['uses', 'ips', 'switches', 'bindings', 'blocking']);
217
218
                    // TODO: ipModule is not wise yet. Redo
219
                    $dataProvider->query
220
                        ->andWhere(['with_requests' => 1])
221
                        ->andWhere(['show_deleted' => 1])
222
                        ->andWhere(['with_discounts' => 1])
223
                        ->andWhere(['with_uses' => 1])
224
                        ->andWhere(['with_ips' => 1])
225
                        ->andWhere(['with_bindings' => 1])
226 1
                        ->andWhere(['with_blocking' => 1])
227 1
                        ->select(['*']);
228
                },
229
                'data' => function ($action) {
230
                    /**
231
                     * @var Action $action
232
                     * @var self $controller
233
                     * @var Server $model
234
                     */
235
                    $controller = $action->controller;
236
                    $model = $action->getModel();
237
                    $model->vnc = $controller->getVNCInfo($model);
0 ignored issues
show
Documentation Bug introduced by
The method getVNCInfo does not exist on object<hipanel\modules\s...trollers\HubController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
238
239
                    $panels = $controller->getPanelTypes();
0 ignored issues
show
Documentation Bug introduced by
The method getPanelTypes does not exist on object<hipanel\modules\s...trollers\HubController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
240
241
                    $cacheKeys = [__METHOD__, 'view', 'tariff', $model->tariff_id, Yii::$app->user->getId()];
242
                    $tariff = Yii::$app->cache->getOrSet($cacheKeys, function () use ($model) {
243
                        return Tariff::find()->where([
244
                            'id' => $model->tariff_id,
245
                            'show_final' => true,
246
                            'show_deleted' => true,
247
                            'with_resources' => true,
248
                        ])->joinWith('resources')->one();
249
                    });
250
251
                    $ispSupported = false;
252
                    if ($tariff !== null) {
253
                        foreach ($tariff->getResources() as $resource) {
254
                            if ($resource->type === 'isp' && $resource->quantity > 0) {
255
                                $ispSupported = true;
256
                            }
257
                        }
258
                    }
259
260
                    $osimages = $controller->getOsimages($model);
0 ignored issues
show
Documentation Bug introduced by
The method getOsimages does not exist on object<hipanel\modules\s...trollers\HubController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
261
                    $groupedOsimages = ServerHelper::groupOsimages($osimages, $ispSupported);
262
263
                    if ($model->isLiveCDSupported()) {
264
                        $osimageslivecd = $controller->getOsimagesLiveCd();
0 ignored issues
show
Documentation Bug introduced by
The method getOsimagesLiveCd does not exist on object<hipanel\modules\s...trollers\HubController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
265
                    }
266
267
                    $blockReasons = $controller->getBlockReasons();
268
269
                    return compact([
270
                        'model',
271
                        'osimages',
272
                        'osimageslivecd',
273
                        'groupedOsimages',
274
                        'panels',
275 1
                        'blockReasons',
276
                    ]);
277
                },
278
            ],
279
            'requests-state' => [
280
                'class' => RequestStateAction::class,
281
                'model' => Server::class,
282
            ],
283 1
            'set-note' => [
284 1
                'class' => SmartUpdateAction::class,
285 1
                'view' => '_bulkSetNote',
286
                'success' => Yii::t('hipanel:server', 'Note changed'),
287
                'error' => Yii::t('hipanel:server', 'Failed to change note'),
288
            ],
289 1
            'set-label' => [
290 1
                'class' => SmartUpdateAction::class,
291 1
                'view' => '_bulkSetLabel',
292
                'success' => Yii::t('hipanel:server', 'Internal note changed'),
293
                'error' => Yii::t('hipanel:server', 'Failed to change internal note'),
294
            ],
295 1
            'set-lock' => [
296 1
                'class' => RenderAction::class,
297
                'success' => Yii::t('hipanel:server', 'Record was changed'),
298
                'error' => Yii::t('hipanel:server', 'Error occurred'),
299
                'POST pjax' => [
300
                    'save' => true,
301
                    'success' => [
302
                        'class' => ProxyAction::class,
303
                        'action' => 'index',
304
                    ],
305
                ],
306
                'POST' => [
307
                    'save' => true,
308 1
                    'success' => [
309
                        'class' => RenderJsonAction::class,
310
                        'return' => function ($action) {
311 1
                            /** @var \hipanel\actions\Action $action */
312
                            return $action->collection->models;
313
                        },
314
                    ],
315
                ],
316
            ],
317 1
            'enable-vnc' => [
318 1
                'class' => ViewAction::class,
319
                'view' => '_vnc',
320
                'data' => function ($action) {
321
                    $model = $action->getModel();
322
                    if ($model->canEnableVNC()) {
323
                        $model->vnc = $this->getVNCInfo($model, true);
324
                    }
325 1
326
                    return [];
327
                },
328
            ],
329 1
            'bulk-sale' => [
330 1
                'class' => SmartUpdateAction::class,
331 1
                'scenario' => 'sale',
332
                'view' => '_bulkSale',
333
                'success' => Yii::t('hipanel:server', 'Servers were sold'),
334
                'POST pjax' => [
335
                    'save' => true,
336
                    'success' => [
337
                        'class' => ProxyAction::class,
338
                        'action' => 'index',
339 1
                    ],
340
                ],
341
                'on beforeSave' => function (Event $event) {
342
                    /** @var \hipanel\actions\Action $action */
343
                    $action = $event->sender;
344
                    $request = Yii::$app->request;
345
346
                    if ($request->isPost) {
347
                        $values = [];
348
                        foreach (['client_id', 'tariff_id', 'sale_time', 'move_accounts'] as $attribute) {
349
                            $value = $request->post($attribute);
350
                            if (!empty($value)) {
351
                                $values[$attribute] = $value;
352
                            }
353
                        }
354
                        foreach ($action->collection->models as $model) {
355
                            foreach ($values as $attr => $value) {
356
                                $model->setAttribute($attr, $value);
357
                            }
358 1
                        }
359
                    }
360
                },
361
            ],
362 1
            'set-type' => [
363 1
                'class' => SmartUpdateAction::class,
364 1
                'view' => '_bulkSetType',
365
                'success' => Yii::t('hipanel:server', 'Type was changed'),
366
                'error' => Yii::t('hipanel:server', 'Failed to change type'),
367
            ],
368 1
            'reboot' => [
369 1
                'class' => SmartPerformAction::class,
370
                'success' => Yii::t('hipanel:server', 'Reboot task has been successfully added to queue'),
371
                'error' => Yii::t('hipanel:server', 'Error during the rebooting'),
372
            ],
373 1
            'reset' => [
374 1
                'class' => SmartPerformAction::class,
375
                'success' => Yii::t('hipanel:server', 'Reset task has been successfully added to queue'),
376
                'error' => Yii::t('hipanel:server', 'Error during the resetting'),
377
            ],
378 1
            'shutdown' => [
379 1
                'class' => SmartPerformAction::class,
380
                'success' => Yii::t('hipanel:server', 'Shutdown task has been successfully added to queue'),
381
                'error' => Yii::t('hipanel:server', 'Error during the shutting down'),
382
            ],
383 1
            'power-off' => [
384 1
                'class' => SmartPerformAction::class,
385
                'success' => Yii::t('hipanel:server', 'Power off task has been successfully added to queue'),
386
                'error' => Yii::t('hipanel:server', 'Error during the turning power off'),
387
            ],
388 1
            'power-on' => [
389 1
                'class' => SmartPerformAction::class,
390
                'success' => Yii::t('hipanel:server', 'Power on task has been successfully added to queue'),
391
                'error' => Yii::t('hipanel:server', 'Error during the turning power on'),
392
            ],
393 1
            'reset-password' => [
394 1
                'class' => SmartPerformAction::class,
395
                'success' => Yii::t('hipanel:server', 'Root password reset task has been successfully added to queue'),
396
                'error' => Yii::t('hipanel:server', 'Error during the resetting root password'),
397
            ],
398 1
            'enable-block' => [
399 1
                'class' => SmartPerformAction::class,
400
                'success' => Yii::t('hipanel:server', 'Server was blocked successfully'),
401
                'error' => Yii::t('hipanel:server', 'Error during the server blocking'),
402
                'POST html' => [
403
                    'save' => true,
404
                    'success' => [
405
                        'class' => RedirectAction::class,
406 1
                    ],
407
                ],
408 View Code Duplication
                'on beforeSave' => function (Event $event) {
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...
409
                    /** @var \hipanel\actions\Action $action */
410
                    $action = $event->sender;
411
                    $type = Yii::$app->request->post('type');
412
                    $comment = Yii::$app->request->post('comment');
413
                    if (!empty($type)) {
414
                        foreach ($action->collection->models as $model) {
415
                            $model->setAttributes([
416
                                'type' => $type,
417
                                'comment' => $comment,
418
                            ]);
419 1
                        }
420
                    }
421
                },
422
            ],
423 1
            'bulk-enable-block-modal' => [
424 1
                'class' => PrepareBulkAction::class,
425
                'view' => '_bulkEnableBlock',
426
                'data' => function ($action, $data) {
427
                    return array_merge($data, [
428 1
                        'blockReasons' => $this->getBlockReasons(),
429
                    ]);
430
                },
431
            ],
432 1
            'disable-block' => [
433 1
                'class' => SmartPerformAction::class,
434
                'success' => Yii::t('hipanel:server', 'Server was unblocked successfully'),
435
                'error' => Yii::t('hipanel:server', 'Error during the server unblocking'),
436
                'POST html' => [
437
                    'save' => true,
438
                    'success' => [
439
                        'class' => RedirectAction::class,
440 1
                    ],
441
                ],
442 View Code Duplication
                'on beforeSave' => function (Event $event) {
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...
443
                    /** @var \hipanel\actions\Action $action */
444
                    $action = $event->sender;
445
                    $type = Yii::$app->request->post('type');
446
                    $comment = Yii::$app->request->post('comment');
447
                    if (!empty($type)) {
448
                        foreach ($action->collection->models as $model) {
449
                            $model->setAttributes([
450
                                'comment' => $comment,
451
                                'type' => $type,
452
                            ]);
453 1
                        }
454
                    }
455
                },
456
            ],
457 1
            'bulk-disable-block-modal' => [
458 1
                'class' => PrepareBulkAction::class,
459
                'view' => '_bulkDisableBlock',
460
                'data' => function ($action, $data) {
461
                    return array_merge($data, [
462 1
                        'blockReasons' => $this->getBlockReasons(),
463
                    ]);
464
                },
465
            ],
466 1
            'refuse' => [
467 1
                'class' => SmartPerformAction::class,
468
                'success' => Yii::t('hipanel:server', 'You have refused the service'),
469
                'error' => Yii::t('hipanel:server', 'Error during the refusing the service'),
470
            ],
471 1
            'enable-autorenewal' => [
472 1
                'class' => SmartUpdateAction::class,
473
                'success' => Yii::t('hipanel:server', 'Server renewal enabled successfully'),
474
                'error' => Yii::t('hipanel:server', 'Error during the renewing the service'),
475
            ],
476 1
            'reinstall' => [
477
                'class' => SmartUpdateAction::class,
478
                'on beforeSave' => function (Event $event) {
479
                    /** @var Action $action */
480
                    $action = $event->sender;
481
                    foreach ($action->collection->models as $model) {
482
                        $model->osimage = Yii::$app->request->post('osimage');
483 1
                        $model->panel = Yii::$app->request->post('panel');
484 1
                    }
485 1
                },
486
                'success' => Yii::t('hipanel:server', 'Server reinstalling task has been successfully added to queue'),
487
                'error' => Yii::t('hipanel:server', 'Error during the server reinstalling'),
488
            ],
489 1
            'boot-live' => [
490
                'class' => SmartPerformAction::class,
491
                'on beforeSave' => function (Event $event) {
492
                    /** @var Action $action */
493
                    $action = $event->sender;
494
                    foreach ($action->collection->models as $model) {
495 1
                        $model->osimage = Yii::$app->request->post('osimage');
496 1
                    }
497 1
                },
498
                'success' => Yii::t('hipanel:server', 'Live CD booting task has been successfully added to queue'),
499
                'error' => Yii::t('hipanel:server', 'Error during the booting live CD'),
500
            ],
501
            'validate-form' => [
502
                'class' => ValidateFormAction::class,
503
            ],
504 1
            'buy' => [
505
                'class' => RedirectAction::class,
506
                'url' => Yii::$app->params['organization.url'],
507
            ],
508
            'add-to-cart-renewal' => [
509
                'class' => AddToCartAction::class,
510
                'productClass' => ServerRenewProduct::class,
511
            ],
512 1
            'delete' => [
513 1
                'class' => SmartDeleteAction::class,
514
                'success' => Yii::t('hipanel:server', 'Server was deleted successfully'),
515
                'error' => Yii::t('hipanel:server', 'Failed to delete server'),
516
            ],
517
            'bulk-delete-modal' => [
518
                'class' => PrepareBulkAction::class,
519
                'view' => '_bulkDelete',
520
            ],
521 1
            'clear-resources' => [
522 1
                'class' => SmartPerformAction::class,
523 1
                'view' => '_clearResources',
524
                'success' => Yii::t('hipanel:server', 'Servers resources were cleared successfully'),
525
                'error' => Yii::t('hipanel:server', 'Error occurred during server resources flushing'),
526
            ],
527
            'clear-resources-modal' => [
528
                'class' => PrepareBulkAction::class,
529
                'view' => '_clearResources',
530
            ],
531 1
            'flush-switch-graphs' => [
532 1
                'class' => SmartPerformAction::class,
533 1
                'view' => '_clearResources',
534
                'success' => Yii::t('hipanel:server', 'Switch graphs were flushed successfully'),
535
                'error' => Yii::t('hipanel:server', 'Error occurred during switch graphs flushing'),
536
            ],
537
            'flush-switch-graphs-modal' => [
538
                'class' => PrepareBulkAction::class,
539
                'view' => '_flushSwitchGraphs',
540
            ],
541
        ]);
542
    }
543
544
    /**
545
     * Gets info of VNC on the server.
546
     *
547
     * @param Server $model
548
     * @param bool $enable
549
     * @throws ResponseErrorException
550
     * @return array
551
     */
552
    public function getVNCInfo($model, $enable = false)
553
    {
554
        if ($enable) {
555
            try {
556
                $vnc = Server::perform('enable-VNC', ['id' => $model->id]);
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<hipanel\modules\server\models\Server>. 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...
557
                $vnc['endTime'] = time() + 28800;
558
                Yii::$app->cache->set([__METHOD__, $model->id, $model], $vnc, 28800);
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<hipanel\modules\server\models\Server>. 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...
559
                $vnc['enabled'] = true;
560
            } catch (ResponseErrorException $e) {
561
                if ($e->getMessage() !== 'vds_has_tasks') {
562
                    throw $e;
563
                }
564
            }
565
        } else {
566
            if ($model->statuses['serverEnableVNC'] !== null && strtotime('+8 hours', strtotime($model->statuses['serverEnableVNC'])) > time()) {
0 ignored issues
show
Documentation introduced by
The property statuses does not exist on object<hipanel\modules\server\models\Server>. 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...
567
                $vnc = Yii::$app->cache->getOrSet([__METHOD__, $model->id, $model], function () use ($model) {
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<hipanel\modules\server\models\Server>. 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...
568
                    return ArrayHelper::merge([
569
                        'endTime' => strtotime($model->statuses['serverEnableVNC']) + 28800,
0 ignored issues
show
Documentation introduced by
The property statuses does not exist on object<hipanel\modules\server\models\Server>. 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...
570
                    ], Server::perform('enable-VNC', ['id' => $model->id]));
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<hipanel\modules\server\models\Server>. 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...
571
                }, 28800);
572
            }
573
            $vnc['enabled'] = $model->statuses['serverEnableVNC'] === null ? false : strtotime('+8 hours', strtotime($model->statuses['serverEnableVNC'])) > time();
0 ignored issues
show
Documentation introduced by
The property statuses does not exist on object<hipanel\modules\server\models\Server>. 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...
Bug introduced by
The variable $vnc does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
574
        }
575
576
        return $vnc;
577
    }
578
579
    public function actionDrawChart()
580
    {
581
        $post = Yii::$app->request->post();
582
        $types = array_merge(['server_traf', 'server_traf95'], array_keys(ResourceConsumption::types()));
583
        if (!in_array($post['type'], $types, true)) {
584
            throw new NotFoundHttpException();
585
        }
586
587
        $searchModel = new ServerUseSearch();
588
        $dataProvider = $searchModel->search([]);
589
        $dataProvider->pagination = false;
590
        $dataProvider->query->action('get-uses');
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface yii\db\QueryInterface as the method action() does only exist in the following implementations of said interface: hipanel\modules\client\models\query\ArticleQuery, hipanel\modules\client\models\query\ClientQuery, hipanel\modules\client\models\query\ContactQuery, hipanel\modules\finance\models\query\TariffQuery, hiqdev\hiart\ActiveQuery, hiqdev\hiart\Query.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
591
        $dataProvider->query->andWhere($post);
592
        $models = $dataProvider->getModels();
593
594
        list($labels, $data) = ServerHelper::groupUsesForChart($models);
0 ignored issues
show
Documentation introduced by
$models is of type array|null, but the function expects a array<integer,object<hip...rver\models\ServerUse>>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
595
596
        return $this->renderAjax('_consumption', [
597
            'labels' => $labels,
598
            'data' => $data,
599
            'consumptionBase' => $post['type'],
600
        ]);
601
    }
602
603
    /**
604
     * Gets OS images.
605
     *
606
     * @param Server $model
607
     * @throws NotFoundHttpException
608
     * @return array
609
     */
610
    protected function getOsimages(Server $model = null)
611
    {
612
        if ($model !== null) {
613
            $type = $model->type;
0 ignored issues
show
Documentation introduced by
The property type does not exist on object<hipanel\modules\server\models\Server>. 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...
614
        } else {
615
            $type = null;
616
        }
617
618
        $models = ServerHelper::getOsimages($type);
619
620
        if ($models === null) {
621
            throw new NotFoundHttpException('The requested page does not exist.');
622
        }
623
624
        return $models;
625
    }
626
627
    protected function getOsimagesLiveCd()
628
    {
629
        $models = Yii::$app->cache->getOrSet([__METHOD__], function () {
630
            return Osimage::findAll(['livecd' => true]);
631
        }, 3600);
632
633
        if ($models !== null) {
634
            return $models;
635
        }
636
637
        throw new NotFoundHttpException('The requested page does not exist.');
638
    }
639
640
    protected function getPanelTypes()
641
    {
642
        return ServerHelper::getPanels();
643
    }
644
645
    public function actionIsOperable($id)
646
    {
647
        Yii::$app->response->format = Response::FORMAT_JSON;
648
649
        $result = ['id' => $id, 'result' => false];
650
651
        if ($server = Server::find()->where(['id' => $id])->one()) {
652
            $result['result'] = $server->isOperable();
653
        }
654
655
        return $result;
656
    }
657
658 View Code Duplication
    protected function getFullFromRef($gtype)
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...
659
    {
660
        $callingMethod = debug_backtrace()[1]['function'];
661
        $result = Yii::$app->get('cache')->getOrSet([$callingMethod], function () use ($gtype) {
662
            $result = ArrayHelper::map(Ref::find()->where([
663
                'gtype' => $gtype,
664
                'select' => 'full',
665
            ])->all(), 'id', function ($model) {
666
                return Yii::t('hipanel:server:hub', $model->label);
667
            });
668
669
            return $result;
670
        }, 86400 * 24); // 24 days
671
672
        return $result;
673
    }
674
675
    public function actionResources($id)
676
    {
677
        $model = Server::find()->joinWith(['uses'])->andWhere(['id' => $id])->andWhere(['with_uses' => 1])->one();
678
        list($chartsLabels, $chartsData) = $model->groupUsesForCharts();
679
680
        return $this->render('resources', compact('model', 'chartsData', 'chartsLabels'));
681
    }
682
}
683