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