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