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