Passed
Push — develop ( 5ed699...652c07 )
by Nikolay
05:25 queued 10s
created

ConfigClass::onAfterModuleEnable()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 0
c 0
b 0
f 0
dl 0
loc 2
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\Modules\Config;
10
11
use MikoPBX\Core\System\MikoPBXConfig;
12
use MikoPBX\PBXCoreREST\Lib\PBXApiResult;
13
use Phalcon\Config;
14
use Phalcon\Di\Injectable;
15
use ReflectionClass as ReflectionClassAlias;
16
17
abstract class ConfigClass extends Injectable implements SystemConfigInterface, AsteriskConfigInterface,
18
                                                         RestAPIConfigInterface
19
{
20
21
    /**
22
     * ID Config class
23
     */
24
    public const ID_CONFIG_CLASS = 'InternalConfigModule';
25
26
27
    /**
28
     * @var \MikoPBX\Core\System\MikoPBXConfig
29
     */
30
    protected MikoPBXConfig $mikoPBXConfig;
31
32
    /**
33
     * @var \Phalcon\Config
34
     */
35
    protected Config $config;
36
37
    /**
38
     * @var bool
39
     */
40
    protected bool $booting;
41
42
    /**
43
     * Error and Notice messages
44
     *
45
     * @var array
46
     */
47
    protected array $messages;
48
49
    /**
50
     * Array of PbxSettings values
51
     */
52
    protected array $generalSettings;
53
54
    /**
55
     * Asterisk config file name
56
     */
57
    protected string $description;
58
59
    /**
60
     * Additional module UniqueID
61
     */
62
    public string $moduleUniqueId;
63
64
    /**
65
     * Additional module directory
66
     */
67
    protected string $moduleDir;
68
69
70
    /**
71
     * ConfigClass constructor.
72
     *
73
     */
74
    public function __construct()
75
    {
76
        $this->config          = $this->di->getShared('config');
77
        $this->booting         = $this->di->getShared('registry')->booting === true;
78
        $this->mikoPBXConfig   = new MikoPBXConfig();
79
        $this->generalSettings = $this->mikoPBXConfig->getGeneralSettings();
80
        $this->moduleUniqueId  = ConfigClass::ID_CONFIG_CLASS;
81
        // Get child class parameters and define module Dir and UniqueID
82
        $reflector        = new ReflectionClassAlias(static::class);
83
        $partsOfNameSpace = explode('\\', $reflector->getNamespaceName());
84
        if (count($partsOfNameSpace) === 3 && $partsOfNameSpace[0] === 'Modules') {
85
            $modulesDir           = $this->config->path('core.modulesDir');
86
            $this->moduleUniqueId = $partsOfNameSpace[1];
87
            $this->moduleDir      = $modulesDir . '/' . $this->moduleUniqueId;
88
        }
89
90
        $this->messages = [];
91
    }
92
93
    public function getSettings(): void
94
    {
95
    }
96
97
    public function generateConfig(): void
98
    {
99
        // Генерация конфигурационных файлов.
100
        $this->echoGenerateConfig();
101
        $this->getSettings();
102
        $this->generateConfigProtected();
103
        $this->echoDone();
104
    }
105
106
107
    /**
108
     * Makes pretty module text block into config file
109
     *
110
     * @param string $addition
111
     *
112
     * @return string
113
     */
114
    protected function confBlockWithComments(string $addition): string
115
    {
116
        $result = '';
117
        if (empty($addition)) {
118
            return $result;
119
        }
120
        if ( ! empty($this->moduleUniqueId) && ConfigClass::ID_CONFIG_CLASS !== $this->moduleUniqueId) {
121
            $result = PHP_EOL . '; ***** BEGIN BY ' . $this->moduleUniqueId . PHP_EOL;
122
            $result .= $addition;
123
            if (substr($addition, -1) !== "\t") {
124
                $result .= "\t";
125
            }
126
            $result .= PHP_EOL . '; ***** END BY ' . $this->moduleUniqueId . PHP_EOL;
127
        } else {
128
            $result .= $addition;
129
        }
130
131
        return $result;
132
    }
133
134
    /**
135
     * Вывод сообщения о генерации конфига.
136
     *
137
     */
138
    protected function echoGenerateConfig(): void
139
    {
140
        if ($this->booting === true && ! empty($this->description)) {
141
            echo "   |- generate config {$this->description}... ";
142
        }
143
    }
144
145
    /**
146
     * Генерация конфигурационного файла asterisk.
147
     */
148
    protected function generateConfigProtected(): void
149
    {
150
    }
151
152
    /**
153
     * Вывод сообщения об окончании генерации.
154
     */
155
    protected function echoDone(): void
156
    {
157
        if ($this->booting === true && ! empty($this->description)) {
158
            echo "\033[32;1mdone\033[0m \n";
159
        }
160
    }
161
162
    // Получаем строки include для секции internal.
163
164
    public function getIncludeInternal(): string
165
    {
166
        // Генерация внутреннего номерного плана.
167
        return '';
168
    }
169
170
    // Получаем строки include для секции internal-transfer.
171
    public function getIncludeInternalTransfer(): string
172
    {
173
        // Генерация внутреннего номерного плана.
174
        return '';
175
    }
176
177
    // Генератор extension для контекста internal.
178
    public function extensionGenInternal(): string
179
    {
180
        // Генерация внутреннего номерного плана.
181
        return '';
182
    }
183
184
    // Генератор extension для контекста internal.
185
    public function extensionGenInternalTransfer(): string
186
    {
187
        // Генерация внутреннего номерного плана.
188
        return '';
189
    }
190
191
192
    // Генератор extension для контекста peers.
193
    public function extensionGenPeerContexts()
194
    {
195
        // Генерация внутреннего номерного плана.
196
        return '';
197
    }
198
199
    // Генератор extensions, дополнительные контексты.
200
    public function extensionGenContexts(): string
201
    {
202
        return '';
203
    }
204
205
    // Генератор хинтов для контекста internal-hints
206
    public function extensionGenHints(): string
207
    {
208
        // Генерация хинтов.
209
        return '';
210
    }
211
212
    // Секция global для extensions.conf.
213
    public function extensionGlobals(): string
214
    {
215
        // Генерация хинтов.
216
        return '';
217
    }
218
219
    // Секция featuremap для features.conf
220
    public function getFeatureMap(): string
221
    {
222
        // Возвращает старкоды.
223
        return '';
224
    }
225
226
    /**
227
     * Генерация контекста для публичных звонков.
228
     *
229
     * @param $conf
230
     *
231
     * @return void
232
     */
233
    public function generatePublicContext(&$conf): void
234
    {
235
    }
236
237
238
    /**
239
     * Будет вызван после старта asterisk.
240
     */
241
    public function onAfterPbxStarted(): void
242
    {
243
    }
244
245
    /**
246
     * Добавление задач в crond.
247
     *
248
     * @param $tasks
249
     */
250
    public function createCronTasks(&$tasks): void
251
    {
252
    }
253
254
255
    /**
256
     * Генератор сеции пиров для sip.conf
257
     *
258
     * @return string
259
     */
260
    public function generatePeersPj(): string
261
    {
262
        return '';
263
    }
264
265
    /**
266
     * Генератор сеции пиров для manager.conf
267
     *
268
     */
269
    public function generateManagerConf(): string
270
    {
271
        return '';
272
    }
273
274
    /**
275
     * Дополнительные параметры для
276
     *
277
     * @param $peer
278
     *
279
     * @return string
280
     */
281
    public function generatePeerPjAdditionalOptions($peer): string
282
    {
283
        return '';
284
    }
285
286
    /**
287
     * Кастомизация исходящего контекста для конкретного маршрута.
288
     *
289
     * @param $rout
290
     *
291
     * @return string
292
     */
293
    public function generateOutRoutContext($rout): string
294
    {
295
        return '';
296
    }
297
298
    /**
299
     * Кастомизация исходящего контекста для конкретного маршрута.
300
     *
301
     * @param $rout
302
     *
303
     * @return string
304
     */
305
    public function generateOutRoutAfterDialContext($rout): string
306
    {
307
        return '';
308
    }
309
310
    /**
311
     * Кастомизация входящего контекста для конкретного маршрута.
312
     *
313
     * @param $id
314
     *
315
     * @return string
316
     */
317
    public function generateIncomingRoutAfterDialContext($id): string
318
    {
319
        return '';
320
    }
321
322
    /**
323
     * Кастомизация входящего контекста для конкретного маршрута.
324
     *
325
     * @param $rout_number
326
     *
327
     * @return string
328
     */
329
    public function generateIncomingRoutBeforeDial($rout_number): string
330
    {
331
        return '';
332
    }
333
334
    /**
335
     * Обработчик события изменения данных в базе настроек mikopbx.db.
336
     *
337
     * @param $data
338
     */
339
    public function modelsEventChangeData($data): void
340
    {
341
    }
342
343
    /**
344
     * Обработчик события изменения данных в базе настроек mikopbx.db.
345
     *
346
     * @param $modified_tables
347
     */
348
    public function modelsEventNeedReload($modified_tables): void
349
    {
350
    }
351
352
    /**
353
     * Returns array of workers classes for WorkerSafeScripts from module
354
     *
355
     * @return array
356
     */
357
    public function getModuleWorkers(): array
358
    {
359
        return [];
360
    }
361
362
    /**
363
     * Returns array of additional firewall rules for module
364
     *
365
     * @return array
366
     */
367
    public function getDefaultFirewallRules(): array
368
    {
369
        return [];
370
    }
371
372
    /**
373
     * Return messages after function or method execution
374
     *
375
     * @return array
376
     */
377
    public function getMessages(): array
378
    {
379
        return $this->messages;
380
    }
381
382
    /**
383
     * Process enable action in web interface
384
     *
385
     * @return bool
386
     */
387
    public function onBeforeModuleEnable(): bool
388
    {
389
        return true;
390
    }
391
392
    /**
393
     * Process after enable action in web interface
394
     *
395
     * @return void
396
     */
397
    public function onAfterModuleEnable(): void
398
    {
399
    }
400
401
    /**
402
     * Process disable action in web interface
403
     *
404
     * @return bool
405
     */
406
    public function onBeforeModuleDisable(): bool
407
    {
408
        return true;
409
    }
410
411
    /**
412
     * Process after disable action in web interface
413
     *
414
     * @return void
415
     */
416
    public function onAfterModuleDisable(): void
417
    {
418
    }
419
420
    /**
421
     * Генератор modules.conf
422
     *
423
     * @return string
424
     */
425
    public function generateModulesConf(): string
426
    {
427
        return '';
428
    }
429
430
    /**
431
     *  Process CoreAPI requests under root rights
432
     *
433
     * @param array $request
434
     *
435
     * @return \MikoPBX\PBXCoreREST\Lib\PBXApiResult
436
     */
437
    public function moduleRestAPICallback(array $request): PBXApiResult
438
    {
439
        $res            = new PBXApiResult();
440
        $res->processor = __METHOD__;
441
        $action         = strtoupper($request['action']);
442
        switch ($action) {
443
            case 'CHECK':
444
            case 'RELOAD':
445
                $res->success = true;
446
                break;
447
            default:
448
                $res->success    = false;
449
                $res->messages[] = 'API action not found in moduleRestAPICallback';
450
        }
451
452
        return $res;
453
    }
454
455
    /**
456
     * Returns array of additional routes for PBXCoreREST interface from module
457
     *
458
     * @return array
459
     */
460
    public function getPBXCoreRESTAdditionalRoutes(): array
461
    {
462
        return [];
463
    }
464
465
    /**
466
     * Create additional Nginx locations from modules
467
     *
468
     */
469
    public function createNginxLocations(): string
470
    {
471
        return '';
472
    }
473
474
    /**
475
     * Generates additional fail2ban jail conf rules from modules
476
     *
477
     * @return string
478
     */
479
    public function generateFail2BanJails(): string
480
    {
481
        return '';
482
    }
483
484
485
}