Completed
Push — master ( bb5bc8...bee967 )
by Dmitry
05:17
created

ServerController::getVNCInfo()   B

Complexity

Conditions 7
Paths 13

Size

Total Lines 25
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 25
ccs 0
cts 17
cp 0
rs 8.8333
c 0
b 0
f 0
cc 7
nc 13
nop 2
crap 56
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-type' => [
398
                'class' => SmartUpdateAction::class,
399 1
                'view' => '_bulkSetType',
400 1
                'success' => Yii::t('hipanel:server', 'Type was changed'),
401 1
                'error' => Yii::t('hipanel:server', 'Failed to change type'),
402
            ],
403
            'reboot' => [
404
                'class' => SmartPerformAction::class,
405 1
                'success' => Yii::t('hipanel:server', 'Reboot task has been successfully added to queue'),
406 1
                'error' => Yii::t('hipanel:server', 'Error during the rebooting'),
407
            ],
408
            'reset' => [
409
                'class' => SmartPerformAction::class,
410 1
                'success' => Yii::t('hipanel:server', 'Reset task has been successfully added to queue'),
411 1
                'error' => Yii::t('hipanel:server', 'Error during the resetting'),
412
            ],
413
            'shutdown' => [
414
                'class' => SmartPerformAction::class,
415 1
                'success' => Yii::t('hipanel:server', 'Shutdown task has been successfully added to queue'),
416 1
                'error' => Yii::t('hipanel:server', 'Error during the shutting down'),
417
            ],
418
            'power-off' => [
419
                'class' => SmartPerformAction::class,
420 1
                'success' => Yii::t('hipanel:server', 'Power off task has been successfully added to queue'),
421 1
                'error' => Yii::t('hipanel:server', 'Error during the turning power off'),
422
            ],
423
            'power-on' => [
424
                'class' => SmartPerformAction::class,
425 1
                'success' => Yii::t('hipanel:server', 'Power on task has been successfully added to queue'),
426 1
                'error' => Yii::t('hipanel:server', 'Error during the turning power on'),
427
            ],
428
            'reset-password' => [
429
                'class' => SmartPerformAction::class,
430 1
                'success' => Yii::t('hipanel:server', 'Root password reset task has been successfully added to queue'),
431 1
                'error' => Yii::t('hipanel:server', 'Error during the resetting root password'),
432
            ],
433
            'enable-block' => [
434
                'class' => SmartPerformAction::class,
435 1
                'success' => Yii::t('hipanel:server', 'Server was blocked successfully'),
436 1
                'error' => Yii::t('hipanel:server', 'Error during the server blocking'),
437
                'POST html' => [
438
                    'save' => true,
439
                    'success' => [
440
                        'class' => RedirectAction::class,
441
                    ],
442
                ],
443 1
                'on beforeSave' => function (Event $event) {
444
                    /** @var \hipanel\actions\Action $action */
445
                    $action = $event->sender;
446
                    $type = Yii::$app->request->post('type');
447
                    $comment = Yii::$app->request->post('comment');
448
                    if (!empty($type)) {
449
                        foreach ($action->collection->models as $model) {
450
                            $model->setAttributes([
451
                                'type' => $type,
452
                                'comment' => $comment,
453
                            ]);
454
                        }
455
                    }
456 1
                },
457
            ],
458
            'bulk-enable-block-modal' => [
459
                'class' => PrepareBulkAction::class,
460 1
                'view' => '_bulkEnableBlock',
461 1
                'data' => function ($action, $data) {
462
                    return array_merge($data, [
463
                        'blockReasons' => $this->getBlockReasons(),
464
                    ]);
465 1
                },
466
            ],
467
            'disable-block' => [
468
                'class' => SmartPerformAction::class,
469 1
                'success' => Yii::t('hipanel:server', 'Server was unblocked successfully'),
470 1
                'error' => Yii::t('hipanel:server', 'Error during the server unblocking'),
471
                'POST html' => [
472
                    'save' => true,
473
                    'success' => [
474
                        'class' => RedirectAction::class,
475
                    ],
476
                ],
477 1
                'on beforeSave' => function (Event $event) {
478
                    /** @var \hipanel\actions\Action $action */
479
                    $action = $event->sender;
480
                    $type = Yii::$app->request->post('type');
481
                    $comment = Yii::$app->request->post('comment');
482
                    if (!empty($type)) {
483
                        foreach ($action->collection->models as $model) {
484
                            $model->setAttributes([
485
                                'comment' => $comment,
486
                                'type' => $type,
487
                            ]);
488
                        }
489
                    }
490 1
                },
491
            ],
492
            'bulk-disable-block-modal' => [
493
                'class' => PrepareBulkAction::class,
494 1
                'view' => '_bulkDisableBlock',
495 1
                'data' => function ($action, $data) {
496
                    return array_merge($data, [
497
                        'blockReasons' => $this->getBlockReasons(),
498
                    ]);
499 1
                },
500
            ],
501
            'refuse' => [
502
                'class' => SmartPerformAction::class,
503 1
                'success' => Yii::t('hipanel:server', 'You have refused the service'),
504 1
                'error' => Yii::t('hipanel:server', 'Error during the refusing the service'),
505
            ],
506
            'enable-autorenewal' => [
507
                'class' => SmartUpdateAction::class,
508 1
                'success' => Yii::t('hipanel:server', 'Server renewal enabled successfully'),
509 1
                'error' => Yii::t('hipanel:server', 'Error during the renewing the service'),
510
            ],
511
            'reinstall' => [
512
                'class' => SmartUpdateAction::class,
513 1
                'on beforeSave' => function (Event $event) {
514
                    /** @var Action $action */
515
                    $action = $event->sender;
516
                    foreach ($action->collection->models as $model) {
517
                        $model->osimage = Yii::$app->request->post('osimage');
518
                        $model->panel = Yii::$app->request->post('panel');
519
                    }
520 1
                },
521 1
                'success' => Yii::t('hipanel:server', 'Server reinstalling task has been successfully added to queue'),
522 1
                'error' => Yii::t('hipanel:server', 'Error during the server reinstalling'),
523
            ],
524
            'boot-live' => [
525
                'class' => SmartPerformAction::class,
526 1
                'on beforeSave' => function (Event $event) {
527
                    /** @var Action $action */
528
                    $action = $event->sender;
529
                    foreach ($action->collection->models as $model) {
530
                        $model->osimage = Yii::$app->request->post('osimage');
531
                    }
532 1
                },
533 1
                'success' => Yii::t('hipanel:server', 'Live CD booting task has been successfully added to queue'),
534 1
                'error' => Yii::t('hipanel:server', 'Error during the booting live CD'),
535
            ],
536
            'validate-crud-form' => [
537
                'class' => ValidateFormAction::class,
538
                'collection' => [
539
                    'class' => Collection::class,
540 1
                    'model' => new ServerForm(),
541
                ],
542
            ],
543
            'validate-form' => [
544
                'class' => ValidateFormAction::class,
545
            ],
546
            'buy' => [
547
                'class' => RedirectAction::class,
548 1
                'url' => Yii::$app->params['organization.url'],
549
            ],
550
            'add-to-cart-renewal' => [
551
                'class' => AddToCartAction::class,
552
                'productClass' => ServerRenewProduct::class,
553
            ],
554
            'delete' => [
555
                'class' => SmartDeleteAction::class,
556 1
                'success' => Yii::t('hipanel:server', 'Server was deleted successfully'),
557 1
                'error' => Yii::t('hipanel:server', 'Failed to delete server'),
558
            ],
559
            'bulk-delete-modal' => [
560
                'class' => PrepareBulkAction::class,
561
                'view' => '_bulkDelete',
562
            ],
563
            'clear-resources' => [
564
                'class' => SmartPerformAction::class,
565 1
                'view' => '_clearResources',
566 1
                'success' => Yii::t('hipanel:server', 'Servers resources were cleared successfully'),
567 1
                'error' => Yii::t('hipanel:server', 'Error occurred during server resources flushing'),
568
            ],
569
            'clear-resources-modal' => [
570
                'class' => PrepareBulkAction::class,
571
                'view' => '_clearResources',
572
            ],
573
            'flush-switch-graphs' => [
574
                'class' => SmartPerformAction::class,
575 1
                'view' => '_clearResources',
576 1
                'success' => Yii::t('hipanel:server', 'Switch graphs were flushed successfully'),
577 1
                'error' => Yii::t('hipanel:server', 'Error occurred during switch graphs flushing'),
578
            ],
579
            'flush-switch-graphs-modal' => [
580
                'class' => PrepareBulkAction::class,
581
                'view' => '_flushSwitchGraphs',
582
            ],
583
        ]);
584
    }
585
586
    /**
587
     * Gets info of VNC on the server.
588
     *
589
     * @param Server $model
590
     * @param bool $enable
591
     * @throws ResponseErrorException
592
     * @return array
593
     */
594
    public function getVNCInfo($model, $enable = false)
595
    {
596
        if ($enable) {
597
            try {
598
                $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...
599
                $vnc['endTime'] = time() + 28800;
600
                Yii::$app->cache->set([__METHOD__, $model->id, $model], $vnc, 28800);
601
                $vnc['enabled'] = true;
602
            } catch (ResponseErrorException $e) {
603
                if ($e->getMessage() !== 'vds_has_tasks') {
604
                    throw $e;
605
                }
606
            }
607
        } else {
608
            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...
609
                $vnc = Yii::$app->cache->getOrSet([__METHOD__, $model->id, $model], function () use ($model) {
610
                    return ArrayHelper::merge([
611
                        '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...
612
                    ], 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...
613
                }, 28800);
614
            }
615
            $vnc['enabled'] = $model->statuses['serverEnableVNC'] === null ? false : strtotime('+8 hours', strtotime($model->statuses['serverEnableVNC'])) > time();
616
        }
617
618
        return $vnc;
619
    }
620
621
    public function actionDrawChart()
622
    {
623
        $post = Yii::$app->request->post();
624
        $types = array_merge(['server_traf', 'server_traf95'], array_keys(ResourceConsumption::types()));
625
        if (!in_array($post['type'], $types, true)) {
626
            throw new NotFoundHttpException();
627
        }
628
629
        $searchModel = new ServerUseSearch();
630
        $dataProvider = $searchModel->search([]);
631
        $dataProvider->pagination = false;
632
        $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

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