Passed
Push — develop ( 3b062d...2b12c9 )
by Nikolay
23:37 queued 09:37
created

SystemManagementProcessor   A

Complexity

Total Complexity 40

Size/Duplication

Total Lines 257
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 40
eloc 184
dl 0
loc 257
rs 9.2
c 2
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getMemInfo() 0 15 1
F systemCallBack() 0 139 32
A getUpTime() 0 8 1
A getInfo() 0 15 1
A getCpu() 0 14 2
A upgradeFromImg() 0 26 3

How to fix   Complexity   

Complex Class

Complex classes like SystemManagementProcessor often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use SystemManagementProcessor, and based on these observations, apply Extract Interface, too.

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, 7 2020
7
 *
8
 */
9
10
namespace MikoPBX\PBXCoreREST\Lib;
11
12
13
use MikoPBX\Common\Providers\PBXConfModulesProvider;
14
use MikoPBX\Core\Asterisk\Configs\VoiceMailConf;
15
use MikoPBX\Core\System\Notifications;
16
use MikoPBX\Core\System\Storage;
17
use MikoPBX\Core\System\System;
18
use MikoPBX\Core\System\Util;
19
use MikoPBX\Modules\PbxExtensionState;
20
use MikoPBX\PBXCoreREST\Workers\WorkerMergeUploadedFile;
21
use Phalcon\Di\Injectable;
22
23
class SystemManagementProcessor extends Injectable
24
{
25
    /**
26
     * Processes System requests
27
     *
28
     * @param array $request
29
     *
30
     * @return \MikoPBX\PBXCoreREST\Lib\PBXApiResult
31
     */
32
    public static function systemCallBack(array $request): PBXApiResult
33
    {
34
        $action = $request['action'];
35
        $data   = $request['data'];
36
        $res    = new PBXApiResult();
37
        $res->processor = __METHOD__;
38
        switch ($action) {
39
            case 'reboot':
40
                System::rebootSync();
41
                $res->success = true;
42
                break;
43
            case 'shutdown':
44
                System::shutdown();
45
                $res->success = true;
46
                break;
47
            case 'mergeUploadedFile':
48
                $phpPath              = Util::which('php');
49
                $workerDownloaderPath = Util::getFilePathByClassName(WorkerMergeUploadedFile::class);
50
                Util::mwExecBg("{$phpPath} -f {$workerDownloaderPath} '{$data['settings_file']}'");
51
                $res->success = true;
52
                break;
53
            case 'setDate':
54
                $res->success = System::setDate($data['date']);
55
                break;
56
            case 'getInfo':
57
                $res = SystemManagementProcessor::getInfo();
58
                break;
59
            case 'updateMailSettings':
60
                // TODO
61
                $res->success = true;
62
                break;
63
            case 'sendMail':
64
                if (isset($data['email']) && isset($data['subject']) && isset($data['body'])) {
65
                    if (isset($data['encode']) && $data['encode'] === 'base64') {
66
                        $data['subject'] = base64_decode($data['subject']);
67
                        $data['body']    = base64_decode($data['body']);
68
                    }
69
                    $result = Notifications::sendMail($data['email'], $data['subject'], $data['body']);
70
                    if ($result===true){
71
                        $res->success    = true;
72
                    } else {
73
                        $res->success    = false;
74
                        $res->messages[] = $result;
75
                    }
76
                } else {
77
                    $res->success    = false;
78
                    $res->messages[] = 'Not all query parameters are set';
79
                }
80
                break;
81
            case 'fileReadContent':
82
                $res = FilesManagementProcessor::fileReadContent($data['filename'], $data['needOriginal']);
83
                break;
84
            case 'getExternalIpInfo':
85
                $res = NetworkManagementProcessor::getExternalIpInfo();
86
                break;
87
            case 'reloadMsmtp':
88
                $notifications = new Notifications();
89
                $notifications->configure();
90
                $voiceMailConfig = new VoiceMailConf();
91
                $voiceMailConfig->generateConfig();
92
                $asteriskPath = Util::which('asterisk');
93
                Util::mwExec("{$asteriskPath} -rx 'voicemail reload'");
94
                $res->success = true;
95
                break;
96
            case 'unBanIp':
97
                $res = FirewallManagementProcessor::fail2banUnbanAll($data['ip']);
98
                break;
99
            case 'getBanIp':
100
                $res = FirewallManagementProcessor::getBanIp();
101
                break;
102
            case 'downloadNewFirmware':
103
                $res = FilesManagementProcessor::downloadNewFirmware($request['data']);
104
                break;
105
            case 'firmwareDownloadStatus':
106
                $res = FilesManagementProcessor::firmwareDownloadStatus();
107
                break;
108
            case 'upgrade':
109
                $res = SystemManagementProcessor::upgradeFromImg($data['temp_filename']);
110
                break;
111
            case 'removeAudioFile':
112
                $res = FilesManagementProcessor::removeAudioFile($data['filename']);
113
                break;
114
            case 'convertAudioFile':
115
                $mvPath = Util::which('mv');
116
                Util::mwExec("{$mvPath} {$data['temp_filename']} {$data['filename']}");
117
                $res = FilesManagementProcessor::convertAudioFile($data['filename']);
118
                break;
119
            case 'downloadNewModule':
120
                $module = $request['data']['uniqid'];
121
                $url    = $request['data']['url'];
122
                $md5    = $request['data']['md5'];
123
                $res    = FilesManagementProcessor::moduleStartDownload($module, $url, $md5);
124
                break;
125
            case 'moduleDownloadStatus':
126
                $module = $request['data']['uniqid'];
127
                $res    = FilesManagementProcessor::moduleDownloadStatus($module);
128
                break;
129
            case 'installNewModule':
130
                $filePath = $request['data']['filePath'];
131
                $res      = FilesManagementProcessor::installModuleFromFile($filePath);
132
                break;
133
            case 'enableModule':
134
                $moduleUniqueID       = $request['data']['uniqid'];
135
                $moduleStateProcessor = new PbxExtensionState($moduleUniqueID);
136
                if ($moduleStateProcessor->enableModule() === false) {
137
                    $res->success  = false;
138
                    $res->messages = $moduleStateProcessor->getMessages();
139
                } else {
140
                    PBXConfModulesProvider::recreateModulesProvider();
141
                    $res->data['needReloadModules'] = true;
142
                    $res->success = true;
143
                }
144
                break;
145
            case 'disableModule':
146
                $moduleUniqueID       = $request['data']['uniqid'];
147
                $moduleStateProcessor = new PbxExtensionState($moduleUniqueID);
148
                if ($moduleStateProcessor->disableModule() === false) {
149
                    $res->success  = false;
150
                    $res->messages = $moduleStateProcessor->getMessages();
151
                } else {
152
                    PBXConfModulesProvider::recreateModulesProvider();
153
                    $res->data['needReloadModules'] = true;
154
                    $res->success = true;
155
                }
156
                break;
157
            case 'uninstallModule':
158
                $moduleUniqueID = $request['data']['uniqid'];
159
                $keepSettings   = $request['data']['keepSettings']==='true';
160
                $res            = FilesManagementProcessor::uninstallModule($moduleUniqueID, $keepSettings);
161
                break;
162
            default:
163
                $res             = new PBXApiResult();
164
                $res->processor = __METHOD__;
165
                $res->messages[] = "Unknown action - {$action} in systemCallBack";
166
        }
167
168
        $res->function = $action;
169
170
        return $res;
171
    }
172
173
    /**
174
     * Получение сведений о системе.
175
     *
176
     * @return PBXApiResult
177
     */
178
    public static function getInfo(): PBXApiResult
179
    {
180
        $res = new PBXApiResult();
181
        $res->processor = __METHOD__;
182
        $res->success = true;
183
184
        $storage        = new Storage();
185
        $res->data           = [
186
            'disks'  => $storage->getAllHdd(),
187
            'cpu'    => self::getCpu(),
188
            'uptime' => self::getUpTime(),
189
            'mem'    => self::getMemInfo(),
190
        ];
191
        $res->processor = __METHOD__;
192
        return $res;
193
    }
194
195
    /**
196
     * Возвращает информацию по загрузке CPU.
197
     */
198
    public static function getCpu()
199
    {
200
        $ut = [];
201
        $grepPath = Util::which('grep');
202
        $mpstatPath = Util::which('mpstat');
203
        Util::mwExec("{$mpstatPath} | {$grepPath} all", $ut);
204
        preg_match("/^.*\s+all\s+.*\s+.*\s+.*\s+.*\s+.*\s+.*\s+.*\s+.*\s+(.*)\s*.*/i", $ut[0], $matches);
205
        $rv = 100 - $matches[1];
206
207
        if (100 < $rv) {
208
            $rv = 100;
209
        }
210
211
        return round($rv, 2);
212
    }
213
214
    /**
215
     * Получаем информацию по времени работы ПК.
216
     */
217
    public static function getUpTime(): string
218
    {
219
        $ut = [];
220
        $uptimePath = Util::which('uptime');
221
        $awkPath = Util::which('awk');
222
        Util::mwExec("{$uptimePath} | {$awkPath} -F \" |,\" '{print $5}'", $ut);
223
224
        return implode('', $ut);
225
    }
226
227
    /**
228
     * Получаем информацию по оперативной памяти.
229
     */
230
    public static function getMemInfo(): array
231
    {
232
        $result = [];
233
        $out    = [];
234
        $catPath = Util::which('cat');
235
        $grepPath = Util::which('grep');
236
        $awkPath = Util::which('awk');
237
        Util::mwExec("{$catPath} /proc/meminfo | {$grepPath} -C 0 'Inactive:' | {$awkPath} '{print $2}'", $out);
238
        $result['inactive'] = round((1 * implode($out)) / 1024, 2);
239
        Util::mwExec("{$catPath} /proc/meminfo | {$grepPath} -C 0 'MemFree:' | {$awkPath} '{print $2}'", $out);
240
        $result['free'] = round((1 * implode($out)) / 1024, 2);
241
        Util::mwExec("{$catPath} /proc/meminfo | {$grepPath} -C 0 'MemTotal:' | {$awkPath} '{print $2}'", $out);
242
        $result['total'] = round((1 * implode($out)) / 1024, 2);
243
244
        return $result;
245
    }
246
247
    /**
248
     * Upgrade MikoPBX from uploaded IMG file
249
     *
250
     * @param string $tempFilename path to uploaded image
251
     *
252
     * @return PBXApiResult
253
     */
254
    public static function upgradeFromImg(string $tempFilename): PBXApiResult
255
    {
256
        $res = new PBXApiResult();
257
        $res->processor = __METHOD__;
258
        $res->success = true;
259
        $res->data['message']='In progress...';
260
261
262
        if (!file_exists($tempFilename)){
263
            $res->success = false;
264
            $res->messages[]="Update file '{$tempFilename}' not found.";
265
            return $res;
266
        }
267
268
        if ( ! file_exists('/var/etc/cfdevice')) {
269
            $res->success = false;
270
            $res->messages[]="The system is not installed";
271
            return $res;
272
        }
273
        $dev = trim(file_get_contents('/var/etc/cfdevice'));
274
275
        $link = '/tmp/firmware_update.img';
276
        Util::createUpdateSymlink($tempFilename, $link);
277
        $mikopbx_firmwarePath = Util::which('mikopbx_firmware');
278
        Util::mwExecBg("{$mikopbx_firmwarePath} recover_upgrade {$link} /dev/{$dev}");
279
        return $res;
280
    }
281
282
}