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 = substr(md5(uniqid(rand(), true)),0, 8).'@'.$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 cleanAddress 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 cleanAddress 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 cleanAddress 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 cleanAddress 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 * cc("föö <foo@bar.com>, me@somewhere.com","TBcc"); 337 * 338 * @param string|array $addresses 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 .= $this->wrappedHeaderLine('Content-Type', $media['mime'].'; id="'.$cid.'"'); 434 $mime .= $this->wrappedHeaderLine('Content-Transfer-Encoding', 'base64'); 435 $mime .= $this->wrappedHeaderLine('Content-ID',"<$cid>"); 436 if($media['embed']) { 437 $mime .= $this->wrappedHeaderLine('Content-Disposition', 'inline; filename='.$media['name']); 438 } else { 439 $mime .= $this->wrappedHeaderLine('Content-Disposition', 'attachment; filename='.$media['name']); 440 } 441 $mime .= MAILHEADER_EOL; //end of headers 442 $mime .= chunk_split(base64_encode($media['data']), 74, MAILHEADER_EOL); 443 444 $part++; 445 } 446 return $mime; 447 } 448 449 /** 450 * Build the body and handles multi part mails 451 * 452 * Needs to be called before prepareHeaders! 453 * 454 * @return string the prepared mail body, false on errors 455 */ 456 protected function prepareBody() { 457 458 // no HTML mails allowed? remove HTML body 459 if(!$this->allowhtml) { 460 $this->html = ''; 461 } 462 463 // check for body 464 if(!$this->text && !$this->html) { 465 return false; 466 } 467 468 // add general headers 469 $this->headers['MIME-Version'] = '1.0'; 470 471 $body = ''; 472 473 if(!$this->html && !count($this->attach)) { // we can send a simple single part message 474 $this->headers['Content-Type'] = 'text/plain; charset=UTF-8'; 475 $this->headers['Content-Transfer-Encoding'] = 'base64'; 476 $body .= chunk_split(base64_encode($this->text), 72, MAILHEADER_EOL); 477 } else { // multi part it is 478 $body .= "This is a multi-part message in MIME format.".MAILHEADER_EOL; 479 480 // prepare the attachments 481 $attachments = $this->prepareAttachments(); 482 483 // do we have alternative text content? 484 if($this->text && $this->html) { 485 $this->headers['Content-Type'] = 'multipart/alternative;'.MAILHEADER_EOL. 486 ' boundary="'.$this->boundary.'XX"'; 487 $body .= '--'.$this->boundary.'XX'.MAILHEADER_EOL; 488 $body .= 'Content-Type: text/plain; charset=UTF-8'.MAILHEADER_EOL; 489 $body .= 'Content-Transfer-Encoding: base64'.MAILHEADER_EOL; 490 $body .= MAILHEADER_EOL; 491 $body .= chunk_split(base64_encode($this->text), 72, MAILHEADER_EOL); 492 $body .= '--'.$this->boundary.'XX'.MAILHEADER_EOL; 493 $body .= 'Content-Type: multipart/related;'.MAILHEADER_EOL. 494 ' boundary="'.$this->boundary.'";'.MAILHEADER_EOL. 495 ' type="text/html"'.MAILHEADER_EOL; 496 $body .= MAILHEADER_EOL; 497 } 498 499 $body .= '--'.$this->boundary.MAILHEADER_EOL; 500 $body .= 'Content-Type: text/html; charset=UTF-8'.MAILHEADER_EOL; 501 $body .= 'Content-Transfer-Encoding: base64'.MAILHEADER_EOL; 502 $body .= MAILHEADER_EOL; 503 $body .= chunk_split(base64_encode($this->html), 72, MAILHEADER_EOL); 504 $body .= MAILHEADER_EOL; 505 $body .= $attachments; 506 $body .= '--'.$this->boundary.'--'.MAILHEADER_EOL; 507 508 // close open multipart/alternative boundary 509 if($this->text && $this->html) { 510 $body .= '--'.$this->boundary.'XX--'.MAILHEADER_EOL; 511 } 512 } 513 514 return $body; 515 } 516 517 /** 518 * Cleanup and encode the headers array 519 */ 520 protected function cleanHeaders() { 521 global $conf; 522 523 // clean up addresses 524 if(empty($this->headers['From'])) $this->from($conf['mailfrom']); 525 $addrs = array('To', 'From', 'Cc', 'Bcc', 'Reply-To', 'Sender'); 526 foreach($addrs as $addr) { 527 if(isset($this->headers[$addr])) { 528 $this->headers[$addr] = $this->cleanAddress($this->headers[$addr]); 529 } 530 } 531 532 if(isset($this->headers['Subject'])) { 533 // add prefix to subject 534 if(empty($conf['mailprefix'])) { 535 if(utf8_strlen($conf['title']) < 20) { 536 $prefix = '['.$conf['title'].']'; 537 } else { 538 $prefix = '['.utf8_substr($conf['title'], 0, 20).'...]'; 539 } 540 } else { 541 $prefix = '['.$conf['mailprefix'].']'; 542 } 543 $len = strlen($prefix); 544 if(substr($this->headers['Subject'], 0, $len) != $prefix) { 545 $this->headers['Subject'] = $prefix.' '.$this->headers['Subject']; 546 } 547 548 // encode subject 549 if(defined('MAILHEADER_ASCIIONLY')) { 550 $this->headers['Subject'] = utf8_deaccent($this->headers['Subject']); 551 $this->headers['Subject'] = utf8_strip($this->headers['Subject']); 552 } 553 if(!utf8_isASCII($this->headers['Subject'])) { 554 $this->headers['Subject'] = '=?UTF-8?B?'.base64_encode($this->headers['Subject']).'?='; 555 } 556 } 557 558 } 559 560 /** 561 * Returns a complete, EOL terminated header line, wraps it if necessary 562 * 563 * @param $key 564 * @param $val 565 * @return string 566 */ 567 protected function wrappedHeaderLine($key, $val){ 568 return wordwrap("$key: $val", 78, MAILHEADER_EOL.' ').MAILHEADER_EOL; 569 } 570 571 /** 572 * Create a string from the headers array 573 * 574 * @returns string the headers 575 */ 576 protected function prepareHeaders() { 577 $headers = ''; 578 foreach($this->headers as $key => $val) { 579 if ($val === '' || is_null($val)) continue; 580 $headers .= $this->wrappedHeaderLine($key, $val); 581 } 582 return $headers; 583 } 584 585 /** 586 * return a full email with all headers 587 * 588 * This is mainly intended for debugging and testing but could also be 589 * used for MHT exports 590 * 591 * @return string the mail, false on errors 592 */ 593 public function dump() { 594 $this->cleanHeaders(); 595 $body = $this->prepareBody(); 596 if($body === false) return false; 597 $headers = $this->prepareHeaders(); 598 599 return $headers.MAILHEADER_EOL.$body; 600 } 601 602 /** 603 * Send the mail 604 * 605 * Call this after all data was set 606 * 607 * @triggers MAIL_MESSAGE_SEND 608 * @return bool true if the mail was successfully passed to the MTA 609 */ 610 public function send() { 611 $success = false; 612 613 // prepare hook data 614 $data = array( 615 // pass the whole mail class to plugin 616 'mail' => $this, 617 // pass references for backward compatibility 618 'to' => &$this->headers['To'], 619 'cc' => &$this->headers['Cc'], 620 'bcc' => &$this->headers['Bcc'], 621 'from' => &$this->headers['From'], 622 'subject' => &$this->headers['Subject'], 623 'body' => &$this->text, 624 'params' => &$this->sendparam, 625 'headers' => '', // plugins shouldn't use this 626 // signal if we mailed successfully to AFTER event 627 'success' => &$success, 628 ); 629 630 // do our thing if BEFORE hook approves 631 $evt = new Doku_Event('MAIL_MESSAGE_SEND', $data); 632 if($evt->advise_before(true)) { 633 // clean up before using the headers 634 $this->cleanHeaders(); 635 636 // any recipients? 637 if(trim($this->headers['To']) === '' && 638 trim($this->headers['Cc']) === '' && 639 trim($this->headers['Bcc']) === '' 640 ) return false; 641 642 // The To: header is special 643 if(array_key_exists('To', $this->headers)) { 644 $to = (string)$this->headers['To']; 645 unset($this->headers['To']); 646 } else { 647 $to = ''; 648 } 649 650 // so is the subject 651 if(array_key_exists('Subject', $this->headers)) { 652 $subject = (string)$this->headers['Subject']; 653 unset($this->headers['Subject']); 654 } else { 655 $subject = ''; 656 } 657 658 // make the body 659 $body = $this->prepareBody(); 660 if($body === false) return false; 661 662 // cook the headers 663 $headers = $this->prepareHeaders(); 664 // add any headers set by legacy plugins 665 if(trim($data['headers'])) { 666 $headers .= MAILHEADER_EOL.trim($data['headers']); 667 } 668 669 // send the thing 670 if(is_null($this->sendparam)) { 671 $success = @mail($to, $subject, $body, $headers); 672 } else { 673 $success = @mail($to, $subject, $body, $headers, $this->sendparam); 674 } 675 } 676 // any AFTER actions? 677 $evt->advise_after(); 678 return $success; 679 } 680} 681