Passed
Push — master ( d23c33...74888d )
by Andrii
03:48
created

ServerController::actions()   F

Complexity

Conditions 31
Paths 1

Size

Total Lines 631
Code Lines 442

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 149
CRAP Score 181.2326

Importance

Changes 0
Metric Value
eloc 442
dl 0
loc 631
ccs 149
cts 323
cp 0.4613
rs 3.3333
c 0
b 0
f 0
cc 31
nc 1
nop 0
crap 181.2326

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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-2018, 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\SmartCreateAction;
23
use hipanel\actions\SmartDeleteAction;
24
use hipanel\actions\SmartPerformAction;
25
use hipanel\actions\SmartUpdateAction;
26
use hipanel\actions\ValidateFormAction;
27
use hipanel\actions\ViewAction;
28
use hipanel\base\CrudController;
29
use hipanel\filters\EasyAccessControl;
30
use hipanel\models\Ref;
31
use hipanel\modules\finance\models\Tariff;
32
use hipanel\modules\server\cart\ServerRenewProduct;
33
use hipanel\modules\server\forms\AssignHubsForm;
34
use hipanel\modules\server\forms\ServerForm;
35
use hipanel\modules\server\helpers\ServerHelper;
36
use hipanel\modules\server\models\HardwareSettings;
37
use hipanel\modules\server\models\MonitoringSettings;
38
use hipanel\modules\server\models\Osimage;
39
use hipanel\modules\server\models\Server;
40
use hipanel\modules\server\models\ServerUseSearch;
41
use hipanel\modules\server\models\SoftwareSettings;
42
use hipanel\modules\server\widgets\ResourceConsumption;
43
use hiqdev\hiart\Collection;
44
use hiqdev\hiart\ResponseErrorException;
45
use hiqdev\yii2\cart\actions\AddToCartAction;
46
use Yii;
47
use yii\base\Event;
48
use yii\filters\VerbFilter;
49
use yii\helpers\ArrayHelper;
50
use yii\web\NotFoundHttpException;
51
use yii\web\Response;
52
53
class ServerController extends CrudController
54
{
55
    public function behaviors()
56
    {
57
        return array_merge(parent::behaviors(), [
58
            'server-actions-verb' => [
59
                'class' => VerbFilter::class,
60
                'actions' => [
61
                    'reboot' => ['post'],
62
                    'reset' => ['post'],
63
                    'shutdown' => ['post'],
64
                    'power-off' => ['post'],
65
                    'power-on' => ['post'],
66
                    'reset-password' => ['post'],
67
                    'enable-block' => ['post'],
68
                    'disable-block' => ['post'],
69
                    'refuse' => ['post'],
70
                    'flush-switch-graphs' => ['post'],
71
                ],
72
            ],
73
            [
74
                'class' => EasyAccessControl::class,
75
                'actions' => [
76
                    'monitoring-settings' => 'support',
77
                    'software-settings' => 'support',
78
                    'hardware-settings' => 'support',
79
                    'create' => 'server.create',
80
                    'update' => 'server.update',
81
                    'delete' => 'server.delete',
82
                    'assign-hubs' => 'server.update',
83
                    'set-units' => 'server.update',
84
                    'set-rack-no' => 'server.update',
85
                    '*' => 'server.read',
86
                ],
87
            ],
88
        ]);
89
    }
90
91 1
    public function actions()
92
    {
93 1
        return array_merge(parent::actions(), [
94 1
            'index' => [
95
                'class' => IndexAction::class,
96
                'findOptions' => ['with_requests' => true, 'with_discounts' => true],
97 1
                'on beforePerform' => function (Event $event) {
98
                    /** @var \hipanel\actions\SearchAction $action */
99
                    $action = $event->sender;
100
                    $dataProvider = $action->getDataProvider();
101
102
                    $dataProvider->query->withBindings();
103
104
                    if (Yii::getAlias('@ip', false)) {
105
                        $dataProvider->query
106
                            ->joinWith(['ips'])
107
                            ->andWhere(['with_ips' => 1]);
108
                    }
109
110
                    $dataProvider->query
111
                        ->andWhere(['with_requests' => 1])
112
                        ->andWhere(['with_discounts' => 1])
113
                        ->select(['*']);
114 1
                },
115
                'filterStorageMap' => [
116
                    'name_like' => 'server.server.name',
117
                    'ips' => 'hosting.ip.ip_in',
118
                    'state' => 'server.server.state',
119
                    'client_id' => 'client.client.id',
120
                    'seller_id' => 'client.client.seller_id',
121
                ],
122
            ],
123
            'search' => [
124
                'class' => ComboSearchAction::class,
125
            ],
126
            'create' => [
127
                'class' => SmartCreateAction::class,
128
                'collection' => [
129
                    'class' => Collection::class,
130 1
                    'model' => new ServerForm(['scenario' => 'create']),
131 1
                    'scenario' => 'create',
132
                ],
133 1
                'success' => Yii::t('hipanel:server', 'Server has been created'),
134
            ],
135
            'update' => [
136
                'class' => SmartUpdateAction::class,
137
                'collection' => [
138
                    'class' => Collection::class,
139 1
                    'model' => new ServerForm(),
140 1
                    'scenario' => 'update',
141
                ],
142 1
                'on beforeFetch' => function (Event $event) {
143
                    /** @var \hipanel\actions\SearchAction $action */
144
                    $action = $event->sender;
145
                    $dataProvider = $action->getDataProvider();
146
                    if (Yii::getAlias('@ip', false)) {
147
                        $dataProvider->query->joinWith('ips');
148
                    }
149 1
                },
150 1
                'data' => function (Action $action, array $data) {
151
                    $result = [];
152
                    foreach ($data['models'] as $model) {
153
                        $result['models'][] = ServerForm::fromServer($model);
154
                    }
155
                    $result['model'] = reset($result['models']);
156
157
                    return $result;
158 1
                },
159 1
                'success' => Yii::t('hipanel:server', 'Server has been updated'),
160
            ],
161
            'assign-hubs' => [
162
                'class' => SmartUpdateAction::class,
163 1
                'success' => Yii::t('hipanel:server', 'Hubs were assigned'),
164 1
                'view' => 'assignHubs',
165 1
                'on beforeFetch' => function (Event $event) {
166
                    /** @var \hipanel\actions\SearchAction $action */
167
                    $action = $event->sender;
168
                    $dataProvider = $action->getDataProvider();
169
                    $dataProvider->query->withBindings()->select(['*']);
170 1
                },
171
                'collection' => [
172
                    'class' => Collection::class,
173 1
                    'model' => new AssignHubsForm(),
174 1
                    'scenario' => 'default',
175
                ],
176 1
                'data' => function (Action $action, array $data) {
177
                    $result = [];
178
                    foreach ($data['models'] as $model) {
179
                        if ($model->canAssignHubs()) {
180
                            $result['models'][] = AssignHubsForm::fromServer($model);
181
                        }
182
                    }
183
                    if (!$result['models']) {
184
                        throw new NotFoundHttpException('There are no entries available for the selected operation. The type of selected records may not be suitable for the selected operation.');
185
                    }
186
                    $result['model'] = reset($result['models']);
187
188
                    return $result;
189 1
                },
190
            ],
191
            'set-units' => [
192
                'class' => SmartUpdateAction::class,
193 1
                'success' => Yii::t('hipanel:server', 'Units property was changed'),
194 1
                'view' => 'setUnits',
195 1
                'on beforeSave' => function (Event $event) {
196
                    /** @var \hipanel\actions\Action $action */
197
                    $action = $event->sender;
198
                    $servers = Yii::$app->request->post('HardwareSettings');
199
                    $units = ArrayHelper::remove($servers, 'units');
200
                    foreach ($servers as $id => $server) {
201
                        $servers[$id]['units'] = $units;
202
                    }
203
                    $action->collection->load($servers);
204 1
                },
205 1
                'on beforeFetch' => function (Event $event) {
206
                    /** @var \hipanel\actions\SearchAction $action */
207
                    $action = $event->sender;
208
                    $dataProvider = $action->getDataProvider();
209
                    $dataProvider->query->joinWith(['hardwareSettings']);
210
                    $dataProvider->query->andWhere(['with_hardwareSettings' => 1])->select(['*']);
211 1
                },
212 1
                'on beforeLoad' => function (Event $event) {
213
                    /** @var Action $action */
214
                    $action = $event->sender;
215
216
                    $action->collection->setModel((new HardwareSettings(['scenario' => 'set-units'])));
217 1
                },
218
            ],
219
            'set-rack-no' => [
220
                'class' => SmartUpdateAction::class,
221 1
                'success' => Yii::t('hipanel:server', 'Rack No. was assigned'),
222 1
                'view' => 'setRackNo',
223
                'collection' => [
224
                    'class' => Collection::class,
225 1
                    'model' => new AssignHubsForm(),
226 1
                    'scenario' => 'default',
227
                ],
228 1
                'on beforeSave' => function (Event $event) {
229
                    /** @var \hipanel\actions\Action $action */
230
                    $action = $event->sender;
231
                    $servers = Yii::$app->request->post('AssignHubsForm');
232
                    $rackId = ArrayHelper::remove($servers, 'rack_id');
233
                    $rackPort = ArrayHelper::remove($servers, 'rack_port');
234
                    foreach ($servers as $id => $server) {
235
                        $servers[$id]['rack_id'] = $rackId;
236
                        $servers[$id]['rack_port'] = $rackPort;
237
                    }
238
                    $action->collection->load($servers);
239 1
                },
240 1
                'on beforeFetch' => function (Event $event) {
241
                    /** @var \hipanel\actions\SearchAction $action */
242
                    $action = $event->sender;
243
                    $dataProvider = $action->getDataProvider();
244
                    $dataProvider->query->withBindings()->select(['*']);
245 1
                },
246 1
                'data' => function (Action $action, array $data) {
247
                    $result = [];
248
                    foreach ($data['models'] as $model) {
249
                        if ($model->canAssignHubs()) {
250
                            $result['models'][] = AssignHubsForm::fromServer($model);
251
                        }
252
                    }
253
                    if (!$result['models']) {
254
                        throw new NotFoundHttpException('There are no entries available for the selected operation. The type of selected records may not be suitable for the selected operation.');
255
                    }
256
                    $result['model'] = reset($result['models']);
257
258
                    return $result;
259 1
                },
260
            ],
261
            'hardware-settings' => [
262
                'class' => SmartUpdateAction::class,
263 1
                'success' => Yii::t('hipanel:server', 'Hardware properties was changed'),
264 1
                'view' => 'hardwareSettings',
265 1
                'on beforeFetch' => function (Event $event) {
266
                    /** @var \hipanel\actions\SearchAction $action */
267
                    $action = $event->sender;
268
                    $dataProvider = $action->getDataProvider();
269
                    $dataProvider->query->joinWith(['hardwareSettings']);
270
                    $dataProvider->query->andWhere(['with_hardwareSettings' => 1])->select(['*']);
271 1
                },
272 1
                'on beforeLoad' => function (Event $event) {
273
                    /** @var Action $action */
274
                    $action = $event->sender;
275
276
                    $action->collection->setModel(HardwareSettings::class);
0 ignored issues
show
Bug introduced by
hipanel\modules\server\m...HardwareSettings::class of type string is incompatible with the type hiqdev\hiart\ActiveRecord|array expected by parameter $model of hiqdev\hiart\Collection::setModel(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

276
                    $action->collection->setModel(/** @scrutinizer ignore-type */ HardwareSettings::class);
Loading history...
277 1
                },
278
                'POST html' => [
279
                    'save' => true,
280
                    'success' => [
281
                        'class' => RedirectAction::class,
282 1
                        'url' => function () {
283
                            $server = Yii::$app->request->post('HardwareSettings');
284
285
                            return ['@server/view', 'id' => $server['id']];
286 1
                        },
287
                    ],
288
                ],
289
            ],
290
            'software-settings' => [
291
                'class' => SmartUpdateAction::class,
292 1
                'success' => Yii::t('hipanel:server', 'Software properties was changed'),
293 1
                'view' => 'softwareSettings',
294 1
                'scenario' => 'default',
295 1
                'on beforeFetch' => function (Event $event) {
296
                    /** @var \hipanel\actions\SearchAction $action */
297
                    $action = $event->sender;
298
                    $dataProvider = $action->getDataProvider();
299
                    $dataProvider->query->joinWith(['softwareSettings']);
300
                    $dataProvider->query->andWhere(['with_softwareSettings' => 1])->select(['*']);
301 1
                },
302 1
                'on beforeLoad' => function (Event $event) {
303
                    /** @var Action $action */
304
                    $action = $event->sender;
305
306
                    $action->collection->setModel(SoftwareSettings::class);
0 ignored issues
show
Bug introduced by
hipanel\modules\server\m...SoftwareSettings::class of type string is incompatible with the type hiqdev\hiart\ActiveRecord|array expected by parameter $model of hiqdev\hiart\Collection::setModel(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

306
                    $action->collection->setModel(/** @scrutinizer ignore-type */ SoftwareSettings::class);
Loading history...
307 1
                },
308
                'POST html' => [
309
                    'save' => true,
310
                    'success' => [
311
                        'class' => RedirectAction::class,
312 1
                        'url' => function () {
313
                            $server = Yii::$app->request->post('SoftwareSettings');
314
315
                            return ['@server/view', 'id' => $server['id']];
316 1
                        },
317
                    ],
318
                ],
319
            ],
320
            'monitoring-settings' => [
321
                'class' => SmartUpdateAction::class,
322 1
                'success' => Yii::t('hipanel:server', 'Monitoring properties was changed'),
323 1
                'view' => 'monitoringSettings',
324 1
                'scenario' => 'default',
325 1
                'on beforeFetch' => function (Event $event) {
326
                    /** @var \hipanel\actions\SearchAction $action */
327
                    $action = $event->sender;
328
                    $dataProvider = $action->getDataProvider();
329
                    $dataProvider->query->joinWith(['monitoringSettings']);
330
                    $dataProvider->query
331
                        ->andWhere(['with_monitoringSettings' => 1])->select(['*']);
332 1
                },
333 1
                'on beforeLoad' => function (Event $event) {
334
                    /** @var Action $action */
335
                    $action = $event->sender;
336
337
                    $action->collection->setModel(MonitoringSettings::class);
0 ignored issues
show
Bug introduced by
hipanel\modules\server\m...nitoringSettings::class of type string is incompatible with the type hiqdev\hiart\ActiveRecord|array expected by parameter $model of hiqdev\hiart\Collection::setModel(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

337
                    $action->collection->setModel(/** @scrutinizer ignore-type */ MonitoringSettings::class);
Loading history...
338 1
                },
339 1
                'data' => function ($action) {
340
                    return [
341
                        'nicMediaOptions' => $action->controller->getFullFromRef('type,nic_media'),
342
                    ];
343 1
                },
344
                'POST html' => [
345
                    'save' => true,
346
                    'success' => [
347
                        'class' => RedirectAction::class,
348 1
                        'url' => function () {
349
                            $server = Yii::$app->request->post('MonitoringSettings');
350
351
                            return ['@server/view', 'id' => $server['id']];
352 1
                        },
353
                    ],
354
                ],
355
            ],
356
            'view' => [
357
                'class' => ViewAction::class,
358 1
                'on beforePerform' => function (Event $event) {
359
                    /** @var \hipanel\actions\SearchAction $action */
360
                    $action = $event->sender;
361
                    $dataProvider = $action->getDataProvider();
362
                    $dataProvider->query->withBindings()->joinWith(['uses', 'switches', 'blocking']);
363
364
                    if (Yii::getAlias('@ip', false)) {
365
                        $dataProvider->query
366
                            ->joinWith(['ips'])
367
                            ->andWhere(['with_ips' => 1]);
368
                    }
369
370
                    // TODO: ipModule is not wise yet. Redo
371
                    $dataProvider->query
372
                        ->andWhere(['with_requests' => 1])
373
                        ->andWhere(['show_deleted' => 1])
374
                        ->andWhere(['with_discounts' => 1])
375
                        ->andWhere(['with_uses' => 1])
376
                        ->andWhere(['with_blocking' => 1])
377
                        ->select(['*']);
378 1
                },
379 1
                'data' => function ($action) {
380
                    /**
381
                     * @var Action
382
                     * @var self $controller
383
                     * @var Server $model
384
                     */
385
                    $controller = $action->controller;
386
                    $model = $action->getModel();
387
                    $model->vnc = $controller->getVNCInfo($model);
388
389
                    $panels = $controller->getPanelTypes();
390
391
                    $cacheKeys = [__METHOD__, 'view', 'tariff', $model->tariff_id, Yii::$app->user->getId()];
0 ignored issues
show
Bug introduced by
The method getId() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

391
                    $cacheKeys = [__METHOD__, 'view', 'tariff', $model->tariff_id, Yii::$app->user->/** @scrutinizer ignore-call */ getId()];

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
392
                    $tariff = Yii::$app->cache->getOrSet($cacheKeys, function () use ($model) {
393
                        return Tariff::find()->where([
394
                            'id' => $model->tariff_id,
395
                            'show_final' => true,
396
                            'show_deleted' => true,
397
                            'with_resources' => true,
398
                        ])->joinWith('resources')->one();
399
                    });
400
401
                    $ispSupported = false;
402
                    if ($tariff !== null) {
403
                        foreach ($tariff->getResources() as $resource) {
404
                            if ($resource->type === 'isp' && $resource->quantity > 0) {
405
                                $ispSupported = true;
406
                            }
407
                        }
408
                    }
409
410
                    $osimages = $controller->getOsimages($model);
411
                    $groupedOsimages = ServerHelper::groupOsimages($osimages, $ispSupported);
412
413
                    if ($model->isLiveCDSupported()) {
414
                        $osimageslivecd = $controller->getOsimagesLiveCd();
415
                    }
416
417
                    $blockReasons = $controller->getBlockReasons();
418
419
                    return compact([
420
                        'model',
421
                        'osimages',
422
                        'osimageslivecd',
423
                        'groupedOsimages',
424
                        'panels',
425
                        'blockReasons',
426
                    ]);
427 1
                },
428
            ],
429
            'requests-state' => [
430
                'class' => RequestStateAction::class,
431
                'model' => Server::class,
432
            ],
433
            'set-note' => [
434
                'class' => SmartUpdateAction::class,
435 1
                'view' => '_bulkSetNote',
436 1
                'success' => Yii::t('hipanel:server', 'Note changed'),
437 1
                'error' => Yii::t('hipanel:server', 'Failed to change note'),
438
            ],
439
            'set-label' => [
440
                'class' => SmartUpdateAction::class,
441 1
                'view' => '_bulkSetLabel',
442 1
                'success' => Yii::t('hipanel:server', 'Internal note changed'),
443 1
                'error' => Yii::t('hipanel:server', 'Failed to change internal note'),
444
            ],
445
            'set-lock' => [
446
                'class' => RenderAction::class,
447 1
                'success' => Yii::t('hipanel:server', 'Record was changed'),
448 1
                'error' => Yii::t('hipanel:server', 'Error occurred'),
449
                'POST pjax' => [
450
                    'save' => true,
451
                    'success' => [
452
                        'class' => ProxyAction::class,
453
                        'action' => 'index',
454
                    ],
455
                ],
456
                'POST' => [
457
                    'save' => true,
458
                    'success' => [
459
                        'class' => RenderJsonAction::class,
460 1
                        'return' => function ($action) {
461
                            /** @var \hipanel\actions\Action $action */
462
                            return $action->collection->models;
463 1
                        },
464
                    ],
465
                ],
466
            ],
467
            'enable-vnc' => [
468
                'class' => ViewAction::class,
469 1
                'view' => '_vnc',
470 1
                'data' => function ($action) {
471
                    $model = $action->getModel();
472
                    if ($model->canEnableVNC()) {
473
                        $model->vnc = $this->getVNCInfo($model, true);
474
                    }
475
476
                    return [];
477 1
                },
478
            ],
479
            'bulk-sale' => [
480
                'class' => SmartUpdateAction::class,
481 1
                'scenario' => 'sale',
482 1
                'view' => '_bulkSale',
483 1
                'success' => Yii::t('hipanel:server', 'Servers were sold'),
484
                'POST pjax' => [
485
                    'save' => true,
486
                    'success' => [
487
                        'class' => ProxyAction::class,
488
                        'action' => 'index',
489
                    ],
490
                ],
491 1
                'on beforeSave' => function (Event $event) {
492
                    /** @var \hipanel\actions\Action $action */
493
                    $action = $event->sender;
494
                    $request = Yii::$app->request;
0 ignored issues
show
Documentation Bug introduced by
It seems like Yii::app->request can also be of type yii\web\Request. However, the property $request is declared as type yii\console\Request. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
495
496
                    if ($request->isPost) {
497
                        $values = [];
498
                        foreach (['client_id', 'tariff_id', 'sale_time', 'move_accounts'] as $attribute) {
499
                            $value = $request->post($attribute);
500
                            if (!empty($value)) {
501
                                $values[$attribute] = $value;
502
                            }
503
                        }
504
                        foreach ($action->collection->models as $model) {
505
                            foreach ($values as $attr => $value) {
506
                                $model->setAttribute($attr, $value);
507
                            }
508
                        }
509
                    }
510 1
                },
511
            ],
512
            'set-one-type' => [
513
                'class' => SmartUpdateAction::class,
514 1
                'view' => 'setOneType',
515 1
                'success' => Yii::t('hipanel:server', 'Type was changed'),
516 1
                'error' => Yii::t('hipanel:server', 'Failed to change type'),
517 1
                'scenario' => 'set-type',
518 1
                'on beforeSave' => function (Event $event) {
519
                    /** @var \hipanel\actions\Action $action */
520
                    $action = $event->sender;
521
                    $servers = Yii::$app->request->post('Server');
522
                    $type = ArrayHelper::remove($servers, 'type');
523
                    foreach ($servers as $id => $server) {
524
                        $servers[$id]['type'] = $type;
525
                    }
526
                    $action->collection->setModel($this->newModel(['scenario' => 'set-type']));
527
                    $action->collection->load($servers);
528 1
                },
529
            ],
530
            'set-type' => [
531
                'class' => SmartUpdateAction::class,
532 1
                'view' => '_bulkSetType',
533 1
                'success' => Yii::t('hipanel:server', 'Type was changed'),
534 1
                'error' => Yii::t('hipanel:server', 'Failed to change type'),
535
            ],
536
            'reboot' => [
537
                'class' => SmartPerformAction::class,
538 1
                'success' => Yii::t('hipanel:server', 'Reboot task has been successfully added to queue'),
539 1
                'error' => Yii::t('hipanel:server', 'Error during the rebooting'),
540
            ],
541
            'reset' => [
542
                'class' => SmartPerformAction::class,
543 1
                'success' => Yii::t('hipanel:server', 'Reset task has been successfully added to queue'),
544 1
                'error' => Yii::t('hipanel:server', 'Error during the resetting'),
545
            ],
546
            'shutdown' => [
547
                'class' => SmartPerformAction::class,
548 1
                'success' => Yii::t('hipanel:server', 'Shutdown task has been successfully added to queue'),
549 1
                'error' => Yii::t('hipanel:server', 'Error during the shutting down'),
550
            ],
551
            'power-off' => [
552
                'class' => SmartPerformAction::class,
553 1
                'success' => Yii::t('hipanel:server', 'Power off task has been successfully added to queue'),
554 1
                'error' => Yii::t('hipanel:server', 'Error during the turning power off'),
555
            ],
556
            'power-on' => [
557
                'class' => SmartPerformAction::class,
558 1
                'success' => Yii::t('hipanel:server', 'Power on task has been successfully added to queue'),
559 1
                'error' => Yii::t('hipanel:server', 'Error during the turning power on'),
560
            ],
561
            'reset-password' => [
562
                'class' => SmartPerformAction::class,
563 1
                'success' => Yii::t('hipanel:server', 'Root password reset task has been successfully added to queue'),
564 1
                'error' => Yii::t('hipanel:server', 'Error during the resetting root password'),
565
            ],
566
            'enable-block' => [
567
                'class' => SmartPerformAction::class,
568 1
                'success' => Yii::t('hipanel:server', 'Server was blocked successfully'),
569 1
                'error' => Yii::t('hipanel:server', 'Error during the server blocking'),
570
                'POST html' => [
571
                    'save' => true,
572
                    'success' => [
573
                        'class' => RedirectAction::class,
574
                    ],
575
                ],
576 1
                'on beforeSave' => function (Event $event) {
577
                    /** @var \hipanel\actions\Action $action */
578
                    $action = $event->sender;
579
                    $type = Yii::$app->request->post('type');
580
                    $comment = Yii::$app->request->post('comment');
581
                    if (!empty($type)) {
582
                        foreach ($action->collection->models as $model) {
583
                            $model->setAttributes([
584
                                'type' => $type,
585
                                'comment' => $comment,
586
                            ]);
587
                        }
588
                    }
589 1
                },
590
            ],
591
            'bulk-enable-block-modal' => [
592
                'class' => PrepareBulkAction::class,
593 1
                'view' => '_bulkEnableBlock',
594 1
                'data' => function ($action, $data) {
595
                    return array_merge($data, [
596
                        'blockReasons' => $this->getBlockReasons(),
597
                    ]);
598 1
                },
599
            ],
600
            'disable-block' => [
601
                'class' => SmartPerformAction::class,
602 1
                'success' => Yii::t('hipanel:server', 'Server was unblocked successfully'),
603 1
                'error' => Yii::t('hipanel:server', 'Error during the server unblocking'),
604
                'POST html' => [
605
                    'save' => true,
606
                    'success' => [
607
                        'class' => RedirectAction::class,
608
                    ],
609
                ],
610 1
                'on beforeSave' => function (Event $event) {
611
                    /** @var \hipanel\actions\Action $action */
612
                    $action = $event->sender;
613
                    $type = Yii::$app->request->post('type');
614
                    $comment = Yii::$app->request->post('comment');
615
                    if (!empty($type)) {
616
                        foreach ($action->collection->models as $model) {
617
                            $model->setAttributes([
618
                                'comment' => $comment,
619
                                'type' => $type,
620
                            ]);
621
                        }
622
                    }
623 1
                },
624
            ],
625
            'bulk-disable-block-modal' => [
626
                'class' => PrepareBulkAction::class,
627 1
                'view' => '_bulkDisableBlock',
628 1
                'data' => function ($action, $data) {
629
                    return array_merge($data, [
630
                        'blockReasons' => $this->getBlockReasons(),
631
                    ]);
632 1
                },
633
            ],
634
            'refuse' => [
635
                'class' => SmartPerformAction::class,
636 1
                'success' => Yii::t('hipanel:server', 'You have refused the service'),
637 1
                'error' => Yii::t('hipanel:server', 'Error during the refusing the service'),
638
            ],
639
            'enable-autorenewal' => [
640
                'class' => SmartUpdateAction::class,
641 1
                'success' => Yii::t('hipanel:server', 'Server renewal enabled successfully'),
642 1
                'error' => Yii::t('hipanel:server', 'Error during the renewing the service'),
643
            ],
644
            'reinstall' => [
645
                'class' => SmartUpdateAction::class,
646 1
                'on beforeSave' => function (Event $event) {
647
                    /** @var Action $action */
648
                    $action = $event->sender;
649
                    foreach ($action->collection->models as $model) {
650
                        $model->osimage = Yii::$app->request->post('osimage');
651
                        $model->panel = Yii::$app->request->post('panel');
652
                    }
653 1
                },
654 1
                'success' => Yii::t('hipanel:server', 'Server reinstalling task has been successfully added to queue'),
655 1
                'error' => Yii::t('hipanel:server', 'Error during the server reinstalling'),
656
            ],
657
            'boot-live' => [
658
                'class' => SmartPerformAction::class,
659 1
                'on beforeSave' => function (Event $event) {
660
                    /** @var Action $action */
661
                    $action = $event->sender;
662
                    foreach ($action->collection->models as $model) {
663
                        $model->osimage = Yii::$app->request->post('osimage');
664
                    }
665 1
                },
666 1
                'success' => Yii::t('hipanel:server', 'Live CD booting task has been successfully added to queue'),
667 1
                'error' => Yii::t('hipanel:server', 'Error during the booting live CD'),
668
            ],
669
            'validate-hw-form' => [
670
                'class' => ValidateFormAction::class,
671
                'collection' => [
672
                    'class' => Collection::class,
673 1
                    'model' => new HardwareSettings(),
674
                ],
675
            ],
676
            'validate-crud-form' => [
677
                'class' => ValidateFormAction::class,
678
                'collection' => [
679
                    'class' => Collection::class,
680 1
                    'model' => new ServerForm(),
681
                ],
682
            ],
683
            'validate-form' => [
684
                'class' => ValidateFormAction::class,
685
            ],
686
            'buy' => [
687
                'class' => RedirectAction::class,
688 1
                'url' => Yii::$app->params['organization.url'],
689
            ],
690
            'add-to-cart-renewal' => [
691
                'class' => AddToCartAction::class,
692
                'productClass' => ServerRenewProduct::class,
693
            ],
694
            'delete' => [
695
                'class' => SmartDeleteAction::class,
696 1
                'success' => Yii::t('hipanel:server', 'Server was deleted successfully'),
697 1
                'error' => Yii::t('hipanel:server', 'Failed to delete server'),
698
            ],
699
            'bulk-delete-modal' => [
700
                'class' => PrepareBulkAction::class,
701
                'view' => '_bulkDelete',
702
            ],
703
            'clear-resources' => [
704
                'class' => SmartPerformAction::class,
705 1
                'view' => '_clearResources',
706 1
                'success' => Yii::t('hipanel:server', 'Servers resources were cleared successfully'),
707 1
                'error' => Yii::t('hipanel:server', 'Error occurred during server resources flushing'),
708
            ],
709
            'clear-resources-modal' => [
710
                'class' => PrepareBulkAction::class,
711
                'view' => '_clearResources',
712
            ],
713
            'flush-switch-graphs' => [
714
                'class' => SmartPerformAction::class,
715 1
                'view' => '_clearResources',
716 1
                'success' => Yii::t('hipanel:server', 'Switch graphs were flushed successfully'),
717 1
                'error' => Yii::t('hipanel:server', 'Error occurred during switch graphs flushing'),
718
            ],
719
            'flush-switch-graphs-modal' => [
720
                'class' => PrepareBulkAction::class,
721
                'view' => '_flushSwitchGraphs',
722
            ],
723
        ]);
724
    }
725
726
    /**
727
     * Gets info of VNC on the server.
728
     *
729
     * @param Server $model
730
     * @param bool $enable
731
     * @throws ResponseErrorException
732
     * @return array
733
     */
734
    public function getVNCInfo($model, $enable = false)
735
    {
736
        if ($enable) {
737
            try {
738
                $vnc = Server::perform('enable-VNC', ['id' => $model->id]);
0 ignored issues
show
Bug Best Practice introduced by
The property id does not exist on hipanel\modules\server\models\Server. Since you implemented __get, consider adding a @property annotation.
Loading history...
739
                $vnc['endTime'] = time() + 28800;
740
                Yii::$app->cache->set([__METHOD__, $model->id, $model], $vnc, 28800);
741
                $vnc['enabled'] = true;
742
            } catch (ResponseErrorException $e) {
743
                if ($e->getMessage() !== 'vds_has_tasks') {
744
                    throw $e;
745
                }
746
            }
747
        } else {
748
            if ($model->statuses['serverEnableVNC'] !== null && strtotime('+8 hours', strtotime($model->statuses['serverEnableVNC'])) > time()) {
0 ignored issues
show
Bug Best Practice introduced by
The property statuses does not exist on hipanel\modules\server\models\Server. Since you implemented __get, consider adding a @property annotation.
Loading history...
749
                $vnc = Yii::$app->cache->getOrSet([__METHOD__, $model->id, $model], function () use ($model) {
750
                    return ArrayHelper::merge([
751
                        'endTime' => strtotime($model->statuses['serverEnableVNC']) + 28800,
0 ignored issues
show
Bug Best Practice introduced by
The property statuses does not exist on hipanel\modules\server\models\Server. Since you implemented __get, consider adding a @property annotation.
Loading history...
752
                    ], Server::perform('enable-VNC', ['id' => $model->id]));
0 ignored issues
show
Bug Best Practice introduced by
The property id does not exist on hipanel\modules\server\models\Server. Since you implemented __get, consider adding a @property annotation.
Loading history...
753
                }, 28800);
754
            }
755
            $vnc['enabled'] = $model->statuses['serverEnableVNC'] === null ? false : strtotime('+8 hours', strtotime($model->statuses['serverEnableVNC'])) > time();
756
        }
757
758
        return $vnc;
759
    }
760
761
    public function actionDrawChart()
762
    {
763
        $post = Yii::$app->request->post();
764
        $types = array_merge(['server_traf', 'server_traf95'], array_keys(ResourceConsumption::types()));
765
        if (!in_array($post['type'], $types, true)) {
766
            throw new NotFoundHttpException();
767
        }
768
769
        $searchModel = new ServerUseSearch();
770
        $dataProvider = $searchModel->search([]);
771
        $dataProvider->pagination = false;
772
        $dataProvider->query->action('get-uses');
0 ignored issues
show
Bug introduced by
The method action() does not exist on yii\db\QueryInterface. It seems like you code against a sub-type of said class. However, the method does not exist in yii\db\ActiveQueryInterface. Are you sure you never get one of those? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

772
        $dataProvider->query->/** @scrutinizer ignore-call */ 
773
                              action('get-uses');
Loading history...
773
        $dataProvider->query->andWhere($post);
774
        $models = $dataProvider->getModels();
775
776
        list($labels, $data) = ServerHelper::groupUsesForChart($models);
777
778
        return $this->renderAjax('_consumption', [
779
            'labels' => $labels,
780
            'data' => $data,
781
            'consumptionBase' => $post['type'],
782
        ]);
783
    }
784
785
    /**
786
     * Gets OS images.
787
     *
788
     * @param Server $model
789
     * @throws NotFoundHttpException
790
     * @return array
791
     */
792
    protected function getOsimages(Server $model = null)
793
    {
794
        if ($model !== null) {
795
            $type = $model->type;
0 ignored issues
show
Bug Best Practice introduced by
The property type does not exist on hipanel\modules\server\models\Server. Since you implemented __get, consider adding a @property annotation.
Loading history...
796
        } else {
797
            $type = null;
798
        }
799
800
        $models = ServerHelper::getOsimages($type);
801
802
        if ($models === null) {
803
            throw new NotFoundHttpException('The requested page does not exist.');
804
        }
805
806
        return $models;
807
    }
808
809
    protected function getOsimagesLiveCd()
810
    {
811
        $models = Yii::$app->cache->getOrSet([__METHOD__], function () {
812
            return Osimage::findAll(['livecd' => true]);
813
        }, 3600);
814
815
        if ($models !== null) {
816
            return $models;
817
        }
818
819
        throw new NotFoundHttpException('The requested page does not exist.');
820
    }
821
822
    protected function getPanelTypes()
823
    {
824
        return ServerHelper::getPanels();
825
    }
826
827
    public function actionIsOperable($id)
828
    {
829
        Yii::$app->response->format = Response::FORMAT_JSON;
830
831
        $result = ['id' => $id, 'result' => false];
832
833
        if ($server = Server::find()->where(['id' => $id])->one()) {
834
            $result['result'] = $server->isOperable();
835
        }
836
837
        return $result;
838
    }
839
840
    protected function getFullFromRef($gtype)
841
    {
842
        $callingMethod = debug_backtrace()[1]['function'];
843
        $result = Yii::$app->get('cache')->getOrSet([$callingMethod], function () use ($gtype) {
844
            $result = ArrayHelper::map(Ref::find()->where([
845
                'gtype' => $gtype,
846
                'select' => 'full',
847
            ])->all(), 'id', function ($model) {
848
                return Yii::t('hipanel:server:hub', $model->label);
849
            });
850
851
            return $result;
852
        }, 86400 * 24); // 24 days
853
854
        return $result;
855
    }
856
857
    public function actionResources($id)
858
    {
859
        $model = Server::find()->joinWith(['uses'])->andWhere(['id' => $id])->andWhere(['with_uses' => 1])->one();
860
        list($chartsLabels, $chartsData) = $model->groupUsesForCharts();
861
862
        return $this->render('resources', compact('model', 'chartsData', 'chartsLabels'));
863
    }
864
}
865