Passed
Push — master ( ccd18c...cdfc25 )
by Andrii
07:58
created

ServerController::actions()   F

Complexity

Conditions 31
Paths 1

Size

Total Lines 653
Code Lines 459

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 154
CRAP Score 188.3705

Importance

Changes 0
Metric Value
eloc 459
dl 0
loc 653
ccs 154
cts 340
cp 0.4529
rs 3.3333
c 0
b 0
f 0
cc 31
nc 1
nop 0
crap 188.3705

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
363
                        ->withBindings()
364
                        ->withUses()
365
                        ->withConsumptions()
366
                        ->joinWith(['switches', 'blocking', 'hardwareSettings', 'softwareSettings']);
367
368
                    if (Yii::getAlias('@ip', false)) {
369
                        $dataProvider->query
370
                            ->joinWith(['ips'])
371
                            ->andWhere(['with_ips' => 1]);
372
                    }
373
374
                    // TODO: ipModule is not wise yet. Redo
375
                    $dataProvider->query
376
                        ->andWhere(['with_requests' => 1])
377
                        ->andWhere(['show_deleted' => 1])
378
                        ->andWhere(['with_discounts' => 1])
379
                        ->andWhere(['with_blocking' => 1])
380
                        ->andWhere(['with_blocking' => 1])
381
                        ->andWhere(['with_hardwareSettings' => 1])
382
                        ->andWhere(['with_softwareSettings' => 1])
383
                        ->select(['*']);
384 1
                },
385 1
                'data' => function ($action) {
386
                    /**
387
                     * @var Action
388
                     * @var self $controller
389
                     * @var Server $model
390
                     */
391
                    $controller = $action->controller;
392
                    $model = $action->getModel();
393
                    $model->vnc = $controller->getVNCInfo($model);
394
395
                    $panels = $controller->getPanelTypes();
396
397
                    $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

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

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