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