Passed
Push — develop ( b7c00c...da1f69 )
by Nikolay
08:07 queued 01:43
created

System::setDate()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

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