Passed
Push — develop ( 48ed7a...f087ba )
by Nikolay
05:31
created

System::rebootSync()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
nc 1
nop 0
1
<?php
2
/**
3
 * Copyright © MIKO LLC - All Rights Reserved
4
 * Unauthorized copying of this file, via any medium is strictly prohibited
5
 * Proprietary and confidential
6
 * Written by Alexey Portnov, 7 2020
7
 */
8
9
namespace MikoPBX\Core\System;
10
11
use MikoPBX\Common\Models\CustomFiles;
12
use MikoPBX\Core\System\Configs\CronConf;
13
use MikoPBX\Core\System\Configs\IptablesConf;
14
use MikoPBX\Core\System\Configs\PHPConf;
15
use MikoPBX\Core\System\Configs\NTPConf;
16
use MikoPBX\Core\Workers\Cron\WorkerSafeScriptsCore;
17
use MikoPBX\Core\Asterisk\Configs\{QueueConf};
18
use Phalcon\Di;
19
20
class System extends Di\Injectable
21
{
22
    private MikoPBXConfig $mikoPBXConfig;
23
24
    /**
25
     * System constructor
26
     */
27
    public function __construct()
28
    {
29
        $this->mikoPBXConfig = new MikoPBXConfig();
30
    }
31
32
    /**
33
     * Returns logs dir
34
     *
35
     * @return string
36
     */
37
    public static function getLogDir(): string
38
    {
39
        $di = Di::getDefault();
40
        if ($di !== null) {
41
            return $di->getConfig()->path('core.logsDir');
42
        }
43
44
        return '/var/log';
45
    }
46
47
    /**
48
     * Refresh networks configs and restarts network daemon
49
     */
50
    public static function networkReload(): void
51
    {
52
        $network = new Network();
53
        $network->hostnameConfigure();
54
        $network->resolvConfGenerate();
55
        $network->loConfigure();
56
        $network->lanConfigure();
57
    }
58
59
    /**
60
     * Updates custom changes in config files
61
     */
62
    public static function updateCustomFiles()
63
    {
64
        $actions = [];
65
        /** @var \MikoPBX\Common\Models\CustomFiles $res_data */
66
        $res_data = CustomFiles::find("changed = '1'");
67
        foreach ($res_data as $file_data) {
68
            // Always restart asterisk after any custom file change
69
            $actions['asterisk_core_reload'] = 100;
70
            $filename                        = basename($file_data->filepath);
71
            switch ($filename) {
72
                case 'manager.conf':
73
                    $actions['manager'] = 10;
74
                    break;
75
                case 'musiconhold.conf':
76
                    $actions['musiconhold'] = 100;
77
                    break;
78
                case 'modules.conf':
79
                    $actions['modules'] = 10;
80
                    break;
81
                case 'http.conf':
82
                    $actions['manager'] = 10;
83
                    break;
84
                case 'root': // crontabs
85
                    $actions['cron'] = 10;
86
                    break;
87
                case 'queues.conf':
88
                    $actions['queues'] = 10;
89
                    break;
90
                case 'features.conf':
91
                    $actions['features'] = 10;
92
                    break;
93
                case 'ntp.conf':
94
                    $actions['systemtime'] = 100;
95
                    break;
96
                case 'jail.local': // fail2ban
97
                    $actions['firewall'] = 100;
98
                    break;
99
            }
100
        }
101
102
        asort($actions);
103
        self::invokeActions($actions);
104
        foreach ($res_data as $file_data) {
105
            /** @var \MikoPBX\Common\Models\CustomFiles $file_data */
106
            $file_data->writeAttribute("changed", '0');
107
            $file_data->save();
108
        }
109
    }
110
111
    /**
112
     * Batch module restart
113
     *
114
     * @param $actions
115
     *
116
     */
117
    public static function invokeActions($actions): void
118
    {
119
        foreach ($actions as $action => $value) {
120
            switch ($action) {
121
                case 'manager':
122
                    PBX::managerReload();
123
                    break;
124
                case 'musiconhold':
125
                    PBX::musicOnHoldReload();
126
                    break;
127
                case 'modules':
128
                    PBX::modulesReload();
129
                    break;
130
                case 'cron':
131
                    $cron = new CronConf();
132
                    $cron->reStart();
133
                    break;
134
                case 'queues':
135
                    QueueConf::queueReload();
136
                    break;
137
                case 'features':
138
                    PBX::managerReload();
139
                    break;
140
                case 'systemtime':
141
                    System::setDate('');
142
                    break;
143
                case 'firewall':
144
                    IptablesConf::reloadFirewall();
145
                    break;
146
                case 'asterisk_core_reload':
147
                    PBX::sipReload();
148
                    PBX::iaxReload();
149
                    PBX::dialplanReload();
150
                    PBX::coreReload();
151
                    break;
152
                default:
153
            }
154
        }
155
    }
156
157
    /**
158
     * Setup system time
159
     *
160
     * @param $date integer 2015.12.31-01:01:20
161
     *
162
     * @return bool
163
     */
164
    public static function setDate($date): bool
165
    {
166
        // Преобразование числа к дате. Если необходимо.
167
        $date = Util::numberToDate($date);
168
        // Валидация даты.
169
        $re_date = '/^\d{4}\.\d{2}\.\d{2}\-\d{2}\:\d{2}\:\d{2}$/';
170
        preg_match_all($re_date, $date, $matches, PREG_SET_ORDER, 0);
171
        if (count($matches) > 0) {
172
            $arr_data = [];
173
            $datePath = Util::which('date');
174
            Util::mwExec("{$datePath} -s '{$date}'", $arr_data);
175
        }
176
177
        $sys = new self();
178
        $sys->timezoneConfigure();
179
180
        return true;
181
    }
182
183
    /**
184
     * Populates /etc/TZ with an appropriate time zone
185
     */
186
    public function timezoneConfigure(): void
187
    {
188
        $timezone = $this->mikoPBXConfig->getGeneralSettings('PBXTimezone');;
189
        if (file_exists('/etc/TZ')) {
190
            unlink("/etc/TZ");
191
        }
192
        if (file_exists('/etc/localtime')) {
193
            unlink("/etc/localtime");
194
        }
195
        if ($timezone) {
196
            $zone_file = "/usr/share/zoneinfo/{$timezone}";
197
            if ( ! file_exists($zone_file)) {
198
                return;
199
            }
200
            $cpPath = Util::which('cp');
201
            Util::mwExec("{$cpPath}  {$zone_file} /etc/localtime");
202
            file_put_contents('/etc/TZ', $timezone);
203
            putenv("TZ={$timezone}");
204
            Util::mwExec("export TZ;");
205
        }
206
        $ntpConf = new NTPConf();
207
        $ntpConf->configure();
208
        PHPConf::phpTimeZoneConfigure();
209
    }
210
211
    /**
212
     * Reboots the system after calling system_reboot_cleanup()
213
     */
214
    public static function rebootSync(): void
215
    {
216
        $mikopbx_rebootPath = Util::which('mikopbx_reboot');
217
        Util::mwExec("{$mikopbx_rebootPath} > /dev/null 2>&1");
218
    }
219
220
    /**
221
     * Reboots the system after calling system_reboot_cleanup()
222
     */
223
    public static function rebootSyncBg(): void
224
    {
225
        $mikopbx_rebootPath = Util::which('mikopbx_reboot');
226
        Util::mwExecBg("{$mikopbx_rebootPath} > /dev/null 2>&1");
227
    }
228
229
    /**
230
     * Shutdown the system
231
     */
232
    public static function shutdown(): void
233
    {
234
        $shutdownPath = Util::which('shutdown');
235
        Util::mwExec("{$shutdownPath} > /dev/null 2>&1");
236
    }
237
238
    /**
239
     * Loads additioanl kernel modules
240
     */
241
    public function loadKernelModules(): void
242
    {
243
        $modprobePath = Util::which('modprobe');
244
        $ulimitPath   = Util::which('ulimit');
245
246
        Util::mwExec("{$modprobePath} -q dahdi");
247
        Util::mwExec("{$modprobePath} -q dahdi_transcode");
248
        Util::mwExec("{$ulimitPath} -n 4096");
249
        Util::mwExec("{$ulimitPath} -p 4096");
250
    }
251
252
    /**
253
     * Restart asterisk processor
254
     */
255
    public function onAfterPbxStarted(): void
256
    {
257
        $additionalModules = $this->di->getShared('pbxConfModules');
258
        foreach ($additionalModules as $appClass) {
259
            /** @var \MikoPBX\Modules\Config\ConfigClass $appClass */
260
            $appClass->onAfterPbxStarted();
261
        }
262
    }
263
264
    /**
265
     * Restart all workers in separate process,
266
     * we use this method after module install or delete
267
     */
268
    public static function restartAllWorkers(): void
269
    {
270
        $workerSafeScriptsPath = Util::getFilePathByClassName(WorkerSafeScriptsCore::class);
271
        $phpPath               = Util::which('php');
272
        $WorkerSafeScripts     = "{$phpPath} -f {$workerSafeScriptsPath} restart > /dev/null 2> /dev/null";
273
        Util::mwExecBg($WorkerSafeScripts,'/dev/null');
274
        exit(0);
1 ignored issue
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
275
    }
276
}
277