Passed
Push — master ( 35e1dc...d5db3a )
by Andrii
07:14
created

ServerController::behaviors()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 26
c 0
b 0
f 0
ccs 0
cts 3
cp 0
rs 9.504
cc 1
nc 1
nop 0
crap 2
1
<?php
2
/**
3
 * Server module for HiPanel
4
 *
5
 * @link      https://github.com/hiqdev/hipanel-module-server
6
 * @package   hipanel-module-server
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2015-2018, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hipanel\modules\server\controllers;
12
13
use hipanel\actions\Action;
14
use hipanel\actions\ComboSearchAction;
15
use hipanel\actions\IndexAction;
16
use hipanel\actions\PrepareBulkAction;
17
use hipanel\actions\ProxyAction;
18
use hipanel\actions\RedirectAction;
19
use hipanel\actions\RenderAction;
20
use hipanel\actions\RenderJsonAction;
21
use hipanel\actions\RequestStateAction;
22
use hipanel\actions\SmartDeleteAction;
23
use hipanel\actions\SmartPerformAction;
24
use hipanel\actions\SmartUpdateAction;
25
use hipanel\actions\ValidateFormAction;
26
use hipanel\actions\ViewAction;
27
use hipanel\base\CrudController;
28
use hipanel\filters\EasyAccessControl;
29
use hipanel\models\Ref;
30
use hipanel\modules\finance\models\Tariff;
31
use hipanel\modules\server\cart\ServerRenewProduct;
32
use hipanel\modules\server\helpers\ServerHelper;
33
use hipanel\modules\server\models\HardwareSettings;
34
use hipanel\modules\server\models\MonitoringSettings;
35
use hipanel\modules\server\models\Osimage;
36
use hipanel\modules\server\models\Server;
37
use hipanel\modules\server\models\ServerUseSearch;
38
use hipanel\modules\server\models\SoftwareSettings;
39
use hipanel\modules\server\widgets\ResourceConsumption;
40
use hiqdev\hiart\ResponseErrorException;
41
use hiqdev\yii2\cart\actions\AddToCartAction;
42
use Yii;
43
use yii\base\Event;
44
use yii\filters\VerbFilter;
45
use yii\helpers\ArrayHelper;
46
use yii\web\NotFoundHttpException;
47
use yii\web\Response;
48
49
class ServerController extends CrudController
50
{
51
    public function behaviors()
52
    {
53
        return array_merge(parent::behaviors(), [
54
            'server-actions-verb' => [
55
                'class' => VerbFilter::class,
56
                'actions' => [
57
                    'reboot' => ['post'],
58
                    'reset' => ['post'],
59
                    'shutdown' => ['post'],
60
                    'power-off' => ['post'],
61
                    'power-on' => ['post'],
62
                    'reset-password' => ['post'],
63
                    'enable-block' => ['post'],
64
                    'disable-block' => ['post'],
65
                    'refuse' => ['post'],
66
                    'flush-switch-graphs' => ['post'],
67
                ],
68
            ],
69
            [
70
                'class' => EasyAccessControl::class,
71
                'actions' => [
72
                    'monitoring-settings' => 'support',
73
                    'software-settings' => 'support',
74
                    'hardware-settings' => 'support',
75
                    'delete' => 'server.delete',
76
                    '*' => 'server.read',
77
                ],
78
            ],
79
        ]);
80
    }
81
82 1
    public function actions()
83
    {
84 1
        return array_merge(parent::actions(), [
85 1
            'index' => [
86
                'class' => IndexAction::class,
87
                'findOptions' => ['with_requests' => true, 'with_discounts' => true],
88 1
                'on beforePerform' => function (Event $event) {
89
                    /** @var \hipanel\actions\SearchAction $action */
90
                    $action = $event->sender;
91
                    $dataProvider = $action->getDataProvider();
92
                    $dataProvider->query->joinWith(['ips', 'bindings']);
93
94
                    $dataProvider->query
95
                        ->andWhere(['with_ips' => 1])
96
                        ->andWhere(['with_requests' => 1])
97
                        ->andWhere(['with_discounts' => 1])
98
                        ->andWhere(['with_bindings' => 1])
99
                        ->select(['*']);
100 1
                },
101
                'filterStorageMap' => [
102
                    'name_like' => 'server.server.name',
103
                    'ips' => 'hosting.ip.ip_in',
104
                    'state' => 'server.server.state',
105
                    'client_id' => 'client.client.id',
106
                    'seller_id' => 'client.client.seller_id',
107
                ],
108
            ],
109
            'search' => [
110
                'class' => ComboSearchAction::class,
111
            ],
112
            'hardware-settings' => [
113
                'class' => SmartUpdateAction::class,
114 1
                'success' => Yii::t('hipanel:server', 'Hardware properties was changed'),
115 1
                'view' => 'hardwareSettings',
116 1
                'scenario' => 'default',
117 1
                'on beforeFetch' => function (Event $event) {
118
                    /** @var \hipanel\actions\SearchAction $action */
119
                    $action = $event->sender;
120
                    $dataProvider = $action->getDataProvider();
121
                    $dataProvider->query->joinWith(['hardwareSettings']);
122
                    $dataProvider->query->andWhere(['with_hardwareSettings' => 1])->select(['*']);
123 1
                },
124 1
                'on beforeLoad' => function (Event $event) {
125
                    /** @var Action $action */
126
                    $action = $event->sender;
127
128
                    $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

128
                    $action->collection->setModel(/** @scrutinizer ignore-type */ HardwareSettings::class);
Loading history...
129 1
                },
130
                'POST html' => [
131
                    'save' => true,
132
                    'success' => [
133
                        'class' => RedirectAction::class,
134 1
                        'url' => function () {
135
                            $server = Yii::$app->request->post('HardwareSettings');
136
137
                            return ['@server/view', 'id' => $server['id']];
138 1
                        },
139
                    ],
140
                ],
141
            ],
142
            'software-settings' => [
143
                'class' => SmartUpdateAction::class,
144 1
                'success' => Yii::t('hipanel:server', 'Software properties was changed'),
145 1
                'view' => 'softwareSettings',
146 1
                'scenario' => 'default',
147 1
                'on beforeFetch' => function (Event $event) {
148
                    /** @var \hipanel\actions\SearchAction $action */
149
                    $action = $event->sender;
150
                    $dataProvider = $action->getDataProvider();
151
                    $dataProvider->query->joinWith(['softwareSettings']);
152
                    $dataProvider->query->andWhere(['with_softwareSettings' => 1])->select(['*']);
153 1
                },
154 1
                'on beforeLoad' => function (Event $event) {
155
                    /** @var Action $action */
156
                    $action = $event->sender;
157
158
                    $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

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

189
                    $action->collection->setModel(/** @scrutinizer ignore-type */ MonitoringSettings::class);
Loading history...
190 1
                },
191 1
                'data' => function ($action) {
192
                    return [
193
                        'nicMediaOptions' => $action->controller->getFullFromRef('type,nic_media'),
194
                    ];
195 1
                },
196
                'POST html' => [
197
                    'save' => true,
198
                    'success' => [
199
                        'class' => RedirectAction::class,
200 1
                        'url' => function () {
201
                            $server = Yii::$app->request->post('MonitoringSettings');
202
203
                            return ['@server/view', 'id' => $server['id']];
204 1
                        },
205
                    ],
206
                ],
207
            ],
208
            'view' => [
209
                'class' => ViewAction::class,
210 1
                'on beforePerform' => function (Event $event) {
211
                    /** @var \hipanel\actions\SearchAction $action */
212
                    $action = $event->sender;
213
                    $dataProvider = $action->getDataProvider();
214
                    $dataProvider->query->joinWith(['uses', 'ips', 'switches', 'bindings', 'blocking']);
215
216
                    // TODO: ipModule is not wise yet. Redo
217
                    $dataProvider->query
218
                        ->andWhere(['with_requests' => 1])
219
                        ->andWhere(['show_deleted' => 1])
220
                        ->andWhere(['with_discounts' => 1])
221
                        ->andWhere(['with_uses' => 1])
222
                        ->andWhere(['with_ips' => 1])
223
                        ->andWhere(['with_bindings' => 1])
224
                        ->andWhere(['with_blocking' => 1])
225
                        ->select(['*']);
226 1
                },
227 1
                'data' => function ($action) {
228
                    /**
229
                     * @var Action
230
                     * @var self $controller
231
                     * @var Server $model
232
                     */
233
                    $controller = $action->controller;
234
                    $model = $action->getModel();
235
                    $model->vnc = $controller->getVNCInfo($model);
236
237
                    $panels = $controller->getPanelTypes();
238
239
                    $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

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

588
        $dataProvider->query->/** @scrutinizer ignore-call */ 
589
                              action('get-uses');
Loading history...
589
        $dataProvider->query->andWhere($post);
590
        $models = $dataProvider->getModels();
591
592
        list($labels, $data) = ServerHelper::groupUsesForChart($models);
593
594
        return $this->renderAjax('_consumption', [
595
            'labels' => $labels,
596
            'data' => $data,
597
            'consumptionBase' => $post['type'],
598
        ]);
599
    }
600
601
    /**
602
     * Gets OS images.
603
     *
604
     * @param Server $model
605
     * @throws NotFoundHttpException
606
     * @return array
607
     */
608
    protected function getOsimages(Server $model = null)
609
    {
610
        if ($model !== null) {
611
            $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...
612
        } else {
613
            $type = null;
614
        }
615
616
        $models = ServerHelper::getOsimages($type);
617
618
        if ($models === null) {
619
            throw new NotFoundHttpException('The requested page does not exist.');
620
        }
621
622
        return $models;
623
    }
624
625
    protected function getOsimagesLiveCd()
626
    {
627
        $models = Yii::$app->cache->getOrSet([__METHOD__], function () {
628
            return Osimage::findAll(['livecd' => true]);
629
        }, 3600);
630
631
        if ($models !== null) {
632
            return $models;
633
        }
634
635
        throw new NotFoundHttpException('The requested page does not exist.');
636
    }
637
638
    protected function getPanelTypes()
639
    {
640
        return ServerHelper::getPanels();
641
    }
642
643
    public function actionIsOperable($id)
644
    {
645
        Yii::$app->response->format = Response::FORMAT_JSON;
646
647
        $result = ['id' => $id, 'result' => false];
648
649
        if ($server = Server::find()->where(['id' => $id])->one()) {
650
            $result['result'] = $server->isOperable();
651
        }
652
653
        return $result;
654
    }
655
656
    protected function getFullFromRef($gtype)
657
    {
658
        $callingMethod = debug_backtrace()[1]['function'];
659
        $result = Yii::$app->get('cache')->getOrSet([$callingMethod], function () use ($gtype) {
660
            $result = ArrayHelper::map(Ref::find()->where([
661
                'gtype' => $gtype,
662
                'select' => 'full',
663
            ])->all(), 'id', function ($model) {
664
                return Yii::t('hipanel:server:hub', $model->label);
665
            });
666
667
            return $result;
668
        }, 86400 * 24); // 24 days
669
670
        return $result;
671
    }
672
673
    public function actionResources($id)
674
    {
675
        $model = Server::find()->joinWith(['uses'])->andWhere(['id' => $id])->andWhere(['with_uses' => 1])->one();
676
        list($chartsLabels, $chartsData) = $model->groupUsesForCharts();
677
678
        return $this->render('resources', compact('model', 'chartsData', 'chartsLabels'));
679
    }
680
}
681