Passed
Pull Request — master (#20)
by Nikolay
04:51
created

AdvicesProcessor::checkStorage()   A

Complexity

Conditions 6
Paths 8

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 16
dl 0
loc 23
rs 9.1111
c 0
b 0
f 0
cc 6
nc 8
nop 0
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\PBXCoreREST\Lib;
11
12
use MikoPBX\Core\System\Storage;
13
use MikoPBX\Common\Models\{NetworkFilters, PbxSettings};
14
use GuzzleHttp;
15
use Phalcon\Di\Injectable;
16
use SimpleXMLElement;
17
18
/**
19
 * Class AdvicesProcessor
20
 *
21
 * @package MikoPBX\PBXCoreREST\Lib
22
 *
23
 * @property \MikoPBX\Common\Providers\LicenseProvider license
24
 * @property \MikoPBX\Common\Providers\TranslationProvider translation
25
 * @property \Phalcon\Config                               config
26
 */
27
class AdvicesProcessor extends Injectable
28
{
29
30
    /**
31
     * Processes Advices request
32
     *
33
     * @param array $request
34
     *
35
     * @return \MikoPBX\PBXCoreREST\Lib\PBXApiResult
36
     */
37
    public static function callBack(array $request): PBXApiResult
38
    {
39
        $action = $request['action'];
40
41
        switch ($action) {
42
            case 'getList':
43
                $proc = new AdvicesProcessor();
44
                $res  = $proc->getAdvicesAction();
45
                break;
46
            default:
47
                $res             = new PBXApiResult();
48
                $res->processor  = __METHOD__;
49
                $res->messages[] = "Unknown action - {$action} in advicesCallBack";
50
                break;
51
        }
52
53
        $res->function = $action;
54
55
        return $res;
56
    }
57
58
59
    /**
60
     * Makes list of notifications about system, firewall, passwords, wrong settings
61
     *
62
     * @return \MikoPBX\PBXCoreREST\Lib\PBXApiResult
63
     */
64
    private function getAdvicesAction(): PBXApiResult
65
    {
66
        $res            = new PBXApiResult();
67
        $res->processor = __METHOD__;
68
69
        $arrMessages     = [];
70
        $arrAdvicesTypes = [
71
            ['type' => 'isConnected', 'cacheTime' => 15],
72
            ['type' => 'checkPasswords', 'cacheTime' => 15],
73
            ['type' => 'checkFirewalls', 'cacheTime' => 15],
74
            ['type' => 'checkStorage', 'cacheTime' => 120],
75
            ['type' => 'checkUpdates', 'cacheTime' => 3600],
76
            ['type' => 'checkRegistration', 'cacheTime' => 86400],
77
        ];
78
79
        $managedCache = $this->getDI()->getShared('managedCache');
80
81
        $language = PbxSettings::getValueByKey('WebAdminLanguage');
82
83
        foreach ($arrAdvicesTypes as $adviceType) {
84
            $currentAdvice = $adviceType['type'];
85
            $cacheTime     = $adviceType['cacheTime'];
86
            if ($managedCache->has($currentAdvice)) {
87
                $oldResult = json_decode($managedCache->get($currentAdvice), true);
88
                if ($language === $oldResult['LastLanguage']) {
89
                    $arrMessages[] = $oldResult['LastMessage'];
90
                    continue;
91
                }
92
            }
93
            $newResult = $this->$currentAdvice();
94
            if ( ! empty($newResult)) {
95
                $arrMessages[] = $newResult;
96
            }
97
            $managedCache->set(
98
                $currentAdvice,
99
                json_encode(
100
                    [
101
                        'LastLanguage' => $language,
102
                        'LastMessage'  => $newResult,
103
                    ]
104
                ),
105
                $cacheTime
106
            );
107
        }
108
        $res->success = true;
109
        $result       = [];
110
        foreach ($arrMessages as $message) {
111
            foreach ($message as $key => $value) {
112
                if ( ! empty($value)) {
113
                    $result[$key][] = $value;
114
                }
115
            }
116
        }
117
        $res->data['advices'] = $result;
118
119
        return $res;
120
    }
121
122
    /**
123
     * Check passwords quality
124
     *
125
     * @return array
126
     */
127
    private function checkPasswords(): array
128
    {
129
        $messages           = [];
130
        $arrOfDefaultValues = PbxSettings::getDefaultArrayValues();
131
        if ($arrOfDefaultValues['WebAdminPassword'] === PbxSettings::getValueByKey('WebAdminPassword')) {
132
            $messages['warning'] = $this->translation->_(
133
                'adv_YouUseDefaultWebPassword',
134
                ['url' => $this->url->get('general-settings/modify/#/passwords')]
135
            );
136
        }
137
        if ($arrOfDefaultValues['SSHPassword'] === PbxSettings::getValueByKey('SSHPassword')) {
138
            $messages['warning'] = $this->translation->_(
139
                'adv_YouUseDefaultSSHPassword',
140
                ['url' => $this->url->get('general-settings/modify/#/ssh')]
141
            );
142
        }
143
144
        return $messages;
145
    }
146
147
    /**
148
     * Check firewall status
149
     *
150
     * @return array
151
     */
152
    private function checkFirewalls(): array
153
    {
154
        $messages = [];
155
        if (PbxSettings::getValueByKey('PBXFirewallEnabled') === '0') {
156
            $messages['warning'] = $this->translation->_(
157
                'adv_FirewallDisabled',
158
                ['url' => $this->url->get('firewall/index/')]
159
            );
160
        }
161
        if (NetworkFilters::count() === 0) {
162
            $messages['warning'] = $this->translation->_(
163
                'adv_NetworksNotConfigured',
164
                ['url' => $this->url->get('firewall/index/')]
165
            );
166
        }
167
168
        return $messages;
169
    }
170
171
    /**
172
     * Check storage is mount and how many space available
173
     *
174
     * @return array
175
     *
176
     */
177
    private function checkStorage(): array
178
    {
179
        $messages           = [];
180
        $st                 = new Storage();
181
        $storageDiskMounted = false;
182
        $disks              = $st->getAllHdd();
183
        foreach ($disks as $disk) {
184
            if (array_key_exists('mounted', $disk)
185
                && strpos($disk['mounted'], '/storage/usbdisk') !== false) {
186
                $storageDiskMounted = true;
187
                if ($disk['free_space'] < 500) {
188
                    $messages['warning']
189
                        = $this->translation->_(
190
                        'adv_StorageDiskRunningOutOfFreeSpace',
191
                        ['free' => $disk['free_space']]
192
                    );
193
                }
194
            }
195
        }
196
        if ($storageDiskMounted === false) {
197
            $messages['error'] = $this->translation->_('adv_StorageDiskUnMounted');
198
        }
199
        return $messages;
200
    }
201
202
    /**
203
     * Check new version PBX
204
     *
205
     * @return array
206
     * @throws \GuzzleHttp\Exception\GuzzleException
207
     */
208
    private function checkUpdates(): array
209
    {
210
        $messages   = [];
211
        $PBXVersion = PbxSettings::getValueByKey('PBXVersion');
212
213
        $client = new GuzzleHttp\Client();
214
        $res    = $client->request(
215
            'POST',
216
            'https://update.askozia.ru/',
217
            [
218
                'form_params' => [
219
                    'TYPE'   => 'FIRMWAREGETNEWS',
220
                    'PBXVER' => $PBXVersion,
221
                ],
222
            ]
223
        );
224
        if ($res->getStatusCode() !== 200) {
225
            return [];
226
        }
227
228
        $answer = json_decode($res->getBody(), false);
229
        if ($answer !== null && $answer->newVersionAvailable === true) {
230
            $messages['info'] = $this->translation->_(
231
                'adv_AvailableNewVersionPBX',
232
                [
233
                    'url' => $this->url->get('update/index/'),
234
                    'ver' => $answer->version,
235
                ]
236
            );
237
        }
238
239
        return $messages;
240
    }
241
242
    /**
243
     * Check mikopbx license status
244
     *
245
     */
246
    private function checkRegistration(): array
247
    {
248
        $messages = [];
249
        $licKey   = PbxSettings::getValueByKey('PBXLicense');
250
        $language   = PbxSettings::getValueByKey('WebAdminLanguage');
251
252
        if ( ! empty($licKey)) {
253
            $checkBaseFeature = $this->license->featureAvailable(33);
254
            if ($checkBaseFeature['success'] === false) {
255
                if ($language === 'ru') {
256
                    $url = 'https://wiki.mikopbx.com/licensing#faq_chavo';
257
                } else {
258
                    $url = "https://wiki.mikopbx.com/{$language}:licensing#faq_chavo";
259
                }
260
261
                $messages['warning'] = $this->translation->_(
262
                    'adv_ThisCopyHasLicensingTroubles',
263
                    [
264
                        'url'   => $url,
265
                        'error' => $this->license->translateLicenseErrorMessage($checkBaseFeature['error']),
266
                    ]
267
                );
268
            }
269
270
            $licenseInfo = $this->license->getLicenseInfo($licKey);
271
            if ($licenseInfo instanceof SimpleXMLElement) {
272
                file_put_contents('/tmp/licenseInfo', json_encode($licenseInfo->attributes()));
273
            }
274
        }
275
276
        return $messages;
277
    }
278
279
    /**
280
     * Checks whether internet connection is available or not
281
     *
282
     * @return array
283
     */
284
    private function isConnected(): array
285
    {
286
        $messages = [];
287
        $connected = @fsockopen("www.google.com", 443);
288
        if ($connected !== false) {
289
            fclose($connected);
290
        } else {
291
            $messages['warning'] = $this->translation->_('adv_ProblemWithInternetConnection');
292
        }
293
        return $messages;
294
    }
295
}