Completed
Push — master ( cdfc25...09065f )
by Dmitry
05:40
created

ServerController::actionIsOperable()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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

277
                    $action->collection->setModel(/** @scrutinizer ignore-type */ HardwareSettings::class);
Loading history...
278 1
                },
279
                'POST html' => [
280
                    'save' => true,
281
                    'success' => [
282
                        'class' => RedirectAction::class,
283 1
                        'url' => function () {
284
                            $server = Yii::$app->request->post('HardwareSettings');
285
286
                            return ['@server/view', 'id' => $server['id']];
287 1
                        },
288
                    ],
289
                ],
290
            ],
291
            'software-settings' => [
292
                'class' => SmartUpdateAction::class,
293 1
                'success' => Yii::t('hipanel:server', 'Software properties was changed'),
294 1
                'view' => 'softwareSettings',
295 1
                'scenario' => 'default',
296 1
                'on beforeFetch' => function (Event $event) {
297
                    /** @var \hipanel\actions\SearchAction $action */
298
                    $action = $event->sender;
299
                    /** @var ServerQuery $query */
300
                    $query = $action->getDataProvider()->query;
301
                    $query->withSoftwareSettings();
302 1
                },
303 1
                'on beforeLoad' => function (Event $event) {
304
                    /** @var Action $action */
305
                    $action = $event->sender;
306
307
                    $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

307
                    $action->collection->setModel(/** @scrutinizer ignore-type */ SoftwareSettings::class);
Loading history...
308 1
                },
309
                'POST html' => [
310
                    'save' => true,
311
                    'success' => [
312
                        'class' => RedirectAction::class,
313 1
                        'url' => function () {
314
                            $server = Yii::$app->request->post('SoftwareSettings');
315
316
                            return ['@server/view', 'id' => $server['id']];
317 1
                        },
318
                    ],
319
                ],
320
            ],
321
            'monitoring-settings' => [
322
                'class' => SmartUpdateAction::class,
323 1
                'success' => Yii::t('hipanel:server', 'Monitoring properties was changed'),
324 1
                'view' => 'monitoringSettings',
325 1
                'scenario' => 'default',
326 1
                'on beforeFetch' => function (Event $event) {
327
                    /** @var \hipanel\actions\SearchAction $action */
328
                    $action = $event->sender;
329
                    $dataProvider = $action->getDataProvider();
330
                    $dataProvider->query->joinWith(['monitoringSettings']);
331
                    $dataProvider->query
332
                        ->andWhere(['with_monitoringSettings' => 1])->select(['*']);
333 1
                },
334 1
                'on beforeLoad' => function (Event $event) {
335
                    /** @var Action $action */
336
                    $action = $event->sender;
337
338
                    $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

338
                    $action->collection->setModel(/** @scrutinizer ignore-type */ MonitoringSettings::class);
Loading history...
339 1
                },
340 1
                'data' => function ($action) {
341
                    return [
342
                        'nicMediaOptions' => $action->controller->getFullFromRef('type,nic_media'),
343
                    ];
344 1
                },
345
                'POST html' => [
346
                    'save' => true,
347
                    'success' => [
348
                        'class' => RedirectAction::class,
349 1
                        'url' => function () {
350
                            $server = Yii::$app->request->post('MonitoringSettings');
351
352
                            return ['@server/view', 'id' => $server['id']];
353 1
                        },
354
                    ],
355
                ],
356
            ],
357
            'view' => [
358
                'class' => ViewAction::class,
359 1
                'on beforePerform' => function (Event $event) {
360
                    /** @var \hipanel\actions\SearchAction $action */
361
                    $action = $event->sender;
362
                    /** @var ServerQuery $query */
363
                    $query = $action->getDataProvider()->query;
364
                    $query
365
                        ->withSoftwareSettings()
366
                        ->withHardwareSettings()
367
                        ->withBindings()
368
                        ->withBlocking()
369
                        ->withUses()
370
                        ->withConsumptions()
371
                        ->joinWith(['switches']);
372
373
                    if (Yii::getAlias('@ip', false)) {
374
                        $query
375
                            ->joinWith(['ips'])
376
                            ->andWhere(['with_ips' => 1]);
377
                    }
378
379
                    // TODO: ipModule is not wise yet. Redo
380
                    $query
381
                        ->andWhere(['with_requests' => 1])
382
                        ->andWhere(['show_deleted' => 1])
383
                        ->andWhere(['with_discounts' => 1])
384
                        ->select(['*']);
385 1
                },
386 1
                'data' => function ($action) {
387
                    /**
388
                     * @var Action
389
                     * @var self $controller
390
                     * @var Server $model
391
                     */
392
                    $controller = $action->controller;
393
                    $model = $action->getModel();
394
                    $model->vnc = $controller->getVNCInfo($model);
395
396
                    $panels = $controller->getPanelTypes();
397
398
                    $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

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

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