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.
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.
9 * @author Andreas Gohr <andi@splitbrain.org>
12 // end of line for mail lines - RFC822 says CRLF but postfix (and other MTAs?)
14 if(!defined('MAILHEADER_EOL')) define('MAILHEADER_EOL', "\n");
15 #define('MAILHEADER_ASCIIONLY',1);
22 protected $headers = array();
23 protected $attach = array();
27 protected $boundary = '';
28 protected $partid = '';
29 protected $sendparam = null;
31 /** @var EmailAddressValidator */
32 protected $validator = null;
33 protected $allowhtml = true;
38 * Initializes the boundary strings and part counters
40 public function __construct() {
43 $server = parse_url(DOKU_URL
, PHP_URL_HOST
);
45 $this->partid
= md5(uniqid(rand(), true)).'@'.$server;
46 $this->boundary
= '----------'.md5(uniqid(rand(), true));
48 $listid = join('.', array_reverse(explode('/', DOKU_BASE
))).$server;
49 $listid = strtolower(trim($listid, '.'));
51 $this->allowhtml
= (bool)$conf['htmlmail'];
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.'>');
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
70 public function attachFile($path, $mime, $name = '', $embed = '') {
72 $name = utf8_basename($path);
75 $this->attach
[] = array(
76 'data' => file_get_contents($path),
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
91 public function attachContent($data, $mime, $name = '', $embed = '') {
93 list(, $ext) = explode('/', $mime);
94 $name = count($this->attach
).".$ext";
97 $this->attach
[] = array(
106 * Callback function to automatically embed images referenced in HTML templates
108 protected function autoembed_cb($matches) {
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
118 // attach it and set placeholder
119 $this->attachFile($file, $mime, '', 'autoembed'.$embeds);
120 return '%%autoembed'.$embeds.'%%';
124 * Add an arbitrary header to the mail
126 * If an empy value is passed, the header is removed
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?
132 public function setHeader($header, $value, $clean = true) {
133 $header = str_replace(' ', '-', ucwords(strtolower(str_replace('-', ' ', $header)))); // streamline casing
135 $header = preg_replace('/[^a-zA-Z0-9_ \-\.\+\@]+/', '', $header);
136 $value = preg_replace('/[^a-zA-Z0-9_ \-\.\+\@<>]+/', '', $value);
139 // empty value deletes
140 if(is_array($value)){
141 $value = array_map('trim', $value);
142 $value = array_filter($value);
143 if(!$value) $value = '';
145 $value = trim($value);
148 if(isset($this->headers
[$header])) unset($this->headers
[$header]);
150 $this->headers
[$header] = $value;
155 * Set additional parameters to be passed to sendmail
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
160 public function setParameters($param) {
161 $this->sendparam
= $param;
165 * Set the text and HTML body and apply replacements
167 * This function applies a whole bunch of default replacements in addition
168 * to the ones specidifed as parameters
170 * If you pass the HTML part or HTML replacements yourself you have to make
171 * sure you encode all HTML special chars correctly
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
179 public function setBody($text, $textrep = null, $htmlrep = null, $html = null, $wrap = true) {
182 $htmlrep = (array)$htmlrep;
183 $textrep = (array)$textrep;
185 // create HTML from text if not given
189 $html = preg_replace('/^-----*$/m', '<hr >', $html);
190 $html = nl2br($html);
193 $wrap = rawLocale('mailwrap', 'html');
194 $html = preg_replace('/\n-- <br \/>.*$/s', '', $html); //strip signature
195 $html = str_replace('@HTMLBODY@', $html, $wrap);
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>';
204 $htmlrep[$key] = hsc($value);
208 // embed media from templates
209 $html = preg_replace_callback(
210 '/@MEDIA\(([^\)]+)\)@/',
211 array($this, 'autoembed_cb'), $html
214 // prepare default replacements
216 $cip = gethostsbyaddrs($ip);
219 'BROWSER' => $_SERVER['HTTP_USER_AGENT'],
222 'TITLE' => $conf['title'],
223 'DOKUWIKIURL' => DOKU_URL
,
224 'USER' => $_SERVER['REMOTE_USER'],
225 'NAME' => $INFO['userinfo']['name'],
226 'MAIL' => $INFO['userinfo']['mail'],
228 $trep = array_merge($trep, (array)$textrep);
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>',
241 $hrep = array_merge($hrep, (array)$htmlrep);
243 // Apply replacements
244 foreach($trep as $key => $substitution) {
245 $text = str_replace('@'.strtoupper($key).'@', $substitution, $text);
247 foreach($hrep as $key => $substitution) {
248 $html = str_replace('@'.strtoupper($key).'@', $substitution, $html);
251 $this->setHTML($html);
252 $this->setText($text);
256 * Set the HTML part of the mail
258 * Placeholders can be used to reference embedded attachments
260 * You probably want to use setBody() instead
262 public function setHTML($html) {
267 * Set the plain text part of the mail
269 * You probably want to use setBody() instead
271 public function setText($text) {
276 * Add the To: recipients
279 * @param string|array $address Multiple adresses separated by commas or as array
281 public function to($address) {
282 $this->setHeader('To', $address, false);
286 * Add the Cc: recipients
289 * @param string|array $address Multiple adresses separated by commas or as array
291 public function cc($address) {
292 $this->setHeader('Cc', $address, false);
296 * Add the Bcc: recipients
299 * @param string|array $address Multiple adresses separated by commas or as array
301 public function bcc($address) {
302 $this->setHeader('Bcc', $address, false);
306 * Add the From: address
308 * This is set to $conf['mailfrom'] when not specified so you shouldn't need
309 * to call this function
312 * @param string $address from address
314 public function from($address) {
315 $this->setHeader('From', $address, false);
319 * Add the mail's Subject: header
321 * @param string $subject the mail subject
323 public function subject($subject) {
324 $this->headers
['Subject'] = $subject;
328 * Sets an email address header with correct encoding
330 * Unicode characters will be deaccented and encoded base64
331 * for headers. Addresses may not contain Non-ASCII data!
334 * setAddress("föö <foo@bar.com>, me@somewhere.com","TBcc");
336 * @param string|array $address Multiple adresses separated by commas or as array
337 * @return bool|string the prepared header (can contain multiple lines)
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;
344 if(!is_array($addresses)){
345 $addresses = explode(',', $addresses);
348 foreach($addresses as $part) {
349 $part = preg_replace('/[\r\n\0]+/', ' ', $part); // remove attack vectors
353 if(preg_match('#(.*?)<(.*?)>#', $part, $matches)) {
354 $text = trim($matches[1]);
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);
370 if(is_null($this->validator
)) {
371 $this->validator
= new EmailAddressValidator();
372 $this->validator
->allowLocalAddresses
= true;
374 if(!$this->validator
->check_email_address($addr)) {
375 msg(htmlspecialchars("E-Mail address <$addr> is not valid"), -1);
380 if(!empty($text) && $names) {
381 // add address quotes
384 if(defined('MAILHEADER_ASCIIONLY')) {
385 $text = utf8_deaccent($text);
386 $text = utf8_strip($text);
389 if(strpos($text, ',') !== false ||
!utf8_isASCII($text)) {
390 $text = '=?UTF-8?B?'.base64_encode($text).'?=';
396 // add to header comma seperated
400 $headers .= $text.' '.$addr;
403 $headers = trim($headers);
404 if(empty($headers)) return false;
411 * Prepare the mime multiparts for all attachments
413 * Replaces placeholders in the HTML with the correct CIDs
415 protected function prepareAttachments() {
418 // embedded attachments
419 foreach($this->attach
as $media) {
421 $cid = 'part'.$part.'.'.$this->partid
;
424 if($media['embed']) {
425 $this->html
= str_replace('%%'.$media['embed'].'%%', 'cid:'.$cid, $this->html
);
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
;
435 $mime .= 'Content-Disposition: attachment; filename="'.$media['name'].'"'.MAILHEADER_EOL
;
437 $mime .= MAILHEADER_EOL
; //end of headers
438 $mime .= chunk_split(base64_encode($media['data']), 74, MAILHEADER_EOL
);
446 * Build the body and handles multi part mails
448 * Needs to be called before prepareHeaders!
450 * @return string the prepared mail body, false on errors
452 protected function prepareBody() {
454 // no HTML mails allowed? remove HTML body
455 if(!$this->allowhtml
) {
460 if(!$this->text
&& !$this->html
) {
464 // add general headers
465 $this->headers
['MIME-Version'] = '1.0';
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
;
476 // prepare the attachments
477 $attachments = $this->prepareAttachments();
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
;
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
;
503 // close open multipart/alternative boundary
504 if($this->text
&& $this->html
) {
505 $body .= '--'.$this->boundary
.'XX--'.MAILHEADER_EOL
;
513 * Cleanup and encode the headers array
515 protected function cleanHeaders() {
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]);
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'].']';
533 $prefix = '['.utf8_substr($conf['title'], 0, 20).'...]';
536 $prefix = '['.$conf['mailprefix'].']';
538 $len = strlen($prefix);
539 if(substr($this->headers
['Subject'], 0, $len) != $prefix) {
540 $this->headers
['Subject'] = $prefix.' '.$this->headers
['Subject'];
544 if(defined('MAILHEADER_ASCIIONLY')) {
545 $this->headers
['Subject'] = utf8_deaccent($this->headers
['Subject']);
546 $this->headers
['Subject'] = utf8_strip($this->headers
['Subject']);
548 if(!utf8_isASCII($this->headers
['Subject'])) {
549 $this->headers
['Subject'] = '=?UTF-8?B?'.base64_encode($this->headers
['Subject']).'?=';
554 foreach($this->headers
as $key => $val) {
555 $this->headers
[$key] = wordwrap($val, 78, MAILHEADER_EOL
.' ');
560 * Create a string from the headers array
562 * @returns string the headers
564 protected function prepareHeaders() {
566 foreach($this->headers
as $key => $val) {
567 if ($val === '') continue;
568 $headers .= "$key: $val".MAILHEADER_EOL
;
574 * return a full email with all headers
576 * This is mainly intended for debugging and testing but could also be
577 * used for MHT exports
579 * @return string the mail, false on errors
581 public function dump() {
582 $this->cleanHeaders();
583 $body = $this->prepareBody();
584 if($body === false) return false;
585 $headers = $this->prepareHeaders();
587 return $headers.MAILHEADER_EOL
.$body;
593 * Call this after all data was set
595 * @triggers MAIL_MESSAGE_SEND
596 * @return bool true if the mail was successfully passed to the MTA
598 public function send() {
603 // pass the whole mail class to plugin
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,
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();
625 if(trim($this->headers
['To']) === '' &&
626 trim($this->headers
['Cc']) === '' &&
627 trim($this->headers
['Bcc']) === ''
630 // The To: header is special
631 if(isset($this->headers
['To'])) {
632 $to = $this->headers
['To'];
633 unset($this->headers
['To']);
639 if(isset($this->headers
['Subject'])) {
640 $subject = $this->headers
['Subject'];
641 unset($this->headers
['Subject']);
647 $body = $this->prepareBody();
648 if($body === false) return false;
651 $headers = $this->prepareHeaders();
652 // add any headers set by legacy plugins
653 if(trim($data['headers'])) {
654 $headers .= MAILHEADER_EOL
.trim($data['headers']);
658 if(is_null($this->sendparam
)) {
659 $success = @mail
($to, $subject, $body, $headers);
661 $success = @mail
($to, $subject, $body, $headers, $this->sendparam
);
664 // any AFTER actions?
665 $evt->advise_after();