Passed
Push — develop ( 7f2f11...c7ac81 )
by Портнов
04:20 queued 10s
created

initPbxSettingsDependencyTable()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 208
Code Lines 133

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 133
c 1
b 0
f 0
dl 0
loc 208
rs 8
cc 1
nc 1
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
 * 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\Workers;
21
22
require_once 'Globals.php';
23
24
use MikoPBX\Common\Models\{AsteriskManagerUsers,
25
    CallQueueMembers,
26
    CallQueues,
27
    Codecs,
28
    ConferenceRooms,
29
    CustomFiles,
30
    DialplanApplications,
31
    ExtensionForwardingRights,
32
    Extensions,
33
    ExternalPhones,
34
    Fail2BanRules,
35
    FirewallRules,
36
    Iax,
37
    IncomingRoutingTable,
38
    IvrMenu,
39
    IvrMenuActions,
40
    LanInterfaces,
41
    NetworkFilters,
42
    OutgoingRoutingTable,
43
    OutWorkTimes,
44
    PbxExtensionModules,
45
    PbxSettings,
46
    Sip,
47
    SipHosts,
48
    SoundFiles,
49
    Users};
50
use MikoPBX\Common\Providers\BeanstalkConnectionModelsProvider;
51
use MikoPBX\Common\Providers\PBXConfModulesProvider;
52
use MikoPBX\Core\Asterisk\Configs\QueueConf;
53
use MikoPBX\Core\System\{BeanstalkClient,
54
    Configs\CronConf,
55
    Configs\Fail2BanConf,
56
    Configs\IptablesConf,
57
    Configs\NatsConf,
58
    Configs\NginxConf,
59
    Configs\NTPConf,
60
    Configs\PHPConf,
61
    Configs\SSHConf,
62
    Configs\SyslogConf,
63
    PBX,
64
    Processes,
65
    System,
66
    Util
67
};
68
use MikoPBX\PBXCoreREST\Workers\WorkerApiCommands;
69
use Phalcon\Di;
70
use Pheanstalk\Contract\PheanstalkInterface;
71
72
ini_set('error_reporting', E_ALL);
73
ini_set('display_startup_errors', 1);
74
75
class WorkerModelsEvents extends WorkerBase
76
{
77
    private const R_MANAGERS = 'reloadManager';
78
79
    public const R_NEED_RESTART = 'needRestart';
80
81
    private const R_QUEUES = 'reloadQueues';
82
83
    private const R_DIALPLAN = 'reloadDialplan';
84
85
    private const R_CUSTOM_F = 'updateCustomFiles';
86
87
    private const R_FIREWALL = 'reloadFirewall';
88
89
    private const R_NETWORK = 'networkReload';
90
91
    private const R_IAX = 'reloadIax';
92
93
    private const R_SIP = 'reloadSip';
94
95
    private const R_FEATURES = 'reloadFeatures';
96
97
    private const R_CRON = 'reloadCron';
98
99
    public const  R_NGINX = 'reloadNginx';
100
101
    public const  R_NGINX_CONF = 'reloadNginxConf';
102
103
    public const  R_FAIL2BAN_CONF = 'reloadFail2BanConf';
104
105
    private const R_PHP_FPM = 'reloadPHPFPM';
106
107
    private const R_TIMEZONE = 'updateTomeZone';
108
109
    private const R_SYSLOG = 'restartSyslogD';
110
111
    private const R_SSH = 'reloadSSH';
112
113
    private const R_LICENSE = 'reloadLicense';
114
115
    private const R_NATS = 'reloadNats';
116
117
    private const R_VOICEMAIL = 'reloadVoicemail';
118
119
    private const R_REST_API_WORKER = 'reloadRestAPIWorker';
120
121
    private const R_CALL_EVENTS_WORKER = 'reloadWorkerCallEvents';
122
123
    private const R_PBX_EXTENSION_STATE = 'afterModuleStateChanged';
124
125
    private const R_MOH = 'reloadMoh';
126
127
    private const R_NTP = 'reloadNtp';
128
129
    private int   $last_change;
130
    private array $modified_tables;
131
132
    private int   $timeout = 2;
133
    private array $arrObject;
134
    private array $PRIORITY_R;
135
    private array $pbxSettingsDependencyTable = [];
136
    private array $modelsDependencyTable = [];
137
138
    /**
139
     * Adds action to queue for postpone apply
140
     *
141
     * @param string $action
142
     * @param int    $priority
143
     */
144
    public static function invokeAction(string $action, $priority = 0): void
145
    {
146
        $di = Di::getDefault();
147
        /** @var BeanstalkClient $queue */
148
        $queue = $di->getShared(BeanstalkConnectionModelsProvider::SERVICE_NAME);
149
        $queue->publish(
150
            $action,
151
            self::class,
152
            $priority,
153
            PheanstalkInterface::DEFAULT_DELAY,
154
            3600
155
        );
156
    }
157
158
    /**
159
     * The entry point
160
     *
161
     * @param $params
162
     */
163
    public function start($params): void
164
    {
165
        $this->last_change = time() - 2;
166
        $this->arrObject   = $this->di->getShared(PBXConfModulesProvider::SERVICE_NAME);
167
168
        $this->initPbxSettingsDependencyTable();
169
        $this->initModelsDependencyTable();
170
171
        $this->PRIORITY_R = [
172
            self::R_PBX_EXTENSION_STATE,
173
            self::R_TIMEZONE,
174
            self::R_SYSLOG,
175
            self::R_REST_API_WORKER,
176
            self::R_NETWORK,
177
            self::R_FIREWALL,
178
            self::R_FAIL2BAN_CONF,
179
            self::R_SSH,
180
            self::R_LICENSE,
181
            self::R_NATS,
182
            self::R_NTP,
183
            self::R_PHP_FPM,
184
            self::R_NGINX,
185
            self::R_NGINX_CONF,
186
            self::R_CRON,
187
            self::R_FEATURES,
188
            self::R_SIP,
189
            self::R_IAX,
190
            self::R_DIALPLAN,
191
            self::R_QUEUES,
192
            self::R_MANAGERS,
193
            self::R_CUSTOM_F,
194
            self::R_VOICEMAIL,
195
            self::R_MOH,
196
            self::R_CALL_EVENTS_WORKER,
197
        ];
198
199
        $this->modified_tables = [];
200
201
        /** @var BeanstalkClient $client */
202
        $client = $this->di->getShared(BeanstalkConnectionModelsProvider::SERVICE_NAME);
203
        $client->subscribe(self::class, [$this, 'processModelChanges']);
204
        $client->subscribe($this->makePingTubeName(self::class), [$this, 'pingCallBack']);
205
        $client->setTimeoutHandler([$this, 'timeoutHandler']);
206
207
        while ($this->needRestart === false) {
208
            $client->wait(5);
209
        }
210
        // Execute all collected changes before exit
211
        $this->timeoutHandler();
212
    }
213
214
    /**
215
     * Timeout handles
216
     */
217
    public function timeoutHandler(): void
218
    {
219
        $this->last_change = time() - $this->timeout;
220
        $this->startReload();
221
    }
222
223
    /**
224
     * Applies changes
225
     *
226
     * @return void
227
     */
228
    private function startReload(): void
229
    {
230
        if (count($this->modified_tables) === 0) {
231
            return;
232
        }
233
        $delta = time() - $this->last_change;
234
        if ($delta < $this->timeout) {
235
            return;
236
        }
237
238
        foreach ($this->PRIORITY_R as $method_name) {
239
            $action     = $this->modified_tables[$method_name] ?? null;
240
            $parameters = $this->modified_tables['parameters'][$method_name] ?? null;
241
            if ($action === null) {
242
                continue;
243
            }
244
            if (method_exists($this, $method_name)) {
245
                Util::sysLogMsg(__METHOD__, "Process changes by {$method_name}", LOG_DEBUG);
246
                if ($parameters === null) {
247
                    $this->$method_name();
248
                } else {
249
                    $this->$method_name($parameters);
250
                }
251
            }
252
        }
253
254
        foreach ($this->arrObject as $appClass) {
255
            $appClass->modelsEventNeedReload($this->modified_tables);
256
        }
257
        $this->modified_tables = [];
258
    }
259
260
    /**
261
     * Parses for received Beanstalk message
262
     *
263
     * @param BeanstalkClient $message
264
     *
265
     * @throws \JsonException
266
     */
267
    public function processModelChanges(BeanstalkClient $message): void
268
    {
269
        $data            = $message->getBody();
270
        $receivedMessage = null;
271
        if ($data === self::R_NEED_RESTART) {
272
            $this->needRestart();
273
        }
274
        if (in_array($data, $this->PRIORITY_R, true)) {
275
            $this->modified_tables[$data] = true;
276
        } else {
277
            $receivedMessage = json_decode($message->getBody(), true, 512, JSON_THROW_ON_ERROR);
278
            $this->fillModifiedTables($receivedMessage);
279
        }
280
        $this->startReload();
281
        if ( ! $receivedMessage) {
282
            return;
283
        }
284
        // Send information about models changes to additional modules
285
        foreach ($this->arrObject as $appClass) {
286
            $appClass->modelsEventChangeData($receivedMessage);
287
        }
288
    }
289
290
    /**
291
     * Restarts Nginx daemon
292
     */
293
    public function needRestart(): void
294
    {
295
        $this->needRestart = true;
296
    }
297
298
    /**
299
     * Collects changes to determine which modules must be reloaded or reconfigured
300
     *
301
     * @param array $data
302
     */
303
    private function fillModifiedTables(array $data): void
304
    {
305
        $count_changes = count($this->modified_tables);
306
        $called_class  = $data['model'] ?? '';
307
        Util::sysLogMsg(__METHOD__, "New changes " . $called_class, LOG_DEBUG);
308
        // Clear all caches on any changed models on backend
309
        PbxSettings::clearCache($called_class, false);
310
311
        // Get new settings gor dependence modules
312
        foreach ($this->arrObject as $appClass) {
313
            $dependencies = $appClass->dependenceModels();
314
            if (in_array($called_class, $dependencies, true)) {
315
                $appClass->getSettings();
316
            }
317
        }
318
        $this->fillModifiedTablesFromModels($called_class);
319
        $this->fillModifiedTablesFromPbxSettingsData($called_class, $data['recordId']);
320
        $this->fillModifiedTablesFromPbxExtensionModules($called_class, $data['recordId']);
321
322
        if ($count_changes === 0 && count($this->modified_tables) > 0) {
323
            // Начинаем отсчет времени при получении первой задачи.
324
            $this->last_change = time();
325
        }
326
    }
327
328
    /**
329
     * Инициализация таблицы зависимостей настроек m_PbxSettings и сервисов АТС.
330
     */
331
    private function initPbxSettingsDependencyTable():void
332
    {
333
        // FeaturesSettings
334
        $tables[] = [
0 ignored issues
show
Comprehensibility Best Practice introduced by
$tables was never initialized. Although not strictly required by PHP, it is generally a good practice to add $tables = array(); before regardless.
Loading history...
335
            'settingName'   => [
336
                'PBXLanguage',
337
                'PBXInternalExtensionLength',
338
                'PBXRecordCalls',
339
                'PBXCallParkingExt',
340
                'PBXCallParkingStartSlot',
341
                'PBXCallParkingEndSlot',
342
                'PBXFeatureAttendedTransfer',
343
                'PBXFeatureBlindTransfer',
344
                'PBXFeatureDigitTimeout',
345
                'PBXFeatureAtxferNoAnswerTimeout',
346
                'PBXFeatureTransferDigitTimeout',
347
                'PBXFeaturePickupExten'
348
            ],
349
            'functions' => [
350
                self::R_FEATURES,
351
                self::R_DIALPLAN
352
            ]
353
        ];
354
        // AMIParameters
355
        $tables[] = [
356
            'settingName'   => [
357
                'AMIPort',
358
                'AJAMPort',
359
                'AJAMPortTLS'
360
            ],
361
            'functions' => [
362
                self::R_MANAGERS
363
            ]
364
        ];
365
366
        // IaxParameters
367
        $tables[] = [
368
            'settingName'   => [
369
                'IAXPort'
370
            ],
371
            'functions' => [
372
                self::R_IAX
373
            ]
374
        ];
375
        // SipParameters
376
        $tables[] = [
377
            'settingName'   => [
378
                'SIPPort',
379
                'RTPPortFrom',
380
                'RTPPortTo',
381
                'SIPDefaultExpiry',
382
                'SIPMinExpiry',
383
                'PBXAllowGuestCalls',
384
                'SIPMaxExpiry',
385
                'PBXLanguage'
386
            ],
387
            'functions' => [
388
                self::R_SIP
389
            ]
390
        ];
391
392
        // SSHParameters
393
        $tables[] = [
394
            'settingName'   => [
395
                'SSHPort',
396
                'SSHPassword',
397
                'SSHAuthorizedKeys',
398
                'SSHRsaKey',
399
                'SSHDssKey',
400
                'SSHecdsaKey'
401
            ],
402
            'functions' => [
403
                self::R_SSH
404
            ]
405
        ];
406
407
        // FirewallParameters
408
        $tables[] = [
409
            'settingName'   => [
410
                'SIPPort',
411
                'RTPPortFrom',
412
                'RTPPortTo',
413
                'IAXPort',
414
                'AMIPort',
415
                'AJAMPort',
416
                'AJAMPortTLS',
417
                'WEBPort',
418
                'WEBHTTPSPort',
419
                'SSHPort',
420
                'PBXFirewallEnabled',
421
                'PBXFail2BanEnabled'
422
            ],
423
            'functions' => [
424
                self::R_FIREWALL
425
            ],
426
            'strPosKey' => 'FirewallSettings'
427
        ];
428
429
        // FirewallParameters
430
        $tables[] = [
431
            'settingName'   => [
432
                'WEBPort',
433
                'WEBHTTPSPort',
434
                'WEBHTTPSPublicKey',
435
                'WEBHTTPSPrivateKey',
436
                'RedirectToHttps'
437
            ],
438
            'functions' => [
439
                self::R_NGINX
440
            ],
441
        ];
442
443
        // CronParameters
444
        $tables[] = [
445
            'settingName'   => [
446
                'RestartEveryNight',
447
            ],
448
            'functions' => [
449
                self::R_CRON
450
            ],
451
        ];
452
453
        // DialplanParameters
454
        $tables[] = [
455
            'settingName'   => [
456
                'PBXLanguage',
457
            ],
458
            'functions' => [
459
                self::R_DIALPLAN
460
            ],
461
        ];
462
463
        // VoiceMailParameters
464
        $tables[] = [
465
            'settingName'   => [
466
                'MailTplVoicemailSubject',
467
                'MailTplVoicemailBody',
468
                'MailSMTPSenderAddress',
469
                'MailSMTPUsername',
470
                'PBXTimezone',
471
                'VoicemailNotificationsEmail',
472
                'SystemNotificationsEmail'
473
            ],
474
            'functions' => [
475
                self::R_VOICEMAIL
476
            ],
477
        ];
478
479
        // VisualLanguageSettings
480
        $tables[] = [
481
            'settingName'   => [
482
                'SSHLanguage',
483
                'WebAdminLanguage',
484
            ],
485
            'functions' => [
486
                self::R_REST_API_WORKER
487
            ],
488
        ];
489
490
        // LicenseSettings
491
        $tables[] = [
492
            'settingName'   => [
493
                'PBXLicense',
494
            ],
495
            'functions' => [
496
                self::R_LICENSE,
497
                self::R_NATS,
498
            ],
499
        ];
500
501
        // TimeZoneSettings
502
        $tables[] = [
503
            'settingName'   => [
504
                'PBXTimezone',
505
            ],
506
            'functions' => [
507
                self::R_TIMEZONE,
508
                self::R_NGINX,
509
                self::R_PHP_FPM,
510
                self::R_REST_API_WORKER,
511
                self::R_SYSLOG,
512
            ],
513
        ];
514
515
        // NTPSettings
516
        $tables[] = [
517
            'settingName'   => [
518
                'PBXManualTimeSettings',
519
                'NTPServer',
520
            ],
521
            'functions' => [
522
                self::R_NTP,
523
            ],
524
        ];
525
526
        // CallRecordSettings
527
        $tables[] = [
528
            'settingName'   => [
529
                'PBXRecordCalls',
530
                'PBXSplitAudioThread',
531
            ],
532
            'functions' => [
533
                self::R_CALL_EVENTS_WORKER,
534
                self::R_DIALPLAN,
535
            ],
536
        ];
537
538
        $this->pbxSettingsDependencyTable = $tables;
539
    }
540
541
    /**
542
     * Инициализация таблицы зависимостей моделей и сервисов АТС.
543
     */
544
    private function initModelsDependencyTable():void
545
    {
546
        $tables = [];
547
        $tables[] = [
548
            'settingName' => [
549
                AsteriskManagerUsers::class
550
            ],
551
            'functions'   => [
552
                self::R_MANAGERS
553
            ]
554
        ];
555
556
        $tables[] = [
557
            'settingName' => [
558
                CallQueueMembers::class
559
            ],
560
            'functions'   => [
561
                self::R_QUEUES
562
            ]
563
        ];
564
565
        $tables[] = [
566
            'settingName' => [
567
                CallQueues::class
568
            ],
569
            'functions'   => [
570
                self::R_QUEUES,
571
                self::R_DIALPLAN
572
            ]
573
        ];
574
        $tables[] = [
575
            'settingName' => [
576
                ExternalPhones::class,
577
                Extensions::class,
578
                DialplanApplications::class,
579
                IncomingRoutingTable::class,
580
                IvrMenu::class,
581
                IvrMenuActions::class,
582
                OutgoingRoutingTable::class,
583
                OutWorkTimes::class,
584
                ConferenceRooms::class,
585
            ],
586
            'functions'   => [
587
                self::R_DIALPLAN
588
            ]
589
        ];
590
591
        $tables[] = [
592
            'settingName' => [
593
                CustomFiles::class,
594
            ],
595
            'functions'   => [
596
                self::R_CUSTOM_F
597
            ]
598
        ];
599
600
        $tables[] = [
601
            'settingName' => [
602
                Sip::class,
603
            ],
604
            'functions'   => [
605
                self::R_SIP,
606
                self::R_DIALPLAN,
607
                self::R_FIREWALL,
608
            ]
609
        ];
610
611
        $tables[] = [
612
            'settingName' => [
613
                Users::class,
614
                ExtensionForwardingRights::class,
615
            ],
616
            'functions'   => [
617
                self::R_SIP,
618
                self::R_DIALPLAN,
619
            ]
620
        ];
621
622
        $tables[] = [
623
            'settingName' => [
624
                FirewallRules::class,
625
                Fail2BanRules::class,
626
            ],
627
            'functions'   => [
628
                self::R_FIREWALL,
629
            ]
630
        ];
631
632
        $tables[] = [
633
            'settingName' => [
634
                Iax::class,
635
            ],
636
            'functions'   => [
637
                self::R_IAX,
638
                self::R_DIALPLAN,
639
            ]
640
        ];
641
642
        $tables[] = [
643
            'settingName' => [
644
                Codecs::class,
645
            ],
646
            'functions'   => [
647
                self::R_IAX,
648
                self::R_SIP,
649
            ]
650
        ];
651
652
        $tables[] = [
653
            'settingName' => [
654
                SoundFiles::class,
655
            ],
656
            'functions'   => [
657
                self::R_MOH,
658
                self::R_DIALPLAN,
659
            ]
660
        ];
661
662
        $tables[] = [
663
            'settingName' => [
664
                LanInterfaces::class,
665
            ],
666
            'functions'   => [
667
                self::R_NETWORK,
668
                self::R_IAX,
669
                self::R_SIP,
670
            ]
671
        ];
672
673
        $tables[] = [
674
            'settingName' => [
675
                SipHosts::class,
676
            ],
677
            'functions'   => [
678
                self::R_FIREWALL,
679
                self::R_SIP,
680
            ]
681
        ];
682
683
        $tables[] = [
684
            'settingName' => [
685
                NetworkFilters::class,
686
            ],
687
            'functions'   => [
688
                self::R_FIREWALL,
689
                self::R_SIP,
690
                self::R_MANAGERS,
691
            ]
692
        ];
693
694
        $this->modelsDependencyTable = $tables;
695
696
    }
697
698
    /**
699
     * Анализ изменения данных моделей ядра.
700
     * @param $called_class
701
     */
702
    private function fillModifiedTablesFromModels($called_class):void{
703
        foreach ($this->modelsDependencyTable as $dependencydata){
704
            if (!in_array($called_class, $dependencydata['settingName'], true)) {
705
                continue;
706
            }
707
            foreach ($dependencydata['functions'] as $function){
708
                $this->modified_tables[$function] = true;
709
            }
710
        }
711
    }
712
713
    /**
714
     * Анализ изменения параметров в m_PbxSettings
715
     * @param $called_class
716
     * @param $recordId
717
     */
718
    private function fillModifiedTablesFromPbxSettingsData($called_class, $recordId):void{
719
        if(PbxSettings::class !== $called_class){
720
            return;
721
        }
722
        /** @var PbxSettings $pbxSettings */
723
        $pbxSettings = PbxSettings::findFirstByKey($recordId);
724
        if ($pbxSettings === null) {
725
            return;
726
        }
727
        $settingName = $pbxSettings->key;
728
        foreach ($this->pbxSettingsDependencyTable as $data){
729
            $additionalConditions = (isset($data['strPosKey']) && strpos($settingName, $data['strPosKey']) !== false);
730
            if (!$additionalConditions && !in_array($settingName, $data['settingName'], true)) {
731
                continue;
732
            }
733
            foreach ($data['functions'] as $function){
734
                $this->modified_tables[$function] = true;
735
            }
736
        }
737
    }
738
739
    /**
740
     * Анализ изменения параметров дополнительный модулей.
741
     * @param $called_class
742
     * @param $recordId
743
     */
744
    private function fillModifiedTablesFromPbxExtensionModules($called_class, $recordId):void{
745
        if(PbxExtensionModules::class !== $called_class){
746
            return;
747
        }
748
        $moduleSettings = PbxExtensionModules::findFirstById($recordId);
749
        if ($moduleSettings!==null){
750
            $this->modified_tables[self::R_PBX_EXTENSION_STATE]               = true;
751
            $this->modified_tables['parameters'][self::R_PBX_EXTENSION_STATE] = $moduleSettings;
752
        }
753
754
    }
755
756
    /**
757
     * Restarts gnats queue server daemon
758
     */
759
    public function reloadNats(): void
760
    {
761
        $natsConf = new NatsConf();
762
        $natsConf->reStart();
763
    }
764
765
    /**
766
     * Reloads Asterisk dialplan
767
     */
768
    public function reloadDialplan(): void
769
    {
770
        PBX::dialplanReload();
771
    }
772
773
    /**
774
     * Reloads Asterisk manager interface module
775
     */
776
    public function reloadManager(): void
777
    {
778
        PBX::managerReload();
779
    }
780
781
    /**
782
     * Generates queue.conf and restart asterisk queue module
783
     */
784
    public function reloadQueues(): void
785
    {
786
        QueueConf::queueReload();
787
    }
788
789
    /**
790
     * Updates custom changes in config files
791
     */
792
    public function updateCustomFiles(): void
793
    {
794
        System::updateCustomFiles();
795
    }
796
797
    /**
798
     * Applies iptables settings and restart firewall
799
     */
800
    public function reloadFirewall(): void
801
    {
802
        IptablesConf::reloadFirewall();
803
    }
804
805
    /**
806
     *  Refreshes networks configs and restarts network daemon
807
     */
808
    public function networkReload(): void
809
    {
810
        System::networkReload();
811
    }
812
813
    /**
814
     * Refreshes IAX configs and reload iax2 module
815
     */
816
    public function reloadIax(): void
817
    {
818
        PBX::iaxReload();
819
    }
820
821
    /**
822
     * Reloads MOH file list in Asterisk.
823
     */
824
    public function reloadMoh(): void
825
    {
826
        PBX::mohReload();
827
    }
828
829
    /**
830
     * Refreshes SIP configs and reload PJSIP module
831
     */
832
    public function reloadSip(): void
833
    {
834
        PBX::sipReload();
835
    }
836
837
    /**
838
     *  Refreshes features configs and reload features module
839
     */
840
    public function reloadFeatures(): void
841
    {
842
        PBX::featuresReload();
843
    }
844
845
    /**
846
     * Restarts CROND daemon
847
     */
848
    public function reloadCron(): void
849
    {
850
        $cron = new CronConf();
851
        $cron->reStart();
852
    }
853
854
    /**
855
     * Restarts NTP daemon
856
     */
857
    public function reloadNtp(): void
858
    {
859
        NTPConf::configure();
860
    }
861
862
    /**
863
     * Restarts Nginx daemon
864
     */
865
    public function reloadNginx(): void
866
    {
867
        $nginxConf = new NginxConf();
868
        $nginxConf->generateConf();
869
        $nginxConf->reStart();
870
    }
871
872
    /**
873
     * Applies modules locations changes and restarts Nginx daemon
874
     */
875
    public function reloadNginxConf(): void
876
    {
877
        $nginxConf = new NginxConf();
878
        $nginxConf->generateModulesConf();
879
        $nginxConf->reStart();
880
    }
881
882
    /**
883
     * Restarts Fail2Ban daemon
884
     */
885
    public function reloadFail2BanConf(): void
886
    {
887
        Fail2BanConf::reloadFail2ban();
888
    }
889
890
    /**
891
     * Restarts PHP-FPM daemon
892
     */
893
    public function reloadPHPFPM(): void
894
    {
895
        PHPConf::reStart();
896
    }
897
898
    /**
899
     * Configures SSH settings
900
     */
901
    public function reloadSSH(): void
902
    {
903
        $sshConf = new SSHConf();
904
        $sshConf->configure();
905
    }
906
907
    /**
908
     * Reconfigures TomeZone settings
909
     */
910
    public function updateTomeZone(): void
911
    {
912
        System::timezoneConfigure();
913
    }
914
915
    /**
916
     * Restarts rsyslog.
917
     */
918
    public function restartSyslogD(): void
919
    {
920
        // Рестарт демона Syslog.
921
        $syslogConf = new SyslogConf();
922
        $syslogConf->reStart();
923
    }
924
925
    /**
926
     *  Reloads Asterisk voicemail module
927
     */
928
    public function reloadVoicemail(): void
929
    {
930
        PBX::voicemailReload();
931
    }
932
933
    /**
934
     *  Reloads WorkerApiCommands worker
935
     */
936
    public function reloadRestAPIWorker(): void
937
    {
938
        Processes::processPHPWorker(WorkerApiCommands::class);
939
    }
940
941
    /**
942
     *  Reloads WorkerCallEvents worker
943
     */
944
    public function reloadWorkerCallEvents(): void
945
    {
946
        Processes::processPHPWorker(WorkerCallEvents::class);
947
    }
948
949
    /**
950
     *  Process after PBXExtension state changes
951
     *
952
     * @param ?\MikoPBX\Common\Models\PbxExtensionModules $record
953
     */
954
    public function afterModuleStateChanged(PbxExtensionModules $record=null): void
955
    {
956
        if ($record===null){
957
            return;
958
        }
959
        // Recreate modules array
960
        PBXConfModulesProvider::recreateModulesProvider();
961
        $this->arrObject = $this->di->get(PBXConfModulesProvider::SERVICE_NAME);
962
963
        $className       = str_replace('Module', '', $record->uniqid);
964
        $configClassName = "\\Modules\\{$record->uniqid}\\Lib\\{$className}Conf";
965
        if (class_exists($configClassName)) {
966
            $configClassObj = new $configClassName();
967
968
            // Reconfigure fail2ban and restart iptables
969
            if (method_exists($configClassObj, 'generateFail2BanJails')
970
                && ! empty($configClassObj->generateFail2BanJails())) {
971
                $this->modified_tables[self::R_FAIL2BAN_CONF] = true;
972
            }
973
974
            // Refresh Nginx conf if module has any locations
975
            if (method_exists($configClassObj, 'createNginxLocations')
976
                && ! empty($configClassObj->createNginxLocations())) {
977
                $this->modified_tables[self::R_NGINX_CONF] = true;
978
            }
979
980
            // Refresh crontab rules if module has any for it
981
            if (method_exists($configClassObj, 'createCronTasks')) {
982
                $tasks = '';
983
                $configClassObj->createCronTasks($tasks);
984
                if ($tasks !== '') {
0 ignored issues
show
introduced by
The condition $tasks !== '' is always false.
Loading history...
985
                    $this->modified_tables[self::R_CRON] = true;
986
                }
987
            }
988
989
            if ($record->disabled === '1' && method_exists($configClassObj, 'onAfterModuleDisable')) {
990
                $configClassObj->onAfterModuleDisable();
991
            } elseif ($record->disabled === '0' && method_exists($configClassObj, 'onAfterModuleEnable')) {
992
                $configClassObj->onAfterModuleEnable();
993
            }
994
        }
995
    }
996
}
997
998
/**
999
 * The start point
1000
 */
1001
WorkerModelsEvents::startWorker($argv??null);