Passed
Push — develop ( 5582a5...387532 )
by Портнов
05:04 queued 14s
created

AdvicesProcessor   A

Complexity

Total Complexity 35

Size/Duplication

Total Lines 282
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 35
eloc 136
c 2
b 0
f 0
dl 0
loc 282
rs 9.6

9 Methods

Rating   Name   Duplication   Size   Complexity  
A checkStorage() 0 23 6
A checkFirewalls() 0 17 3
A isConnected() 0 10 2
A checkPasswords() 0 18 3
A callBack() 0 13 2
A checkCorruptedFiles() 0 9 2
A checkUpdates() 0 31 4
A checkRegistration() 0 31 5
B getAdvicesAction() 0 55 8
1
<?php
2
/*
3
 * MikoPBX - free phone system for small business
4
 * Copyright (C) 2017-2020 Alexey Portnov and Nikolay Beketov
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation; either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License along with this program.
17
 * If not, see <https://www.gnu.org/licenses/>.
18
 */
19
20
namespace MikoPBX\PBXCoreREST\Lib;
21
22
use MikoPBX\Common\Providers\ManagedCacheProvider;
23
use MikoPBX\Core\System\Storage;
24
use MikoPBX\Common\Models\{NetworkFilters, PbxSettings};
25
use GuzzleHttp;
26
use Phalcon\Di\Injectable;
27
use SimpleXMLElement;
28
use MikoPBX\Service\Main;
29
30
/**
31
 * Class AdvicesProcessor
32
 *
33
 * @package MikoPBX\PBXCoreREST\Lib
34
 *
35
 * @property \MikoPBX\Common\Providers\LicenseProvider license
36
 * @property \MikoPBX\Common\Providers\TranslationProvider translation
37
 * @property \Phalcon\Config                               config
38
 */
39
class AdvicesProcessor extends Injectable
40
{
41
42
    /**
43
     * Processes Advices request
44
     *
45
     * @param array $request
46
     *
47
     * @return PBXApiResult
48
     */
49
    public static function callBack(array $request): PBXApiResult
50
    {
51
        $action = $request['action'];
52
        if('getList' === $action){
53
            $proc = new self();
54
            $res  = $proc->getAdvicesAction();
55
        }else{
56
            $res             = new PBXApiResult();
57
            $res->processor  = __METHOD__;
58
            $res->messages[] = "Unknown action - {$action} in advicesCallBack";
59
        }
60
        $res->function = $action;
61
        return $res;
62
    }
63
64
65
    /**
66
     * Makes list of notifications about system, firewall, passwords, wrong settings
67
     *
68
     * @return PBXApiResult
69
     */
70
    private function getAdvicesAction(): PBXApiResult
71
    {
72
        $res            = new PBXApiResult();
73
        $res->processor = __METHOD__;
74
75
        $arrMessages     = [];
76
        $arrAdvicesTypes = [
77
            ['type' => 'isConnected', 'cacheTime' => 15],
78
            ['type' => 'checkCorruptedFiles', 'cacheTime' => 15],
79
            ['type' => 'checkPasswords', 'cacheTime' => 15],
80
            ['type' => 'checkFirewalls', 'cacheTime' => 15],
81
            ['type' => 'checkStorage', 'cacheTime' => 120],
82
            ['type' => 'checkUpdates', 'cacheTime' => 3600],
83
            ['type' => 'checkRegistration', 'cacheTime' => 86400],
84
        ];
85
86
        $managedCache = $this->getDI()->getShared(ManagedCacheProvider::SERVICE_NAME);
87
        $language = PbxSettings::getValueByKey('WebAdminLanguage');
88
89
        foreach ($arrAdvicesTypes as $adviceType) {
90
            $currentAdvice = $adviceType['type'];
91
            $cacheTime     = $adviceType['cacheTime'];
92
            $cacheKey      = 'AdvicesProcessor:getAdvicesAction:'.$currentAdvice;
93
            if ($managedCache->has($cacheKey)) {
94
                $oldResult = json_decode($managedCache->get($cacheKey), true, 512, JSON_THROW_ON_ERROR);
95
                if ($language === $oldResult['LastLanguage']) {
96
                    $arrMessages[] = $oldResult['LastMessage'];
97
                    continue;
98
                }
99
            }
100
            $newResult = $this->$currentAdvice();
101
            if ( ! empty($newResult)) {
102
                $arrMessages[] = $newResult;
103
            }
104
            $managedCache->set(
105
                $cacheKey,
106
                json_encode([
107
                                'LastLanguage' => $language,
108
                                'LastMessage' => $newResult,
109
                            ], JSON_THROW_ON_ERROR),
110
                $cacheTime
111
            );
112
        }
113
        $res->success = true;
114
        $result       = [];
115
        foreach ($arrMessages as $message) {
116
            foreach ($message as $key => $value) {
117
                if ( ! empty($value)) {
118
                    $result[$key][] = $value;
119
                }
120
            }
121
        }
122
        $res->data['advices'] = $result;
123
124
        return $res;
125
    }
126
127
    /**
128
     * Check passwords quality
129
     *
130
     * @return array
131
     * @noinspection PhpUnusedPrivateMethodInspection
132
     */
133
    private function checkPasswords(): array
134
    {
135
        $messages           = [];
136
        $arrOfDefaultValues = PbxSettings::getDefaultArrayValues();
137
        if ($arrOfDefaultValues['WebAdminPassword'] === PbxSettings::getValueByKey('WebAdminPassword')) {
138
            $messages['warning'] = $this->translation->_(
139
                'adv_YouUseDefaultWebPassword',
140
                ['url' => $this->url->get('general-settings/modify/#/passwords')]
141
            );
142
        }
143
        if ($arrOfDefaultValues['SSHPassword'] === PbxSettings::getValueByKey('SSHPassword')) {
144
            $messages['warning'] = $this->translation->_(
145
                'adv_YouUseDefaultSSHPassword',
146
                ['url' => $this->url->get('general-settings/modify/#/ssh')]
147
            );
148
        }
149
150
        return $messages;
151
    }
152
153
    /**
154
     * Check passwords quality
155
     *
156
     * @return array
157
     * @noinspection PhpUnusedPrivateMethodInspection
158
     */
159
    private function checkCorruptedFiles(): array
160
    {
161
        $messages           = [];
162
        $files = Main::checkForCorruptedFiles();
163
        if (count($files) !== 0) {
164
            $messages['warning'] = $this->translation->_('The integrity of the system is broken', ['url' => '']).'. '.$this->translation->_('systemBrokenComment', ['url' => '']);
165
        }
166
167
        return $messages;
168
    }
169
170
    /**
171
     * Check firewall status
172
     *
173
     * @return array
174
     * @noinspection PhpUnusedPrivateMethodInspection
175
     */
176
    private function checkFirewalls(): array
177
    {
178
        $messages = [];
179
        if (PbxSettings::getValueByKey('PBXFirewallEnabled') === '0') {
180
            $messages['warning'] = $this->translation->_(
181
                'adv_FirewallDisabled',
182
                ['url' => $this->url->get('firewall/index/')]
183
            );
184
        }
185
        if (NetworkFilters::count() === 0) {
186
            $messages['warning'] = $this->translation->_(
187
                'adv_NetworksNotConfigured',
188
                ['url' => $this->url->get('firewall/index/')]
189
            );
190
        }
191
192
        return $messages;
193
    }
194
195
    /**
196
     * Check storage is mount and how many space available
197
     *
198
     * @return array
199
     *
200
     * @noinspection PhpUnusedPrivateMethodInspection
201
     */
202
    private function checkStorage(): array
203
    {
204
        $messages           = [];
205
        $st                 = new Storage();
206
        $storageDiskMounted = false;
207
        $disks              = $st->getAllHdd();
208
        foreach ($disks as $disk) {
209
            if (array_key_exists('mounted', $disk)
210
                && strpos($disk['mounted'], '/storage/usbdisk') !== false) {
211
                $storageDiskMounted = true;
212
                if ($disk['free_space'] < 500) {
213
                    $messages['warning']
214
                        = $this->translation->_(
215
                        'adv_StorageDiskRunningOutOfFreeSpace',
216
                        ['free' => $disk['free_space']]
217
                    );
218
                }
219
            }
220
        }
221
        if ($storageDiskMounted === false) {
222
            $messages['error'] = $this->translation->_('adv_StorageDiskUnMounted');
223
        }
224
        return $messages;
225
    }
226
227
    /**
228
     * Check new version PBX
229
     *
230
     * @return array
231
     * @throws \GuzzleHttp\Exception\GuzzleException
232
     * @noinspection PhpUnusedPrivateMethodInspection
233
     */
234
    private function checkUpdates(): array
235
    {
236
        $messages   = [];
237
        $PBXVersion = PbxSettings::getValueByKey('PBXVersion');
238
239
        $client = new GuzzleHttp\Client();
240
        $res    = $client->request(
241
            'POST',
242
            'https://releases.mikopbx.com/releases/v1/mikopbx/ifNewReleaseAvailable',
243
            [
244
                'form_params' => [
245
                    'PBXVER' => $PBXVersion,
246
                ],
247
            ]
248
        );
249
        if ($res->getStatusCode() !== 200) {
250
            return [];
251
        }
252
253
        $answer = json_decode($res->getBody(), false);
254
        if ($answer !== null && $answer->newVersionAvailable === true) {
255
            $messages['info'] = $this->translation->_(
256
                'adv_AvailableNewVersionPBX',
257
                [
258
                    'url' => $this->url->get('update/index/'),
259
                    'ver' => $answer->version,
260
                ]
261
            );
262
        }
263
264
        return $messages;
265
    }
266
267
    /**
268
     * Check mikopbx license status
269
     *
270
     * @noinspection PhpUnusedPrivateMethodInspection
271
     */
272
    private function checkRegistration(): array
273
    {
274
        $messages = [];
275
        $licKey   = PbxSettings::getValueByKey('PBXLicense');
276
        $language   = PbxSettings::getValueByKey('WebAdminLanguage');
277
278
        if ( ! empty($licKey)) {
279
            $checkBaseFeature = $this->license->featureAvailable(33);
280
            if ($checkBaseFeature['success'] === false) {
281
                if ($language === 'ru') {
282
                    $url = 'https://wiki.mikopbx.com/licensing#faq_chavo';
283
                } else {
284
                    $url = "https://wiki.mikopbx.com/{$language}:licensing#faq_chavo";
285
                }
286
                $textError = (string)($checkBaseFeature['error']??'');
287
                $messages['warning'] = $this->translation->_(
288
                    'adv_ThisCopyHasLicensingTroubles',
289
                    [
290
                        'url'   => $url,
291
                        'error' => $this->license->translateLicenseErrorMessage($textError),
292
                    ]
293
                );
294
            }
295
296
            $licenseInfo = $this->license->getLicenseInfo($licKey);
297
            if ($licenseInfo instanceof SimpleXMLElement) {
298
                file_put_contents('/tmp/licenseInfo', json_encode($licenseInfo->attributes()));
299
            }
300
        }
301
302
        return $messages;
303
    }
304
305
    /**
306
     * Checks whether internet connection is available or not
307
     *
308
     * @return array
309
     * @noinspection PhpUnusedPrivateMethodInspection
310
     */
311
    private function isConnected(): array
312
    {
313
        $messages = [];
314
        $connected = @fsockopen("www.google.com", 443);
315
        if ($connected !== false) {
316
            fclose($connected);
317
        } else {
318
            $messages['warning'] = $this->translation->_('adv_ProblemWithInternetConnection');
319
        }
320
        return $messages;
321
    }
322
}