Passed
Push — master ( 800e97...8e736f )
by Dmitry
05:42
created

ServerController::actionDrawChart()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 21
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 21
ccs 0
cts 16
cp 0
rs 9.7666
c 0
b 0
f 0
cc 2
nc 2
nop 0
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(['bindings']);
98
99
                    if (Yii::getAlias('@ip', false)) {
100
                        $dataProvider->query
101
                            ->joinWith(['ips'])
102
                            ->andWhere(['with_ips' => 1]);
103
                    }
104
105
                    $dataProvider->query
106
                        ->andWhere(['with_requests' => 1])
107
                        ->andWhere(['with_discounts' => 1])
108
                        ->andWhere(['with_bindings' => 1])
109
                        ->select(['*']);
110 1
                },
111
                'filterStorageMap' => [
112
                    'name_like' => 'server.server.name',
113
                    'ips' => 'hosting.ip.ip_in',
114
                    'state' => 'server.server.state',
115
                    'client_id' => 'client.client.id',
116
                    'seller_id' => 'client.client.seller_id',
117
                ],
118
            ],
119
            'search' => [
120
                'class' => ComboSearchAction::class,
121
            ],
122
            'create' => [
123
                'class' => SmartCreateAction::class,
124
                'collection' => [
125
                    'class' => Collection::class,
126 1
                    'model' => new ServerForm(['scenario' => 'create']),
127 1
                    'scenario' => 'create',
128
                ],
129 1
                'success' => Yii::t('hipanel:server', 'Server has been created'),
130
            ],
131
            'update' => [
132
                'class' => SmartUpdateAction::class,
133
                'collection' => [
134
                    'class' => Collection::class,
135 1
                    'model' => new ServerForm(),
136 1
                    'scenario' => 'update',
137
                ],
138 1
                'on beforeFetch' => function (Event $event) {
139
                    /** @var \hipanel\actions\SearchAction $action */
140
                    $action = $event->sender;
141
                    $dataProvider = $action->getDataProvider();
142
                    if (Yii::getAlias('@ip', false)) {
143
                        $dataProvider->query->joinWith('ips');
144
                    }
145 1
                },
146 1
                'data' => function (Action $action, array $data) {
147
                    $result = [];
148
                    foreach ($data['models'] as $model) {
149
                        $result['models'][] = ServerForm::fromServer($model);
150
                    }
151
                    $result['model'] = reset($result['models']);
152
153
                    return $result;
154 1
                },
155 1
                'success' => Yii::t('hipanel:server', 'Server has been updated'),
156
            ],
157
            'hardware-settings' => [
158
                'class' => SmartUpdateAction::class,
159 1
                'success' => Yii::t('hipanel:server', 'Hardware properties was changed'),
160 1
                'view' => 'hardwareSettings',
161 1
                'on beforeFetch' => function (Event $event) {
162
                    /** @var \hipanel\actions\SearchAction $action */
163
                    $action = $event->sender;
164
                    $dataProvider = $action->getDataProvider();
165
                    $dataProvider->query->joinWith(['hardwareSettings']);
166
                    $dataProvider->query->andWhere(['with_hardwareSettings' => 1])->select(['*']);
167 1
                },
168 1
                'on beforeLoad' => function (Event $event) {
169
                    /** @var Action $action */
170
                    $action = $event->sender;
171
172
                    $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

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

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

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

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

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