Passed
Push — develop ( 59cb4c...debec8 )
by Nikolay
06:26 queued 31s
created

AdvicesController::checkStorage()   C

Complexity

Conditions 12
Paths 7

Size

Total Lines 39
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 26
dl 0
loc 39
rs 6.9666
c 0
b 0
f 0
cc 12
nc 7
nop 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Copyright (C) MIKO LLC - All Rights Reserved
4
 * Unauthorized copying of this file, via any medium is strictly prohibited
5
 * Proprietary and confidential
6
 * Written by Nikolay Beketov, 11 2018
7
 *
8
 */
9
10
namespace MikoPBX\AdminCabinet\Controllers;
11
12
use MikoPBX\Common\Models\{NetworkFilters, PbxSettings};
13
use GuzzleHttp;
14
use SimpleXMLElement;
15
16
/**
17
 * @property \MikoPBX\Service\License license
18
 */
19
class AdvicesController extends BaseController
20
{
21
22
    /**
23
     * Вызывается через AJAX периодически из веб интервейса,
24
     * формирует список советов для администратора PBX о неправильных настройках
25
     */
26
    public function getAdvicesAction(): void
27
    {
28
        $arrMessages     = [[]];
29
        $arrAdvicesTypes = [
30
            ['type' => 'checkPasswords', 'cacheTime' => 15],
31
            ['type' => 'checkFirewalls', 'cacheTime' => 15],
32
            ['type' => 'checkStorage', 'cacheTime' => 120],
33
            ['type' => 'checkUpdates', 'cacheTime' => 3600],
34
            ['type' => 'checkRegistration', 'cacheTime' => 86400],
35
        ];
36
        $language        = $this->getSessionData('WebAdminLanguage');
37
        $roSession       = $this->sessionRO;
38
39
        foreach ($arrAdvicesTypes as $adviceType) {
40
            $currentAdvice = $adviceType['type'];
41
            if ($roSession !== null && array_key_exists($currentAdvice, $roSession)) {
42
                $oldResult = json_decode($roSession[$currentAdvice], true);
43
                if ($language === $oldResult['LastLanguage']
44
                    && (time() - $oldResult['LastTimeStamp'] < $adviceType['cacheTime'])) {
45
                    $arrMessages[] = $oldResult['LastMessage'];
46
                    continue;
47
                }
48
            }
49
            $newResult = $this->$currentAdvice();
50
            if ( ! empty($newResult)) {
51
                $arrMessages[] = $newResult;
52
            }
53
            $this->session->set(
54
                $currentAdvice,
55
                json_encode(
56
                    [
57
                        'LastLanguage'  => $language,
58
                        'LastMessage'   => $newResult,
59
                        'LastTimeStamp' => time(),
60
                    ],
61
                    JSON_THROW_ON_ERROR
62
                )
63
            );
64
        }
65
        $this->view->success = true;
66
        $result              = [];
67
        foreach ($arrMessages as $message) {
68
            foreach ($message as $key => $value) {
69
                if ( ! empty($value)) {
70
                    $result[$key][] = $value;
71
                }
72
            }
73
        }
74
        $this->view->message = $result;
75
    }
76
77
    /**
78
     * Проверка установлены ли корректно пароли
79
     *
80
     * @return array
81
     */
82
    private function checkPasswords(): array
83
    {
84
        $messages           = [];
85
        $arrOfDefaultValues = PbxSettings::getDefaultArrayValues();
86
        if ($arrOfDefaultValues['WebAdminPassword']
87
            === PbxSettings::getValueByKey('WebAdminPassword')) {
88
            $messages['warning'] = $this->translation->_(
89
                'adv_YouUseDefaultWebPassword',
90
                ['url' => $this->url->get('general-settings/modify/#/passwords')]
91
            );
92
        }
93
        if ($arrOfDefaultValues['SSHPassword']
94
            === PbxSettings::getValueByKey('SSHPassword')) {
95
            $messages['warning'] = $this->translation->_(
96
                'adv_YouUseDefaultSSHPassword',
97
                ['url' => $this->url->get('general-settings/modify/#/ssh')]
98
            );
99
        }
100
101
        return $messages ?? [];
102
    }
103
104
    /**
105
     * Проверка включен ли Firewall
106
     *
107
     * @return array
108
     */
109
    private function checkFirewalls(): array
110
    {
111
        if (PbxSettings::getValueByKey('PBXFirewallEnabled') === '0') {
112
            $messages['warning'] = $this->translation->_(
0 ignored issues
show
Comprehensibility Best Practice introduced by
$messages was never initialized. Although not strictly required by PHP, it is generally a good practice to add $messages = array(); before regardless.
Loading history...
113
                'adv_FirewallDisabled',
114
                ['url' => $this->url->get('firewall/index/')]
115
            );
116
        }
117
        if (NetworkFilters::count() === 0) {
118
            $messages['warning'] = $this->translation->_(
119
                'adv_NetworksNotConfigured',
120
                ['url' => $this->url->get('firewall/index/')]
121
            );
122
        }
123
124
        return $messages ?? [];
125
    }
126
127
    /**
128
     * Проверка подключен ли диск для хранения данных
129
     *
130
     * @return array
131
     * @throws \GuzzleHttp\Exception\GuzzleException
132
     */
133
    private function checkStorage(): array
134
    {
135
        if ( ! is_array($_COOKIE) || ! array_key_exists(session_name(), $_COOKIE)) {
136
            return [];
137
        }
138
139
        $WEBPort = PbxSettings::getValueByKey('WEBPort');
140
        $url     = "http://127.0.0.1:{$WEBPort}/pbxcore/api/storage/list";
141
        $client  = new GuzzleHttp\Client();
142
        $res     = $client->request('GET', $url);
143
        if ($res->getStatusCode() !== 200) {
144
            return [];
145
        }
146
        $storageList = json_decode($res->getBody(), false);
147
        if ($storageList !== null && property_exists($storageList, 'data')) {
148
            $storageDiskMounted = false;
149
            $disks              = $storageList->data;
150
            if ( ! is_array($disks)) {
151
                $disks = [$disks];
152
            }
153
            foreach ($disks as $disk) {
154
                if (property_exists($disk, 'mounted')
155
                    && strpos($disk->mounted, '/storage/usbdisk') !== false) {
156
                    $storageDiskMounted = true;
157
                    if ($disk->free_space < 500) {
158
                        $messages['warning']
159
                            = $this->translation->_(
160
                            'adv_StorageDiskRunningOutOfFreeSpace',
161
                            ['free' => $disk->free_space]
162
                        );
163
                    }
164
                }
165
            }
166
            if ($storageDiskMounted === false) {
167
                $messages['error'] = $this->translation->_('adv_StorageDiskUnMounted');
168
            }
169
        }
170
171
        return $messages ?? [];
172
    }
173
174
    /**
175
     * Проверка наличия обновлений
176
     *
177
     * @return array
178
     */
179
    private
180
    function checkUpdates(): array
181
    {
182
        $PBXVersion = $this->getSessionData('PBXVersion');
183
184
        $client = new GuzzleHttp\Client();
185
        $res    = $client->request(
186
            'POST',
187
            'https://update.askozia.ru/',
188
            [
189
                'form_params' => [
190
                    'TYPE'   => 'FIRMWAREGETNEWS',
191
                    'PBXVER' => $PBXVersion,
192
                ],
193
            ]
194
        );
195
        if ($res->getStatusCode() !== 200) {
196
            return [];
197
        }
198
199
        $answer = json_decode($res->getBody(), false);
200
        if ($answer !== null && $answer->newVersionAvailable === true) {
201
            $messages['info'] = $this->translation->_(
0 ignored issues
show
Comprehensibility Best Practice introduced by
$messages was never initialized. Although not strictly required by PHP, it is generally a good practice to add $messages = array(); before regardless.
Loading history...
202
                'adv_AvailableNewVersionPBX',
203
                [
204
                    'url' => $this->url->get('update/index/'),
205
                    'ver' => $answer->version,
206
                ]
207
            );
208
        }
209
210
        return $messages ?? [];
211
    }
212
213
    /**
214
     * Проверка зарегистрирована ли копия Askozia
215
     *
216
     */
217
    private
218
    function checkRegistration(): array
219
    {
220
        $licKey = PbxSettings::getValueByKey('PBXLicense');
221
        if ( ! empty($licKey)) {
222
            $checkBaseFeature = $this->license->featureAvailable(33);
223
            if ($checkBaseFeature['success'] === false) {
224
                if ($this->language === 'ru') {
225
                    $url = 'https://wiki.mikopbx.com/licensing#faq_chavo';
226
                } else {
227
                    $url = "https://wiki.mikopbx.com/{$this->language}:licensing#faq_chavo";
228
                }
229
230
                $messages['warning'] = $this->translation->_(
0 ignored issues
show
Comprehensibility Best Practice introduced by
$messages was never initialized. Although not strictly required by PHP, it is generally a good practice to add $messages = array(); before regardless.
Loading history...
231
                    'adv_ThisCopyHasLicensingTroubles',
232
                    [
233
                        'url'   => $url,
234
                        'error' => $this->license->translateLicenseErrorMessage($checkBaseFeature['error']),
235
                    ]
236
                );
237
            }
238
239
            $licenseInfo = $this->license->getLicenseInfo($licKey);
240
            if ($licenseInfo instanceof SimpleXMLElement) {
241
                file_put_contents('/tmp/licenseInfo', json_encode($licenseInfo->attributes()));
242
            }
243
        }
244
245
        return $messages ?? [];
246
    }
247
}