translation update
[dokuwiki.git] / inc / Mailer.class.php
blob0f3321bb99a7ad96d5327b7ad382abc6cff1e466
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.
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?)
13 // think different
14 if(!defined('MAILHEADER_EOL')) define('MAILHEADER_EOL', "\n");
15 #define('MAILHEADER_ASCIIONLY',1);
17 /**
18 * Mail Handling
20 class Mailer {
22 protected $headers = array();
23 protected $attach = array();
24 protected $html = '';
25 protected $text = '';
27 protected $boundary = '';
28 protected $partid = '';
29 protected $sendparam = null;
31 /** @var EmailAddressValidator */
32 protected $validator = null;
33 protected $allowhtml = true;
35 /**
36 * Constructor
38 * Initializes the boundary strings and part counters
40 public function __construct() {
41 global $conf;
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.'>');
62 /**
63 * Attach a file
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 = '') {
71 if(!$name) {
72 $name = utf8_basename($path);
75 $this->attach[] = array(
76 'data' => file_get_contents($path),
77 'mime' => $mime,
78 'name' => $name,
79 'embed' => $embed
83 /**
84 * Attach a file
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 = '') {
92 if(!$name) {
93 list(, $ext) = explode('/', $mime);
94 $name = count($this->attach).".$ext";
97 $this->attach[] = array(
98 'data' => $data,
99 'mime' => $mime,
100 'name' => $name,
101 'embed' => $embed
106 * Callback function to automatically embed images referenced in HTML templates
108 protected function autoembed_cb($matches) {
109 static $embeds = 0;
110 $embeds++;
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
134 if($clean) {
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 = '';
144 }else{
145 $value = trim($value);
147 if($value === '') {
148 if(isset($this->headers[$header])) unset($this->headers[$header]);
149 } else {
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) {
180 global $INFO;
181 global $conf;
182 $htmlrep = (array)$htmlrep;
183 $textrep = (array)$textrep;
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);
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);
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);
208 // embed media from templates
209 $html = preg_replace_callback(
210 '/@MEDIA\(([^\)]+)\)@/',
211 array($this, 'autoembed_cb'), $html
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'],
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>',
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) {
263 $this->html = $html;
267 * Set the plain text part of the mail
269 * You probably want to use setBody() instead
271 public function setText($text) {
272 $this->text = $text;
276 * Add the To: recipients
278 * @see setAddress
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
288 * @see setAddress
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
298 * @see setAddress
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
311 * @see setAddress
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!
333 * Example:
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;
343 $headers = '';
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
350 $part = trim($part);
352 // parse address
353 if(preg_match('#(.*?)<(.*?)>#', $part, $matches)) {
354 $text = trim($matches[1]);
355 $addr = $matches[2];
356 } else {
357 $addr = $part;
359 // skip empty ones
360 if(empty($addr)) {
361 continue;
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;
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);
376 continue;
379 // text was given
380 if(!empty($text) && $names) {
381 // add address quotes
382 $addr = "<$addr>";
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).'?=';
392 } else {
393 $text = '';
396 // add to header comma seperated
397 if($headers != '') {
398 $headers .= ', ';
400 $headers .= $text.' '.$addr;
403 $headers = trim($headers);
404 if(empty($headers)) return false;
406 return $headers;
411 * Prepare the mime multiparts for all attachments
413 * Replaces placeholders in the HTML with the correct CIDs
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;
423 // replace wildcards
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;
434 } else {
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);
440 $part++;
442 return $mime;
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) {
456 $this->html = '';
459 // check for body
460 if(!$this->text && !$this->html) {
461 return false;
464 // add general headers
465 $this->headers['MIME-Version'] = '1.0';
467 $body = '';
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;
509 return $body;
513 * Cleanup and encode the headers array
515 protected function cleanHeaders() {
516 global $conf;
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'].']';
532 } else {
533 $prefix = '['.utf8_substr($conf['title'], 0, 20).'...]';
535 } else {
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'];
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']);
548 if(!utf8_isASCII($this->headers['Subject'])) {
549 $this->headers['Subject'] = '=?UTF-8?B?'.base64_encode($this->headers['Subject']).'?=';
553 // wrap headers
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() {
565 $headers = '';
566 foreach($this->headers as $key => $val) {
567 if ($val === '') continue;
568 $headers .= "$key: $val".MAILHEADER_EOL;
570 return $headers;
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;
591 * Send the mail
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() {
599 $success = false;
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,
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();
624 // any recipients?
625 if(trim($this->headers['To']) === '' &&
626 trim($this->headers['Cc']) === '' &&
627 trim($this->headers['Bcc']) === ''
628 ) return false;
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 = '';
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 = '';
646 // make the body
647 $body = $this->prepareBody();
648 if($body === false) return false;
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']);
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);
664 // any AFTER actions?
665 $evt->advise_after();
666 return $success;