Passed
Branch develop (309f3f)
by Nikolay
10:15
created

VoiceMailConf::generateConfigProtected()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 71
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 38
dl 0
loc 71
rs 9.312
c 0
b 0
f 0
cc 3
nc 4
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\Asterisk\Configs;
21
22
23
use MikoPBX\Core\System\Processes;
24
use MikoPBX\Core\System\Storage;
25
use MikoPBX\Core\System\Util;
26
27
class VoiceMailConf extends CoreConfigClass
28
{
29
    protected string $description = 'voicemail.conf';
30
31
    /**
32
     * Prepares additional contexts sections in the extensions.conf file
33
     *
34
     * @return string
35
     */
36
    public function extensionGenContexts(): string
37
    {
38
        $conf  = "[voice_mail_peer] \n";
39
        $conf .= 'exten => voicemail,1,Answer()' . "\n\t";
40
        $conf .= 'same => n,ExecIf($["${CHANNEL:0:5}" == "Local"]?Set(pl=${IF($["${CHANNEL:-1}" == "1"]?2:1)}))' . "\n\t";
41
        $conf .= 'same => n,ExecIf($["${CHANNEL:0:5}" == "Local"]?Set(bridgePeer=${IMPORT(${CUT(CHANNEL,\;,1)}\;${pl},BRIDGEPEER)}))' . "\n\t";
42
        $conf .= 'same => n,ExecIf($[ "${FROM_CHAN}" == "${bridgePeer}" ]?ChannelRedirect(${bridgePeer},${CONTEXT},${EXTEN},2))' . "\n\t";
43
        $conf .= 'same => n,AGI(/usr/www/src/Core/Asterisk/agi-bin/clean_timeout.php)' . "\n\t";
44
        $conf .= 'same => n,Gosub(voicemail_start,${EXTEN},1)' . "\n\t";
45
        $conf .= 'same => n,VoiceMail(admin@voicemailcontext)' . "\n\t";
46
        $conf .= 'same => n,Hangup()' . "\n\n";
47
48
        return  $conf;
49
    }
50
51
    protected function generateConfigProtected(): void
52
    {
53
        // Уважаемый ${VM_NAME}:\n\n\tВам пришло новое голосовое сообщение длиной ${VM_DUR}
54
        // под номером (number ${VM_MSGNUM})\nв ящик ${VM_MAILBOX} от ${VM_CALLERID}, в ${VM_DATE}. \n\t
55
        $emailsubject = $this->generalSettings['MailTplVoicemailSubject'];
56
        $emailsubject = str_replace(["\n", "\t"], '', $emailsubject);
57
58
        $emailbody = $this->generalSettings['MailTplVoicemailBody'];
59
        $emailbody = str_replace(["\n", "\t"], ['\n', ''], $emailbody);
60
61
        $emailfooter = $this->generalSettings['MailTplVoicemailFooter'];
62
        $emailfooter = str_replace(["\n", "\t"], ['\n', ''], $emailfooter);
63
64
        $from = $this->generalSettings['MailSMTPSenderAddress'];
65
        if (empty($from)) {
66
            $from =  $this->generalSettings['MailSMTPUsername'];
67
        }
68
69
        $timezone = $this->generalSettings['PBXTimezone'];
70
        $msmtpPath = Util::which('voicemail-sender');
71
72
        $conf     = "[general]\n" .
73
            "format=wav\n" .
74
            "attach=yes\n" .
75
            "maxmsg=100\n" .
76
            "maxsecs=120\n" .
77
            "maxgreet=60\n" .
78
            "maxsilence=10\n" .
79
            "silencethreshold=128\n" .
80
            "maxlogins=3\n" .
81
            "moveheard=yes\n" .
82
            "charset=UTF-8\n" .
83
            "pbxskip=yes\n" .
84
            "fromstring=VoiceMail\n" .
85
            "emailsubject={$emailsubject}\n" .
86
            "emailbody={$emailbody}".'\n\n'."{$emailfooter}\n" .
87
            "emaildateformat=%A, %d %B %Y в %H:%M:%S\n" .
88
            "pagerdateformat=%T %D\n" .
89
            // "mailcmd={$msmtpPath} --file=/etc/msmtp.conf -t\n" .
90
            "mailcmd={$msmtpPath}\n" .
91
            "serveremail={$from}\n\n" .
92
            "[zonemessages]\n" .
93
            "local={$timezone}|'vm-received' q 'digits/at' H 'hours' M 'minutes'\n\n";
94
95
        $conf .= "[voicemailcontext]\n";
96
97
        $mail_box = $this->generalSettings['VoicemailNotificationsEmail'];
98
        if (empty($mail_box)) {
99
            $mail_box = $this->generalSettings['SystemNotificationsEmail'];
100
        }
101
        $conf .= "admin => admin," . Util::translate("user") . ",{$mail_box},,attach=yes|tz=local|delete=yes\n";
102
        /*
103
        $peers = Sip::find('type="peer"');
104
        foreach ($peers as $peer){
105
            $username = $peer->extension;
106
            $mail_box = '';
107
            $exten = Extensions::findFirst("number='{$username}'");
108
            if($exten !== null){
109
                $user = Users::findFirst("id='{$exten->userid}'");
110
                if($user !== null){
111
                    $username = $user->username;
112
                    $mail_box = $user->email;
113
                }
114
            }
115
116
            // $conf.= "{$peer->extension} => {$peer->extension},{$username},{$mail_box},,attach=yes|tz=local|delete=yes\n";
117
            $conf.= "{$peer->extension} => {$peer->extension},{$username},{$mail_box},,attach=yes|tz=local\n";
118
        }
119
        //*/
120
121
        Util::fileWriteContent($this->config->path('asterisk.astetcdir') . '/voicemail.conf', $conf);
122
    }
123
124
    /**
125
     * @param      $srcFileName
126
     * @param      $time
127
     * @param bool $copy
128
     * @return string
129
     */
130
    public static function getCopyFilename($srcFileName, $linkedId, $time, bool $copy = true):string{
131
        $filename = Util::trimExtensionForFile($srcFileName) . '.wav';
132
        $recordingFile = '';
133
        // Переопределим путь к файлу записи разговора. Для конферецнии файл один.
134
        $monitor_dir = Storage::getMonitorDir();
135
        $sub_dir     = date('Y/m/d', $time);
136
        $dirName = "$monitor_dir/$sub_dir/INBOX/";
137
        if(Util::mwMkdir($dirName)){
138
            $recordingFile = $dirName.$linkedId.'.wav';
139
            $cpPath = Util::which('cp');
140
            if($copy === true){
141
                Processes::mwExec("{$cpPath} {$filename} {$recordingFile}");
142
            }
143
            if($copy === true && !file_exists($recordingFile)){
144
                $recordingFile = '';
145
            }else{
146
                $recordingFile = Util::trimExtensionForFile($recordingFile) . '.mp3';
147
            }
148
        }
149
        return $recordingFile;
150
    }
151
152
}