Passed
Push — develop ( 2448c8...de9fda )
by Nikolay
06:00 queued 10s
created

AdvicesProcessor::getAdvicesAction()   B

Complexity

Conditions 8
Paths 24

Size

Total Lines 55
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 36
c 0
b 0
f 0
dl 0
loc 55
rs 8.0995
cc 8
nc 24
nop 0

How to fix   Long Method   

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\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
    public string $baseUri = '';
31
32
    /**
33
     * AdvicesProcessor constructor.
34
     *
35
     */
36
    public function __construct()
37
    {
38
        $this->baseUri = $this->config->path('adminApplication.baseUri');
39
    }
40
41
42
    /**
43
     * Processes Advices request
44
     *
45
     * @param array $request
46
     *
47
     * @return \MikoPBX\PBXCoreREST\Lib\PBXApiResult
48
     */
49
    public static function advicesCallBack(array $request): PBXApiResult
50
    {
51
        $action = $request['action'];
52
53
        switch ($action) {
54
            case 'getList':
55
                $proc = new AdvicesProcessor();
56
                $res  = $proc->getAdvicesAction();
57
                break;
58
            default:
59
                $res             = new PBXApiResult();
60
                $res->processor  = __METHOD__;
61
                $res->messages[] = "Unknown action - {$action} in advicesCallBack";
62
                break;
63
        }
64
65
        $res->function = $action;
66
67
        return $res;
68
    }
69
70
71
    /**
72
     * Makes list of notifications about system, firewall, passwords, wrong settings
73
     *
74
     * @return \MikoPBX\PBXCoreREST\Lib\PBXApiResult
75
     */
76
    private function getAdvicesAction(): PBXApiResult
77
    {
78
        $res            = new PBXApiResult();
79
        $res->processor = __METHOD__;
80
81
        $arrMessages     = [];
82
        $arrAdvicesTypes = [
83
            ['type' => 'checkPasswords', 'cacheTime' => 15],
84
            ['type' => 'checkFirewalls', 'cacheTime' => 15],
85
            ['type' => 'checkStorage', 'cacheTime' => 120],
86
            ['type' => 'checkUpdates', 'cacheTime' => 3600],
87
            ['type' => 'checkRegistration', 'cacheTime' => 86400],
88
        ];
89
90
        $managedCache = $this->getDI()->getShared('managedCache');
91
92
        $language = PbxSettings::getValueByKey('WebAdminLanguage');
93
94
        foreach ($arrAdvicesTypes as $adviceType) {
95
            $currentAdvice = $adviceType['type'];
96
            $cacheTime     = $adviceType['cacheTime'];
97
            if ($managedCache->has($currentAdvice)) {
98
                $oldResult = json_decode($managedCache->get($currentAdvice), true);
99
                if ($language === $oldResult['LastLanguage']) {
100
                    $arrMessages[] = $oldResult['LastMessage'];
101
                    continue;
102
                }
103
            }
104
            $newResult = $this->$currentAdvice();
105
            if ( ! empty($newResult)) {
106
                $arrMessages[] = $newResult;
107
            }
108
            $managedCache->set(
109
                $currentAdvice,
110
                json_encode(
111
                    [
112
                        'LastLanguage' => $language,
113
                        'LastMessage'  => $newResult,
114
                    ]
115
                ),
116
                $cacheTime
117
            );
118
        }
119
        $res->success = true;
120
        $result       = [];
121
        foreach ($arrMessages as $message) {
122
            foreach ($message as $key => $value) {
123
                if ( ! empty($value)) {
124
                    $result[$key][] = $value;
125
                }
126
            }
127
        }
128
        $res->data['advices'] = $result;
129
130
        return $res;
131
    }
132
133
    /**
134
     * Check passwords quality
135
     *
136
     * @return array
137
     */
138
    private function checkPasswords(): array
139
    {
140
        $messages           = [];
141
        $arrOfDefaultValues = PbxSettings::getDefaultArrayValues();
142
        if ($arrOfDefaultValues['WebAdminPassword'] === PbxSettings::getValueByKey('WebAdminPassword')) {
143
            $messages['warning'] = $this->translation->_(
144
                'adv_YouUseDefaultWebPassword',
145
                ['url' => $this->url->get('general-settings/modify/#/passwords', null, null, $this->baseUri)]
0 ignored issues
show
Unused Code introduced by
The call to Phalcon\Url\UrlInterface::get() has too many arguments starting with $this->baseUri. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

145
                ['url' => $this->url->/** @scrutinizer ignore-call */ get('general-settings/modify/#/passwords', null, null, $this->baseUri)]

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
146
            );
147
        }
148
        if ($arrOfDefaultValues['SSHPassword'] === PbxSettings::getValueByKey('SSHPassword')) {
149
            $messages['warning'] = $this->translation->_(
150
                'adv_YouUseDefaultSSHPassword',
151
                ['url' => $this->url->get('general-settings/modify/#/ssh', null, null, $this->baseUri)]
152
            );
153
        }
154
155
        return $messages;
156
    }
157
158
    /**
159
     * Check firewall status
160
     *
161
     * @return array
162
     */
163
    private function checkFirewalls(): array
164
    {
165
        $messages = [];
166
        if (PbxSettings::getValueByKey('PBXFirewallEnabled') === '0') {
167
            $messages['warning'] = $this->translation->_(
168
                'adv_FirewallDisabled',
169
                ['url' => $this->url->get('firewall/index/', null, null, $this->baseUri)]
0 ignored issues
show
Unused Code introduced by
The call to Phalcon\Url\UrlInterface::get() has too many arguments starting with $this->baseUri. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

169
                ['url' => $this->url->/** @scrutinizer ignore-call */ get('firewall/index/', null, null, $this->baseUri)]

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
170
            );
171
        }
172
        if (NetworkFilters::count() === 0) {
173
            $messages['warning'] = $this->translation->_(
174
                'adv_NetworksNotConfigured',
175
                ['url' => $this->url->get('firewall/index/', null, null, $this->baseUri)]
176
            );
177
        }
178
179
        return $messages;
180
    }
181
182
    /**
183
     * Check storage is mount and how many space available
184
     *
185
     * @return array
186
     *
187
     */
188
    private function checkStorage(): array
189
    {
190
        $messages           = [];
191
        $st                 = new Storage();
192
        $storageDiskMounted = false;
193
        $disks              = $st->getAllHdd();
194
        if ( ! is_array($disks)) {
0 ignored issues
show
introduced by
The condition is_array($disks) is always true.
Loading history...
195
            $disks = [$disks];
196
        }
197
        foreach ($disks as $disk) {
198
            if (array_key_exists('mounted', $disk)
199
                && strpos($disk['mounted'], '/storage/usbdisk') !== false) {
200
                $storageDiskMounted = true;
201
                if ($disk['free_space'] < 500) {
202
                    $messages['warning']
203
                        = $this->translation->_(
204
                        'adv_StorageDiskRunningOutOfFreeSpace',
205
                        ['free' => $disk['free_space']]
206
                    );
207
                }
208
            }
209
        }
210
        if ($storageDiskMounted === false) {
211
            $messages['error'] = $this->translation->_('adv_StorageDiskUnMounted');
212
        }
213
        return $messages;
214
    }
215
216
    /**
217
     * Check new version PBX
218
     *
219
     * @return array
220
     * @throws \GuzzleHttp\Exception\GuzzleException
221
     */
222
    private function checkUpdates(): array
223
    {
224
        $messages   = [];
225
        $PBXVersion = PbxSettings::getValueByKey('PBXVersion');
226
227
        $client = new GuzzleHttp\Client();
228
        $res    = $client->request(
229
            'POST',
230
            'https://update.askozia.ru/',
231
            [
232
                'form_params' => [
233
                    'TYPE'   => 'FIRMWAREGETNEWS',
234
                    'PBXVER' => $PBXVersion,
235
                ],
236
            ]
237
        );
238
        if ($res->getStatusCode() !== 200) {
239
            return [];
240
        }
241
242
        $answer = json_decode($res->getBody(), false);
243
        if ($answer !== null && $answer->newVersionAvailable === true) {
244
            $messages['info'] = $this->translation->_(
245
                'adv_AvailableNewVersionPBX',
246
                [
247
                    'url' => $this->url->get('update/index/', null, null, $this->baseUri),
0 ignored issues
show
Unused Code introduced by
The call to Phalcon\Url\UrlInterface::get() has too many arguments starting with $this->baseUri. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

247
                    'url' => $this->url->/** @scrutinizer ignore-call */ get('update/index/', null, null, $this->baseUri),

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
248
                    'ver' => $answer->version,
249
                ]
250
            );
251
        }
252
253
        return $messages;
254
    }
255
256
    /**
257
     * Check mikopbx license status
258
     *
259
     */
260
    private function checkRegistration(): array
261
    {
262
        $messages = [];
263
        $licKey   = PbxSettings::getValueByKey('PBXLicense');
264
        $language   = PbxSettings::getValueByKey('WebAdminLanguage');
265
266
        if ( ! empty($licKey)) {
267
            $checkBaseFeature = $this->license->featureAvailable(33);
268
            if ($checkBaseFeature['success'] === false) {
269
                if ($language === 'ru') {
270
                    $url = 'https://wiki.mikopbx.com/licensing#faq_chavo';
271
                } else {
272
                    $url = "https://wiki.mikopbx.com/{$language}:licensing#faq_chavo";
273
                }
274
275
                $messages['warning'] = $this->translation->_(
276
                    'adv_ThisCopyHasLicensingTroubles',
277
                    [
278
                        'url'   => $url,
279
                        'error' => $this->license->translateLicenseErrorMessage($checkBaseFeature['error']),
280
                    ]
281
                );
282
            }
283
284
            $licenseInfo = $this->license->getLicenseInfo($licKey);
285
            if ($licenseInfo instanceof SimpleXMLElement) {
0 ignored issues
show
introduced by
$licenseInfo is never a sub-type of SimpleXMLElement.
Loading history...
286
                file_put_contents('/tmp/licenseInfo', json_encode($licenseInfo->attributes()));
287
            }
288
        }
289
290
        return $messages;
291
    }
292
}