Completed
Push — master ( c2d4ba...2895c3 )
by
unknown
02:24
created

Mailer::send()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
cc 5
eloc 11
nc 4
nop 1
dl 0
loc 19
rs 8.8571
c 2
b 0
f 1
1
<?php namespace Helpers;
2
3
include_once(MODX_BASE_PATH . 'assets/lib/APIHelpers.class.php');
4
include_once(MODX_MANAGER_PATH . 'includes/extenders/modxmailer.class.inc.php');
5
6
/**
7
 * Class Mailer
8
 * @package Helpers
9
 */
10
class Mailer
11
{
12
    /**
13
     * @var \PHPMailer $mail
14
     */
15
    protected $mail = null;
16
    protected $modx = null;
17
    public $config = array();
18
    protected $debug = false;
19
    protected $queuePath = 'assets/cache/mail/';
20
21
    /**
22
     * Mailer constructor.
23
     * @param \DocumentParser $modx
24
     * @param $cfg
25
     * @param bool $debug
26
     */
27
    public function __construct(\DocumentParser $modx, $cfg, $debug = false)
28
    {
29
        $this->modx = $modx;
30
        $this->mail = new \MODxMailer();
0 ignored issues
show
Documentation Bug introduced by
It seems like new \MODxMailer() of type object<MODxMailer> is incompatible with the declared type object<PHPMailer> of property $mail.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
31
        $this->mail->init($modx);
32
        $this->config = $cfg;
33
        $this->debug = $debug;
34
        $this->applyMailConfig();
35
    }
36
37
    /**
38
     * @param string $type
39
     * @param string $addr
40
     * @return $this
41
     */
42
    public function addAddressToMailer($type, $addr)
43
    {
44
        if (!empty($addr)) {
45
            $a = array_filter(array_map('trim', explode(',', $addr)));
46
            foreach ($a as $address) {
47
                switch ($type) {
48
                    case 'to':
49
                        $this->mail->AddAddress($address);
50
                        break;
51
                    case 'cc':
52
                        $this->mail->AddCC($address);
53
                        break;
54
                    case 'bcc':
55
                        $this->mail->AddBCC($address);
56
                        break;
57
                    case 'replyTo':
58
                        $this->mail->AddReplyTo($address);
59
                }
60
            }
61
        }
62
63
        return $this;
64
    }
65
66
    /**
67
     * @param array $filelist
68
     * @return $this
69
     */
70
    public function attachFiles($filelist = array())
71
    {
72
        $contentType = "application/octetstream";
73
        foreach ($filelist as $file) {
74
            $this->mail->AddAttachment($file['filepath'], $file['filename'], "base64", $contentType);
75
        }
76
77
        return $this;
78
    }
79
80
    /**
81
     * @param $report
82
     * @return bool
83
     */
84
    public function send($report)
85
    {
86
        //если отправлять некуда или незачем, то делаем вид, что отправили
87
        if (!$this->getCFGDef('to') || $this->getCFGDef('noemail')) {
88
            return true;
89
        } elseif (empty($report)) {
90
            return false;
91
        }
92
93
        $this->mail->Body = $report;
94
95
        $result = $this->mail->send();
96
        if ($result) {
97
            $this->mail->ClearAllRecipients();
98
            $this->mail->ClearAttachments();
99
        }
100
101
        return $result;
102
    }
103
104
    /**
105
     * @param $report
106
     * @return bool
107
     */
108
    public function toQueue($report)
109
    {
110
        //если отправлять некуда или незачем, то делаем вид, что отправили
111
        if (!$this->getCFGDef('to') || $this->getCFGDef('noemail')) {
112
            return true;
113
        } elseif (empty($report)) {
114
            return false;
115
        }
116
117
        $this->mail->Body = $report;
118
119
        $this->Body = $this->modx->removeSanitizeSeed($this->mail->Body);
0 ignored issues
show
Bug introduced by
The property Body does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
120
        $this->Subject = $this->modx->removeSanitizeSeed($this->mail->Subject);
0 ignored issues
show
Bug introduced by
The property Subject does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
121
        try {
122
            $result = $this->mail->preSend() && $this->saveMessage();
123
        } catch (\phpmailerException $e) {
0 ignored issues
show
Bug introduced by
The class phpmailerException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
124
            $this->mail->SetError($e->getMessage());
125
126
            $result = false;
127
        }
128
129
        if ($result) {
130
            $this->mail->ClearAllRecipients();
131
            $this->mail->ClearAttachments();
132
            $result = $this->getFileName();
133
        }
134
135
        return $result;
136
    }
137
138
    /**
139
     * @param string $path
140
     * @return bool
141
     */
142
    public function setQueuePath($path = '') {
143
        if (!empty($path)) {
144
            $this->queuePath = $path;
145
            return true;
146
        } else {
147
            return false;
148
        }
149
    }
150
151
    /**
152
     * @return mixed
153
     */
154
    protected function saveMessage()
155
    {
156
        $data = serialize(array(
157
            "header" => $this->mail->getMIMEHeader(),
158
            "body"   => $this->mail->getMIMEBody(),
159
            "config" => $this->config
160
        ));
161
        $file = $this->getFileName();
162
        $dir = MODX_BASE_PATH . $this->queuePath;
163
        if (!is_dir($dir)) {
164
            @mkdir($dir);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
165
        }
166
        $result = @file_put_contents($dir . $file, $data) !== false;
167
        if ($result) {
168
            $result = $file;
169
        }
170
171
        return $result;
172
    }
173
174
    /**
175
     * @return string
176
     */
177
    protected function getFileName() {
178
        return $this->mail->getMessageID() . '.eml';
179
    }
180
181
    /**
182
     * @param $file
183
     * @return bool
184
     */
185
    public function fromQueue($file)
186
    {
187
        $result = false;
188
        $dir = MODX_BASE_PATH . $this->queuePath;
189
        if (file_exists($dir . $file) && is_readable($dir . $file)) {
190
            $message = unserialize(file_get_contents($dir . $file));
191
            $this->config = $message['config'];
192
            $this->applyMailConfig();
193
            $this->mail->setMIMEHeader($message['header'])->setMIMEBody($message['body']);
194
            unset($message);
195
            $result = $this->mail->postSend();
196
            if ($result) {
197
                $this->mail->setMIMEBody()->setMIMEHeader();
198
                @unlink($dir . $file);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
199
            }
200
        }
201
202
        return $result;
203
    }
204
205
    /**
206
     * @return $this
207
     */
208
    protected function applyMailConfig()
209
    {
210
        $this->mail->IsHTML($this->getCFGDef('isHtml', 1));
211
        $this->mail->From = $this->getCFGDef('from', $this->modx->config['emailsender']);
212
        $this->mail->FromName = $this->getCFGDef('fromName', $this->modx->config['site_name']);
213
        $this->mail->Subject = $this->getCFGDef('subject');
214
        $this->addAddressToMailer("replyTo", $this->getCFGDef('replyTo'));
215
        $this->addAddressToMailer("to", $this->getCFGDef('to'));
216
        $this->addAddressToMailer("cc", $this->getCFGDef('cc'));
217
        $this->addAddressToMailer("bcc", $this->getCFGDef('bcc'));
218
219
        return $this;
220
    }
221
222
    /**
223
     * @param string $param
224
     * @param mixed $default
225
     * @return mixed
226
     */
227
    public function getCFGDef($param, $default = null)
228
    {
229
        return \APIhelpers::getkey($this->config, $param, $default);
230
    }
231
}
232