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