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 use dokuwiki\Extension\Event
;
14 // end of line for mail lines - RFC822 says CRLF but postfix (and other MTAs?)
16 if(!defined('MAILHEADER_EOL')) define('MAILHEADER_EOL', "\n");
17 #define('MAILHEADER_ASCIIONLY',1);
24 protected $headers = array();
25 protected $attach = array();
29 protected $boundary = '';
30 protected $partid = '';
31 protected $sendparam = null;
33 protected $allowhtml = true;
35 protected $replacements = array('text'=> array(), 'html' => array());
40 * Initializes the boundary strings, part counters and token replacements
42 public function __construct() {
44 /* @var Input $INPUT */
47 $server = parse_url(DOKU_URL
, PHP_URL_HOST
);
48 if(strpos($server,'.') === false) $server .= '.localhost';
50 $this->partid
= substr(md5(uniqid(mt_rand(), true)),0, 8).'@'.$server;
51 $this->boundary
= '__________'.md5(uniqid(mt_rand(), true));
53 $listid = implode('.', array_reverse(explode('/', DOKU_BASE
))).$server;
54 $listid = strtolower(trim($listid, '.'));
56 $this->allowhtml
= (bool)$conf['htmlmail'];
58 // add some default headers for mailfiltering FS#2247
59 if(!empty($conf['mailreturnpath'])) {
60 $this->setHeader('Return-Path', $conf['mailreturnpath']);
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);
70 $this->prepareTokenReplacements();
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
81 public function attachFile($path, $mime, $name = '', $embed = '') {
83 $name = \dokuwiki\Utf8\PhpString
::basename($path);
86 $this->attach
[] = array(
87 'data' => file_get_contents($path),
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
102 public function attachContent($data, $mime, $name = '', $embed = '') {
104 list(, $ext) = explode('/', $mime);
105 $name = count($this->attach
).".$ext";
108 $this->attach
[] = array(
117 * Callback function to automatically embed images referenced in HTML templates
119 * @param array $matches
120 * @return string placeholder
122 protected function autoEmbedCallBack($matches) {
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
132 // attach it and set placeholder
133 $this->attachFile($file, $mime, '', 'autoembed'.$embeds);
134 return '%%autoembed'.$embeds.'%%';
138 * Add an arbitrary header to the mail
140 * If an empy value is passed, the header is removed
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?
146 public function setHeader($header, $value, $clean = true) {
147 $header = str_replace(' ', '-', ucwords(strtolower(str_replace('-', ' ', $header)))); // streamline casing
149 $header = preg_replace('/[^a-zA-Z0-9_ \-\.\+\@]+/', '', $header);
150 $value = preg_replace('/[^a-zA-Z0-9_ \-\.\+\@<>]+/', '', $value);
153 // empty value deletes
154 if(is_array($value)){
155 $value = array_map('trim', $value);
156 $value = array_filter($value);
157 if(!$value) $value = '';
159 $value = trim($value);
162 if(isset($this->headers
[$header])) unset($this->headers
[$header]);
164 $this->headers
[$header] = $value;
169 * Set additional parameters to be passed to sendmail
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
174 * @param string $param
176 public function setParameters($param) {
177 $this->sendparam
= $param;
181 * Set the text and HTML body and apply replacements
183 * This function applies a whole bunch of default replacements in addition
184 * to the ones specified as parameters
186 * If you pass the HTML part or HTML replacements yourself you have to make
187 * sure you encode all HTML special chars correctly
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
195 public function setBody($text, $textrep = null, $htmlrep = null, $html = null, $wrap = true) {
197 $htmlrep = (array)$htmlrep;
198 $textrep = (array)$textrep;
200 // create HTML from text if not given
204 $html = preg_replace('/^----+$/m', '<hr >', $html);
205 $html = nl2br($html);
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);
214 if(strpos($text, '@EMAILSIGNATURE@') === false) {
215 $text .= '@EMAILSIGNATURE@';
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>';
224 $htmlrep[$key] = hsc($value);
228 // embed media from templates
229 $html = preg_replace_callback(
230 '/@MEDIA\(([^\)]+)\)@/',
231 array($this, 'autoEmbedCallBack'), $html
234 // add default token replacements
235 $trep = array_merge($this->replacements
['text'], (array)$textrep);
236 $hrep = array_merge($this->replacements
['html'], (array)$htmlrep);
238 // Apply replacements
239 foreach($trep as $key => $substitution) {
240 $text = str_replace('@'.strtoupper($key).'@', $substitution, $text);
242 foreach($hrep as $key => $substitution) {
243 $html = str_replace('@'.strtoupper($key).'@', $substitution, $html);
246 $this->setHTML($html);
247 $this->setText($text);
251 * Set the HTML part of the mail
253 * Placeholders can be used to reference embedded attachments
255 * You probably want to use setBody() instead
257 * @param string $html
259 public function setHTML($html) {
264 * Set the plain text part of the mail
266 * You probably want to use setBody() instead
268 * @param string $text
270 public function setText($text) {
275 * Add the To: recipients
278 * @param string|string[] $address Multiple adresses separated by commas or as array
280 public function to($address) {
281 $this->setHeader('To', $address, false);
285 * Add the Cc: recipients
288 * @param string|string[] $address Multiple adresses separated by commas or as array
290 public function cc($address) {
291 $this->setHeader('Cc', $address, false);
295 * Add the Bcc: recipients
298 * @param string|string[] $address Multiple adresses separated by commas or as array
300 public function bcc($address) {
301 $this->setHeader('Bcc', $address, false);
305 * Add the From: address
307 * This is set to $conf['mailfrom'] when not specified so you shouldn't need
308 * to call this function
311 * @param string $address from address
313 public function from($address) {
314 $this->setHeader('From', $address, false);
318 * Add the mail's Subject: header
320 * @param string $subject the mail subject
322 public function subject($subject) {
323 $this->headers
['Subject'] = $subject;
327 * Return a clean name which can be safely used in mail address
328 * fields. That means the name will be enclosed in '"' if it includes
329 * a '"' or a ','. Also a '"' will be escaped as '\"'.
331 * @param string $name the name to clean-up
334 public function getCleanName($name) {
335 $name = trim($name, ' \t"');
336 $name = str_replace('"', '\"', $name, $count);
337 if ($count > 0 ||
strpos($name, ',') !== false) {
338 $name = '"'.$name.'"';
344 * Sets an email address header with correct encoding
346 * Unicode characters will be deaccented and encoded base64
347 * for headers. Addresses may not contain Non-ASCII data!
349 * If @$addresses is a string then it will be split into multiple
350 * addresses. Addresses must be separated by a comma. If the display
351 * name includes a comma then it MUST be properly enclosed by '"' to
352 * prevent spliting at the wrong point.
355 * cc("föö <foo@bar.com>, me@somewhere.com","TBcc");
356 * to("foo, Dr." <foo@bar.com>, me@somewhere.com");
358 * @param string|string[] $addresses Multiple adresses separated by commas or as array
359 * @return false|string the prepared header (can contain multiple lines)
361 public function cleanAddress($addresses) {
363 if(!is_array($addresses)){
364 $count = preg_match_all('/\s*(?:("[^"]*"[^,]+),*)|([^,]+)\s*,*/', $addresses, $matches, PREG_SET_ORDER
);
365 $addresses = array();
366 if ($count !== false && is_array($matches)) {
367 foreach ($matches as $match) {
368 array_push($addresses, $match[0]);
373 foreach($addresses as $part) {
374 $part = preg_replace('/[\r\n\0]+/', ' ', $part); // remove attack vectors
378 if(preg_match('#(.*?)<(.*?)>#', $part, $matches)) {
379 $text = trim($matches[1]);
389 // FIXME: is there a way to encode the localpart of a emailaddress?
390 if(!\dokuwiki\Utf8\Clean
::isASCII($addr)) {
391 msg(hsc("E-Mail address <$addr> is not ASCII"), -1);
395 if(!mail_isvalid($addr)) {
396 msg(hsc("E-Mail address <$addr> is not valid"), -1);
401 if(!empty($text) && !isWindows()) { // No named recipients for To: in Windows (see FS#652)
402 // add address quotes
405 if(defined('MAILHEADER_ASCIIONLY')) {
406 $text = \dokuwiki\Utf8\Clean
::deaccent($text);
407 $text = \dokuwiki\Utf8\Clean
::strip($text);
410 if(strpos($text, ',') !== false ||
!\dokuwiki\Utf8\Clean
::isASCII($text)) {
411 $text = '=?UTF-8?B?'.base64_encode($text).'?=';
417 // add to header comma seperated
421 $headers .= $text.' '.$addr;
424 $headers = trim($headers);
425 if(empty($headers)) return false;
432 * Prepare the mime multiparts for all attachments
434 * Replaces placeholders in the HTML with the correct CIDs
436 * @return string mime multiparts
438 protected function prepareAttachments() {
441 // embedded attachments
442 foreach($this->attach
as $media) {
443 $media['name'] = str_replace(':', '_', cleanID($media['name'], true));
446 $cid = 'part'.$part.'.'.$this->partid
;
449 if($media['embed']) {
450 $this->html
= str_replace('%%'.$media['embed'].'%%', 'cid:'.$cid, $this->html
);
453 $mime .= '--'.$this->boundary
.MAILHEADER_EOL
;
454 $mime .= $this->wrappedHeaderLine('Content-Type', $media['mime'].'; id="'.$cid.'"');
455 $mime .= $this->wrappedHeaderLine('Content-Transfer-Encoding', 'base64');
456 $mime .= $this->wrappedHeaderLine('Content-ID',"<$cid>");
457 if($media['embed']) {
458 $mime .= $this->wrappedHeaderLine('Content-Disposition', 'inline; filename='.$media['name']);
460 $mime .= $this->wrappedHeaderLine('Content-Disposition', 'attachment; filename='.$media['name']);
462 $mime .= MAILHEADER_EOL
; //end of headers
463 $mime .= chunk_split(base64_encode($media['data']), 74, MAILHEADER_EOL
);
471 * Build the body and handles multi part mails
473 * Needs to be called before prepareHeaders!
475 * @return string the prepared mail body, false on errors
477 protected function prepareBody() {
479 // no HTML mails allowed? remove HTML body
480 if(!$this->allowhtml
) {
485 if(!$this->text
&& !$this->html
) {
489 // add general headers
490 $this->headers
['MIME-Version'] = '1.0';
494 if(!$this->html
&& !count($this->attach
)) { // we can send a simple single part message
495 $this->headers
['Content-Type'] = 'text/plain; charset=UTF-8';
496 $this->headers
['Content-Transfer-Encoding'] = 'base64';
497 $body .= chunk_split(base64_encode($this->text
), 72, MAILHEADER_EOL
);
498 } else { // multi part it is
499 $body .= "This is a multi-part message in MIME format.".MAILHEADER_EOL
;
501 // prepare the attachments
502 $attachments = $this->prepareAttachments();
504 // do we have alternative text content?
505 if($this->text
&& $this->html
) {
506 $this->headers
['Content-Type'] = 'multipart/alternative;'.MAILHEADER_EOL
.
507 ' boundary="'.$this->boundary
.'XX"';
508 $body .= '--'.$this->boundary
.'XX'.MAILHEADER_EOL
;
509 $body .= 'Content-Type: text/plain; charset=UTF-8'.MAILHEADER_EOL
;
510 $body .= 'Content-Transfer-Encoding: base64'.MAILHEADER_EOL
;
511 $body .= MAILHEADER_EOL
;
512 $body .= chunk_split(base64_encode($this->text
), 72, MAILHEADER_EOL
);
513 $body .= '--'.$this->boundary
.'XX'.MAILHEADER_EOL
;
514 $body .= 'Content-Type: multipart/related;'.MAILHEADER_EOL
.
515 ' boundary="'.$this->boundary
.'";'.MAILHEADER_EOL
.
516 ' type="text/html"'.MAILHEADER_EOL
;
517 $body .= MAILHEADER_EOL
;
520 $body .= '--'.$this->boundary
.MAILHEADER_EOL
;
521 $body .= 'Content-Type: text/html; charset=UTF-8'.MAILHEADER_EOL
;
522 $body .= 'Content-Transfer-Encoding: base64'.MAILHEADER_EOL
;
523 $body .= MAILHEADER_EOL
;
524 $body .= chunk_split(base64_encode($this->html
), 72, MAILHEADER_EOL
);
525 $body .= MAILHEADER_EOL
;
526 $body .= $attachments;
527 $body .= '--'.$this->boundary
.'--'.MAILHEADER_EOL
;
529 // close open multipart/alternative boundary
530 if($this->text
&& $this->html
) {
531 $body .= '--'.$this->boundary
.'XX--'.MAILHEADER_EOL
;
539 * Cleanup and encode the headers array
541 protected function cleanHeaders() {
544 // clean up addresses
545 if(empty($this->headers
['From'])) $this->from($conf['mailfrom']);
546 $addrs = array('To', 'From', 'Cc', 'Bcc', 'Reply-To', 'Sender');
547 foreach($addrs as $addr) {
548 if(isset($this->headers
[$addr])) {
549 $this->headers
[$addr] = $this->cleanAddress($this->headers
[$addr]);
553 if(isset($this->headers
['Subject'])) {
554 // add prefix to subject
555 if(empty($conf['mailprefix'])) {
556 if(\dokuwiki\Utf8\PhpString
::strlen($conf['title']) < 20) {
557 $prefix = '['.$conf['title'].']';
559 $prefix = '['.\dokuwiki\Utf8\PhpString
::substr($conf['title'], 0, 20).'...]';
562 $prefix = '['.$conf['mailprefix'].']';
564 $len = strlen($prefix);
565 if(substr($this->headers
['Subject'], 0, $len) != $prefix) {
566 $this->headers
['Subject'] = $prefix.' '.$this->headers
['Subject'];
570 if(defined('MAILHEADER_ASCIIONLY')) {
571 $this->headers
['Subject'] = \dokuwiki\Utf8\Clean
::deaccent($this->headers
['Subject']);
572 $this->headers
['Subject'] = \dokuwiki\Utf8\Clean
::strip($this->headers
['Subject']);
574 if(!\dokuwiki\Utf8\Clean
::isASCII($this->headers
['Subject'])) {
575 $this->headers
['Subject'] = '=?UTF-8?B?'.base64_encode($this->headers
['Subject']).'?=';
582 * Returns a complete, EOL terminated header line, wraps it if necessary
586 * @return string line
588 protected function wrappedHeaderLine($key, $val){
589 return wordwrap("$key: $val", 78, MAILHEADER_EOL
.' ').MAILHEADER_EOL
;
593 * Create a string from the headers array
595 * @returns string the headers
597 protected function prepareHeaders() {
599 foreach($this->headers
as $key => $val) {
600 if ($val === '' ||
$val === null) continue;
601 $headers .= $this->wrappedHeaderLine($key, $val);
607 * return a full email with all headers
609 * This is mainly intended for debugging and testing but could also be
610 * used for MHT exports
612 * @return string the mail, false on errors
614 public function dump() {
615 $this->cleanHeaders();
616 $body = $this->prepareBody();
617 if($body === false) return false;
618 $headers = $this->prepareHeaders();
620 return $headers.MAILHEADER_EOL
.$body;
624 * Prepare default token replacement strings
626 * Populates the '$replacements' property.
627 * Should be called by the class constructor
629 protected function prepareTokenReplacements() {
632 /* @var Input $INPUT */
637 $cip = gethostsbyaddrs($ip);
638 $name = isset($INFO) ?
$INFO['userinfo']['name'] : '';
639 $mail = isset($INFO) ?
$INFO['userinfo']['mail'] : '';
641 $this->replacements
['text'] = array(
643 'BROWSER' => $INPUT->server
->str('HTTP_USER_AGENT'),
646 'TITLE' => $conf['title'],
647 'DOKUWIKIURL' => DOKU_URL
,
648 'USER' => $INPUT->server
->str('REMOTE_USER'),
652 $signature = str_replace(
654 $this->replacements
['text']['DOKUWIKIURL'],
655 $lang['email_signature_text']
657 $this->replacements
['text']['EMAILSIGNATURE'] = "\n-- \n" . $signature . "\n";
659 $this->replacements
['html'] = array(
660 'DATE' => '<i>' . hsc(dformat()) . '</i>',
661 'BROWSER' => hsc($INPUT->server
->str('HTTP_USER_AGENT')),
662 'IPADDRESS' => '<code>' . hsc($ip) . '</code>',
663 'HOSTNAME' => '<code>' . hsc($cip) . '</code>',
664 'TITLE' => hsc($conf['title']),
665 'DOKUWIKIURL' => '<a href="' . DOKU_URL
. '">' . DOKU_URL
. '</a>',
666 'USER' => hsc($INPUT->server
->str('REMOTE_USER')),
667 'NAME' => hsc($name),
668 'MAIL' => '<a href="mailto:"' . hsc($mail) . '">' .
671 $signature = $lang['email_signature_text'];
672 if(!empty($lang['email_signature_html'])) {
673 $signature = $lang['email_signature_html'];
675 $signature = str_replace(
681 $this->replacements
['html']['DOKUWIKIURL'],
686 $this->replacements
['html']['EMAILSIGNATURE'] = $signature;
692 * Call this after all data was set
694 * @triggers MAIL_MESSAGE_SEND
695 * @return bool true if the mail was successfully passed to the MTA
697 public function send() {
702 // pass the whole mail class to plugin
704 // pass references for backward compatibility
705 'to' => &$this->headers
['To'],
706 'cc' => &$this->headers
['Cc'],
707 'bcc' => &$this->headers
['Bcc'],
708 'from' => &$this->headers
['From'],
709 'subject' => &$this->headers
['Subject'],
710 'body' => &$this->text
,
711 'params' => &$this->sendparam
,
712 'headers' => '', // plugins shouldn't use this
713 // signal if we mailed successfully to AFTER event
714 'success' => &$success,
717 // do our thing if BEFORE hook approves
718 $evt = new Event('MAIL_MESSAGE_SEND', $data);
719 if($evt->advise_before(true)) {
720 // clean up before using the headers
721 $this->cleanHeaders();
724 if(trim($this->headers
['To']) === '' &&
725 trim($this->headers
['Cc']) === '' &&
726 trim($this->headers
['Bcc']) === ''
729 // The To: header is special
730 if(array_key_exists('To', $this->headers
)) {
731 $to = (string)$this->headers
['To'];
732 unset($this->headers
['To']);
738 if(array_key_exists('Subject', $this->headers
)) {
739 $subject = (string)$this->headers
['Subject'];
740 unset($this->headers
['Subject']);
746 $body = $this->prepareBody();
747 if($body === false) return false;
750 $headers = $this->prepareHeaders();
751 // add any headers set by legacy plugins
752 if(trim($data['headers'])) {
753 $headers .= MAILHEADER_EOL
.trim($data['headers']);
757 if($this->sendparam
=== null) {
758 $success = @mail
($to, $subject, $body, $headers);
760 $success = @mail
($to, $subject, $body, $headers, $this->sendparam
);
763 // any AFTER actions?
764 $evt->advise_after();