xref: /dokuwiki/inc/Mailer.class.php (revision ba2c2f17509ffd7d52e706172a16985d8e11b551)
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        $text = trim($text);
199
200        // create HTML from text if not given
201        if(is_null($html)) {
202            $html = $text;
203            $html = hsc($html);
204            $html = preg_replace('/^----+$/m', '<hr >', $html);
205            $html = nl2br($html);
206            $html .= '<br /><br /><br /><br /><hr /><small>' . $lang['email_signature'] . ':<br />@DOKUWIKIURL@</small>';
207        }
208        if($wrap) {
209            $html = '<html><head><title>' . hsc($conf['title']) . '</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body>' . $html . '</body></html>';
210        }
211
212        $text .= "\n\n\n\n-- \n" . $lang['email_signature'] . ":\n@DOKUWIKIURL@\n";
213
214        // copy over all replacements missing for HTML (autolink URLs)
215        foreach($textrep as $key => $value) {
216            if(isset($htmlrep[$key])) continue;
217            if(media_isexternal($value)) {
218                $htmlrep[$key] = '<a href="'.hsc($value).'">'.hsc($value).'</a>';
219            } else {
220                $htmlrep[$key] = hsc($value);
221            }
222        }
223
224        // embed media from templates
225        $html = preg_replace_callback(
226            '/@MEDIA\(([^\)]+)\)@/',
227            array($this, 'autoembed_cb'), $html
228        );
229
230        // prepare default replacements
231        $ip   = clientIP();
232        $cip  = gethostsbyaddrs($ip);
233        $trep = array(
234            'DATE'        => dformat(),
235            'BROWSER'     => $INPUT->server->str('HTTP_USER_AGENT'),
236            'IPADDRESS'   => $ip,
237            'HOSTNAME'    => $cip,
238            'TITLE'       => $conf['title'],
239            'DOKUWIKIURL' => DOKU_URL,
240            'USER'        => $INPUT->server->str('REMOTE_USER'),
241            'NAME'        => $INFO['userinfo']['name'],
242            'MAIL'        => $INFO['userinfo']['mail'],
243        );
244        $trep = array_merge($trep, (array)$textrep);
245        $hrep = array(
246            'DATE'        => '<i>'.hsc(dformat()).'</i>',
247            'BROWSER'     => hsc($INPUT->server->str('HTTP_USER_AGENT')),
248            'IPADDRESS'   => '<code>'.hsc($ip).'</code>',
249            'HOSTNAME'    => '<code>'.hsc($cip).'</code>',
250            'TITLE'       => hsc($conf['title']),
251            'DOKUWIKIURL' => '<a href="'.DOKU_URL.'">'.DOKU_URL.'</a>',
252            'USER'        => hsc($INPUT->server->str('REMOTE_USER')),
253            'NAME'        => hsc($INFO['userinfo']['name']),
254            'MAIL'        => '<a href="mailto:"'.hsc($INFO['userinfo']['mail']).'">'.
255                hsc($INFO['userinfo']['mail']).'</a>',
256        );
257        $hrep = array_merge($hrep, (array)$htmlrep);
258
259        // Apply replacements
260        foreach($trep as $key => $substitution) {
261            $text = str_replace('@'.strtoupper($key).'@', $substitution, $text);
262        }
263        foreach($hrep as $key => $substitution) {
264            $html = str_replace('@'.strtoupper($key).'@', $substitution, $html);
265        }
266
267        $this->setHTML($html);
268        $this->setText($text);
269    }
270
271    /**
272     * Set the HTML part of the mail
273     *
274     * Placeholders can be used to reference embedded attachments
275     *
276     * You probably want to use setBody() instead
277     *
278     * @param string $html
279     */
280    public function setHTML($html) {
281        $this->html = $html;
282    }
283
284    /**
285     * Set the plain text part of the mail
286     *
287     * You probably want to use setBody() instead
288     *
289     * @param string $text
290     */
291    public function setText($text) {
292        $this->text = $text;
293    }
294
295    /**
296     * Add the To: recipients
297     *
298     * @see cleanAddress
299     * @param string|string[]  $address Multiple adresses separated by commas or as array
300     */
301    public function to($address) {
302        $this->setHeader('To', $address, false);
303    }
304
305    /**
306     * Add the Cc: recipients
307     *
308     * @see cleanAddress
309     * @param string|string[]  $address Multiple adresses separated by commas or as array
310     */
311    public function cc($address) {
312        $this->setHeader('Cc', $address, false);
313    }
314
315    /**
316     * Add the Bcc: recipients
317     *
318     * @see cleanAddress
319     * @param string|string[]  $address Multiple adresses separated by commas or as array
320     */
321    public function bcc($address) {
322        $this->setHeader('Bcc', $address, false);
323    }
324
325    /**
326     * Add the From: address
327     *
328     * This is set to $conf['mailfrom'] when not specified so you shouldn't need
329     * to call this function
330     *
331     * @see cleanAddress
332     * @param string  $address from address
333     */
334    public function from($address) {
335        $this->setHeader('From', $address, false);
336    }
337
338    /**
339     * Add the mail's Subject: header
340     *
341     * @param string $subject the mail subject
342     */
343    public function subject($subject) {
344        $this->headers['Subject'] = $subject;
345    }
346
347    /**
348     * Sets an email address header with correct encoding
349     *
350     * Unicode characters will be deaccented and encoded base64
351     * for headers. Addresses may not contain Non-ASCII data!
352     *
353     * Example:
354     *   cc("föö <foo@bar.com>, me@somewhere.com","TBcc");
355     *
356     * @param string|string[]  $addresses Multiple adresses separated by commas or as array
357     * @return false|string  the prepared header (can contain multiple lines)
358     */
359    public function cleanAddress($addresses) {
360        // No named recipients for To: in Windows (see FS#652)
361        $names = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? false : true;
362
363        $headers = '';
364        if(!is_array($addresses)){
365            $addresses = explode(',', $addresses);
366        }
367
368        foreach($addresses as $part) {
369            $part = preg_replace('/[\r\n\0]+/', ' ', $part); // remove attack vectors
370            $part = trim($part);
371
372            // parse address
373            if(preg_match('#(.*?)<(.*?)>#', $part, $matches)) {
374                $text = trim($matches[1]);
375                $addr = $matches[2];
376            } else {
377                $addr = $part;
378            }
379            // skip empty ones
380            if(empty($addr)) {
381                continue;
382            }
383
384            // FIXME: is there a way to encode the localpart of a emailaddress?
385            if(!utf8_isASCII($addr)) {
386                msg(htmlspecialchars("E-Mail address <$addr> is not ASCII"), -1);
387                continue;
388            }
389
390            if(is_null($this->validator)) {
391                $this->validator                      = new EmailAddressValidator();
392                $this->validator->allowLocalAddresses = true;
393            }
394            if(!$this->validator->check_email_address($addr)) {
395                msg(htmlspecialchars("E-Mail address <$addr> is not valid"), -1);
396                continue;
397            }
398
399            // text was given
400            if(!empty($text) && $names) {
401                // add address quotes
402                $addr = "<$addr>";
403
404                if(defined('MAILHEADER_ASCIIONLY')) {
405                    $text = utf8_deaccent($text);
406                    $text = utf8_strip($text);
407                }
408
409                if(strpos($text, ',') !== false || !utf8_isASCII($text)) {
410                    $text = '=?UTF-8?B?'.base64_encode($text).'?=';
411                }
412            } else {
413                $text = '';
414            }
415
416            // add to header comma seperated
417            if($headers != '') {
418                $headers .= ', ';
419            }
420            $headers .= $text.' '.$addr;
421        }
422
423        $headers = trim($headers);
424        if(empty($headers)) return false;
425
426        return $headers;
427    }
428
429
430    /**
431     * Prepare the mime multiparts for all attachments
432     *
433     * Replaces placeholders in the HTML with the correct CIDs
434     *
435     * @return string mime multiparts
436     */
437    protected function prepareAttachments() {
438        $mime = '';
439        $part = 1;
440        // embedded attachments
441        foreach($this->attach as $media) {
442            $media['name'] = str_replace(':', '_', cleanID($media['name'], true));
443
444            // create content id
445            $cid = 'part'.$part.'.'.$this->partid;
446
447            // replace wildcards
448            if($media['embed']) {
449                $this->html = str_replace('%%'.$media['embed'].'%%', 'cid:'.$cid, $this->html);
450            }
451
452            $mime .= '--'.$this->boundary.MAILHEADER_EOL;
453            $mime .= $this->wrappedHeaderLine('Content-Type', $media['mime'].'; id="'.$cid.'"');
454            $mime .= $this->wrappedHeaderLine('Content-Transfer-Encoding', 'base64');
455            $mime .= $this->wrappedHeaderLine('Content-ID',"<$cid>");
456            if($media['embed']) {
457                $mime .= $this->wrappedHeaderLine('Content-Disposition', 'inline; filename='.$media['name']);
458            } else {
459                $mime .= $this->wrappedHeaderLine('Content-Disposition', 'attachment; filename='.$media['name']);
460            }
461            $mime .= MAILHEADER_EOL; //end of headers
462            $mime .= chunk_split(base64_encode($media['data']), 74, MAILHEADER_EOL);
463
464            $part++;
465        }
466        return $mime;
467    }
468
469    /**
470     * Build the body and handles multi part mails
471     *
472     * Needs to be called before prepareHeaders!
473     *
474     * @return string the prepared mail body, false on errors
475     */
476    protected function prepareBody() {
477
478        // no HTML mails allowed? remove HTML body
479        if(!$this->allowhtml) {
480            $this->html = '';
481        }
482
483        // check for body
484        if(!$this->text && !$this->html) {
485            return false;
486        }
487
488        // add general headers
489        $this->headers['MIME-Version'] = '1.0';
490
491        $body = '';
492
493        if(!$this->html && !count($this->attach)) { // we can send a simple single part message
494            $this->headers['Content-Type']              = 'text/plain; charset=UTF-8';
495            $this->headers['Content-Transfer-Encoding'] = 'base64';
496            $body .= chunk_split(base64_encode($this->text), 72, MAILHEADER_EOL);
497        } else { // multi part it is
498            $body .= "This is a multi-part message in MIME format.".MAILHEADER_EOL;
499
500            // prepare the attachments
501            $attachments = $this->prepareAttachments();
502
503            // do we have alternative text content?
504            if($this->text && $this->html) {
505                $this->headers['Content-Type'] = 'multipart/alternative;'.MAILHEADER_EOL.
506                    '  boundary="'.$this->boundary.'XX"';
507                $body .= '--'.$this->boundary.'XX'.MAILHEADER_EOL;
508                $body .= 'Content-Type: text/plain; charset=UTF-8'.MAILHEADER_EOL;
509                $body .= 'Content-Transfer-Encoding: base64'.MAILHEADER_EOL;
510                $body .= MAILHEADER_EOL;
511                $body .= chunk_split(base64_encode($this->text), 72, MAILHEADER_EOL);
512                $body .= '--'.$this->boundary.'XX'.MAILHEADER_EOL;
513                $body .= 'Content-Type: multipart/related;'.MAILHEADER_EOL.
514                    '  boundary="'.$this->boundary.'";'.MAILHEADER_EOL.
515                    '  type="text/html"'.MAILHEADER_EOL;
516                $body .= MAILHEADER_EOL;
517            }
518
519            $body .= '--'.$this->boundary.MAILHEADER_EOL;
520            $body .= 'Content-Type: text/html; charset=UTF-8'.MAILHEADER_EOL;
521            $body .= 'Content-Transfer-Encoding: base64'.MAILHEADER_EOL;
522            $body .= MAILHEADER_EOL;
523            $body .= chunk_split(base64_encode($this->html), 72, MAILHEADER_EOL);
524            $body .= MAILHEADER_EOL;
525            $body .= $attachments;
526            $body .= '--'.$this->boundary.'--'.MAILHEADER_EOL;
527
528            // close open multipart/alternative boundary
529            if($this->text && $this->html) {
530                $body .= '--'.$this->boundary.'XX--'.MAILHEADER_EOL;
531            }
532        }
533
534        return $body;
535    }
536
537    /**
538     * Cleanup and encode the headers array
539     */
540    protected function cleanHeaders() {
541        global $conf;
542
543        // clean up addresses
544        if(empty($this->headers['From'])) $this->from($conf['mailfrom']);
545        $addrs = array('To', 'From', 'Cc', 'Bcc', 'Reply-To', 'Sender');
546        foreach($addrs as $addr) {
547            if(isset($this->headers[$addr])) {
548                $this->headers[$addr] = $this->cleanAddress($this->headers[$addr]);
549            }
550        }
551
552        if(isset($this->headers['Subject'])) {
553            // add prefix to subject
554            if(empty($conf['mailprefix'])) {
555                if(utf8_strlen($conf['title']) < 20) {
556                    $prefix = '['.$conf['title'].']';
557                } else {
558                    $prefix = '['.utf8_substr($conf['title'], 0, 20).'...]';
559                }
560            } else {
561                $prefix = '['.$conf['mailprefix'].']';
562            }
563            $len = strlen($prefix);
564            if(substr($this->headers['Subject'], 0, $len) != $prefix) {
565                $this->headers['Subject'] = $prefix.' '.$this->headers['Subject'];
566            }
567
568            // encode subject
569            if(defined('MAILHEADER_ASCIIONLY')) {
570                $this->headers['Subject'] = utf8_deaccent($this->headers['Subject']);
571                $this->headers['Subject'] = utf8_strip($this->headers['Subject']);
572            }
573            if(!utf8_isASCII($this->headers['Subject'])) {
574                $this->headers['Subject'] = '=?UTF-8?B?'.base64_encode($this->headers['Subject']).'?=';
575            }
576        }
577
578    }
579
580    /**
581     * Returns a complete, EOL terminated header line, wraps it if necessary
582     *
583     * @param string $key
584     * @param string $val
585     * @return string line
586     */
587    protected function wrappedHeaderLine($key, $val){
588        return wordwrap("$key: $val", 78, MAILHEADER_EOL.'  ').MAILHEADER_EOL;
589    }
590
591    /**
592     * Create a string from the headers array
593     *
594     * @returns string the headers
595     */
596    protected function prepareHeaders() {
597        $headers = '';
598        foreach($this->headers as $key => $val) {
599            if ($val === '' || is_null($val)) continue;
600            $headers .= $this->wrappedHeaderLine($key, $val);
601        }
602        return $headers;
603    }
604
605    /**
606     * return a full email with all headers
607     *
608     * This is mainly intended for debugging and testing but could also be
609     * used for MHT exports
610     *
611     * @return string the mail, false on errors
612     */
613    public function dump() {
614        $this->cleanHeaders();
615        $body = $this->prepareBody();
616        if($body === false) return false;
617        $headers = $this->prepareHeaders();
618
619        return $headers.MAILHEADER_EOL.$body;
620    }
621
622    /**
623     * Send the mail
624     *
625     * Call this after all data was set
626     *
627     * @triggers MAIL_MESSAGE_SEND
628     * @return bool true if the mail was successfully passed to the MTA
629     */
630    public function send() {
631        $success = false;
632
633        // prepare hook data
634        $data = array(
635            // pass the whole mail class to plugin
636            'mail'    => $this,
637            // pass references for backward compatibility
638            'to'      => &$this->headers['To'],
639            'cc'      => &$this->headers['Cc'],
640            'bcc'     => &$this->headers['Bcc'],
641            'from'    => &$this->headers['From'],
642            'subject' => &$this->headers['Subject'],
643            'body'    => &$this->text,
644            'params'  => &$this->sendparam,
645            'headers' => '', // plugins shouldn't use this
646            // signal if we mailed successfully to AFTER event
647            'success' => &$success,
648        );
649
650        // do our thing if BEFORE hook approves
651        $evt = new Doku_Event('MAIL_MESSAGE_SEND', $data);
652        if($evt->advise_before(true)) {
653            // clean up before using the headers
654            $this->cleanHeaders();
655
656            // any recipients?
657            if(trim($this->headers['To']) === '' &&
658                trim($this->headers['Cc']) === '' &&
659                trim($this->headers['Bcc']) === ''
660            ) return false;
661
662            // The To: header is special
663            if(array_key_exists('To', $this->headers)) {
664                $to = (string)$this->headers['To'];
665                unset($this->headers['To']);
666            } else {
667                $to = '';
668            }
669
670            // so is the subject
671            if(array_key_exists('Subject', $this->headers)) {
672                $subject = (string)$this->headers['Subject'];
673                unset($this->headers['Subject']);
674            } else {
675                $subject = '';
676            }
677
678            // make the body
679            $body = $this->prepareBody();
680            if($body === false) return false;
681
682            // cook the headers
683            $headers = $this->prepareHeaders();
684            // add any headers set by legacy plugins
685            if(trim($data['headers'])) {
686                $headers .= MAILHEADER_EOL.trim($data['headers']);
687            }
688
689            // send the thing
690            if(is_null($this->sendparam)) {
691                $success = @mail($to, $subject, $body, $headers);
692            } else {
693                $success = @mail($to, $subject, $body, $headers, $this->sendparam);
694            }
695        }
696        // any AFTER actions?
697        $evt->advise_after();
698        return $success;
699    }
700}
701