Completed
Push — master ( cd81f9...a9cd5a )
by Dmitry
38:39 queued 23:40
created

src/controllers/ServerController.php (1 issue)

1
<?php
2
/**
3
 * Server module for HiPanel
4
 *
5
 * @link      https://github.com/hiqdev/hipanel-module-server
6
 * @package   hipanel-module-server
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2015-2018, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hipanel\modules\server\controllers;
12
13
use hipanel\actions\Action;
14
use hipanel\actions\ComboSearchAction;
15
use hipanel\actions\IndexAction;
16
use hipanel\actions\PrepareBulkAction;
17
use hipanel\actions\ProxyAction;
18
use hipanel\actions\RedirectAction;
19
use hipanel\actions\RenderAction;
20
use hipanel\actions\RenderJsonAction;
21
use hipanel\actions\RequestStateAction;
22
use hipanel\actions\SmartCreateAction;
23
use hipanel\actions\SmartDeleteAction;
24
use hipanel\actions\SmartPerformAction;
25
use hipanel\actions\SmartUpdateAction;
26
use hipanel\actions\ValidateFormAction;
27
use hipanel\actions\ViewAction;
28
use hipanel\base\CrudController;
29
use hipanel\filters\EasyAccessControl;
30
use hipanel\models\Ref;
31
use hipanel\modules\finance\models\Tariff;
32
use hipanel\modules\server\cart\ServerRenewProduct;
33
use hipanel\modules\server\forms\AssignHubsForm;
34
use hipanel\modules\server\forms\ServerForm;
35
use hipanel\modules\server\helpers\ServerHelper;
36
use hipanel\modules\server\models\HardwareSettings;
37
use hipanel\modules\server\models\MonitoringSettings;
38
use hipanel\modules\server\models\Osimage;
39
use hipanel\modules\server\models\query\ServerQuery;
40
use hipanel\modules\server\models\Server;
41
use hipanel\modules\server\models\ServerUseSearch;
42
use hipanel\modules\server\models\SoftwareSettings;
43
use hipanel\modules\server\widgets\ResourceConsumption;
44
use hiqdev\hiart\Collection;
45
use hiqdev\hiart\ResponseErrorException;
46
use hiqdev\yii2\cart\actions\AddToCartAction;
47
use Yii;
48
use yii\base\Event;
49
use yii\filters\VerbFilter;
50
use yii\helpers\ArrayHelper;
51
use yii\web\NotFoundHttpException;
52
use yii\web\Response;
53
54
class ServerController extends CrudController
55
{
56
    public function behaviors()
57
    {
58
        return array_merge(parent::behaviors(), [
59
            'server-actions-verb' => [
60
                'class' => VerbFilter::class,
61
                'actions' => [
62
                    'reboot' => ['post'],
63
                    'reset' => ['post'],
64
                    'shutdown' => ['post'],
65
                    'power-off' => ['post'],
66
                    'power-on' => ['post'],
67
                    'reset-password' => ['post'],
68
                    'enable-block' => ['post'],
69
                    'disable-block' => ['post'],
70
                    'refuse' => ['post'],
71
                    'flush-switch-graphs' => ['post'],
72
                ],
73
            ],
74
            [
75
                'class' => EasyAccessControl::class,
76
                'actions' => [
77
                    'monitoring-settings' => 'support',
78
                    'software-settings' => 'support',
79
                    'hardware-settings' => 'support',
80
                    'create' => 'server.create',
81
                    'update' => 'server.update',
82
                    'delete' => 'server.delete',
83
                    'renew' => 'server.pay',
84
                    'refuse' => 'server.pay',
85
                    'assign-hubs' => 'server.update',
86
                    'set-units' => 'server.update',
87
                    'set-rack-no' => 'server.update',
88
                    'reboot' => 'server.control-power',
89
                    'shutdown' => 'server.control-power',
90
                    'power-on' => 'server.control-power',
91
                    'power-off' => 'server.control-power',
92
                    'reset' => 'server.control-power',
93
                    'reinstall' => 'server.control-system',
94
                    'boot-live' => 'server.control-system',
95
                    'enable-wizzard' => 'server.update',
96
                    'disable-wizzard' => 'server.wizzard',
97
                    'enable-vnc' => 'server.control-system',
98
                    'enable-block' => 'server.enable-block',
99
                    'disable-block' => 'server.disable-block',
100
                    'set-label' => 'server.set-label',
101
                    'set-note' => 'server.set-note',
102
                    'clear-resources' => 'consumption.delete',
103
                    'flush-switch-graphs' => 'consumption.delete',
104
                    '*' => 'server.read',
105
                ],
106
            ],
107
        ]);
108
    }
109
110 1
    public function actions()
111
    {
112 1
        return array_merge(parent::actions(), [
113 1
            'index' => [
114
                'class' => IndexAction::class,
115
                'findOptions' => ['with_requests' => true, 'with_discounts' => true],
116 1
                'on beforePerform' => function (Event $event) {
117
                    /** @var \hipanel\actions\SearchAction $action */
118
                    $action = $event->sender;
119
                    $dataProvider = $action->getDataProvider();
120
121
                    $dataProvider->query->withBindings();
122
123
                    if (Yii::getAlias('@ip', false)) {
124
                        $dataProvider->query
125
                            ->joinWith(['ips'])
126
                            ->andWhere(['with_ips' => 1]);
127
                    }
128
129
                    if ($this->indexPageUiOptionsModel->representation === 'billing' && Yii::$app->user->can('consumption.read')) {
130
                        $dataProvider->query->withConsumptions()->withHardwarePrices();
131
                    }
132
133
                    $dataProvider->query
134
                        ->andWhere(['with_requests' => 1])
135
                        ->andWhere(['with_discounts' => 1])
136
                        ->select(['*']);
137 1
                },
138
                'filterStorageMap' => [
139
                    'name_like' => 'server.server.name',
140
                    'ips' => 'hosting.ip.ip_in',
141
                    'state' => 'server.server.state',
142
                    'client_id' => 'client.client.id',
143
                    'seller_id' => 'client.client.seller_id',
144
                ],
145
            ],
146
            'search' => [
147
                'class' => ComboSearchAction::class,
148
            ],
149
            'create' => [
150
                'class' => SmartCreateAction::class,
151
                'collection' => [
152
                    'class' => Collection::class,
153 1
                    'model' => new ServerForm(['scenario' => 'create']),
154 1
                    'scenario' => 'create',
155
                ],
156 1
                'success' => Yii::t('hipanel:server', 'Server has been created'),
157
            ],
158
            'update' => [
159
                'class' => SmartUpdateAction::class,
160
                'collection' => [
161
                    'class' => Collection::class,
162 1
                    'model' => new ServerForm(),
163 1
                    'scenario' => 'update',
164
                ],
165 1
                'on beforeFetch' => function (Event $event) {
166
                    /** @var \hipanel\actions\SearchAction $action */
167
                    $action = $event->sender;
168
                    $dataProvider = $action->getDataProvider();
169
                    if (Yii::getAlias('@ip', false)) {
170
                        $dataProvider->query->joinWith('ips');
171
                    }
172 1
                },
173 1
                'data' => function (Action $action, array $data) {
174
                    $result = [];
175
                    foreach ($data['models'] as $model) {
176
                        $result['models'][] = ServerForm::fromServer($model);
177
                    }
178
                    $result['model'] = reset($result['models']);
179
180
                    return $result;
181 1
                },
182 1
                'success' => Yii::t('hipanel:server', 'Server has been updated'),
183
            ],
184
            'assign-hubs' => [
185
                'class' => SmartUpdateAction::class,
186 1
                'success' => Yii::t('hipanel:server', 'Hubs were assigned'),
187 1
                'view' => 'assignHubs',
188 1
                'on beforeFetch' => function (Event $event) {
189
                    /** @var \hipanel\actions\SearchAction $action */
190
                    $action = $event->sender;
191
                    $dataProvider = $action->getDataProvider();
192
                    $dataProvider->query->withBindings()->select(['*']);
193 1
                },
194
                'collection' => [
195
                    'class' => Collection::class,
196 1
                    'model' => new AssignHubsForm(),
197 1
                    'scenario' => 'default',
198
                ],
199 1
                'data' => function (Action $action, array $data) {
200
                    $result = [];
201
                    foreach ($data['models'] as $model) {
202
                        if ($model->canAssignHubs()) {
203
                            $result['models'][] = AssignHubsForm::fromServer($model);
204
                        }
205
                    }
206
                    if (!$result['models']) {
207
                        throw new NotFoundHttpException('There are no entries available for the selected operation. The type of selected records may not be suitable for the selected operation.');
208
                    }
209
                    $result['model'] = reset($result['models']);
210
211
                    return $result;
212 1
                },
213
            ],
214
            'set-units' => [
215
                'class' => SmartUpdateAction::class,
216 1
                'success' => Yii::t('hipanel:server', 'Units property was changed'),
217 1
                'view' => 'setUnits',
218 1
                'on beforeSave' => function (Event $event) {
219
                    /** @var \hipanel\actions\Action $action */
220
                    $action = $event->sender;
221
                    $servers = Yii::$app->request->post('HardwareSettings');
222
                    $units = ArrayHelper::remove($servers, 'units');
223
                    foreach ($servers as $id => $server) {
224
                        $servers[$id]['units'] = $units;
225
                    }
226
                    $action->collection->load($servers);
227 1
                },
228 1
                'on beforeFetch' => function (Event $event) {
229
                    /** @var \hipanel\actions\SearchAction $action */
230
                    $action = $event->sender;
231
                    /** @var ServerQuery $query */
232
                    $query = $action->getDataProvider()->query;
233
                    $query->withHardwareSettings();
234 1
                },
235 1
                'on beforeLoad' => function (Event $event) {
236
                    /** @var Action $action */
237
                    $action = $event->sender;
238
239
                    $action->collection->setModel((new HardwareSettings(['scenario' => 'set-units'])));
240 1
                },
241
            ],
242
            'set-rack-no' => [
243
                'class' => SmartUpdateAction::class,
244 1
                'success' => Yii::t('hipanel:server', 'Rack No. was assigned'),
245 1
                'view' => 'setRackNo',
246
                'collection' => [
247
                    'class' => Collection::class,
248 1
                    'model' => new AssignHubsForm(),
249 1
                    'scenario' => 'default',
250
                ],
251 1
                'on beforeSave' => function (Event $event) {
252
                    /** @var \hipanel\actions\Action $action */
253
                    $action = $event->sender;
254
                    $servers = Yii::$app->request->post('AssignHubsForm');
255
                    $rackId = ArrayHelper::remove($servers, 'rack_id');
256
                    $rackPort = ArrayHelper::remove($servers, 'rack_port');
257
                    foreach ($servers as $id => $server) {
258
                        $servers[$id]['rack_id'] = $rackId;
259
                        $servers[$id]['rack_port'] = $rackPort;
260
                    }
261
                    $action->collection->load($servers);
262 1
                },
263 1
                'on beforeFetch' => function (Event $event) {
264
                    /** @var \hipanel\actions\SearchAction $action */
265
                    $action = $event->sender;
266
                    $dataProvider = $action->getDataProvider();
267
                    $dataProvider->query->withBindings()->select(['*']);
268 1
                },
269 1
                'data' => function (Action $action, array $data) {
270
                    $result = [];
271
                    foreach ($data['models'] as $model) {
272
                        if ($model->canAssignHubs()) {
273
                            $result['models'][] = AssignHubsForm::fromServer($model);
274
                        }
275
                    }
276
                    if (!$result['models']) {
277
                        throw new NotFoundHttpException('There are no entries available for the selected operation. The type of selected records may not be suitable for the selected operation.');
278
                    }
279
                    $result['model'] = reset($result['models']);
280
281
                    return $result;
282 1
                },
283
            ],
284
            'hardware-settings' => [
285
                'class' => SmartUpdateAction::class,
286 1
                'success' => Yii::t('hipanel:server', 'Hardware properties was changed'),
287 1
                'view' => 'hardwareSettings',
288 1
                'on beforeFetch' => function (Event $event) {
289
                    /** @var \hipanel\actions\SearchAction $action */
290
                    $action = $event->sender;
291
                    /** @var ServerQuery $query */
292
                    $query = $action->getDataProvider()->query;
293
                    $query->withHardwareSettings();
294 1
                },
295 1
                'on beforeLoad' => function (Event $event) {
296
                    /** @var Action $action */
297
                    $action = $event->sender;
298
299
                    $action->collection->setModel(HardwareSettings::class);
300 1
                },
301
                'POST html' => [
302
                    'save' => true,
303
                    'success' => [
304
                        'class' => RedirectAction::class,
305 1
                        'url' => function () {
306
                            $server = Yii::$app->request->post('HardwareSettings');
307
308
                            return ['@server/view', 'id' => $server['id']];
309 1
                        },
310
                    ],
311
                ],
312
            ],
313
            'software-settings' => [
314
                'class' => SmartUpdateAction::class,
315 1
                'success' => Yii::t('hipanel:server', 'Software properties was changed'),
316 1
                'view' => 'softwareSettings',
317 1
                'scenario' => 'default',
318 1
                'on beforeFetch' => function (Event $event) {
319
                    /** @var \hipanel\actions\SearchAction $action */
320
                    $action = $event->sender;
321
                    /** @var ServerQuery $query */
322
                    $query = $action->getDataProvider()->query;
323
                    $query->withSoftwareSettings();
324 1
                },
325 1
                'on beforeLoad' => function (Event $event) {
326
                    /** @var Action $action */
327
                    $action = $event->sender;
328
329
                    $action->collection->setModel(SoftwareSettings::class);
330 1
                },
331
                'POST html' => [
332
                    'save' => true,
333
                    'success' => [
334
                        'class' => RedirectAction::class,
335 1
                        'url' => function () {
336
                            $server = Yii::$app->request->post('SoftwareSettings');
337
338
                            return ['@server/view', 'id' => $server['id']];
339 1
                        },
340
                    ],
341
                ],
342
            ],
343
            'monitoring-settings' => [
344
                'class' => SmartUpdateAction::class,
345 1
                'success' => Yii::t('hipanel:server', 'Monitoring properties was changed'),
346 1
                'view' => 'monitoringSettings',
347 1
                'scenario' => 'default',
348 1
                'on beforeFetch' => function (Event $event) {
349
                    /** @var \hipanel\actions\SearchAction $action */
350
                    $action = $event->sender;
351
                    $dataProvider = $action->getDataProvider();
352
                    $dataProvider->query->joinWith(['monitoringSettings']);
353
                    $dataProvider->query
354
                        ->andWhere(['with_monitoringSettings' => 1])->select(['*']);
355 1
                },
356 1
                'on beforeLoad' => function (Event $event) {
357
                    /** @var Action $action */
358
                    $action = $event->sender;
359
360
                    $action->collection->setModel(MonitoringSettings::class);
361 1
                },
362 1
                'data' => function ($action) {
363
                    return [
364
                        'nicMediaOptions' => $action->controller->getFullFromRef('type,nic_media'),
365
                    ];
366 1
                },
367
                'POST html' => [
368
                    'save' => true,
369
                    'success' => [
370
                        'class' => RedirectAction::class,
371 1
                        'url' => function () {
372
                            $server = Yii::$app->request->post('MonitoringSettings');
373
374
                            return ['@server/view', 'id' => $server['id']];
375 1
                        },
376
                    ],
377
                ],
378
            ],
379
            'view' => [
380
                'class' => ViewAction::class,
381 1
                'on beforePerform' => function (Event $event) {
382
                    /** @var \hipanel\actions\SearchAction $action */
383
                    $action = $event->sender;
384
                    /** @var ServerQuery $query */
385
                    $query = $action->getDataProvider()->query;
386
                    $query
387
                        ->withSoftwareSettings()
388
                        ->withHardwareSettings()
389
                        ->withBindings()
390
                        ->withBlocking()
391
                        ->withUses()
392
                        ->withConsumptions()
393
                        ->joinWith(['switches']);
394
395
                    if (Yii::getAlias('@ip', false)) {
396
                        $query
397
                            ->joinWith(['ips'])
398
                            ->andWhere(['with_ips' => 1]);
399
                    }
400
401
                    // TODO: ipModule is not wise yet. Redo
402
                    $query
403
                        ->andWhere(['with_requests' => 1])
404
                        ->andWhere(['show_deleted' => 1])
405
                        ->andWhere(['with_discounts' => 1])
406
                        ->select(['*']);
407 1
                },
408 1
                'data' => function ($action) {
409
                    /**
410
                     * @var Action
411
                     * @var self $controller
412
                     * @var Server $model
413
                     */
414
                    $controller = $action->controller;
415
                    $model = $action->getModel();
416
                    $model->vnc = $controller->getVNCInfo($model);
417
418
                    $panels = $controller->getPanelTypes();
419
420
                    $cacheKeys = [__METHOD__, 'view', 'tariff', $model->tariff_id, Yii::$app->user->getId()];
421
                    $tariff = Yii::$app->cache->getOrSet($cacheKeys, function () use ($model) {
422
                        return Tariff::find()->where([
423
                            'id' => $model->tariff_id,
424
                            'show_final' => true,
425
                            'show_deleted' => true,
426
                            'with_resources' => true,
427
                        ])->joinWith('resources')->one();
428
                    });
429
430
                    $ispSupported = false;
431
                    if ($tariff !== null) {
432
                        foreach ($tariff->getResources() as $resource) {
433
                            if ($resource->type === 'isp' && $resource->quantity > 0) {
434
                                $ispSupported = true;
435
                            }
436
                        }
437
                    }
438
439
                    $osimages = $controller->getOsimages($model);
440
                    $groupedOsimages = ServerHelper::groupOsimages($osimages, $ispSupported);
441
442
                    if ($model->isLiveCDSupported()) {
443
                        $osimageslivecd = $controller->getOsimagesLiveCd();
444
                    }
445
446
                    $blockReasons = $controller->getBlockReasons();
447
448
                    return compact([
449
                        'model',
450
                        'osimages',
451
                        'osimageslivecd',
452
                        'groupedOsimages',
453
                        'panels',
454
                        'blockReasons',
455
                    ]);
456 1
                },
457
            ],
458
            'resources' => [
459
                'class' => ViewAction::class,
460 1
                'view' => 'resources',
461 1
                'on beforePerform' => function (Event $event) {
462
                    /** @var \hipanel\actions\SearchAction $action */
463
                    $action = $event->sender;
464
                    $dataProvider = $action->getDataProvider();
465
                    $dataProvider->query->withUses()->select(['*']);
466 1
                },
467 1
                'data' => function ($action) {
468
                    $model = $action->getModel();
469
                    list($chartsLabels, $chartsData) = $model->groupUsesForCharts();
470
471
                    return compact('model', 'chartsData', 'chartsLabels');
472 1
                }
473
            ],
474
            'requests-state' => [
475
                'class' => RequestStateAction::class,
476
                'model' => Server::class,
477
            ],
478
            'set-note' => [
479
                'class' => SmartUpdateAction::class,
480 1
                'view' => 'modal/_bulkSetNote',
481 1
                'success' => Yii::t('hipanel:server', 'Note changed'),
482 1
                'error' => Yii::t('hipanel:server', 'Failed to change note'),
483
            ],
484
            'set-label' => [
485
                'class' => SmartUpdateAction::class,
486 1
                'view' => 'modal/_bulkSetLabel',
487 1
                'success' => Yii::t('hipanel:server', 'Internal note changed'),
488 1
                'error' => Yii::t('hipanel:server', 'Failed to change internal note'),
489
            ],
490
            'set-lock' => [
491
                'class' => RenderAction::class,
492 1
                'success' => Yii::t('hipanel:server', 'Record was changed'),
493 1
                'error' => Yii::t('hipanel:server', 'Error occurred'),
494
                'POST pjax' => [
495
                    'save' => true,
496
                    'success' => [
497
                        'class' => ProxyAction::class,
498
                        'action' => 'index',
499
                    ],
500
                ],
501
                'POST' => [
502
                    'save' => true,
503
                    'success' => [
504
                        'class' => RenderJsonAction::class,
505 1
                        'return' => function ($action) {
506
                            /** @var \hipanel\actions\Action $action */
507
                            return $action->collection->models;
508 1
                        },
509
                    ],
510
                ],
511
            ],
512
            'enable-vnc' => [
513
                'class' => ViewAction::class,
514 1
                'view' => '_vnc',
515 1
                'data' => function ($action) {
516
                    $model = $action->getModel();
517
                    if ($model->canEnableVNC()) {
518
                        $model->vnc = $this->getVNCInfo($model, true);
519
                    }
520
521
                    return [];
522 1
                },
523
            ],
524
            'bulk-sale' => [
525
                'class' => SmartUpdateAction::class,
526 1
                'scenario' => 'sale',
527 1
                'view' => 'modal/_bulkSale',
528 1
                'success' => Yii::t('hipanel:server', 'Servers were sold'),
529
                'POST pjax' => [
530
                    'save' => true,
531
                    'success' => [
532
                        'class' => ProxyAction::class,
533
                        'action' => 'index',
534
                    ],
535
                ],
536 1
                'on beforeSave' => function (Event $event) {
537
                    /** @var \hipanel\actions\Action $action */
538
                    $action = $event->sender;
539
                    $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...
540
541
                    if ($request->isPost) {
542
                        $values = [];
543
                        foreach (['client_id', 'tariff_id', 'sale_time', 'move_accounts'] as $attribute) {
544
                            $value = $request->post($attribute);
545
                            if (!empty($value)) {
546
                                $values[$attribute] = $value;
547
                            }
548
                        }
549
                        foreach ($action->collection->models as $model) {
550
                            foreach ($values as $attr => $value) {
551
                                $model->setAttribute($attr, $value);
552
                            }
553
                        }
554
                    }
555 1
                },
556
            ],
557
            'set-one-type' => [
558
                'class' => SmartUpdateAction::class,
559 1
                'view' => 'setOneType',
560 1
                'success' => Yii::t('hipanel:server', 'Type was changed'),
561 1
                'error' => Yii::t('hipanel:server', 'Failed to change type'),
562 1
                'scenario' => 'set-type',
563 1
                'on beforeSave' => function (Event $event) {
564
                    /** @var \hipanel\actions\Action $action */
565
                    $action = $event->sender;
566
                    $servers = Yii::$app->request->post('Server');
567
                    $type = ArrayHelper::remove($servers, 'type');
568
                    foreach ($servers as $id => $server) {
569
                        $servers[$id]['type'] = $type;
570
                    }
571
                    $action->collection->setModel($this->newModel(['scenario' => 'set-type']));
572
                    $action->collection->load($servers);
573 1
                },
574
            ],
575
            'set-type' => [
576
                'class' => SmartUpdateAction::class,
577 1
                'view' => '_bulkSetType',
578 1
                'success' => Yii::t('hipanel:server', 'Type was changed'),
579 1
                'error' => Yii::t('hipanel:server', 'Failed to change type'),
580
            ],
581
            'reboot' => [
582
                'class' => SmartPerformAction::class,
583 1
                'success' => Yii::t('hipanel:server', 'Reboot task has been successfully added to queue'),
584 1
                'error' => Yii::t('hipanel:server', 'Error during the rebooting'),
585
            ],
586
            'reset' => [
587
                'class' => SmartPerformAction::class,
588 1
                'success' => Yii::t('hipanel:server', 'Reset task has been successfully added to queue'),
589 1
                'error' => Yii::t('hipanel:server', 'Error during the resetting'),
590
            ],
591
            'shutdown' => [
592
                'class' => SmartPerformAction::class,
593 1
                'success' => Yii::t('hipanel:server', 'Shutdown task has been successfully added to queue'),
594 1
                'error' => Yii::t('hipanel:server', 'Error during the shutting down'),
595
            ],
596
            'power-off' => [
597
                'class' => SmartPerformAction::class,
598 1
                'success' => Yii::t('hipanel:server', 'Power off task has been successfully added to queue'),
599 1
                'error' => Yii::t('hipanel:server', 'Error during the turning power off'),
600
            ],
601
            'power-on' => [
602
                'class' => SmartPerformAction::class,
603 1
                'success' => Yii::t('hipanel:server', 'Power on task has been successfully added to queue'),
604 1
                'error' => Yii::t('hipanel:server', 'Error during the turning power on'),
605
            ],
606
            'reset-password' => [
607
                'class' => SmartPerformAction::class,
608 1
                'success' => Yii::t('hipanel:server', 'Root password reset task has been successfully added to queue'),
609 1
                'error' => Yii::t('hipanel:server', 'Error during the resetting root password'),
610
            ],
611
            'enable-block' => [
612
                'class' => SmartPerformAction::class,
613 1
                'success' => Yii::t('hipanel:server', 'Server was blocked successfully'),
614 1
                'error' => Yii::t('hipanel:server', 'Error during the server blocking'),
615
                'POST html' => [
616
                    'save' => true,
617
                    'success' => [
618
                        'class' => RedirectAction::class,
619
                    ],
620
                ],
621 1
                'on beforeSave' => function (Event $event) {
622
                    /** @var \hipanel\actions\Action $action */
623
                    $action = $event->sender;
624
                    $type = Yii::$app->request->post('type');
625
                    $comment = Yii::$app->request->post('comment');
626
                    if (!empty($type)) {
627
                        foreach ($action->collection->models as $model) {
628
                            $model->setAttributes([
629
                                'type' => $type,
630
                                'comment' => $comment,
631
                            ]);
632
                        }
633
                    }
634 1
                },
635
            ],
636
            'bulk-enable-block-modal' => [
637
                'class' => PrepareBulkAction::class,
638 1
                'view' => 'modal/_bulkEnableBlock',
639 1
                'data' => function ($action, $data) {
640
                    return array_merge($data, [
641
                        'blockReasons' => $this->getBlockReasons(),
642
                    ]);
643 1
                },
644
            ],
645
            'disable-block' => [
646
                'class' => SmartPerformAction::class,
647 1
                'success' => Yii::t('hipanel:server', 'Server was unblocked successfully'),
648 1
                'error' => Yii::t('hipanel:server', 'Error during the server unblocking'),
649
                'POST html' => [
650
                    'save' => true,
651
                    'success' => [
652
                        'class' => RedirectAction::class,
653
                    ],
654
                ],
655 1
                'on beforeSave' => function (Event $event) {
656
                    /** @var \hipanel\actions\Action $action */
657
                    $action = $event->sender;
658
                    $type = Yii::$app->request->post('type');
659
                    $comment = Yii::$app->request->post('comment');
660
                    if (!empty($type)) {
661
                        foreach ($action->collection->models as $model) {
662
                            $model->setAttributes([
663
                                'comment' => $comment,
664
                                'type' => $type,
665
                            ]);
666
                        }
667
                    }
668 1
                },
669
            ],
670
            'bulk-disable-block-modal' => [
671
                'class' => PrepareBulkAction::class,
672 1
                'view' => 'modal/_bulkDisableBlock',
673 1
                'data' => function ($action, $data) {
674
                    return array_merge($data, [
675
                        'blockReasons' => $this->getBlockReasons(),
676
                    ]);
677 1
                },
678
            ],
679
            'refuse' => [
680
                'class' => SmartPerformAction::class,
681 1
                'success' => Yii::t('hipanel:server', 'You have refused the service'),
682 1
                'error' => Yii::t('hipanel:server', 'Error during the refusing the service'),
683
            ],
684
            'enable-autorenewal' => [
685
                'class' => SmartUpdateAction::class,
686 1
                'success' => Yii::t('hipanel:server', 'Server renewal enabled successfully'),
687 1
                'error' => Yii::t('hipanel:server', 'Error during the renewing the service'),
688
            ],
689
            'reinstall' => [
690
                'class' => SmartUpdateAction::class,
691 1
                'on beforeSave' => function (Event $event) {
692
                    /** @var Action $action */
693
                    $action = $event->sender;
694
                    foreach ($action->collection->models as $model) {
695
                        $model->osimage = Yii::$app->request->post('osimage');
696
                        $model->panel = Yii::$app->request->post('panel');
697
                    }
698 1
                },
699 1
                'success' => Yii::t('hipanel:server', 'Server reinstalling task has been successfully added to queue'),
700 1
                'error' => Yii::t('hipanel:server', 'Error during the server reinstalling'),
701
            ],
702
            'boot-live' => [
703
                'class' => SmartPerformAction::class,
704 1
                'on beforeSave' => function (Event $event) {
705
                    /** @var Action $action */
706
                    $action = $event->sender;
707
                    foreach ($action->collection->models as $model) {
708
                        $model->osimage = Yii::$app->request->post('osimage');
709
                    }
710 1
                },
711 1
                'success' => Yii::t('hipanel:server', 'Live CD booting task has been successfully added to queue'),
712 1
                'error' => Yii::t('hipanel:server', 'Error during the booting live CD'),
713
            ],
714
            'validate-hw-form' => [
715
                'class' => ValidateFormAction::class,
716
                'collection' => [
717
                    'class' => Collection::class,
718 1
                    'model' => new HardwareSettings(),
719
                ],
720
            ],
721
            'validate-crud-form' => [
722
                'class' => ValidateFormAction::class,
723
                'collection' => [
724
                    'class' => Collection::class,
725 1
                    'model' => new ServerForm(),
726
                ],
727
            ],
728
            'validate-assign-hubs-form' => [
729
                'class' => ValidateFormAction::class,
730
                'collection' => [
731
                    'class' => Collection::class,
732 1
                    'model' => new AssignHubsForm(),
733
                ],
734
            ],
735
            'validate-form' => [
736
                'class' => ValidateFormAction::class,
737
            ],
738
            'buy' => [
739
                'class' => RedirectAction::class,
740 1
                'url' => Yii::$app->params['organization.url'],
741
            ],
742
            'add-to-cart-renewal' => [
743
                'class' => AddToCartAction::class,
744
                'productClass' => ServerRenewProduct::class,
745
            ],
746
            'delete' => [
747
                'class' => SmartDeleteAction::class,
748 1
                'success' => Yii::t('hipanel:server', 'Server was deleted successfully'),
749 1
                'error' => Yii::t('hipanel:server', 'Failed to delete server'),
750
            ],
751
            'bulk-delete-modal' => [
752
                'class' => PrepareBulkAction::class,
753
                'view' => 'modal/_bulkDelete',
754
            ],
755
            'clear-resources' => [
756
                'class' => SmartPerformAction::class,
757 1
                'view' => '_clearResources',
758 1
                'success' => Yii::t('hipanel:server', 'Servers resources were cleared successfully'),
759 1
                'error' => Yii::t('hipanel:server', 'Error occurred during server resources flushing'),
760
            ],
761
            'clear-resources-modal' => [
762
                'class' => PrepareBulkAction::class,
763
                'view' => '_clearResources',
764
            ],
765
            'flush-switch-graphs' => [
766
                'class' => SmartPerformAction::class,
767 1
                'view' => '_clearResources',
768 1
                'success' => Yii::t('hipanel:server', 'Switch graphs were flushed successfully'),
769 1
                'error' => Yii::t('hipanel:server', 'Error occurred during switch graphs flushing'),
770
            ],
771
            'flush-switch-graphs-modal' => [
772
                'class' => PrepareBulkAction::class,
773
                'view' => '_flushSwitchGraphs',
774
            ],
775
        ]);
776
    }
777
778
    /**
779
     * Gets info of VNC on the server.
780
     *
781
     * @param Server $model
782
     * @param bool $enable
783
     * @throws ResponseErrorException
784
     * @return array
785
     */
786
    public function getVNCInfo($model, $enable = false)
787
    {
788
        if ($enable) {
789
            try {
790
                $vnc = Server::perform('enable-VNC', ['id' => $model->id]);
791
                $vnc['endTime'] = time() + 28800;
792
                Yii::$app->cache->set([__METHOD__, $model->id, $model], $vnc, 28800);
793
                $vnc['enabled'] = true;
794
            } catch (ResponseErrorException $e) {
795
                if ($e->getMessage() !== 'vds_has_tasks') {
796
                    throw $e;
797
                }
798
            }
799
        } else {
800
            if ($model->statuses['serverEnableVNC'] !== null && strtotime('+8 hours', strtotime($model->statuses['serverEnableVNC'])) > time()) {
801
                $vnc = Yii::$app->cache->getOrSet([__METHOD__, $model->id, $model], function () use ($model) {
802
                    return ArrayHelper::merge([
803
                        'endTime' => strtotime($model->statuses['serverEnableVNC']) + 28800,
804
                    ], Server::perform('enable-VNC', ['id' => $model->id]));
805
                }, 28800);
806
            }
807
            $vnc['enabled'] = $model->statuses['serverEnableVNC'] === null ? false : strtotime('+8 hours', strtotime($model->statuses['serverEnableVNC'])) > time();
808
        }
809
810
        return $vnc;
811
    }
812
813
    public function actionDrawChart()
814
    {
815
        $post = Yii::$app->request->post();
816
        $types = array_merge(['server_traf', 'server_traf95'], array_keys(ResourceConsumption::types()));
817
        if (!in_array($post['type'], $types, true)) {
818
            throw new NotFoundHttpException();
819
        }
820
821
        $searchModel = new ServerUseSearch();
822
        $dataProvider = $searchModel->search([]);
823
        $dataProvider->pagination = false;
824
        $dataProvider->query->action('get-uses');
825
        $dataProvider->query->andWhere($post);
826
        $models = $dataProvider->getModels();
827
828
        list($labels, $data) = ServerHelper::groupUsesForChart($models);
829
830
        return $this->renderAjax('_consumption', [
831
            'labels' => $labels,
832
            'data' => $data,
833
            'consumptionBase' => $post['type'],
834
        ]);
835
    }
836
837
    /**
838
     * Gets OS images.
839
     *
840
     * @param Server $model
841
     * @throws NotFoundHttpException
842
     * @return array
843
     */
844
    protected function getOsimages(Server $model = null)
845
    {
846
        if ($model !== null) {
847
            $type = $model->type;
848
        } else {
849
            $type = null;
850
        }
851
852
        $models = ServerHelper::getOsimages($type);
853
854
        if ($models === null) {
855
            throw new NotFoundHttpException('The requested page does not exist.');
856
        }
857
858
        return $models;
859
    }
860
861
    protected function getOsimagesLiveCd()
862
    {
863
        $models = Yii::$app->cache->getOrSet([__METHOD__], function () {
864
            return Osimage::findAll(['livecd' => true]);
865
        }, 3600);
866
867
        if ($models !== null) {
868
            return $models;
869
        }
870
871
        throw new NotFoundHttpException('The requested page does not exist.');
872
    }
873
874
    protected function getPanelTypes()
875
    {
876
        return ServerHelper::getPanels();
877
    }
878
879
    public function actionIsOperable($id)
880
    {
881
        Yii::$app->response->format = Response::FORMAT_JSON;
882
883
        $result = ['id' => $id, 'result' => false];
884
885
        if ($server = Server::find()->where(['id' => $id])->one()) {
886
            $result['result'] = $server->isOperable();
887
        }
888
889
        return $result;
890
    }
891
892
    protected function getFullFromRef($gtype)
893
    {
894
        $callingMethod = debug_backtrace()[1]['function'];
895
        $result = Yii::$app->get('cache')->getOrSet([$callingMethod], function () use ($gtype) {
896
            $result = ArrayHelper::map(Ref::find()->where([
897
                'gtype' => $gtype,
898
                'select' => 'full',
899
            ])->all(), 'id', function ($model) {
900
                return Yii::t('hipanel:server:hub', $model->label);
901
            });
902
903
            return $result;
904
        }, 86400 * 24); // 24 days
905
906
        return $result;
907
    }
908
}
909