Passed
Push — master ( 64f0e1...a65aba )
by Dmitry
05:02
created

ServerController::getFullFromRef()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 15
ccs 0
cts 9
cp 0
rs 9.9332
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
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()->withUses()->joinWith(['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_blocking' => 1])
376
                        ->andWhere(['with_blocking' => 1])
377
                        ->andWhere(['with_hardwareSettings' => 1])
378
                        ->andWhere(['with_softwareSettings' => 1])
379
                        ->select(['*']);
380 1
                },
381 1
                'data' => function ($action) {
382
                    /**
383
                     * @var Action
384
                     * @var self $controller
385
                     * @var Server $model
386
                     */
387
                    $controller = $action->controller;
388
                    $model = $action->getModel();
389
                    $model->vnc = $controller->getVNCInfo($model);
390
391
                    $panels = $controller->getPanelTypes();
392
393
                    $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

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

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