Completed
Push — master ( 30ac7d...64f0e1 )
by Andrii
18:46 queued 14:31
created

ServerController::actions()   F

Complexity

Conditions 31
Paths 1

Size

Total Lines 634
Code Lines 445

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 149
CRAP Score 184.774

Importance

Changes 0
Metric Value
eloc 445
dl 0
loc 634
ccs 149
cts 326
cp 0.4571
rs 3.3333
c 0
b 0
f 0
cc 31
nc 1
nop 0
crap 184.774

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', 'hardwareSettings', 'softwareSettings']);
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
                        ->andWhere(['with_blocking' => 1])
378
                        ->andWhere(['with_hardwareSettings' => 1])
379
                        ->andWhere(['with_softwareSettings' => 1])
380
                        ->select(['*']);
381 1
                },
382 1
                'data' => function ($action) {
383
                    /**
384
                     * @var Action
385
                     * @var self $controller
386
                     * @var Server $model
387
                     */
388
                    $controller = $action->controller;
389
                    $model = $action->getModel();
390
                    $model->vnc = $controller->getVNCInfo($model);
391
392
                    $panels = $controller->getPanelTypes();
393
394
                    $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

394
                    $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...
395
                    $tariff = Yii::$app->cache->getOrSet($cacheKeys, function () use ($model) {
396
                        return Tariff::find()->where([
397
                            'id' => $model->tariff_id,
398
                            'show_final' => true,
399
                            'show_deleted' => true,
400
                            'with_resources' => true,
401
                        ])->joinWith('resources')->one();
402
                    });
403
404
                    $ispSupported = false;
405
                    if ($tariff !== null) {
406
                        foreach ($tariff->getResources() as $resource) {
407
                            if ($resource->type === 'isp' && $resource->quantity > 0) {
408
                                $ispSupported = true;
409
                            }
410
                        }
411
                    }
412
413
                    $osimages = $controller->getOsimages($model);
414
                    $groupedOsimages = ServerHelper::groupOsimages($osimages, $ispSupported);
415
416
                    if ($model->isLiveCDSupported()) {
417
                        $osimageslivecd = $controller->getOsimagesLiveCd();
418
                    }
419
420
                    $blockReasons = $controller->getBlockReasons();
421
422
                    return compact([
423
                        'model',
424
                        'osimages',
425
                        'osimageslivecd',
426
                        'groupedOsimages',
427
                        'panels',
428
                        'blockReasons',
429
                    ]);
430 1
                },
431
            ],
432
            'requests-state' => [
433
                'class' => RequestStateAction::class,
434
                'model' => Server::class,
435
            ],
436
            'set-note' => [
437
                'class' => SmartUpdateAction::class,
438 1
                'view' => 'modal/_bulkSetNote',
439 1
                'success' => Yii::t('hipanel:server', 'Note changed'),
440 1
                'error' => Yii::t('hipanel:server', 'Failed to change note'),
441
            ],
442
            'set-label' => [
443
                'class' => SmartUpdateAction::class,
444 1
                'view' => 'modal/_bulkSetLabel',
445 1
                'success' => Yii::t('hipanel:server', 'Internal note changed'),
446 1
                'error' => Yii::t('hipanel:server', 'Failed to change internal note'),
447
            ],
448
            'set-lock' => [
449
                'class' => RenderAction::class,
450 1
                'success' => Yii::t('hipanel:server', 'Record was changed'),
451 1
                'error' => Yii::t('hipanel:server', 'Error occurred'),
452
                'POST pjax' => [
453
                    'save' => true,
454
                    'success' => [
455
                        'class' => ProxyAction::class,
456
                        'action' => 'index',
457
                    ],
458
                ],
459
                'POST' => [
460
                    'save' => true,
461
                    'success' => [
462
                        'class' => RenderJsonAction::class,
463 1
                        'return' => function ($action) {
464
                            /** @var \hipanel\actions\Action $action */
465
                            return $action->collection->models;
466 1
                        },
467
                    ],
468
                ],
469
            ],
470
            'enable-vnc' => [
471
                'class' => ViewAction::class,
472 1
                'view' => '_vnc',
473 1
                'data' => function ($action) {
474
                    $model = $action->getModel();
475
                    if ($model->canEnableVNC()) {
476
                        $model->vnc = $this->getVNCInfo($model, true);
477
                    }
478
479
                    return [];
480 1
                },
481
            ],
482
            'bulk-sale' => [
483
                'class' => SmartUpdateAction::class,
484 1
                'scenario' => 'sale',
485 1
                'view' => 'modal/_bulkSale',
486 1
                'success' => Yii::t('hipanel:server', 'Servers were sold'),
487
                'POST pjax' => [
488
                    'save' => true,
489
                    'success' => [
490
                        'class' => ProxyAction::class,
491
                        'action' => 'index',
492
                    ],
493
                ],
494 1
                'on beforeSave' => function (Event $event) {
495
                    /** @var \hipanel\actions\Action $action */
496
                    $action = $event->sender;
497
                    $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...
498
499
                    if ($request->isPost) {
500
                        $values = [];
501
                        foreach (['client_id', 'tariff_id', 'sale_time', 'move_accounts'] as $attribute) {
502
                            $value = $request->post($attribute);
503
                            if (!empty($value)) {
504
                                $values[$attribute] = $value;
505
                            }
506
                        }
507
                        foreach ($action->collection->models as $model) {
508
                            foreach ($values as $attr => $value) {
509
                                $model->setAttribute($attr, $value);
510
                            }
511
                        }
512
                    }
513 1
                },
514
            ],
515
            'set-one-type' => [
516
                'class' => SmartUpdateAction::class,
517 1
                'view' => 'setOneType',
518 1
                'success' => Yii::t('hipanel:server', 'Type was changed'),
519 1
                'error' => Yii::t('hipanel:server', 'Failed to change type'),
520 1
                'scenario' => 'set-type',
521 1
                'on beforeSave' => function (Event $event) {
522
                    /** @var \hipanel\actions\Action $action */
523
                    $action = $event->sender;
524
                    $servers = Yii::$app->request->post('Server');
525
                    $type = ArrayHelper::remove($servers, 'type');
526
                    foreach ($servers as $id => $server) {
527
                        $servers[$id]['type'] = $type;
528
                    }
529
                    $action->collection->setModel($this->newModel(['scenario' => 'set-type']));
530
                    $action->collection->load($servers);
531 1
                },
532
            ],
533
            'set-type' => [
534
                'class' => SmartUpdateAction::class,
535 1
                'view' => '_bulkSetType',
536 1
                'success' => Yii::t('hipanel:server', 'Type was changed'),
537 1
                'error' => Yii::t('hipanel:server', 'Failed to change type'),
538
            ],
539
            'reboot' => [
540
                'class' => SmartPerformAction::class,
541 1
                'success' => Yii::t('hipanel:server', 'Reboot task has been successfully added to queue'),
542 1
                'error' => Yii::t('hipanel:server', 'Error during the rebooting'),
543
            ],
544
            'reset' => [
545
                'class' => SmartPerformAction::class,
546 1
                'success' => Yii::t('hipanel:server', 'Reset task has been successfully added to queue'),
547 1
                'error' => Yii::t('hipanel:server', 'Error during the resetting'),
548
            ],
549
            'shutdown' => [
550
                'class' => SmartPerformAction::class,
551 1
                'success' => Yii::t('hipanel:server', 'Shutdown task has been successfully added to queue'),
552 1
                'error' => Yii::t('hipanel:server', 'Error during the shutting down'),
553
            ],
554
            'power-off' => [
555
                'class' => SmartPerformAction::class,
556 1
                'success' => Yii::t('hipanel:server', 'Power off task has been successfully added to queue'),
557 1
                'error' => Yii::t('hipanel:server', 'Error during the turning power off'),
558
            ],
559
            'power-on' => [
560
                'class' => SmartPerformAction::class,
561 1
                'success' => Yii::t('hipanel:server', 'Power on task has been successfully added to queue'),
562 1
                'error' => Yii::t('hipanel:server', 'Error during the turning power on'),
563
            ],
564
            'reset-password' => [
565
                'class' => SmartPerformAction::class,
566 1
                'success' => Yii::t('hipanel:server', 'Root password reset task has been successfully added to queue'),
567 1
                'error' => Yii::t('hipanel:server', 'Error during the resetting root password'),
568
            ],
569
            'enable-block' => [
570
                'class' => SmartPerformAction::class,
571 1
                'success' => Yii::t('hipanel:server', 'Server was blocked successfully'),
572 1
                'error' => Yii::t('hipanel:server', 'Error during the server blocking'),
573
                'POST html' => [
574
                    'save' => true,
575
                    'success' => [
576
                        'class' => RedirectAction::class,
577
                    ],
578
                ],
579 1
                'on beforeSave' => function (Event $event) {
580
                    /** @var \hipanel\actions\Action $action */
581
                    $action = $event->sender;
582
                    $type = Yii::$app->request->post('type');
583
                    $comment = Yii::$app->request->post('comment');
584
                    if (!empty($type)) {
585
                        foreach ($action->collection->models as $model) {
586
                            $model->setAttributes([
587
                                'type' => $type,
588
                                'comment' => $comment,
589
                            ]);
590
                        }
591
                    }
592 1
                },
593
            ],
594
            'bulk-enable-block-modal' => [
595
                'class' => PrepareBulkAction::class,
596 1
                'view' => 'modal/_bulkEnableBlock',
597 1
                'data' => function ($action, $data) {
598
                    return array_merge($data, [
599
                        'blockReasons' => $this->getBlockReasons(),
600
                    ]);
601 1
                },
602
            ],
603
            'disable-block' => [
604
                'class' => SmartPerformAction::class,
605 1
                'success' => Yii::t('hipanel:server', 'Server was unblocked successfully'),
606 1
                'error' => Yii::t('hipanel:server', 'Error during the server unblocking'),
607
                'POST html' => [
608
                    'save' => true,
609
                    'success' => [
610
                        'class' => RedirectAction::class,
611
                    ],
612
                ],
613 1
                'on beforeSave' => function (Event $event) {
614
                    /** @var \hipanel\actions\Action $action */
615
                    $action = $event->sender;
616
                    $type = Yii::$app->request->post('type');
617
                    $comment = Yii::$app->request->post('comment');
618
                    if (!empty($type)) {
619
                        foreach ($action->collection->models as $model) {
620
                            $model->setAttributes([
621
                                'comment' => $comment,
622
                                'type' => $type,
623
                            ]);
624
                        }
625
                    }
626 1
                },
627
            ],
628
            'bulk-disable-block-modal' => [
629
                'class' => PrepareBulkAction::class,
630 1
                'view' => 'modal/_bulkDisableBlock',
631 1
                'data' => function ($action, $data) {
632
                    return array_merge($data, [
633
                        'blockReasons' => $this->getBlockReasons(),
634
                    ]);
635 1
                },
636
            ],
637
            'refuse' => [
638
                'class' => SmartPerformAction::class,
639 1
                'success' => Yii::t('hipanel:server', 'You have refused the service'),
640 1
                'error' => Yii::t('hipanel:server', 'Error during the refusing the service'),
641
            ],
642
            'enable-autorenewal' => [
643
                'class' => SmartUpdateAction::class,
644 1
                'success' => Yii::t('hipanel:server', 'Server renewal enabled successfully'),
645 1
                'error' => Yii::t('hipanel:server', 'Error during the renewing the service'),
646
            ],
647
            'reinstall' => [
648
                'class' => SmartUpdateAction::class,
649 1
                'on beforeSave' => function (Event $event) {
650
                    /** @var Action $action */
651
                    $action = $event->sender;
652
                    foreach ($action->collection->models as $model) {
653
                        $model->osimage = Yii::$app->request->post('osimage');
654
                        $model->panel = Yii::$app->request->post('panel');
655
                    }
656 1
                },
657 1
                'success' => Yii::t('hipanel:server', 'Server reinstalling task has been successfully added to queue'),
658 1
                'error' => Yii::t('hipanel:server', 'Error during the server reinstalling'),
659
            ],
660
            'boot-live' => [
661
                'class' => SmartPerformAction::class,
662 1
                'on beforeSave' => function (Event $event) {
663
                    /** @var Action $action */
664
                    $action = $event->sender;
665
                    foreach ($action->collection->models as $model) {
666
                        $model->osimage = Yii::$app->request->post('osimage');
667
                    }
668 1
                },
669 1
                'success' => Yii::t('hipanel:server', 'Live CD booting task has been successfully added to queue'),
670 1
                'error' => Yii::t('hipanel:server', 'Error during the booting live CD'),
671
            ],
672
            'validate-hw-form' => [
673
                'class' => ValidateFormAction::class,
674
                'collection' => [
675
                    'class' => Collection::class,
676 1
                    'model' => new HardwareSettings(),
677
                ],
678
            ],
679
            'validate-crud-form' => [
680
                'class' => ValidateFormAction::class,
681
                'collection' => [
682
                    'class' => Collection::class,
683 1
                    'model' => new ServerForm(),
684
                ],
685
            ],
686
            'validate-form' => [
687
                'class' => ValidateFormAction::class,
688
            ],
689
            'buy' => [
690
                'class' => RedirectAction::class,
691 1
                'url' => Yii::$app->params['organization.url'],
692
            ],
693
            'add-to-cart-renewal' => [
694
                'class' => AddToCartAction::class,
695
                'productClass' => ServerRenewProduct::class,
696
            ],
697
            'delete' => [
698
                'class' => SmartDeleteAction::class,
699 1
                'success' => Yii::t('hipanel:server', 'Server was deleted successfully'),
700 1
                'error' => Yii::t('hipanel:server', 'Failed to delete server'),
701
            ],
702
            'bulk-delete-modal' => [
703
                'class' => PrepareBulkAction::class,
704
                'view' => 'modal/_bulkDelete',
705
            ],
706
            'clear-resources' => [
707
                'class' => SmartPerformAction::class,
708 1
                'view' => '_clearResources',
709 1
                'success' => Yii::t('hipanel:server', 'Servers resources were cleared successfully'),
710 1
                'error' => Yii::t('hipanel:server', 'Error occurred during server resources flushing'),
711
            ],
712
            'clear-resources-modal' => [
713
                'class' => PrepareBulkAction::class,
714
                'view' => '_clearResources',
715
            ],
716
            'flush-switch-graphs' => [
717
                'class' => SmartPerformAction::class,
718 1
                'view' => '_clearResources',
719 1
                'success' => Yii::t('hipanel:server', 'Switch graphs were flushed successfully'),
720 1
                'error' => Yii::t('hipanel:server', 'Error occurred during switch graphs flushing'),
721
            ],
722
            'flush-switch-graphs-modal' => [
723
                'class' => PrepareBulkAction::class,
724
                'view' => '_flushSwitchGraphs',
725
            ],
726
        ]);
727
    }
728
729
    /**
730
     * Gets info of VNC on the server.
731
     *
732
     * @param Server $model
733
     * @param bool $enable
734
     * @throws ResponseErrorException
735
     * @return array
736
     */
737
    public function getVNCInfo($model, $enable = false)
738
    {
739
        if ($enable) {
740
            try {
741
                $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...
742
                $vnc['endTime'] = time() + 28800;
743
                Yii::$app->cache->set([__METHOD__, $model->id, $model], $vnc, 28800);
744
                $vnc['enabled'] = true;
745
            } catch (ResponseErrorException $e) {
746
                if ($e->getMessage() !== 'vds_has_tasks') {
747
                    throw $e;
748
                }
749
            }
750
        } else {
751
            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...
752
                $vnc = Yii::$app->cache->getOrSet([__METHOD__, $model->id, $model], function () use ($model) {
753
                    return ArrayHelper::merge([
754
                        '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...
755
                    ], 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...
756
                }, 28800);
757
            }
758
            $vnc['enabled'] = $model->statuses['serverEnableVNC'] === null ? false : strtotime('+8 hours', strtotime($model->statuses['serverEnableVNC'])) > time();
759
        }
760
761
        return $vnc;
762
    }
763
764
    public function actionDrawChart()
765
    {
766
        $post = Yii::$app->request->post();
767
        $types = array_merge(['server_traf', 'server_traf95'], array_keys(ResourceConsumption::types()));
768
        if (!in_array($post['type'], $types, true)) {
769
            throw new NotFoundHttpException();
770
        }
771
772
        $searchModel = new ServerUseSearch();
773
        $dataProvider = $searchModel->search([]);
774
        $dataProvider->pagination = false;
775
        $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

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