Passed
Push — develop ( de9fda...ff84ae )
by Nikolay
15:18
created

AdvicesProcessor::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
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 advicesCallBack(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' => 'checkPasswords', 'cacheTime' => 15],
72
            ['type' => 'checkFirewalls', 'cacheTime' => 15],
73
            ['type' => 'checkStorage', 'cacheTime' => 120],
74
            ['type' => 'checkUpdates', 'cacheTime' => 3600],
75
            ['type' => 'checkRegistration', 'cacheTime' => 86400],
76
        ];
77
78
        $managedCache = $this->getDI()->getShared('managedCache');
79
80
        $language = PbxSettings::getValueByKey('WebAdminLanguage');
81
82
        foreach ($arrAdvicesTypes as $adviceType) {
83
            $currentAdvice = $adviceType['type'];
84
            $cacheTime     = $adviceType['cacheTime'];
85
            if ($managedCache->has($currentAdvice)) {
86
                $oldResult = json_decode($managedCache->get($currentAdvice), true);
87
                if ($language === $oldResult['LastLanguage']) {
88
                    $arrMessages[] = $oldResult['LastMessage'];
89
                    continue;
90
                }
91
            }
92
            $newResult = $this->$currentAdvice();
93
            if ( ! empty($newResult)) {
94
                $arrMessages[] = $newResult;
95
            }
96
            $managedCache->set(
97
                $currentAdvice,
98
                json_encode(
99
                    [
100
                        'LastLanguage' => $language,
101
                        'LastMessage'  => $newResult,
102
                    ]
103
                ),
104
                $cacheTime
105
            );
106
        }
107
        $res->success = true;
108
        $result       = [];
109
        foreach ($arrMessages as $message) {
110
            foreach ($message as $key => $value) {
111
                if ( ! empty($value)) {
112
                    $result[$key][] = $value;
113
                }
114
            }
115
        }
116
        $res->data['advices'] = $result;
117
118
        return $res;
119
    }
120
121
    /**
122
     * Check passwords quality
123
     *
124
     * @return array
125
     */
126
    private function checkPasswords(): array
127
    {
128
        $messages           = [];
129
        $arrOfDefaultValues = PbxSettings::getDefaultArrayValues();
130
        if ($arrOfDefaultValues['WebAdminPassword'] === PbxSettings::getValueByKey('WebAdminPassword')) {
131
            $messages['warning'] = $this->translation->_(
132
                'adv_YouUseDefaultWebPassword',
133
                ['url' => $this->url->get('general-settings/modify/#/passwords')]
134
            );
135
        }
136
        if ($arrOfDefaultValues['SSHPassword'] === PbxSettings::getValueByKey('SSHPassword')) {
137
            $messages['warning'] = $this->translation->_(
138
                'adv_YouUseDefaultSSHPassword',
139
                ['url' => $this->url->get('general-settings/modify/#/ssh')]
140
            );
141
        }
142
143
        return $messages;
144
    }
145
146
    /**
147
     * Check firewall status
148
     *
149
     * @return array
150
     */
151
    private function checkFirewalls(): array
152
    {
153
        $messages = [];
154
        if (PbxSettings::getValueByKey('PBXFirewallEnabled') === '0') {
155
            $messages['warning'] = $this->translation->_(
156
                'adv_FirewallDisabled',
157
                ['url' => $this->url->get('firewall/index/')]
158
            );
159
        }
160
        if (NetworkFilters::count() === 0) {
161
            $messages['warning'] = $this->translation->_(
162
                'adv_NetworksNotConfigured',
163
                ['url' => $this->url->get('firewall/index/')]
164
            );
165
        }
166
167
        return $messages;
168
    }
169
170
    /**
171
     * Check storage is mount and how many space available
172
     *
173
     * @return array
174
     *
175
     */
176
    private function checkStorage(): array
177
    {
178
        $messages           = [];
179
        $st                 = new Storage();
180
        $storageDiskMounted = false;
181
        $disks              = $st->getAllHdd();
182
        if ( ! is_array($disks)) {
0 ignored issues
show
introduced by
The condition is_array($disks) is always true.
Loading history...
183
            $disks = [$disks];
184
        }
185
        foreach ($disks as $disk) {
186
            if (array_key_exists('mounted', $disk)
187
                && strpos($disk['mounted'], '/storage/usbdisk') !== false) {
188
                $storageDiskMounted = true;
189
                if ($disk['free_space'] < 500) {
190
                    $messages['warning']
191
                        = $this->translation->_(
192
                        'adv_StorageDiskRunningOutOfFreeSpace',
193
                        ['free' => $disk['free_space']]
194
                    );
195
                }
196
            }
197
        }
198
        if ($storageDiskMounted === false) {
199
            $messages['error'] = $this->translation->_('adv_StorageDiskUnMounted');
200
        }
201
        return $messages;
202
    }
203
204
    /**
205
     * Check new version PBX
206
     *
207
     * @return array
208
     * @throws \GuzzleHttp\Exception\GuzzleException
209
     */
210
    private function checkUpdates(): array
211
    {
212
        $messages   = [];
213
        $PBXVersion = PbxSettings::getValueByKey('PBXVersion');
214
215
        $client = new GuzzleHttp\Client();
216
        $res    = $client->request(
217
            'POST',
218
            'https://update.askozia.ru/',
219
            [
220
                'form_params' => [
221
                    'TYPE'   => 'FIRMWAREGETNEWS',
222
                    'PBXVER' => $PBXVersion,
223
                ],
224
            ]
225
        );
226
        if ($res->getStatusCode() !== 200) {
227
            return [];
228
        }
229
230
        $answer = json_decode($res->getBody(), false);
231
        if ($answer !== null && $answer->newVersionAvailable === true) {
232
            $messages['info'] = $this->translation->_(
233
                'adv_AvailableNewVersionPBX',
234
                [
235
                    'url' => $this->url->get('update/index/'),
236
                    'ver' => $answer->version,
237
                ]
238
            );
239
        }
240
241
        return $messages;
242
    }
243
244
    /**
245
     * Check mikopbx license status
246
     *
247
     */
248
    private function checkRegistration(): array
249
    {
250
        $messages = [];
251
        $licKey   = PbxSettings::getValueByKey('PBXLicense');
252
        $language   = PbxSettings::getValueByKey('WebAdminLanguage');
253
254
        if ( ! empty($licKey)) {
255
            $checkBaseFeature = $this->license->featureAvailable(33);
256
            if ($checkBaseFeature['success'] === false) {
257
                if ($language === 'ru') {
258
                    $url = 'https://wiki.mikopbx.com/licensing#faq_chavo';
259
                } else {
260
                    $url = "https://wiki.mikopbx.com/{$language}:licensing#faq_chavo";
261
                }
262
263
                $messages['warning'] = $this->translation->_(
264
                    'adv_ThisCopyHasLicensingTroubles',
265
                    [
266
                        'url'   => $url,
267
                        'error' => $this->license->translateLicenseErrorMessage($checkBaseFeature['error']),
268
                    ]
269
                );
270
            }
271
272
            $licenseInfo = $this->license->getLicenseInfo($licKey);
273
            if ($licenseInfo instanceof SimpleXMLElement) {
0 ignored issues
show
introduced by
$licenseInfo is never a sub-type of SimpleXMLElement.
Loading history...
274
                file_put_contents('/tmp/licenseInfo', json_encode($licenseInfo->attributes()));
275
            }
276
        }
277
278
        return $messages;
279
    }
280
}