Completed
Push — master ( 693de4...31a216 )
by Dmitry
03:52
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\ServerForm;
34
use hipanel\modules\server\helpers\ServerHelper;
35
use hipanel\modules\server\models\HardwareSettings;
36
use hipanel\modules\server\models\MonitoringSettings;
37
use hipanel\modules\server\models\Osimage;
38
use hipanel\modules\server\models\Server;
39
use hipanel\modules\server\models\ServerUseSearch;
40
use hipanel\modules\server\models\SoftwareSettings;
41
use hipanel\modules\server\widgets\ResourceConsumption;
42
use hiqdev\hiart\Collection;
43
use hiqdev\hiart\ResponseErrorException;
44
use hiqdev\yii2\cart\actions\AddToCartAction;
45
use Yii;
46
use yii\base\Event;
47
use yii\filters\VerbFilter;
48
use yii\helpers\ArrayHelper;
49
use yii\web\NotFoundHttpException;
50
use yii\web\Response;
51
52
class ServerController extends CrudController
53
{
54
    public function behaviors()
55
    {
56
        return array_merge(parent::behaviors(), [
57
            'server-actions-verb' => [
58
                'class' => VerbFilter::class,
59
                'actions' => [
60
                    'reboot' => ['post'],
61
                    'reset' => ['post'],
62
                    'shutdown' => ['post'],
63
                    'power-off' => ['post'],
64
                    'power-on' => ['post'],
65
                    'reset-password' => ['post'],
66
                    'enable-block' => ['post'],
67
                    'disable-block' => ['post'],
68
                    'refuse' => ['post'],
69
                    'flush-switch-graphs' => ['post'],
70
                ],
71
            ],
72
            [
73
                'class' => EasyAccessControl::class,
74
                'actions' => [
75
                    'monitoring-settings' => 'support',
76
                    'software-settings' => 'support',
77
                    'hardware-settings' => 'support',
78
                    'create' => 'server.create',
79
                    'update' => 'server.update',
80
                    'delete' => 'server.delete',
81
                    '*' => 'server.read',
82
                ],
83
            ],
84
        ]);
85
    }
86
87 1
    public function actions()
88
    {
89 1
        return array_merge(parent::actions(), [
90 1
            'index' => [
91
                'class' => IndexAction::class,
92
                'findOptions' => ['with_requests' => true, 'with_discounts' => true],
93 1
                'on beforePerform' => function (Event $event) {
94
                    /** @var \hipanel\actions\SearchAction $action */
95
                    $action = $event->sender;
96
                    $dataProvider = $action->getDataProvider();
97
                    $dataProvider->query->joinWith(['ips', 'bindings']);
98
99
                    $dataProvider->query
100
                        ->andWhere(['with_ips' => 1])
101
                        ->andWhere(['with_requests' => 1])
102
                        ->andWhere(['with_discounts' => 1])
103
                        ->andWhere(['with_bindings' => 1])
104
                        ->select(['*']);
105 1
                },
106
                'filterStorageMap' => [
107
                    'name_like' => 'server.server.name',
108
                    'ips' => 'hosting.ip.ip_in',
109
                    'state' => 'server.server.state',
110
                    'client_id' => 'client.client.id',
111
                    'seller_id' => 'client.client.seller_id',
112
                ],
113
            ],
114
            'search' => [
115
                'class' => ComboSearchAction::class,
116
            ],
117
            'create' => [
118
                'class' => SmartCreateAction::class,
119
                'collection' => [
120
                    'class' => Collection::class,
121 1
                    'model' => new ServerForm(['scenario' => 'create']),
122 1
                    'scenario' => 'create',
123
                ],
124 1
                'success' => Yii::t('hipanel:stock', 'Server has been created'),
125
            ],
126
            'update' => [
127
                'class' => SmartUpdateAction::class,
128
                'collection' => [
129
                    'class' => Collection::class,
130 1
                    'model' => new ServerForm(),
131 1
                    'scenario' => 'update',
132
                ],
133 1
                'on beforeFetch' => function (Event $event) {
134
                    /** @var \hipanel\actions\SearchAction $action */
135
                    $action = $event->sender;
136
                    $dataProvider = $action->getDataProvider();
137
                    $dataProvider->query->joinWith('ips');
138 1
                },
139 1
                'data' => function (Action $action, array $data) {
140
                    $result = [];
141
                    foreach ($data['models'] as $model) {
142
                        $result['models'][] = ServerForm::fromServer($model);
143
                    }
144
                    $result['model'] = reset($result['models']);
145
146
                    return $result;
147 1
                },
148 1
                'success' => Yii::t('hipanel:stock', 'Server has been updated'),
149
            ],
150
            'hardware-settings' => [
151
                'class' => SmartUpdateAction::class,
152 1
                'success' => Yii::t('hipanel:server', 'Hardware properties was changed'),
153 1
                'view' => 'hardwareSettings',
154 1
                'on beforeFetch' => function (Event $event) {
155
                    /** @var \hipanel\actions\SearchAction $action */
156
                    $action = $event->sender;
157
                    $dataProvider = $action->getDataProvider();
158
                    $dataProvider->query->joinWith(['hardwareSettings']);
159
                    $dataProvider->query->andWhere(['with_hardwareSettings' => 1])->select(['*']);
160 1
                },
161 1
                'on beforeLoad' => function (Event $event) {
162
                    /** @var Action $action */
163
                    $action = $event->sender;
164
165
                    $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

165
                    $action->collection->setModel(/** @scrutinizer ignore-type */ HardwareSettings::class);
Loading history...
166 1
                },
167
                'POST html' => [
168
                    'save' => true,
169
                    'success' => [
170
                        'class' => RedirectAction::class,
171 1
                        'url' => function () {
172
                            $server = Yii::$app->request->post('HardwareSettings');
173
174
                            return ['@server/view', 'id' => $server['id']];
175 1
                        },
176
                    ],
177
                ],
178
            ],
179
            'software-settings' => [
180
                'class' => SmartUpdateAction::class,
181 1
                'success' => Yii::t('hipanel:server', 'Software properties was changed'),
182 1
                'view' => 'softwareSettings',
183 1
                'scenario' => 'default',
184 1
                'on beforeFetch' => function (Event $event) {
185
                    /** @var \hipanel\actions\SearchAction $action */
186
                    $action = $event->sender;
187
                    $dataProvider = $action->getDataProvider();
188
                    $dataProvider->query->joinWith(['softwareSettings']);
189
                    $dataProvider->query->andWhere(['with_softwareSettings' => 1])->select(['*']);
190 1
                },
191 1
                'on beforeLoad' => function (Event $event) {
192
                    /** @var Action $action */
193
                    $action = $event->sender;
194
195
                    $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

195
                    $action->collection->setModel(/** @scrutinizer ignore-type */ SoftwareSettings::class);
Loading history...
196 1
                },
197
                'POST html' => [
198
                    'save' => true,
199
                    'success' => [
200
                        'class' => RedirectAction::class,
201 1
                        'url' => function () {
202
                            $server = Yii::$app->request->post('SoftwareSettings');
203
204
                            return ['@server/view', 'id' => $server['id']];
205 1
                        },
206
                    ],
207
                ],
208
            ],
209
            'monitoring-settings' => [
210
                'class' => SmartUpdateAction::class,
211 1
                'success' => Yii::t('hipanel:server', 'Monitoring properties was changed'),
212 1
                'view' => 'monitoringSettings',
213 1
                'scenario' => 'default',
214 1
                'on beforeFetch' => function (Event $event) {
215
                    /** @var \hipanel\actions\SearchAction $action */
216
                    $action = $event->sender;
217
                    $dataProvider = $action->getDataProvider();
218
                    $dataProvider->query->joinWith(['monitoringSettings']);
219
                    $dataProvider->query
220
                        ->andWhere(['with_monitoringSettings' => 1])->select(['*']);
221 1
                },
222 1
                'on beforeLoad' => function (Event $event) {
223
                    /** @var Action $action */
224
                    $action = $event->sender;
225
226
                    $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

226
                    $action->collection->setModel(/** @scrutinizer ignore-type */ MonitoringSettings::class);
Loading history...
227 1
                },
228 1
                'data' => function ($action) {
229
                    return [
230
                        'nicMediaOptions' => $action->controller->getFullFromRef('type,nic_media'),
231
                    ];
232 1
                },
233
                'POST html' => [
234
                    'save' => true,
235
                    'success' => [
236
                        'class' => RedirectAction::class,
237 1
                        'url' => function () {
238
                            $server = Yii::$app->request->post('MonitoringSettings');
239
240
                            return ['@server/view', 'id' => $server['id']];
241 1
                        },
242
                    ],
243
                ],
244
            ],
245
            'view' => [
246
                'class' => ViewAction::class,
247 1
                'on beforePerform' => function (Event $event) {
248
                    /** @var \hipanel\actions\SearchAction $action */
249
                    $action = $event->sender;
250
                    $dataProvider = $action->getDataProvider();
251
                    $dataProvider->query->joinWith(['uses', 'ips', 'switches', 'bindings', 'blocking']);
252
253
                    // TODO: ipModule is not wise yet. Redo
254
                    $dataProvider->query
255
                        ->andWhere(['with_requests' => 1])
256
                        ->andWhere(['show_deleted' => 1])
257
                        ->andWhere(['with_discounts' => 1])
258
                        ->andWhere(['with_uses' => 1])
259
                        ->andWhere(['with_ips' => 1])
260
                        ->andWhere(['with_bindings' => 1])
261
                        ->andWhere(['with_blocking' => 1])
262
                        ->select(['*']);
263 1
                },
264 1
                'data' => function ($action) {
265
                    /**
266
                     * @var Action
267
                     * @var self $controller
268
                     * @var Server $model
269
                     */
270
                    $controller = $action->controller;
271
                    $model = $action->getModel();
272
                    $model->vnc = $controller->getVNCInfo($model);
273
274
                    $panels = $controller->getPanelTypes();
275
276
                    $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

276
                    $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...
277
                    $tariff = Yii::$app->cache->getOrSet($cacheKeys, function () use ($model) {
278
                        return Tariff::find()->where([
279
                            'id' => $model->tariff_id,
280
                            'show_final' => true,
281
                            'show_deleted' => true,
282
                            'with_resources' => true,
283
                        ])->joinWith('resources')->one();
284
                    });
285
286
                    $ispSupported = false;
287
                    if ($tariff !== null) {
288
                        foreach ($tariff->getResources() as $resource) {
289
                            if ($resource->type === 'isp' && $resource->quantity > 0) {
290
                                $ispSupported = true;
291
                            }
292
                        }
293
                    }
294
295
                    $osimages = $controller->getOsimages($model);
296
                    $groupedOsimages = ServerHelper::groupOsimages($osimages, $ispSupported);
297
298
                    if ($model->isLiveCDSupported()) {
299
                        $osimageslivecd = $controller->getOsimagesLiveCd();
300
                    }
301
302
                    $blockReasons = $controller->getBlockReasons();
303
304
                    return compact([
305
                        'model',
306
                        'osimages',
307
                        'osimageslivecd',
308
                        'groupedOsimages',
309
                        'panels',
310
                        'blockReasons',
311
                    ]);
312 1
                },
313
            ],
314
            'requests-state' => [
315
                'class' => RequestStateAction::class,
316
                'model' => Server::class,
317
            ],
318
            'set-note' => [
319
                'class' => SmartUpdateAction::class,
320 1
                'view' => '_bulkSetNote',
321 1
                'success' => Yii::t('hipanel:server', 'Note changed'),
322 1
                'error' => Yii::t('hipanel:server', 'Failed to change note'),
323
            ],
324
            'set-label' => [
325
                'class' => SmartUpdateAction::class,
326 1
                'view' => '_bulkSetLabel',
327 1
                'success' => Yii::t('hipanel:server', 'Internal note changed'),
328 1
                'error' => Yii::t('hipanel:server', 'Failed to change internal note'),
329
            ],
330
            'set-lock' => [
331
                'class' => RenderAction::class,
332 1
                'success' => Yii::t('hipanel:server', 'Record was changed'),
333 1
                'error' => Yii::t('hipanel:server', 'Error occurred'),
334
                'POST pjax' => [
335
                    'save' => true,
336
                    'success' => [
337
                        'class' => ProxyAction::class,
338
                        'action' => 'index',
339
                    ],
340
                ],
341
                'POST' => [
342
                    'save' => true,
343
                    'success' => [
344
                        'class' => RenderJsonAction::class,
345 1
                        'return' => function ($action) {
346
                            /** @var \hipanel\actions\Action $action */
347
                            return $action->collection->models;
348 1
                        },
349
                    ],
350
                ],
351
            ],
352
            'enable-vnc' => [
353
                'class' => ViewAction::class,
354 1
                'view' => '_vnc',
355 1
                'data' => function ($action) {
356
                    $model = $action->getModel();
357
                    if ($model->canEnableVNC()) {
358
                        $model->vnc = $this->getVNCInfo($model, true);
359
                    }
360
361
                    return [];
362 1
                },
363
            ],
364
            'bulk-sale' => [
365
                'class' => SmartUpdateAction::class,
366 1
                'scenario' => 'sale',
367 1
                'view' => '_bulkSale',
368 1
                'success' => Yii::t('hipanel:server', 'Servers were sold'),
369
                'POST pjax' => [
370
                    'save' => true,
371
                    'success' => [
372
                        'class' => ProxyAction::class,
373
                        'action' => 'index',
374
                    ],
375
                ],
376 1
                'on beforeSave' => function (Event $event) {
377
                    /** @var \hipanel\actions\Action $action */
378
                    $action = $event->sender;
379
                    $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...
380
381
                    if ($request->isPost) {
382
                        $values = [];
383
                        foreach (['client_id', 'tariff_id', 'sale_time', 'move_accounts'] as $attribute) {
384
                            $value = $request->post($attribute);
385
                            if (!empty($value)) {
386
                                $values[$attribute] = $value;
387
                            }
388
                        }
389
                        foreach ($action->collection->models as $model) {
390
                            foreach ($values as $attr => $value) {
391
                                $model->setAttribute($attr, $value);
392
                            }
393
                        }
394
                    }
395 1
                },
396
            ],
397
            'set-one-type' => [
398
                'class' => SmartUpdateAction::class,
399 1
                'view' => 'setOneType',
400 1
                'success' => Yii::t('hipanel:server', 'Type was changed'),
401 1
                'error' => Yii::t('hipanel:server', 'Failed to change type'),
402 1
                'scenario' => 'set-type',
403 1
                'on beforeSave' => function (Event $event) {
404
                    /** @var \hipanel\actions\Action $action */
405
                    $action = $event->sender;
406
                    $servers = Yii::$app->request->post('Server');
407
                    $type = ArrayHelper::remove($servers, 'type');
408
                    foreach ($servers as $id => $server) {
409
                        $servers[$id]['type'] = $type;
410
                    }
411
                    $action->collection->setModel($this->newModel(['scenario' => 'set-type']));
412
                    $action->collection->load($servers);
413 1
                },
414
            ],
415
            'set-type' => [
416
                'class' => SmartUpdateAction::class,
417 1
                'view' => '_bulkSetType',
418 1
                'success' => Yii::t('hipanel:server', 'Type was changed'),
419 1
                'error' => Yii::t('hipanel:server', 'Failed to change type'),
420
            ],
421
            'reboot' => [
422
                'class' => SmartPerformAction::class,
423 1
                'success' => Yii::t('hipanel:server', 'Reboot task has been successfully added to queue'),
424 1
                'error' => Yii::t('hipanel:server', 'Error during the rebooting'),
425
            ],
426
            'reset' => [
427
                'class' => SmartPerformAction::class,
428 1
                'success' => Yii::t('hipanel:server', 'Reset task has been successfully added to queue'),
429 1
                'error' => Yii::t('hipanel:server', 'Error during the resetting'),
430
            ],
431
            'shutdown' => [
432
                'class' => SmartPerformAction::class,
433 1
                'success' => Yii::t('hipanel:server', 'Shutdown task has been successfully added to queue'),
434 1
                'error' => Yii::t('hipanel:server', 'Error during the shutting down'),
435
            ],
436
            'power-off' => [
437
                'class' => SmartPerformAction::class,
438 1
                'success' => Yii::t('hipanel:server', 'Power off task has been successfully added to queue'),
439 1
                'error' => Yii::t('hipanel:server', 'Error during the turning power off'),
440
            ],
441
            'power-on' => [
442
                'class' => SmartPerformAction::class,
443 1
                'success' => Yii::t('hipanel:server', 'Power on task has been successfully added to queue'),
444 1
                'error' => Yii::t('hipanel:server', 'Error during the turning power on'),
445
            ],
446
            'reset-password' => [
447
                'class' => SmartPerformAction::class,
448 1
                'success' => Yii::t('hipanel:server', 'Root password reset task has been successfully added to queue'),
449 1
                'error' => Yii::t('hipanel:server', 'Error during the resetting root password'),
450
            ],
451
            'enable-block' => [
452
                'class' => SmartPerformAction::class,
453 1
                'success' => Yii::t('hipanel:server', 'Server was blocked successfully'),
454 1
                'error' => Yii::t('hipanel:server', 'Error during the server blocking'),
455
                'POST html' => [
456
                    'save' => true,
457
                    'success' => [
458
                        'class' => RedirectAction::class,
459
                    ],
460
                ],
461 1
                'on beforeSave' => function (Event $event) {
462
                    /** @var \hipanel\actions\Action $action */
463
                    $action = $event->sender;
464
                    $type = Yii::$app->request->post('type');
465
                    $comment = Yii::$app->request->post('comment');
466
                    if (!empty($type)) {
467
                        foreach ($action->collection->models as $model) {
468
                            $model->setAttributes([
469
                                'type' => $type,
470
                                'comment' => $comment,
471
                            ]);
472
                        }
473
                    }
474 1
                },
475
            ],
476
            'bulk-enable-block-modal' => [
477
                'class' => PrepareBulkAction::class,
478 1
                'view' => '_bulkEnableBlock',
479 1
                'data' => function ($action, $data) {
480
                    return array_merge($data, [
481
                        'blockReasons' => $this->getBlockReasons(),
482
                    ]);
483 1
                },
484
            ],
485
            'disable-block' => [
486
                'class' => SmartPerformAction::class,
487 1
                'success' => Yii::t('hipanel:server', 'Server was unblocked successfully'),
488 1
                'error' => Yii::t('hipanel:server', 'Error during the server unblocking'),
489
                'POST html' => [
490
                    'save' => true,
491
                    'success' => [
492
                        'class' => RedirectAction::class,
493
                    ],
494
                ],
495 1
                'on beforeSave' => function (Event $event) {
496
                    /** @var \hipanel\actions\Action $action */
497
                    $action = $event->sender;
498
                    $type = Yii::$app->request->post('type');
499
                    $comment = Yii::$app->request->post('comment');
500
                    if (!empty($type)) {
501
                        foreach ($action->collection->models as $model) {
502
                            $model->setAttributes([
503
                                'comment' => $comment,
504
                                'type' => $type,
505
                            ]);
506
                        }
507
                    }
508 1
                },
509
            ],
510
            'bulk-disable-block-modal' => [
511
                'class' => PrepareBulkAction::class,
512 1
                'view' => '_bulkDisableBlock',
513 1
                'data' => function ($action, $data) {
514
                    return array_merge($data, [
515
                        'blockReasons' => $this->getBlockReasons(),
516
                    ]);
517 1
                },
518
            ],
519
            'refuse' => [
520
                'class' => SmartPerformAction::class,
521 1
                'success' => Yii::t('hipanel:server', 'You have refused the service'),
522 1
                'error' => Yii::t('hipanel:server', 'Error during the refusing the service'),
523
            ],
524
            'enable-autorenewal' => [
525
                'class' => SmartUpdateAction::class,
526 1
                'success' => Yii::t('hipanel:server', 'Server renewal enabled successfully'),
527 1
                'error' => Yii::t('hipanel:server', 'Error during the renewing the service'),
528
            ],
529
            'reinstall' => [
530
                'class' => SmartUpdateAction::class,
531 1
                'on beforeSave' => function (Event $event) {
532
                    /** @var Action $action */
533
                    $action = $event->sender;
534
                    foreach ($action->collection->models as $model) {
535
                        $model->osimage = Yii::$app->request->post('osimage');
536
                        $model->panel = Yii::$app->request->post('panel');
537
                    }
538 1
                },
539 1
                'success' => Yii::t('hipanel:server', 'Server reinstalling task has been successfully added to queue'),
540 1
                'error' => Yii::t('hipanel:server', 'Error during the server reinstalling'),
541
            ],
542
            'boot-live' => [
543
                'class' => SmartPerformAction::class,
544 1
                'on beforeSave' => function (Event $event) {
545
                    /** @var Action $action */
546
                    $action = $event->sender;
547
                    foreach ($action->collection->models as $model) {
548
                        $model->osimage = Yii::$app->request->post('osimage');
549
                    }
550 1
                },
551 1
                'success' => Yii::t('hipanel:server', 'Live CD booting task has been successfully added to queue'),
552 1
                'error' => Yii::t('hipanel:server', 'Error during the booting live CD'),
553
            ],
554
            'validate-crud-form' => [
555
                'class' => ValidateFormAction::class,
556
                'collection' => [
557
                    'class' => Collection::class,
558 1
                    'model' => new ServerForm(),
559
                ],
560
            ],
561
            'validate-form' => [
562
                'class' => ValidateFormAction::class,
563
            ],
564
            'buy' => [
565
                'class' => RedirectAction::class,
566 1
                'url' => Yii::$app->params['organization.url'],
567
            ],
568
            'add-to-cart-renewal' => [
569
                'class' => AddToCartAction::class,
570
                'productClass' => ServerRenewProduct::class,
571
            ],
572
            'delete' => [
573
                'class' => SmartDeleteAction::class,
574 1
                'success' => Yii::t('hipanel:server', 'Server was deleted successfully'),
575 1
                'error' => Yii::t('hipanel:server', 'Failed to delete server'),
576
            ],
577
            'bulk-delete-modal' => [
578
                'class' => PrepareBulkAction::class,
579
                'view' => '_bulkDelete',
580
            ],
581
            'clear-resources' => [
582
                'class' => SmartPerformAction::class,
583 1
                'view' => '_clearResources',
584 1
                'success' => Yii::t('hipanel:server', 'Servers resources were cleared successfully'),
585 1
                'error' => Yii::t('hipanel:server', 'Error occurred during server resources flushing'),
586
            ],
587
            'clear-resources-modal' => [
588
                'class' => PrepareBulkAction::class,
589
                'view' => '_clearResources',
590
            ],
591
            'flush-switch-graphs' => [
592
                'class' => SmartPerformAction::class,
593 1
                'view' => '_clearResources',
594 1
                'success' => Yii::t('hipanel:server', 'Switch graphs were flushed successfully'),
595 1
                'error' => Yii::t('hipanel:server', 'Error occurred during switch graphs flushing'),
596
            ],
597
            'flush-switch-graphs-modal' => [
598
                'class' => PrepareBulkAction::class,
599
                'view' => '_flushSwitchGraphs',
600
            ],
601
        ]);
602
    }
603
604
    /**
605
     * Gets info of VNC on the server.
606
     *
607
     * @param Server $model
608
     * @param bool $enable
609
     * @throws ResponseErrorException
610
     * @return array
611
     */
612
    public function getVNCInfo($model, $enable = false)
613
    {
614
        if ($enable) {
615
            try {
616
                $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...
617
                $vnc['endTime'] = time() + 28800;
618
                Yii::$app->cache->set([__METHOD__, $model->id, $model], $vnc, 28800);
619
                $vnc['enabled'] = true;
620
            } catch (ResponseErrorException $e) {
621
                if ($e->getMessage() !== 'vds_has_tasks') {
622
                    throw $e;
623
                }
624
            }
625
        } else {
626
            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...
627
                $vnc = Yii::$app->cache->getOrSet([__METHOD__, $model->id, $model], function () use ($model) {
628
                    return ArrayHelper::merge([
629
                        '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...
630
                    ], 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...
631
                }, 28800);
632
            }
633
            $vnc['enabled'] = $model->statuses['serverEnableVNC'] === null ? false : strtotime('+8 hours', strtotime($model->statuses['serverEnableVNC'])) > time();
634
        }
635
636
        return $vnc;
637
    }
638
639
    public function actionDrawChart()
640
    {
641
        $post = Yii::$app->request->post();
642
        $types = array_merge(['server_traf', 'server_traf95'], array_keys(ResourceConsumption::types()));
643
        if (!in_array($post['type'], $types, true)) {
644
            throw new NotFoundHttpException();
645
        }
646
647
        $searchModel = new ServerUseSearch();
648
        $dataProvider = $searchModel->search([]);
649
        $dataProvider->pagination = false;
650
        $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

650
        $dataProvider->query->/** @scrutinizer ignore-call */ 
651
                              action('get-uses');
Loading history...
651
        $dataProvider->query->andWhere($post);
652
        $models = $dataProvider->getModels();
653
654
        list($labels, $data) = ServerHelper::groupUsesForChart($models);
655
656
        return $this->renderAjax('_consumption', [
657
            'labels' => $labels,
658
            'data' => $data,
659
            'consumptionBase' => $post['type'],
660
        ]);
661
    }
662
663
    /**
664
     * Gets OS images.
665
     *
666
     * @param Server $model
667
     * @throws NotFoundHttpException
668
     * @return array
669
     */
670
    protected function getOsimages(Server $model = null)
671
    {
672
        if ($model !== null) {
673
            $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...
674
        } else {
675
            $type = null;
676
        }
677
678
        $models = ServerHelper::getOsimages($type);
679
680
        if ($models === null) {
681
            throw new NotFoundHttpException('The requested page does not exist.');
682
        }
683
684
        return $models;
685
    }
686
687
    protected function getOsimagesLiveCd()
688
    {
689
        $models = Yii::$app->cache->getOrSet([__METHOD__], function () {
690
            return Osimage::findAll(['livecd' => true]);
691
        }, 3600);
692
693
        if ($models !== null) {
694
            return $models;
695
        }
696
697
        throw new NotFoundHttpException('The requested page does not exist.');
698
    }
699
700
    protected function getPanelTypes()
701
    {
702
        return ServerHelper::getPanels();
703
    }
704
705
    public function actionIsOperable($id)
706
    {
707
        Yii::$app->response->format = Response::FORMAT_JSON;
708
709
        $result = ['id' => $id, 'result' => false];
710
711
        if ($server = Server::find()->where(['id' => $id])->one()) {
712
            $result['result'] = $server->isOperable();
713
        }
714
715
        return $result;
716
    }
717
718
    protected function getFullFromRef($gtype)
719
    {
720
        $callingMethod = debug_backtrace()[1]['function'];
721
        $result = Yii::$app->get('cache')->getOrSet([$callingMethod], function () use ($gtype) {
722
            $result = ArrayHelper::map(Ref::find()->where([
723
                'gtype' => $gtype,
724
                'select' => 'full',
725
            ])->all(), 'id', function ($model) {
726
                return Yii::t('hipanel:server:hub', $model->label);
727
            });
728
729
            return $result;
730
        }, 86400 * 24); // 24 days
731
732
        return $result;
733
    }
734
735
    public function actionResources($id)
736
    {
737
        $model = Server::find()->joinWith(['uses'])->andWhere(['id' => $id])->andWhere(['with_uses' => 1])->one();
738
        list($chartsLabels, $chartsData) = $model->groupUsesForCharts();
739
740
        return $this->render('resources', compact('model', 'chartsData', 'chartsLabels'));
741
    }
742
}
743