Passed
Push — develop ( 162268...ccaf35 )
by Портнов
07:13
created

System::invokeActions()   C

Complexity

Conditions 13
Paths 13

Size

Total Lines 42
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 40
c 1
b 0
f 0
dl 0
loc 42
rs 6.6166
cc 13
nc 13
nop 1

How to fix   Complexity   

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
 * 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\Core\System;
21
22
use DateTime;
23
use DateTimeZone;
24
use MikoPBX\Common\Models\CustomFiles;
25
use MikoPBX\Common\Models\PbxSettings;
26
use MikoPBX\Core\System\Configs\CronConf;
27
use MikoPBX\Core\System\Configs\IptablesConf;
28
use MikoPBX\Core\System\Configs\PHPConf;
29
use MikoPBX\Core\System\Configs\NTPConf;
30
use MikoPBX\Core\Asterisk\Configs\QueueConf;
31
use Phalcon\Di;
32
33
class System extends Di\Injectable
34
{
35
    private MikoPBXConfig $mikoPBXConfig;
36
37
    /**
38
     * System constructor
39
     */
40
    public function __construct()
41
    {
42
        $this->mikoPBXConfig = new MikoPBXConfig();
43
    }
44
45
    /**
46
     * Returns logs dir
47
     *
48
     * @return string
49
     */
50
    public static function getLogDir(): string
51
    {
52
        $di = Di::getDefault();
53
        if ($di !== null) {
54
            return $di->getConfig()->path('core.logsDir');
55
        }
56
57
        return '/var/log';
58
    }
59
60
    /**
61
     * Refresh networks configs and restarts network daemon
62
     */
63
    public static function networkReload(): void
64
    {
65
        $network = new Network();
66
        $network->hostnameConfigure();
67
        $network->resolvConfGenerate();
68
        $network->loConfigure();
69
        $network->lanConfigure();
70
    }
71
72
    /**
73
     * Updates custom changes in config files
74
     */
75
    public static function updateCustomFiles():void
76
    {
77
        $actions = [];
78
        /** @var CustomFiles $res_data */
79
        $res_data = CustomFiles::find("changed = '1'");
80
        foreach ($res_data as $file_data) {
81
            // Always restart asterisk after any custom file change
82
            $actions['asterisk_core_reload'] = 100;
83
            $filename                        = basename($file_data->filepath);
84
            switch ($filename) {
85
                case 'manager.conf':
86
                    $actions['manager'] = 10;
87
                    break;
88
                case 'musiconhold.conf':
89
                    $actions['musiconhold'] = 100;
90
                    break;
91
                case 'modules.conf':
92
                    $actions['modules'] = 10;
93
                    break;
94
                case 'http.conf':
95
                    $actions['manager'] = 10; //
96
                    break;
97
                case 'root': // crontabs
98
                    $actions['cron'] = 10;
99
                    break;
100
                case 'queues.conf':
101
                    $actions['queues'] = 10;
102
                    break;
103
                case 'features.conf':
104
                    $actions['features'] = 10;
105
                    break;
106
                case 'ntp.conf':
107
                    $actions['ntp'] = 100;
108
                    break;
109
                case 'rtp.conf':
110
                    $actions['rtp'] = 10;
111
                    break;
112
                case 'static-routes':
113
                case 'openvpn.ovpn':
114
                    $actions['network'] = 100;
115
                    break;
116
                case 'jail.local': // fail2ban
117
                    $actions['firewall'] = 100;
118
                    break;
119
                default:
120
                    break;
121
            }
122
        }
123
        asort($actions);
124
        self::invokeActions($actions);
125
        foreach ($res_data as $file_data) {
126
            /** @var CustomFiles $file_data */
127
            $file_data->writeAttribute("changed", '0');
128
            $file_data->save();
129
        }
130
    }
131
132
    /**
133
     * Batch module restart
134
     *
135
     * @param $actions
136
     *
137
     */
138
    public static function invokeActions($actions): void
139
    {
140
        foreach ($actions as $action => $value) {
141
            switch ($action) {
142
                case 'manager':
143
                    PBX::managerReload();
144
                    break;
145
                case 'musiconhold':
146
                    PBX::musicOnHoldReload();
147
                    break;
148
                case 'rtp':
149
                    PBX::rtpReload();
150
                    break;
151
                case 'modules':
152
                    PBX::modulesReload();
153
                    break;
154
                case 'cron':
155
                    $cron = new CronConf();
156
                    $cron->reStart();
157
                    break;
158
                case 'queues':
159
                    QueueConf::queueReload();
160
                    break;
161
                case 'features':
162
                    PBX::managerReload(); //
163
                    break;
164
                case 'ntp':
165
                    NTPConf::configure();
166
                    break;
167
                case 'firewall':
168
                    IptablesConf::reloadFirewall();
169
                    break;
170
                case 'network':
171
                    self::networkReload();
172
                    break;
173
                case 'asterisk_core_reload':
174
                    PBX::sipReload();
175
                    PBX::iaxReload();
176
                    PBX::dialplanReload();
177
                    PBX::coreReload();
178
                    break;
179
                default:
180
            }
181
        }
182
    }
183
184
    /**
185
     * Setup system time
186
     *
187
     * @param int    $timeStamp
188
     * @param string $remote_tz
189
     *
190
     * @return bool
191
     * @throws \Exception
192
     */
193
    public static function setDate(int $timeStamp, string $remote_tz): bool
194
    {
195
        $datePath = Util::which('date');
196
        $db_tz = PbxSettings::getValueByKey('PBXTimezone');
197
        $origin_tz = '';
198
        if (file_exists('/etc/TZ')) {
199
            $origin_tz = file_get_contents("/etc/TZ");
200
        }
201
        if ($origin_tz !== $db_tz){
202
            self::timezoneConfigure();
203
        }
204
        $origin_tz = $db_tz;
205
        $origin_dtz = new DateTimeZone($origin_tz);
206
        $remote_dtz = new DateTimeZone($remote_tz);
207
        $origin_dt  = new DateTime('now', $origin_dtz);
208
        $remote_dt  = new DateTime('now', $remote_dtz);
209
        $offset     = $origin_dtz->getOffset($origin_dt) - $remote_dtz->getOffset($remote_dt);
210
        $timeStamp  = $timeStamp - $offset;
211
        Processes::mwExec("{$datePath} +%s -s @{$timeStamp}");
212
        // Для 1 января должно быть передано 1577829662
213
        // Установлено 1577818861
214
215
        return true;
216
    }
217
218
    /**
219
     * Reboots the system after calling system_reboot_cleanup()
220
     */
221
    public static function rebootSync(): void
222
    {
223
        $mikopbx_rebootPath = Util::which('mikopbx_reboot');
224
        Processes::mwExec("{$mikopbx_rebootPath} > /dev/null 2>&1");
225
    }
226
227
    /**
228
     * Reboots the system after calling system_reboot_cleanup()
229
     */
230
    public static function rebootSyncBg(): void
231
    {
232
        $mikopbx_rebootPath = Util::which('mikopbx_reboot');
233
        Processes::mwExecBg("{$mikopbx_rebootPath} > /dev/null 2>&1");
234
    }
235
236
    /**
237
     * Shutdown the system
238
     */
239
    public static function shutdown(): void
240
    {
241
        $shutdownPath = Util::which('shutdown');
242
        Processes::mwExec("{$shutdownPath} > /dev/null 2>&1");
243
    }
244
245
246
    /**
247
     * Populates /etc/TZ with an appropriate time zone
248
     */
249
    public static function timezoneConfigure(): void
250
    {
251
        $timezone = PbxSettings::getValueByKey('PBXTimezone');
252
        if (file_exists('/etc/TZ')) {
253
            unlink("/etc/TZ");
254
        }
255
        if (file_exists('/etc/localtime')) {
256
            unlink("/etc/localtime");
257
        }
258
        if ($timezone) {
259
            $zone_file = "/usr/share/zoneinfo/{$timezone}";
260
            if ( ! file_exists($zone_file)) {
261
                return;
262
            }
263
            $cpPath = Util::which('cp');
264
            Processes::mwExec("{$cpPath}  {$zone_file} /etc/localtime");
265
            file_put_contents('/etc/TZ', $timezone);
266
            putenv("TZ={$timezone}");
267
            Processes::mwExec("export TZ;");
268
269
            PHPConf::phpTimeZoneConfigure();
270
        }
271
272
    }
273
274
    /**
275
     * Loads additional kernel modules
276
     */
277
    public function loadKernelModules(): bool
278
    {
279
        if(Util::isDocker()){
280
            return true;
281
        }
282
283
        $modprobePath = Util::which('modprobe');
284
        $ulimitPath   = Util::which('ulimit');
285
286
        $res1 = Processes::mwExec("{$modprobePath} -q dahdi");
287
        $res2 = Processes::mwExec("{$modprobePath} -q dahdi_transcode");
288
        Processes::mwExec("{$ulimitPath} -n 4096");
289
        Processes::mwExec("{$ulimitPath} -p 4096");
290
291
        return ($res1 === 0 && $res2 === 0);
292
    }
293
294
    /**
295
     * Вычисляет хэш сертификатов SSL и распаковывает их из ca-certificates.crt.
296
     * @return void
297
     */
298
    public static function sslRehash(): void
299
    {
300
        $openSslPath = Util::which('openssl');
301
        $cutPath     = Util::which('cut');
302
        $openSslDir  = trim(shell_exec("$openSslPath version -d | $cutPath -d '\"' -f 2"));
303
        $certFile    = "$openSslDir/certs/ca-certificates.crt";
304
        $tmpFile     = tempnam('/tmp', 'cert-');
305
        $rawData     = file_get_contents($certFile);
306
        $certs       = explode(PHP_EOL.PHP_EOL, $rawData);
307
        foreach ($certs as $cert){
308
            if(strpos($cert, '-----BEGIN CERTIFICATE-----') === false){
309
                continue;
310
            }
311
            file_put_contents($tmpFile, $cert);
312
            $hash = trim(shell_exec("$openSslPath x509 -subject_hash -noout -in '$tmpFile'"));
313
            rename($tmpFile, "$openSslDir/certs/$hash.0");
314
        }
315
        if(file_exists($tmpFile)){
316
            unlink($tmpFile);
317
        }
318
    }
319
}
320