Passed
Push — develop ( 4dd23c...f02a5e )
by Портнов
05:07
created

Notifications::configure()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 35
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 27
c 0
b 0
f 0
dl 0
loc 35
rs 9.1768
cc 5
nc 6
nop 0
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\System;
21
22
use PHPMailer\PHPMailer\PHPMailer;
23
use Throwable;
24
25
/**
26
 * Уведомления.
27
 */
28
class Notifications
29
{
30
    public const TYPE_PHP_MAILER = 'PHP_MAILER';
31
    private array $settings;
32
    private bool  $enableNotifications;
33
    private string $fromAddres;
34
    private string $fromName;
35
36
    /**
37
     * Notifications constructor.
38
     */
39
    public function __construct()
40
    {
41
        $mikoPBXConfig  = new MikoPBXConfig();
42
        $this->settings = $mikoPBXConfig->getGeneralSettings();
43
        $this->enableNotifications = $this->settings['MailEnableNotifications'] === '1';
44
45
        $mailSMTPSenderAddress = $this->settings['MailSMTPSenderAddress'] ?? '';
46
        if (!empty($mailSMTPSenderAddress)) {
47
            $this->fromAddres = $mailSMTPSenderAddress;
48
        } else {
49
            $this->fromAddres = $this->settings['MailSMTPUsername'];
50
        }
51
52
        if (empty($this->settings['MailSMTPFromUsername'])) {
53
            $this->fromName = 'MikoPBX Notification';
54
        } else {
55
            $this->fromName = $this->settings['MailSMTPFromUsername'];
56
        }
57
    }
58
59
    /**
60
     * Возвращает инициализированный объект PHPMailer.
61
     * @return PHPMailer
62
     */
63
    public function getMailSender():PHPMailer
64
    {
65
        $mail = new PHPMailer();
66
        $mail->isSMTP();
67
        $mail->SMTPDebug = 0;
68
        $mail->Timeout   = 5;
69
        $mail->Host = $this->settings['MailSMTPHost'];
70
        if ($this->settings["MailSMTPUseTLS"] === "1") {
71
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
72
            // $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
73
        } else {
74
            $mail->SMTPSecure = '';
75
        }
76
        if (empty($this->settings['MailSMTPUsername']) && empty($this->settings['MailSMTPPassword'])) {
77
            $mail->SMTPAuth = false;
78
        } else {
79
            $mail->SMTPAuth = true;
80
            $mail->Username = $this->settings['MailSMTPUsername'];
81
            $mail->Password = $this->settings['MailSMTPPassword'];
82
            if ($this->settings["MailSMTPCertCheck"] !== '1') {
83
                $mail->SMTPOptions = [
84
                    'ssl' => [
85
                        'verify_peer'       => false,
86
                        'verify_peer_name'  => false,
87
                        'allow_self_signed' => true,
88
                    ],
89
                ];
90
            }
91
        }
92
        $mail->Port    = (integer)$this->settings['MailSMTPPort'];
93
        $mail->CharSet = 'UTF-8';
94
95
        return $mail;
96
    }
97
98
    public static function checkConnection($type):bool
99
    {
100
        $timeoutPath = Util::which('timeout');
101
        $phpPath = Util::which('php');
102
        $result  = Processes::mwExec("$timeoutPath 5 $phpPath -f /etc/rc/emailTestConnection.php ".$type);
103
        if($result !== 0 ){
104
            Util::sysLogMsg('PHPMailer', 'Error connect to SMTP server... ('. $type.')', LOG_ERR);
105
        }
106
107
        return ($result === 0);
108
    }
109
110
    /**
111
     * Отправка сообщения с использованием PHPMailer
112
     *
113
     * @param      $to
114
     * @param        $subject
115
     * @param        $message
116
     * @param string $filename
117
     *
118
     * @return bool
119
     */
120
    public function sendMail($to, $subject, $message, string $filename = ''):bool
121
    {
122
        if (! $this->enableNotifications) {
123
            return false;
124
        }
125
        $messages = [];
126
        try {
127
            $mail = $this->getMailSender();
128
            $mail->setFrom($this->fromAddres, $this->fromName);
129
            $to = explode(',', $to);
130
            foreach ($to as $email){
131
                $mail->addAddress($email);
132
            }
133
            if (file_exists($filename)) {
134
                $mail->addAttachment($filename);
135
            }
136
            $mail->isHTML(true);
137
            $mail->Subject = $subject;
138
            $mail->Body    = $message;
139
140
            if(!self::checkConnection(self::TYPE_PHP_MAILER)){
141
                return false;
142
            }
143
            if ( ! $mail->send()) {
144
                $messages[] = $mail->ErrorInfo;
145
            }
146
        } catch (Throwable $e) {
147
            $messages[] = $e->getMessage();
148
        }
149
        if (!empty($messages)) {
150
            Util::sysLogMsg('PHPMailer', implode(' ', $messages), LOG_ERR);
151
        }
152
        return true;
153
    }
154
155
    /**
156
     * Отправка тестового сообщения.
157
     * @return bool
158
     */
159
    public function sendTestMail(): bool{
160
        if(!self::checkConnection(self::TYPE_PHP_MAILER)){
161
            return false;
162
        }
163
        $systemNotificationsEmail = $this->settings['SystemNotificationsEmail'];
164
        $result = $this->sendMail($systemNotificationsEmail, 'Test mail from MIKO PBX', '<b>Test message</b><hr>');
165
        return ($result===true);
166
    }
167
168
    public static function testConnectionMSMTP():bool
169
    {
170
        $path = Util::which('msmtp');
171
        $result = Processes::mwExec("$path --file=/etc/msmtp.conf -S --timeout 1", $out);
172
        return ($result === 0);
173
    }
174
175
    public function testConnectionPHPMailer():bool
176
    {
177
        $mail = $this->getMailSender();
178
        try {
179
            $result = $mail->smtpConnect();
180
        }catch (\Exception $e){
181
            $result = false;
182
        }
183
        return $result;
184
    }
185
}