[ Index ]

PHP Cross Reference of DokuWiki

title

Body

[close]

/inc/ -> Mailer.class.php (source)

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