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