xref: /dokuwiki/inc/Mailer.class.php (revision 486f82fcdeb063c787481ca7ff91976dc6961f85)
1<?php
2/**
3 * A class to build and send multi part mails (with HTML content and embedded
4 * attachments). All mails are assumed to be in UTF-8 encoding.
5 *
6 * Attachments are handled in memory so this shouldn't be used to send huge
7 * files, but then again mail shouldn't be used to send huge files either.
8 *
9 * @author Andreas Gohr <andi@splitbrain.org>
10 */
11
12use dokuwiki\Extension\Event;
13
14/**
15 * Mail Handling
16 */
17class Mailer {
18
19    protected $headers   = array();
20    protected $attach    = array();
21    protected $html      = '';
22    protected $text      = '';
23
24    protected $boundary  = '';
25    protected $partid    = '';
26    protected $sendparam = null;
27
28    protected $allowhtml = true;
29
30    protected $replacements = array('text'=> array(), 'html' => array());
31
32    /**
33     * Constructor
34     *
35     * Initializes the boundary strings, part counters and token replacements
36     */
37    public function __construct() {
38        global $conf;
39        /* @var Input $INPUT */
40        global $INPUT;
41
42        $server = parse_url(DOKU_URL, PHP_URL_HOST);
43        if(strpos($server,'.') === false) $server .= '.localhost';
44
45        $this->partid   = substr(md5(uniqid(mt_rand(), true)),0, 8).'@'.$server;
46        $this->boundary = '__________'.md5(uniqid(mt_rand(), true));
47
48        $listid = implode('.', array_reverse(explode('/', DOKU_BASE))).$server;
49        $listid = strtolower(trim($listid, '.'));
50        $messageid = uniqid(mt_rand(), true) . "@$server";
51
52        $this->allowhtml = (bool)$conf['htmlmail'];
53
54        // add some default headers for mailfiltering FS#2247
55        if(!empty($conf['mailreturnpath'])) {
56            $this->setHeader('Return-Path', $conf['mailreturnpath']);
57        }
58        $this->setHeader('X-Mailer', 'DokuWiki');
59        $this->setHeader('X-DokuWiki-User', $INPUT->server->str('REMOTE_USER'));
60        $this->setHeader('X-DokuWiki-Title', $conf['title']);
61        $this->setHeader('X-DokuWiki-Server', $server);
62        $this->setHeader('X-Auto-Response-Suppress', 'OOF');
63        $this->setHeader('List-Id', $conf['title'].' <'.$listid.'>');
64        $this->setHeader('Date', date('r'), false);
65        $this->setHeader('Message-Id', "<$messageid>");
66
67        $this->prepareTokenReplacements();
68    }
69
70    /**
71     * Attach a file
72     *
73     * @param string $path  Path to the file to attach
74     * @param string $mime  Mimetype of the attached file
75     * @param string $name The filename to use
76     * @param string $embed Unique key to reference this file from the HTML part
77     */
78    public function attachFile($path, $mime, $name = '', $embed = '') {
79        if(!$name) {
80            $name = \dokuwiki\Utf8\PhpString::basename($path);
81        }
82
83        $this->attach[] = array(
84            'data'  => file_get_contents($path),
85            'mime'  => $mime,
86            'name'  => $name,
87            'embed' => $embed
88        );
89    }
90
91    /**
92     * Attach a file
93     *
94     * @param string $data  The file contents to attach
95     * @param string $mime  Mimetype of the attached file
96     * @param string $name  The filename to use
97     * @param string $embed Unique key to reference this file from the HTML part
98     */
99    public function attachContent($data, $mime, $name = '', $embed = '') {
100        if(!$name) {
101            list(, $ext) = explode('/', $mime);
102            $name = count($this->attach).".$ext";
103        }
104
105        $this->attach[] = array(
106            'data'  => $data,
107            'mime'  => $mime,
108            'name'  => $name,
109            'embed' => $embed
110        );
111    }
112
113    /**
114     * Callback function to automatically embed images referenced in HTML templates
115     *
116     * @param array $matches
117     * @return string placeholder
118     */
119    protected function autoEmbedCallBack($matches) {
120        static $embeds = 0;
121        $embeds++;
122
123        // get file and mime type
124        $media = cleanID($matches[1]);
125        list(, $mime) = mimetype($media);
126        $file = mediaFN($media);
127        if(!file_exists($file)) return $matches[0]; //bad reference, keep as is
128
129        // attach it and set placeholder
130        $this->attachFile($file, $mime, '', 'autoembed'.$embeds);
131        return '%%autoembed'.$embeds.'%%';
132    }
133
134    /**
135     * Add an arbitrary header to the mail
136     *
137     * If an empy value is passed, the header is removed
138     *
139     * @param string $header the header name (no trailing colon!)
140     * @param string|string[] $value  the value of the header
141     * @param bool   $clean  remove all non-ASCII chars and line feeds?
142     */
143    public function setHeader($header, $value, $clean = true) {
144        $header = str_replace(' ', '-', ucwords(strtolower(str_replace('-', ' ', $header)))); // streamline casing
145        if($clean) {
146            $header = preg_replace('/[^a-zA-Z0-9_ \-\.\+\@]+/', '', $header);
147            $value  = preg_replace('/[^a-zA-Z0-9_ \-\.\+\@<>]+/', '', $value);
148        }
149
150        // empty value deletes
151        if(is_array($value)){
152            $value = array_map('trim', $value);
153            $value = array_filter($value);
154            if(!$value) $value = '';
155        }else{
156            $value = trim($value);
157        }
158        if($value === '') {
159            if(isset($this->headers[$header])) unset($this->headers[$header]);
160        } else {
161            $this->headers[$header] = $value;
162        }
163    }
164
165    /**
166     * Set additional parameters to be passed to sendmail
167     *
168     * Whatever is set here is directly passed to PHP's mail() command as last
169     * parameter. Depending on the PHP setup this might break mailing alltogether
170     *
171     * @param string $param
172     */
173    public function setParameters($param) {
174        $this->sendparam = $param;
175    }
176
177    /**
178     * Set the text and HTML body and apply replacements
179     *
180     * This function applies a whole bunch of default replacements in addition
181     * to the ones specified as parameters
182     *
183     * If you pass the HTML part or HTML replacements yourself you have to make
184     * sure you encode all HTML special chars correctly
185     *
186     * @param string $text     plain text body
187     * @param array  $textrep  replacements to apply on the text part
188     * @param array  $htmlrep  replacements to apply on the HTML part, null to use $textrep (urls wrapped in <a> tags)
189     * @param string $html     the HTML body, leave null to create it from $text
190     * @param bool   $wrap     wrap the HTML in the default header/Footer
191     */
192    public function setBody($text, $textrep = null, $htmlrep = null, $html = null, $wrap = true) {
193
194        $htmlrep = (array)$htmlrep;
195        $textrep = (array)$textrep;
196
197        // create HTML from text if not given
198        if($html === null) {
199            $html = $text;
200            $html = hsc($html);
201            $html = preg_replace('/^----+$/m', '<hr >', $html);
202            $html = nl2br($html);
203        }
204        if($wrap) {
205            $wrapper = rawLocale('mailwrap', 'html');
206            $html = preg_replace('/\n-- <br \/>.*$/s', '', $html); //strip signature
207            $html = str_replace('@EMAILSIGNATURE@', '', $html); //strip @EMAILSIGNATURE@
208            $html = str_replace('@HTMLBODY@', $html, $wrapper);
209        }
210
211        if(strpos($text, '@EMAILSIGNATURE@') === false) {
212            $text .= '@EMAILSIGNATURE@';
213        }
214
215        // copy over all replacements missing for HTML (autolink URLs)
216        foreach($textrep as $key => $value) {
217            if(isset($htmlrep[$key])) continue;
218            if(media_isexternal($value)) {
219                $htmlrep[$key] = '<a href="'.hsc($value).'">'.hsc($value).'</a>';
220            } else {
221                $htmlrep[$key] = hsc($value);
222            }
223        }
224
225        // embed media from templates
226        $html = preg_replace_callback(
227            '/@MEDIA\(([^\)]+)\)@/',
228            array($this, 'autoEmbedCallBack'), $html
229        );
230
231        // add default token replacements
232        $trep = array_merge($this->replacements['text'], (array)$textrep);
233        $hrep = array_merge($this->replacements['html'], (array)$htmlrep);
234
235        // Apply replacements
236        foreach($trep as $key => $substitution) {
237            $text = str_replace('@'.strtoupper($key).'@', $substitution, $text);
238        }
239        foreach($hrep as $key => $substitution) {
240            $html = str_replace('@'.strtoupper($key).'@', $substitution, $html);
241        }
242
243        $this->setHTML($html);
244        $this->setText($text);
245    }
246
247    /**
248     * Set the HTML part of the mail
249     *
250     * Placeholders can be used to reference embedded attachments
251     *
252     * You probably want to use setBody() instead
253     *
254     * @param string $html
255     */
256    public function setHTML($html) {
257        $this->html = $html;
258    }
259
260    /**
261     * Set the plain text part of the mail
262     *
263     * You probably want to use setBody() instead
264     *
265     * @param string $text
266     */
267    public function setText($text) {
268        $this->text = $text;
269    }
270
271    /**
272     * Add the To: recipients
273     *
274     * @see cleanAddress
275     * @param string|string[]  $address Multiple adresses separated by commas or as array
276     */
277    public function to($address) {
278        $this->setHeader('To', $address, false);
279    }
280
281    /**
282     * Add the Cc: recipients
283     *
284     * @see cleanAddress
285     * @param string|string[]  $address Multiple adresses separated by commas or as array
286     */
287    public function cc($address) {
288        $this->setHeader('Cc', $address, false);
289    }
290
291    /**
292     * Add the Bcc: recipients
293     *
294     * @see cleanAddress
295     * @param string|string[]  $address Multiple adresses separated by commas or as array
296     */
297    public function bcc($address) {
298        $this->setHeader('Bcc', $address, false);
299    }
300
301    /**
302     * Add the From: address
303     *
304     * This is set to $conf['mailfrom'] when not specified so you shouldn't need
305     * to call this function
306     *
307     * @see cleanAddress
308     * @param string  $address from address
309     */
310    public function from($address) {
311        $this->setHeader('From', $address, false);
312    }
313
314    /**
315     * Add the mail's Subject: header
316     *
317     * @param string $subject the mail subject
318     */
319    public function subject($subject) {
320        $this->headers['Subject'] = $subject;
321    }
322
323    /**
324     * Return a clean name which can be safely used in mail address
325     * fields. That means the name will be enclosed in '"' if it includes
326     * a '"' or a ','. Also a '"' will be escaped as '\"'.
327     *
328     * @param string $name the name to clean-up
329     * @see cleanAddress
330     */
331    public function getCleanName($name) {
332        $name = trim($name, " \t\"");
333        $name = str_replace('"', '\"', $name, $count);
334        if ($count > 0 || strpos($name, ',') !== false) {
335            $name = '"'.$name.'"';
336        }
337        return $name;
338    }
339
340    /**
341     * Sets an email address header with correct encoding
342     *
343     * Unicode characters will be deaccented and encoded base64
344     * for headers. Addresses may not contain Non-ASCII data!
345     *
346     * If @$addresses is a string then it will be split into multiple
347     * addresses. Addresses must be separated by a comma. If the display
348     * name includes a comma then it MUST be properly enclosed by '"' to
349     * prevent spliting at the wrong point.
350     *
351     * Example:
352     *   cc("föö <foo@bar.com>, me@somewhere.com","TBcc");
353     *   to("foo, Dr." <foo@bar.com>, me@somewhere.com");
354     *
355     * @param string|string[]  $addresses Multiple adresses separated by commas or as array
356     * @return false|string  the prepared header (can contain multiple lines)
357     */
358    public function cleanAddress($addresses) {
359        $headers = '';
360        if(!is_array($addresses)){
361            $count = preg_match_all('/\s*(?:("[^"]*"[^,]+),*)|([^,]+)\s*,*/', $addresses, $matches, PREG_SET_ORDER);
362            $addresses = array();
363            if ($count !== false && is_array($matches)) {
364                foreach ($matches as $match) {
365                    array_push($addresses, rtrim($match[0], ','));
366                }
367            }
368        }
369
370        foreach($addresses as $part) {
371            $part = preg_replace('/[\r\n\0]+/', ' ', $part); // remove attack vectors
372            $part = trim($part);
373
374            // parse address
375            if(preg_match('#(.*?)<(.*?)>#', $part, $matches)) {
376                $text = trim($matches[1]);
377                $addr = $matches[2];
378            } else {
379                $text = '';
380                $addr = $part;
381            }
382            // skip empty ones
383            if(empty($addr)) {
384                continue;
385            }
386
387            // FIXME: is there a way to encode the localpart of a emailaddress?
388            if(!\dokuwiki\Utf8\Clean::isASCII($addr)) {
389                msg(hsc("E-Mail address <$addr> is not ASCII"), -1, __LINE__, __FILE__, MSG_ADMINS_ONLY);
390                continue;
391            }
392
393            if(!mail_isvalid($addr)) {
394                msg(hsc("E-Mail address <$addr> is not valid"), -1, __LINE__, __FILE__, MSG_ADMINS_ONLY);
395                continue;
396            }
397
398            // text was given
399            if(!empty($text) && !isWindows()) { // No named recipients for To: in Windows (see FS#652)
400                // add address quotes
401                $addr = "<$addr>";
402
403                if(defined('MAILHEADER_ASCIIONLY')) {
404                    $text = \dokuwiki\Utf8\Clean::deaccent($text);
405                    $text = \dokuwiki\Utf8\Clean::strip($text);
406                }
407
408                if(strpos($text, ',') !== false || !\dokuwiki\Utf8\Clean::isASCII($text)) {
409                    $text = '=?UTF-8?B?'.base64_encode($text).'?=';
410                }
411            } else {
412                $text = '';
413            }
414
415            // add to header comma seperated
416            if($headers != '') {
417                $headers .= ', ';
418            }
419            $headers .= $text.' '.$addr;
420        }
421
422        $headers = trim($headers);
423        if(empty($headers)) return false;
424
425        return $headers;
426    }
427
428
429    /**
430     * Prepare the mime multiparts for all attachments
431     *
432     * Replaces placeholders in the HTML with the correct CIDs
433     *
434     * @return string mime multiparts
435     */
436    protected function prepareAttachments() {
437        $mime = '';
438        $part = 1;
439        // embedded attachments
440        foreach($this->attach as $media) {
441            $media['name'] = str_replace(':', '_', cleanID($media['name'], true));
442
443            // create content id
444            $cid = 'part'.$part.'.'.$this->partid;
445
446            // replace wildcards
447            if($media['embed']) {
448                $this->html = str_replace('%%'.$media['embed'].'%%', 'cid:'.$cid, $this->html);
449            }
450
451            $mime .= '--'.$this->boundary.MAILHEADER_EOL;
452            $mime .= $this->wrappedHeaderLine('Content-Type', $media['mime'].'; id="'.$cid.'"');
453            $mime .= $this->wrappedHeaderLine('Content-Transfer-Encoding', 'base64');
454            $mime .= $this->wrappedHeaderLine('Content-ID',"<$cid>");
455            if($media['embed']) {
456                $mime .= $this->wrappedHeaderLine('Content-Disposition', 'inline; filename='.$media['name']);
457            } else {
458                $mime .= $this->wrappedHeaderLine('Content-Disposition', 'attachment; filename='.$media['name']);
459            }
460            $mime .= MAILHEADER_EOL; //end of headers
461            $mime .= chunk_split(base64_encode($media['data']), 74, MAILHEADER_EOL);
462
463            $part++;
464        }
465        return $mime;
466    }
467
468    /**
469     * Build the body and handles multi part mails
470     *
471     * Needs to be called before prepareHeaders!
472     *
473     * @return string the prepared mail body, false on errors
474     */
475    protected function prepareBody() {
476
477        // no HTML mails allowed? remove HTML body
478        if(!$this->allowhtml) {
479            $this->html = '';
480        }
481
482        // check for body
483        if(!$this->text && !$this->html) {
484            return false;
485        }
486
487        // add general headers
488        $this->headers['MIME-Version'] = '1.0';
489
490        $body = '';
491
492        if(!$this->html && !count($this->attach)) { // we can send a simple single part message
493            $this->headers['Content-Type']              = 'text/plain; charset=UTF-8';
494            $this->headers['Content-Transfer-Encoding'] = 'base64';
495            $body .= chunk_split(base64_encode($this->text), 72, MAILHEADER_EOL);
496        } else { // multi part it is
497            $body .= "This is a multi-part message in MIME format.".MAILHEADER_EOL;
498
499            // prepare the attachments
500            $attachments = $this->prepareAttachments();
501
502            // do we have alternative text content?
503            if($this->text && $this->html) {
504                $this->headers['Content-Type'] = 'multipart/alternative;'.MAILHEADER_EOL.
505                    '  boundary="'.$this->boundary.'XX"';
506                $body .= '--'.$this->boundary.'XX'.MAILHEADER_EOL;
507                $body .= 'Content-Type: text/plain; charset=UTF-8'.MAILHEADER_EOL;
508                $body .= 'Content-Transfer-Encoding: base64'.MAILHEADER_EOL;
509                $body .= MAILHEADER_EOL;
510                $body .= chunk_split(base64_encode($this->text), 72, MAILHEADER_EOL);
511                $body .= '--'.$this->boundary.'XX'.MAILHEADER_EOL;
512                $body .= 'Content-Type: multipart/related;'.MAILHEADER_EOL.
513                    '  boundary="'.$this->boundary.'";'.MAILHEADER_EOL.
514                    '  type="text/html"'.MAILHEADER_EOL;
515                $body .= MAILHEADER_EOL;
516            }
517
518            $body .= '--'.$this->boundary.MAILHEADER_EOL;
519            $body .= 'Content-Type: text/html; charset=UTF-8'.MAILHEADER_EOL;
520            $body .= 'Content-Transfer-Encoding: base64'.MAILHEADER_EOL;
521            $body .= MAILHEADER_EOL;
522            $body .= chunk_split(base64_encode($this->html), 72, MAILHEADER_EOL);
523            $body .= MAILHEADER_EOL;
524            $body .= $attachments;
525            $body .= '--'.$this->boundary.'--'.MAILHEADER_EOL;
526
527            // close open multipart/alternative boundary
528            if($this->text && $this->html) {
529                $body .= '--'.$this->boundary.'XX--'.MAILHEADER_EOL;
530            }
531        }
532
533        return $body;
534    }
535
536    /**
537     * Cleanup and encode the headers array
538     */
539    protected function cleanHeaders() {
540        global $conf;
541
542        // clean up addresses
543        if(empty($this->headers['From'])) $this->from($conf['mailfrom']);
544        $addrs = array('To', 'From', 'Cc', 'Bcc', 'Reply-To', 'Sender');
545        foreach($addrs as $addr) {
546            if(isset($this->headers[$addr])) {
547                $this->headers[$addr] = $this->cleanAddress($this->headers[$addr]);
548            }
549        }
550
551        if(isset($this->headers['Subject'])) {
552            // add prefix to subject
553            if(empty($conf['mailprefix'])) {
554                if(\dokuwiki\Utf8\PhpString::strlen($conf['title']) < 20) {
555                    $prefix = '['.$conf['title'].']';
556                } else {
557                    $prefix = '['.\dokuwiki\Utf8\PhpString::substr($conf['title'], 0, 20).'...]';
558                }
559            } else {
560                $prefix = '['.$conf['mailprefix'].']';
561            }
562            $len = strlen($prefix);
563            if(substr($this->headers['Subject'], 0, $len) != $prefix) {
564                $this->headers['Subject'] = $prefix.' '.$this->headers['Subject'];
565            }
566
567            // encode subject
568            if(defined('MAILHEADER_ASCIIONLY')) {
569                $this->headers['Subject'] = \dokuwiki\Utf8\Clean::deaccent($this->headers['Subject']);
570                $this->headers['Subject'] = \dokuwiki\Utf8\Clean::strip($this->headers['Subject']);
571            }
572            if(!\dokuwiki\Utf8\Clean::isASCII($this->headers['Subject'])) {
573                $this->headers['Subject'] = '=?UTF-8?B?'.base64_encode($this->headers['Subject']).'?=';
574            }
575        }
576
577    }
578
579    /**
580     * Returns a complete, EOL terminated header line, wraps it if necessary
581     *
582     * @param string $key
583     * @param string $val
584     * @return string line
585     */
586    protected function wrappedHeaderLine($key, $val){
587        return wordwrap("$key: $val", 78, MAILHEADER_EOL.'  ').MAILHEADER_EOL;
588    }
589
590    /**
591     * Create a string from the headers array
592     *
593     * @returns string the headers
594     */
595    protected function prepareHeaders() {
596        $headers = '';
597        foreach($this->headers as $key => $val) {
598            if ($val === '' || $val === null) continue;
599            $headers .= $this->wrappedHeaderLine($key, $val);
600        }
601        return $headers;
602    }
603
604    /**
605     * return a full email with all headers
606     *
607     * This is mainly intended for debugging and testing but could also be
608     * used for MHT exports
609     *
610     * @return string the mail, false on errors
611     */
612    public function dump() {
613        $this->cleanHeaders();
614        $body = $this->prepareBody();
615        if($body === false) return false;
616        $headers = $this->prepareHeaders();
617
618        return $headers.MAILHEADER_EOL.$body;
619    }
620
621    /**
622     * Prepare default token replacement strings
623     *
624     * Populates the '$replacements' property.
625     * Should be called by the class constructor
626     */
627    protected function prepareTokenReplacements() {
628        global $INFO;
629        global $conf;
630        /* @var Input $INPUT */
631        global $INPUT;
632        global $lang;
633
634        $ip   = clientIP();
635        $cip  = gethostsbyaddrs($ip);
636        $name = $INFO['userinfo']['name'] ?? '';
637        $mail = $INFO['userinfo']['mail'] ?? '';
638
639        $this->replacements['text'] = array(
640            'DATE' => dformat(),
641            'BROWSER' => $INPUT->server->str('HTTP_USER_AGENT'),
642            'IPADDRESS' => $ip,
643            'HOSTNAME' => $cip,
644            'TITLE' => $conf['title'],
645            'DOKUWIKIURL' => DOKU_URL,
646            'USER' => $INPUT->server->str('REMOTE_USER'),
647            'NAME' => $name,
648            'MAIL' => $mail
649        );
650        $signature = str_replace(
651            '@DOKUWIKIURL@',
652            $this->replacements['text']['DOKUWIKIURL'],
653            $lang['email_signature_text']
654        );
655        $this->replacements['text']['EMAILSIGNATURE'] = "\n-- \n" . $signature . "\n";
656
657        $this->replacements['html'] = array(
658            'DATE' => '<i>' . hsc(dformat()) . '</i>',
659            'BROWSER' => hsc($INPUT->server->str('HTTP_USER_AGENT')),
660            'IPADDRESS' => '<code>' . hsc($ip) . '</code>',
661            'HOSTNAME' => '<code>' . hsc($cip) . '</code>',
662            'TITLE' => hsc($conf['title']),
663            'DOKUWIKIURL' => '<a href="' . DOKU_URL . '">' . DOKU_URL . '</a>',
664            'USER' => hsc($INPUT->server->str('REMOTE_USER')),
665            'NAME' => hsc($name),
666            'MAIL' => '<a href="mailto:"' . hsc($mail) . '">' .
667                hsc($mail) . '</a>'
668        );
669        $signature = $lang['email_signature_text'];
670        if(!empty($lang['email_signature_html'])) {
671            $signature = $lang['email_signature_html'];
672        }
673        $signature = str_replace(
674            array(
675                '@DOKUWIKIURL@',
676                "\n"
677            ),
678            array(
679                $this->replacements['html']['DOKUWIKIURL'],
680                '<br />'
681            ),
682            $signature
683        );
684        $this->replacements['html']['EMAILSIGNATURE'] = $signature;
685    }
686
687    /**
688     * Send the mail
689     *
690     * Call this after all data was set
691     *
692     * @triggers MAIL_MESSAGE_SEND
693     * @return bool true if the mail was successfully passed to the MTA
694     */
695    public function send() {
696        global $lang;
697        $success = false;
698
699        // prepare hook data
700        $data = array(
701            // pass the whole mail class to plugin
702            'mail'    => $this,
703            // pass references for backward compatibility
704            'to'      => &$this->headers['To'],
705            'cc'      => &$this->headers['Cc'],
706            'bcc'     => &$this->headers['Bcc'],
707            'from'    => &$this->headers['From'],
708            'subject' => &$this->headers['Subject'],
709            'body'    => &$this->text,
710            'params'  => &$this->sendparam,
711            'headers' => '', // plugins shouldn't use this
712            // signal if we mailed successfully to AFTER event
713            'success' => &$success,
714        );
715
716        // do our thing if BEFORE hook approves
717        $evt = new Event('MAIL_MESSAGE_SEND', $data);
718        if($evt->advise_before(true)) {
719            // clean up before using the headers
720            $this->cleanHeaders();
721
722            // any recipients?
723            if(trim($this->headers['To']) === '' &&
724                trim($this->headers['Cc']) === '' &&
725                trim($this->headers['Bcc']) === ''
726            ) return false;
727
728            // The To: header is special
729            if(array_key_exists('To', $this->headers)) {
730                $to = (string)$this->headers['To'];
731                unset($this->headers['To']);
732            } else {
733                $to = '';
734            }
735
736            // so is the subject
737            if(array_key_exists('Subject', $this->headers)) {
738                $subject = (string)$this->headers['Subject'];
739                unset($this->headers['Subject']);
740            } else {
741                $subject = '';
742            }
743
744            // make the body
745            $body = $this->prepareBody();
746            if($body === false) return false;
747
748            // cook the headers
749            $headers = $this->prepareHeaders();
750            // add any headers set by legacy plugins
751            if(trim($data['headers'])) {
752                $headers .= MAILHEADER_EOL.trim($data['headers']);
753            }
754
755            if(!function_exists('mail')){
756                $emsg = $lang['email_fail'] . $subject;
757                error_log($emsg);
758                msg(hsc($emsg), -1, __LINE__, __FILE__, MSG_MANAGERS_ONLY);
759                $evt->advise_after();
760                return false;
761            }
762
763            // send the thing
764            if($to === '') $to = '(undisclosed-recipients)'; // #1422
765            if($this->sendparam === null) {
766                $success = @mail($to, $subject, $body, $headers);
767            } else {
768                $success = @mail($to, $subject, $body, $headers, $this->sendparam);
769            }
770        }
771        // any AFTER actions?
772        $evt->advise_after();
773        return $success;
774    }
775}
776