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