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