xref: /dokuwiki/inc/Mailer.class.php (revision 3819cafdf98a496587b7b80f913b955650a0b449)
1bb01c27cSAndreas Gohr<?php
2bb01c27cSAndreas Gohr/**
31d045709SAndreas Gohr * A class to build and send multi part mails (with HTML content and embedded
41d045709SAndreas Gohr * attachments). All mails are assumed to be in UTF-8 encoding.
51d045709SAndreas Gohr *
61d045709SAndreas Gohr * Attachments are handled in memory so this shouldn't be used to send huge
71d045709SAndreas Gohr * files, but then again mail shouldn't be used to send huge files either.
81d045709SAndreas Gohr *
9bb01c27cSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
10bb01c27cSAndreas Gohr */
11bb01c27cSAndreas Gohr
12bb01c27cSAndreas Gohr// end of line for mail lines - RFC822 says CRLF but postfix (and other MTAs?)
13bb01c27cSAndreas Gohr// think different
14bb01c27cSAndreas Gohrif(!defined('MAILHEADER_EOL')) define('MAILHEADER_EOL', "\n");
15bb01c27cSAndreas Gohr#define('MAILHEADER_ASCIIONLY',1);
16bb01c27cSAndreas Gohr
17a89c75afSAndreas Gohr/**
18a89c75afSAndreas Gohr * Mail Handling
19a89c75afSAndreas Gohr */
20bb01c27cSAndreas Gohrclass Mailer {
21bb01c27cSAndreas Gohr
22f41c79d7SAndreas Gohr    protected $headers   = array();
23f41c79d7SAndreas Gohr    protected $attach    = array();
24f41c79d7SAndreas Gohr    protected $html      = '';
25f41c79d7SAndreas Gohr    protected $text      = '';
26bb01c27cSAndreas Gohr
27f41c79d7SAndreas Gohr    protected $boundary  = '';
28f41c79d7SAndreas Gohr    protected $partid    = '';
29f41c79d7SAndreas Gohr    protected $sendparam = null;
30bb01c27cSAndreas Gohr
31a89c75afSAndreas Gohr    /** @var EmailAddressValidator */
32f41c79d7SAndreas Gohr    protected $validator = null;
33f41c79d7SAndreas Gohr    protected $allowhtml = true;
341d045709SAndreas Gohr
351d045709SAndreas Gohr    /**
361d045709SAndreas Gohr     * Constructor
371d045709SAndreas Gohr     *
381d045709SAndreas Gohr     * Initializes the boundary strings and part counters
391d045709SAndreas Gohr     */
401d045709SAndreas Gohr    public function __construct() {
419f3eca0bSAndreas Gohr        global $conf;
42585bf44eSChristopher Smith        /* @var Input $INPUT */
43585bf44eSChristopher Smith        global $INPUT;
449f3eca0bSAndreas Gohr
459f3eca0bSAndreas Gohr        $server = parse_url(DOKU_URL, PHP_URL_HOST);
46d6e04b60SAndreas Gohr        if(strpos($server,'.') === false) $server = $server.'.localhost';
471d045709SAndreas Gohr
481d8036c2SAndreas Gohr        $this->partid   = substr(md5(uniqid(rand(), true)),0, 8).'@'.$server;
49b3577cf9SAndreas Gohr        $this->boundary = '__________'.md5(uniqid(rand(), true));
509f3eca0bSAndreas Gohr
519f3eca0bSAndreas Gohr        $listid = join('.', array_reverse(explode('/', DOKU_BASE))).$server;
529f3eca0bSAndreas Gohr        $listid = strtolower(trim($listid, '.'));
539f3eca0bSAndreas Gohr
542398a2b5SAndreas Gohr        $this->allowhtml = (bool)$conf['htmlmail'];
552398a2b5SAndreas Gohr
569f3eca0bSAndreas Gohr        // add some default headers for mailfiltering FS#2247
576a1f928fSAndreas Gohr        $this->setHeader('X-Mailer', 'DokuWiki');
58585bf44eSChristopher Smith        $this->setHeader('X-DokuWiki-User', $INPUT->server->str('REMOTE_USER'));
599f3eca0bSAndreas Gohr        $this->setHeader('X-DokuWiki-Title', $conf['title']);
609f3eca0bSAndreas Gohr        $this->setHeader('X-DokuWiki-Server', $server);
619f3eca0bSAndreas Gohr        $this->setHeader('X-Auto-Response-Suppress', 'OOF');
629f3eca0bSAndreas Gohr        $this->setHeader('List-Id', $conf['title'].' <'.$listid.'>');
63d6e04b60SAndreas Gohr        $this->setHeader('Date', date('r'), false);
64bb01c27cSAndreas Gohr    }
65bb01c27cSAndreas Gohr
66bb01c27cSAndreas Gohr    /**
67bb01c27cSAndreas Gohr     * Attach a file
68bb01c27cSAndreas Gohr     *
69a89c75afSAndreas Gohr     * @param string $path  Path to the file to attach
70a89c75afSAndreas Gohr     * @param string $mime  Mimetype of the attached file
71a89c75afSAndreas Gohr     * @param string $name The filename to use
72a89c75afSAndreas Gohr     * @param string $embed Unique key to reference this file from the HTML part
73bb01c27cSAndreas Gohr     */
74bb01c27cSAndreas Gohr    public function attachFile($path, $mime, $name = '', $embed = '') {
75bb01c27cSAndreas Gohr        if(!$name) {
763009a773SAndreas Gohr            $name = utf8_basename($path);
77bb01c27cSAndreas Gohr        }
78bb01c27cSAndreas Gohr
79bb01c27cSAndreas Gohr        $this->attach[] = array(
80bb01c27cSAndreas Gohr            'data'  => file_get_contents($path),
81bb01c27cSAndreas Gohr            'mime'  => $mime,
82bb01c27cSAndreas Gohr            'name'  => $name,
83bb01c27cSAndreas Gohr            'embed' => $embed
84bb01c27cSAndreas Gohr        );
85bb01c27cSAndreas Gohr    }
86bb01c27cSAndreas Gohr
87bb01c27cSAndreas Gohr    /**
88bb01c27cSAndreas Gohr     * Attach a file
89bb01c27cSAndreas Gohr     *
90a89c75afSAndreas Gohr     * @param string $data  The file contents to attach
91a89c75afSAndreas Gohr     * @param string $mime  Mimetype of the attached file
92a89c75afSAndreas Gohr     * @param string $name  The filename to use
93a89c75afSAndreas Gohr     * @param string $embed Unique key to reference this file from the HTML part
94bb01c27cSAndreas Gohr     */
95bb01c27cSAndreas Gohr    public function attachContent($data, $mime, $name = '', $embed = '') {
96bb01c27cSAndreas Gohr        if(!$name) {
97a89c75afSAndreas Gohr            list(, $ext) = explode('/', $mime);
98bb01c27cSAndreas Gohr            $name = count($this->attach).".$ext";
99bb01c27cSAndreas Gohr        }
100bb01c27cSAndreas Gohr
101bb01c27cSAndreas Gohr        $this->attach[] = array(
102bb01c27cSAndreas Gohr            'data'  => $data,
103bb01c27cSAndreas Gohr            'mime'  => $mime,
104bb01c27cSAndreas Gohr            'name'  => $name,
105bb01c27cSAndreas Gohr            'embed' => $embed
106bb01c27cSAndreas Gohr        );
107bb01c27cSAndreas Gohr    }
108bb01c27cSAndreas Gohr
109bb01c27cSAndreas Gohr    /**
110850dbf1fSAndreas Gohr     * Callback function to automatically embed images referenced in HTML templates
11142ea7f44SGerrit Uitslag     *
11242ea7f44SGerrit Uitslag     * @param array $matches
11342ea7f44SGerrit Uitslag     * @return string placeholder
114850dbf1fSAndreas Gohr     */
115850dbf1fSAndreas Gohr    protected function autoembed_cb($matches) {
116850dbf1fSAndreas Gohr        static $embeds = 0;
117850dbf1fSAndreas Gohr        $embeds++;
118850dbf1fSAndreas Gohr
119850dbf1fSAndreas Gohr        // get file and mime type
120850dbf1fSAndreas Gohr        $media = cleanID($matches[1]);
121a89c75afSAndreas Gohr        list(, $mime) = mimetype($media);
122850dbf1fSAndreas Gohr        $file = mediaFN($media);
123850dbf1fSAndreas Gohr        if(!file_exists($file)) return $matches[0]; //bad reference, keep as is
124850dbf1fSAndreas Gohr
125850dbf1fSAndreas Gohr        // attach it and set placeholder
126850dbf1fSAndreas Gohr        $this->attachFile($file, $mime, '', 'autoembed'.$embeds);
127850dbf1fSAndreas Gohr        return '%%autoembed'.$embeds.'%%';
128850dbf1fSAndreas Gohr    }
129850dbf1fSAndreas Gohr
130850dbf1fSAndreas Gohr    /**
1311d045709SAndreas Gohr     * Add an arbitrary header to the mail
1321d045709SAndreas Gohr     *
133a36fc348SAndreas Gohr     * If an empy value is passed, the header is removed
134a36fc348SAndreas Gohr     *
1351d045709SAndreas Gohr     * @param string $header the header name (no trailing colon!)
13659bc3b48SGerrit Uitslag     * @param string|string[] $value  the value of the header
1371d045709SAndreas Gohr     * @param bool   $clean  remove all non-ASCII chars and line feeds?
1381d045709SAndreas Gohr     */
1391d045709SAndreas Gohr    public function setHeader($header, $value, $clean = true) {
1409f3eca0bSAndreas Gohr        $header = str_replace(' ', '-', ucwords(strtolower(str_replace('-', ' ', $header)))); // streamline casing
1411d045709SAndreas Gohr        if($clean) {
142578b2c23SAndreas Gohr            $header = preg_replace('/[^a-zA-Z0-9_ \-\.\+\@]+/', '', $header);
143578b2c23SAndreas Gohr            $value  = preg_replace('/[^a-zA-Z0-9_ \-\.\+\@<>]+/', '', $value);
1441d045709SAndreas Gohr        }
145a36fc348SAndreas Gohr
146a36fc348SAndreas Gohr        // empty value deletes
147b6c97c70SAndreas Gohr        if(is_array($value)){
148b6c97c70SAndreas Gohr            $value = array_map('trim', $value);
149b6c97c70SAndreas Gohr            $value = array_filter($value);
150b6c97c70SAndreas Gohr            if(!$value) $value = '';
151b6c97c70SAndreas Gohr        }else{
152a36fc348SAndreas Gohr            $value = trim($value);
153b6c97c70SAndreas Gohr        }
154a36fc348SAndreas Gohr        if($value === '') {
155a36fc348SAndreas Gohr            if(isset($this->headers[$header])) unset($this->headers[$header]);
156a36fc348SAndreas Gohr        } else {
1571d045709SAndreas Gohr            $this->headers[$header] = $value;
1581d045709SAndreas Gohr        }
159a36fc348SAndreas Gohr    }
1601d045709SAndreas Gohr
1611d045709SAndreas Gohr    /**
1621d045709SAndreas Gohr     * Set additional parameters to be passed to sendmail
1631d045709SAndreas Gohr     *
1641d045709SAndreas Gohr     * Whatever is set here is directly passed to PHP's mail() command as last
1651d045709SAndreas Gohr     * parameter. Depending on the PHP setup this might break mailing alltogether
16642ea7f44SGerrit Uitslag     *
16742ea7f44SGerrit Uitslag     * @param string $param
1681d045709SAndreas Gohr     */
1691d045709SAndreas Gohr    public function setParameters($param) {
1701d045709SAndreas Gohr        $this->sendparam = $param;
1711d045709SAndreas Gohr    }
1721d045709SAndreas Gohr
1731d045709SAndreas Gohr    /**
174abbf0890SAndreas Gohr     * Set the text and HTML body and apply replacements
175abbf0890SAndreas Gohr     *
176abbf0890SAndreas Gohr     * This function applies a whole bunch of default replacements in addition
177abbf0890SAndreas Gohr     * to the ones specidifed as parameters
178abbf0890SAndreas Gohr     *
179abbf0890SAndreas Gohr     * If you pass the HTML part or HTML replacements yourself you have to make
180abbf0890SAndreas Gohr     * sure you encode all HTML special chars correctly
181abbf0890SAndreas Gohr     *
182abbf0890SAndreas Gohr     * @param string $text     plain text body
183abbf0890SAndreas Gohr     * @param array  $textrep  replacements to apply on the text part
184abbf0890SAndreas Gohr     * @param array  $htmlrep  replacements to apply on the HTML part, leave null to use $textrep
18559bc3b48SGerrit Uitslag     * @param string $html     the HTML body, leave null to create it from $text
186f08086ecSAndreas Gohr     * @param bool   $wrap     wrap the HTML in the default header/Footer
187abbf0890SAndreas Gohr     */
188f08086ecSAndreas Gohr    public function setBody($text, $textrep = null, $htmlrep = null, $html = null, $wrap = true) {
189abbf0890SAndreas Gohr        global $INFO;
190abbf0890SAndreas Gohr        global $conf;
191585bf44eSChristopher Smith        /* @var Input $INPUT */
192585bf44eSChristopher Smith        global $INPUT;
193ba2c2f17Sfurun        global $lang;
194585bf44eSChristopher Smith
19576efd6d0SAndreas Gohr        $htmlrep = (array)$htmlrep;
19676efd6d0SAndreas Gohr        $textrep = (array)$textrep;
197abbf0890SAndreas Gohr
198abbf0890SAndreas Gohr        // create HTML from text if not given
199abbf0890SAndreas Gohr        if(is_null($html)) {
200ba9c057bSAndreas Gohr            $html = $text;
201ba9c057bSAndreas Gohr            $html = hsc($html);
202ba2c2f17Sfurun            $html = preg_replace('/^----+$/m', '<hr >', $html);
203ba9c057bSAndreas Gohr            $html = nl2br($html);
204abbf0890SAndreas Gohr        }
205f08086ecSAndreas Gohr        if($wrap) {
206*3819cafdSfurun            $wrap = rawLocale('mailwrap', 'html');
207*3819cafdSfurun            $html = preg_replace('/\n-- <br \/>.*$/s', '', $html); //strip signature
208*3819cafdSfurun            $html = str_replace('@EMAILSIGNATURE@', '', $html); //strip @EMAILSIGNATURE@
209*3819cafdSfurun            $html = str_replace('@HTMLBODY@', $html, $wrap);
210f08086ecSAndreas Gohr        }
211f08086ecSAndreas Gohr
212*3819cafdSfurun        if(strpos($text, '@EMAILSIGNATURE@') === false) {
213*3819cafdSfurun            $text = rtrim($text);
214ba2c2f17Sfurun            $text .= "\n\n\n\n-- \n" . $lang['email_signature'] . ":\n@DOKUWIKIURL@\n";
215*3819cafdSfurun        }
216ba2c2f17Sfurun
21776efd6d0SAndreas Gohr        // copy over all replacements missing for HTML (autolink URLs)
21876efd6d0SAndreas Gohr        foreach($textrep as $key => $value) {
21976efd6d0SAndreas Gohr            if(isset($htmlrep[$key])) continue;
2203e7e6067SKlap-in            if(media_isexternal($value)) {
22176efd6d0SAndreas Gohr                $htmlrep[$key] = '<a href="'.hsc($value).'">'.hsc($value).'</a>';
22276efd6d0SAndreas Gohr            } else {
22376efd6d0SAndreas Gohr                $htmlrep[$key] = hsc($value);
22476efd6d0SAndreas Gohr            }
225abbf0890SAndreas Gohr        }
226abbf0890SAndreas Gohr
227850dbf1fSAndreas Gohr        // embed media from templates
228a89c75afSAndreas Gohr        $html = preg_replace_callback(
229a89c75afSAndreas Gohr            '/@MEDIA\(([^\)]+)\)@/',
230a89c75afSAndreas Gohr            array($this, 'autoembed_cb'), $html
231a89c75afSAndreas Gohr        );
232850dbf1fSAndreas Gohr
233abbf0890SAndreas Gohr        // prepare default replacements
234abbf0890SAndreas Gohr        $ip   = clientIP();
235f08086ecSAndreas Gohr        $cip  = gethostsbyaddrs($ip);
236abbf0890SAndreas Gohr        $trep = array(
237abbf0890SAndreas Gohr            'DATE'           => dformat(),
238585bf44eSChristopher Smith            'BROWSER'        => $INPUT->server->str('HTTP_USER_AGENT'),
239abbf0890SAndreas Gohr            'IPADDRESS'      => $ip,
240f08086ecSAndreas Gohr            'HOSTNAME'       => $cip,
241abbf0890SAndreas Gohr            'TITLE'          => $conf['title'],
242abbf0890SAndreas Gohr            'DOKUWIKIURL'    => DOKU_URL,
243585bf44eSChristopher Smith            'USER'           => $INPUT->server->str('REMOTE_USER'),
244abbf0890SAndreas Gohr            'NAME'           => $INFO['userinfo']['name'],
245abbf0890SAndreas Gohr            'MAIL'           => $INFO['userinfo']['mail'],
246*3819cafdSfurun            'EMAILSIGNATURE' => "\n-- \n".$lang['email_signature'].":\n".DOKU_URL."\n",
247abbf0890SAndreas Gohr        );
248abbf0890SAndreas Gohr        $trep = array_merge($trep, (array)$textrep);
249abbf0890SAndreas Gohr        $hrep = array(
250abbf0890SAndreas Gohr            'DATE'           => '<i>'.hsc(dformat()).'</i>',
251585bf44eSChristopher Smith            'BROWSER'        => hsc($INPUT->server->str('HTTP_USER_AGENT')),
252abbf0890SAndreas Gohr            'IPADDRESS'      => '<code>'.hsc($ip).'</code>',
253f08086ecSAndreas Gohr            'HOSTNAME'       => '<code>'.hsc($cip).'</code>',
254abbf0890SAndreas Gohr            'TITLE'          => hsc($conf['title']),
255abbf0890SAndreas Gohr            'DOKUWIKIURL'    => '<a href="'.DOKU_URL.'">'.DOKU_URL.'</a>',
256585bf44eSChristopher Smith            'USER'           => hsc($INPUT->server->str('REMOTE_USER')),
257abbf0890SAndreas Gohr            'NAME'           => hsc($INFO['userinfo']['name']),
258abbf0890SAndreas Gohr            'MAIL'           => '<a href="mailto:"'.hsc($INFO['userinfo']['mail']).'">'.
259abbf0890SAndreas Gohr                hsc($INFO['userinfo']['mail']).'</a>',
260*3819cafdSfurun            'EMAILSIGNATURE' => hsc($lang['email_signature']).':<br />' .
261*3819cafdSfurun                '<a href="'.DOKU_URL.'">'.DOKU_URL.'</a>',
262abbf0890SAndreas Gohr        );
263abbf0890SAndreas Gohr        $hrep = array_merge($hrep, (array)$htmlrep);
264abbf0890SAndreas Gohr
265abbf0890SAndreas Gohr        // Apply replacements
266abbf0890SAndreas Gohr        foreach($trep as $key => $substitution) {
267abbf0890SAndreas Gohr            $text = str_replace('@'.strtoupper($key).'@', $substitution, $text);
268abbf0890SAndreas Gohr        }
269abbf0890SAndreas Gohr        foreach($hrep as $key => $substitution) {
270abbf0890SAndreas Gohr            $html = str_replace('@'.strtoupper($key).'@', $substitution, $html);
271abbf0890SAndreas Gohr        }
272abbf0890SAndreas Gohr
273abbf0890SAndreas Gohr        $this->setHTML($html);
274abbf0890SAndreas Gohr        $this->setText($text);
275abbf0890SAndreas Gohr    }
276abbf0890SAndreas Gohr
277abbf0890SAndreas Gohr    /**
278bb01c27cSAndreas Gohr     * Set the HTML part of the mail
279bb01c27cSAndreas Gohr     *
280bb01c27cSAndreas Gohr     * Placeholders can be used to reference embedded attachments
281abbf0890SAndreas Gohr     *
282abbf0890SAndreas Gohr     * You probably want to use setBody() instead
28342ea7f44SGerrit Uitslag     *
28442ea7f44SGerrit Uitslag     * @param string $html
285bb01c27cSAndreas Gohr     */
2861d045709SAndreas Gohr    public function setHTML($html) {
287bb01c27cSAndreas Gohr        $this->html = $html;
288bb01c27cSAndreas Gohr    }
289bb01c27cSAndreas Gohr
290bb01c27cSAndreas Gohr    /**
291bb01c27cSAndreas Gohr     * Set the plain text part of the mail
292abbf0890SAndreas Gohr     *
293abbf0890SAndreas Gohr     * You probably want to use setBody() instead
29442ea7f44SGerrit Uitslag     *
29542ea7f44SGerrit Uitslag     * @param string $text
296bb01c27cSAndreas Gohr     */
2971d045709SAndreas Gohr    public function setText($text) {
298bb01c27cSAndreas Gohr        $this->text = $text;
299bb01c27cSAndreas Gohr    }
300bb01c27cSAndreas Gohr
301bb01c27cSAndreas Gohr    /**
302a36fc348SAndreas Gohr     * Add the To: recipients
303a36fc348SAndreas Gohr     *
3048c253612SGerrit Uitslag     * @see cleanAddress
30559bc3b48SGerrit Uitslag     * @param string|string[]  $address Multiple adresses separated by commas or as array
306a36fc348SAndreas Gohr     */
307a36fc348SAndreas Gohr    public function to($address) {
308a36fc348SAndreas Gohr        $this->setHeader('To', $address, false);
309a36fc348SAndreas Gohr    }
310a36fc348SAndreas Gohr
311a36fc348SAndreas Gohr    /**
312a36fc348SAndreas Gohr     * Add the Cc: recipients
313a36fc348SAndreas Gohr     *
3148c253612SGerrit Uitslag     * @see cleanAddress
31559bc3b48SGerrit Uitslag     * @param string|string[]  $address Multiple adresses separated by commas or as array
316a36fc348SAndreas Gohr     */
317a36fc348SAndreas Gohr    public function cc($address) {
318a36fc348SAndreas Gohr        $this->setHeader('Cc', $address, false);
319a36fc348SAndreas Gohr    }
320a36fc348SAndreas Gohr
321a36fc348SAndreas Gohr    /**
322a36fc348SAndreas Gohr     * Add the Bcc: recipients
323a36fc348SAndreas Gohr     *
3248c253612SGerrit Uitslag     * @see cleanAddress
32559bc3b48SGerrit Uitslag     * @param string|string[]  $address Multiple adresses separated by commas or as array
326a36fc348SAndreas Gohr     */
327a36fc348SAndreas Gohr    public function bcc($address) {
328a36fc348SAndreas Gohr        $this->setHeader('Bcc', $address, false);
329a36fc348SAndreas Gohr    }
330a36fc348SAndreas Gohr
331a36fc348SAndreas Gohr    /**
332a36fc348SAndreas Gohr     * Add the From: address
333a36fc348SAndreas Gohr     *
334a36fc348SAndreas Gohr     * This is set to $conf['mailfrom'] when not specified so you shouldn't need
335a36fc348SAndreas Gohr     * to call this function
336a36fc348SAndreas Gohr     *
3378c253612SGerrit Uitslag     * @see cleanAddress
338a36fc348SAndreas Gohr     * @param string  $address from address
339a36fc348SAndreas Gohr     */
340a36fc348SAndreas Gohr    public function from($address) {
341a36fc348SAndreas Gohr        $this->setHeader('From', $address, false);
342a36fc348SAndreas Gohr    }
343a36fc348SAndreas Gohr
344a36fc348SAndreas Gohr    /**
345a36fc348SAndreas Gohr     * Add the mail's Subject: header
346a36fc348SAndreas Gohr     *
347a36fc348SAndreas Gohr     * @param string $subject the mail subject
348a36fc348SAndreas Gohr     */
349a36fc348SAndreas Gohr    public function subject($subject) {
350a36fc348SAndreas Gohr        $this->headers['Subject'] = $subject;
351a36fc348SAndreas Gohr    }
352a36fc348SAndreas Gohr
353a36fc348SAndreas Gohr    /**
3541d045709SAndreas Gohr     * Sets an email address header with correct encoding
355bb01c27cSAndreas Gohr     *
356bb01c27cSAndreas Gohr     * Unicode characters will be deaccented and encoded base64
357bb01c27cSAndreas Gohr     * for headers. Addresses may not contain Non-ASCII data!
358bb01c27cSAndreas Gohr     *
359bb01c27cSAndreas Gohr     * Example:
3608c253612SGerrit Uitslag     *   cc("föö <foo@bar.com>, me@somewhere.com","TBcc");
361bb01c27cSAndreas Gohr     *
36242ea7f44SGerrit Uitslag     * @param string|string[]  $addresses Multiple adresses separated by commas or as array
36342ea7f44SGerrit Uitslag     * @return false|string  the prepared header (can contain multiple lines)
364bb01c27cSAndreas Gohr     */
365b6c97c70SAndreas Gohr    public function cleanAddress($addresses) {
366bb01c27cSAndreas Gohr        // No named recipients for To: in Windows (see FS#652)
367bb01c27cSAndreas Gohr        $names = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? false : true;
368bb01c27cSAndreas Gohr
369bb01c27cSAndreas Gohr        $headers = '';
370b6c97c70SAndreas Gohr        if(!is_array($addresses)){
371b6c97c70SAndreas Gohr            $addresses = explode(',', $addresses);
372b6c97c70SAndreas Gohr        }
373b6c97c70SAndreas Gohr
374b6c97c70SAndreas Gohr        foreach($addresses as $part) {
375b6c97c70SAndreas Gohr            $part = preg_replace('/[\r\n\0]+/', ' ', $part); // remove attack vectors
376bb01c27cSAndreas Gohr            $part = trim($part);
377bb01c27cSAndreas Gohr
378bb01c27cSAndreas Gohr            // parse address
379bb01c27cSAndreas Gohr            if(preg_match('#(.*?)<(.*?)>#', $part, $matches)) {
380bb01c27cSAndreas Gohr                $text = trim($matches[1]);
381bb01c27cSAndreas Gohr                $addr = $matches[2];
382bb01c27cSAndreas Gohr            } else {
383bb01c27cSAndreas Gohr                $addr = $part;
384bb01c27cSAndreas Gohr            }
385bb01c27cSAndreas Gohr            // skip empty ones
386bb01c27cSAndreas Gohr            if(empty($addr)) {
387bb01c27cSAndreas Gohr                continue;
388bb01c27cSAndreas Gohr            }
389bb01c27cSAndreas Gohr
390bb01c27cSAndreas Gohr            // FIXME: is there a way to encode the localpart of a emailaddress?
391bb01c27cSAndreas Gohr            if(!utf8_isASCII($addr)) {
392bb01c27cSAndreas Gohr                msg(htmlspecialchars("E-Mail address <$addr> is not ASCII"), -1);
393bb01c27cSAndreas Gohr                continue;
394bb01c27cSAndreas Gohr            }
395bb01c27cSAndreas Gohr
3961d045709SAndreas Gohr            if(is_null($this->validator)) {
3971d045709SAndreas Gohr                $this->validator                      = new EmailAddressValidator();
3981d045709SAndreas Gohr                $this->validator->allowLocalAddresses = true;
3991d045709SAndreas Gohr            }
4001d045709SAndreas Gohr            if(!$this->validator->check_email_address($addr)) {
401bb01c27cSAndreas Gohr                msg(htmlspecialchars("E-Mail address <$addr> is not valid"), -1);
402bb01c27cSAndreas Gohr                continue;
403bb01c27cSAndreas Gohr            }
404bb01c27cSAndreas Gohr
405bb01c27cSAndreas Gohr            // text was given
406bb01c27cSAndreas Gohr            if(!empty($text) && $names) {
407bb01c27cSAndreas Gohr                // add address quotes
408bb01c27cSAndreas Gohr                $addr = "<$addr>";
409bb01c27cSAndreas Gohr
410bb01c27cSAndreas Gohr                if(defined('MAILHEADER_ASCIIONLY')) {
411bb01c27cSAndreas Gohr                    $text = utf8_deaccent($text);
412bb01c27cSAndreas Gohr                    $text = utf8_strip($text);
413bb01c27cSAndreas Gohr                }
414bb01c27cSAndreas Gohr
415b6c97c70SAndreas Gohr                if(strpos($text, ',') !== false || !utf8_isASCII($text)) {
416bb01c27cSAndreas Gohr                    $text = '=?UTF-8?B?'.base64_encode($text).'?=';
417bb01c27cSAndreas Gohr                }
418bb01c27cSAndreas Gohr            } else {
419bb01c27cSAndreas Gohr                $text = '';
420bb01c27cSAndreas Gohr            }
421bb01c27cSAndreas Gohr
422bb01c27cSAndreas Gohr            // add to header comma seperated
423bb01c27cSAndreas Gohr            if($headers != '') {
424bb01c27cSAndreas Gohr                $headers .= ', ';
425bb01c27cSAndreas Gohr            }
426bb01c27cSAndreas Gohr            $headers .= $text.' '.$addr;
427bb01c27cSAndreas Gohr        }
428bb01c27cSAndreas Gohr
429b6c97c70SAndreas Gohr        $headers = trim($headers);
430bb01c27cSAndreas Gohr        if(empty($headers)) return false;
431bb01c27cSAndreas Gohr
432bb01c27cSAndreas Gohr        return $headers;
433bb01c27cSAndreas Gohr    }
434bb01c27cSAndreas Gohr
435bb01c27cSAndreas Gohr
436bb01c27cSAndreas Gohr    /**
437bb01c27cSAndreas Gohr     * Prepare the mime multiparts for all attachments
438bb01c27cSAndreas Gohr     *
439bb01c27cSAndreas Gohr     * Replaces placeholders in the HTML with the correct CIDs
44042ea7f44SGerrit Uitslag     *
44142ea7f44SGerrit Uitslag     * @return string mime multiparts
442bb01c27cSAndreas Gohr     */
443bb01c27cSAndreas Gohr    protected function prepareAttachments() {
444bb01c27cSAndreas Gohr        $mime = '';
445bb01c27cSAndreas Gohr        $part = 1;
446bb01c27cSAndreas Gohr        // embedded attachments
447bb01c27cSAndreas Gohr        foreach($this->attach as $media) {
448ce9d2cc8SAndreas Gohr            $media['name'] = str_replace(':', '_', cleanID($media['name'], true));
449ce9d2cc8SAndreas Gohr
450bb01c27cSAndreas Gohr            // create content id
451bb01c27cSAndreas Gohr            $cid = 'part'.$part.'.'.$this->partid;
452bb01c27cSAndreas Gohr
453bb01c27cSAndreas Gohr            // replace wildcards
454bb01c27cSAndreas Gohr            if($media['embed']) {
455bb01c27cSAndreas Gohr                $this->html = str_replace('%%'.$media['embed'].'%%', 'cid:'.$cid, $this->html);
456bb01c27cSAndreas Gohr            }
457bb01c27cSAndreas Gohr
458bb01c27cSAndreas Gohr            $mime .= '--'.$this->boundary.MAILHEADER_EOL;
4591d8036c2SAndreas Gohr            $mime .= $this->wrappedHeaderLine('Content-Type', $media['mime'].'; id="'.$cid.'"');
4601d8036c2SAndreas Gohr            $mime .= $this->wrappedHeaderLine('Content-Transfer-Encoding', 'base64');
4611d8036c2SAndreas Gohr            $mime .= $this->wrappedHeaderLine('Content-ID',"<$cid>");
462bb01c27cSAndreas Gohr            if($media['embed']) {
4631d8036c2SAndreas Gohr                $mime .= $this->wrappedHeaderLine('Content-Disposition', 'inline; filename='.$media['name']);
464bb01c27cSAndreas Gohr            } else {
4651d8036c2SAndreas Gohr                $mime .= $this->wrappedHeaderLine('Content-Disposition', 'attachment; filename='.$media['name']);
466bb01c27cSAndreas Gohr            }
467bb01c27cSAndreas Gohr            $mime .= MAILHEADER_EOL; //end of headers
468bb01c27cSAndreas Gohr            $mime .= chunk_split(base64_encode($media['data']), 74, MAILHEADER_EOL);
469bb01c27cSAndreas Gohr
470bb01c27cSAndreas Gohr            $part++;
471bb01c27cSAndreas Gohr        }
472bb01c27cSAndreas Gohr        return $mime;
473bb01c27cSAndreas Gohr    }
474bb01c27cSAndreas Gohr
4751d045709SAndreas Gohr    /**
4761d045709SAndreas Gohr     * Build the body and handles multi part mails
4771d045709SAndreas Gohr     *
4781d045709SAndreas Gohr     * Needs to be called before prepareHeaders!
4791d045709SAndreas Gohr     *
4801d045709SAndreas Gohr     * @return string the prepared mail body, false on errors
4811d045709SAndreas Gohr     */
4821d045709SAndreas Gohr    protected function prepareBody() {
4831d045709SAndreas Gohr
4842398a2b5SAndreas Gohr        // no HTML mails allowed? remove HTML body
4852398a2b5SAndreas Gohr        if(!$this->allowhtml) {
4862398a2b5SAndreas Gohr            $this->html = '';
4872398a2b5SAndreas Gohr        }
4882398a2b5SAndreas Gohr
489bb01c27cSAndreas Gohr        // check for body
490bb01c27cSAndreas Gohr        if(!$this->text && !$this->html) {
491bb01c27cSAndreas Gohr            return false;
492bb01c27cSAndreas Gohr        }
493bb01c27cSAndreas Gohr
494bb01c27cSAndreas Gohr        // add general headers
495bb01c27cSAndreas Gohr        $this->headers['MIME-Version'] = '1.0';
496bb01c27cSAndreas Gohr
4971d045709SAndreas Gohr        $body = '';
4981d045709SAndreas Gohr
499bb01c27cSAndreas Gohr        if(!$this->html && !count($this->attach)) { // we can send a simple single part message
500bb01c27cSAndreas Gohr            $this->headers['Content-Type']              = 'text/plain; charset=UTF-8';
501bb01c27cSAndreas Gohr            $this->headers['Content-Transfer-Encoding'] = 'base64';
502be3cc6abSAndreas Gohr            $body .= chunk_split(base64_encode($this->text), 72, MAILHEADER_EOL);
503bb01c27cSAndreas Gohr        } else { // multi part it is
5041d045709SAndreas Gohr            $body .= "This is a multi-part message in MIME format.".MAILHEADER_EOL;
505bb01c27cSAndreas Gohr
506bb01c27cSAndreas Gohr            // prepare the attachments
507bb01c27cSAndreas Gohr            $attachments = $this->prepareAttachments();
508bb01c27cSAndreas Gohr
509bb01c27cSAndreas Gohr            // do we have alternative text content?
510bb01c27cSAndreas Gohr            if($this->text && $this->html) {
511a36fc348SAndreas Gohr                $this->headers['Content-Type'] = 'multipart/alternative;'.MAILHEADER_EOL.
512a36fc348SAndreas Gohr                    '  boundary="'.$this->boundary.'XX"';
513bb01c27cSAndreas Gohr                $body .= '--'.$this->boundary.'XX'.MAILHEADER_EOL;
5141d045709SAndreas Gohr                $body .= 'Content-Type: text/plain; charset=UTF-8'.MAILHEADER_EOL;
5151d045709SAndreas Gohr                $body .= 'Content-Transfer-Encoding: base64'.MAILHEADER_EOL;
516bb01c27cSAndreas Gohr                $body .= MAILHEADER_EOL;
517be3cc6abSAndreas Gohr                $body .= chunk_split(base64_encode($this->text), 72, MAILHEADER_EOL);
518bb01c27cSAndreas Gohr                $body .= '--'.$this->boundary.'XX'.MAILHEADER_EOL;
519a36fc348SAndreas Gohr                $body .= 'Content-Type: multipart/related;'.MAILHEADER_EOL.
520d6e04b60SAndreas Gohr                    '  boundary="'.$this->boundary.'";'.MAILHEADER_EOL.
521d6e04b60SAndreas Gohr                    '  type="text/html"'.MAILHEADER_EOL;
522bb01c27cSAndreas Gohr                $body .= MAILHEADER_EOL;
523bb01c27cSAndreas Gohr            }
524bb01c27cSAndreas Gohr
5251d045709SAndreas Gohr            $body .= '--'.$this->boundary.MAILHEADER_EOL;
5261d045709SAndreas Gohr            $body .= 'Content-Type: text/html; charset=UTF-8'.MAILHEADER_EOL;
5271d045709SAndreas Gohr            $body .= 'Content-Transfer-Encoding: base64'.MAILHEADER_EOL;
528bb01c27cSAndreas Gohr            $body .= MAILHEADER_EOL;
529be3cc6abSAndreas Gohr            $body .= chunk_split(base64_encode($this->html), 72, MAILHEADER_EOL);
530bb01c27cSAndreas Gohr            $body .= MAILHEADER_EOL;
531bb01c27cSAndreas Gohr            $body .= $attachments;
532bb01c27cSAndreas Gohr            $body .= '--'.$this->boundary.'--'.MAILHEADER_EOL;
533bb01c27cSAndreas Gohr
534bb01c27cSAndreas Gohr            // close open multipart/alternative boundary
535bb01c27cSAndreas Gohr            if($this->text && $this->html) {
536bb01c27cSAndreas Gohr                $body .= '--'.$this->boundary.'XX--'.MAILHEADER_EOL;
537bb01c27cSAndreas Gohr            }
538bb01c27cSAndreas Gohr        }
539bb01c27cSAndreas Gohr
540bb01c27cSAndreas Gohr        return $body;
541bb01c27cSAndreas Gohr    }
542bb01c27cSAndreas Gohr
543bb01c27cSAndreas Gohr    /**
544a36fc348SAndreas Gohr     * Cleanup and encode the headers array
545a36fc348SAndreas Gohr     */
546a36fc348SAndreas Gohr    protected function cleanHeaders() {
547a36fc348SAndreas Gohr        global $conf;
548a36fc348SAndreas Gohr
549a36fc348SAndreas Gohr        // clean up addresses
550a36fc348SAndreas Gohr        if(empty($this->headers['From'])) $this->from($conf['mailfrom']);
551acbf061cSGerrit Uitslag        $addrs = array('To', 'From', 'Cc', 'Bcc', 'Reply-To', 'Sender');
552a36fc348SAndreas Gohr        foreach($addrs as $addr) {
553a36fc348SAndreas Gohr            if(isset($this->headers[$addr])) {
554a36fc348SAndreas Gohr                $this->headers[$addr] = $this->cleanAddress($this->headers[$addr]);
555a36fc348SAndreas Gohr            }
556a36fc348SAndreas Gohr        }
557a36fc348SAndreas Gohr
55845992a63SAndreas Gohr        if(isset($this->headers['Subject'])) {
559a36fc348SAndreas Gohr            // add prefix to subject
56054f30755SAndreas Gohr            if(empty($conf['mailprefix'])) {
5618a215f09SAndreas Gohr                if(utf8_strlen($conf['title']) < 20) {
56254f30755SAndreas Gohr                    $prefix = '['.$conf['title'].']';
56354f30755SAndreas Gohr                } else {
5648a215f09SAndreas Gohr                    $prefix = '['.utf8_substr($conf['title'], 0, 20).'...]';
5658a215f09SAndreas Gohr                }
5668a215f09SAndreas Gohr            } else {
567a36fc348SAndreas Gohr                $prefix = '['.$conf['mailprefix'].']';
56854f30755SAndreas Gohr            }
569a36fc348SAndreas Gohr            $len = strlen($prefix);
57045992a63SAndreas Gohr            if(substr($this->headers['Subject'], 0, $len) != $prefix) {
57145992a63SAndreas Gohr                $this->headers['Subject'] = $prefix.' '.$this->headers['Subject'];
572a36fc348SAndreas Gohr            }
573a36fc348SAndreas Gohr
574a36fc348SAndreas Gohr            // encode subject
575a36fc348SAndreas Gohr            if(defined('MAILHEADER_ASCIIONLY')) {
57645992a63SAndreas Gohr                $this->headers['Subject'] = utf8_deaccent($this->headers['Subject']);
57745992a63SAndreas Gohr                $this->headers['Subject'] = utf8_strip($this->headers['Subject']);
578a36fc348SAndreas Gohr            }
579a36fc348SAndreas Gohr            if(!utf8_isASCII($this->headers['Subject'])) {
58045992a63SAndreas Gohr                $this->headers['Subject'] = '=?UTF-8?B?'.base64_encode($this->headers['Subject']).'?=';
581a36fc348SAndreas Gohr            }
582a36fc348SAndreas Gohr        }
583a36fc348SAndreas Gohr
584a36fc348SAndreas Gohr    }
5851d8036c2SAndreas Gohr
5861d8036c2SAndreas Gohr    /**
5871d8036c2SAndreas Gohr     * Returns a complete, EOL terminated header line, wraps it if necessary
5881d8036c2SAndreas Gohr     *
58942ea7f44SGerrit Uitslag     * @param string $key
59042ea7f44SGerrit Uitslag     * @param string $val
59142ea7f44SGerrit Uitslag     * @return string line
5921d8036c2SAndreas Gohr     */
5931d8036c2SAndreas Gohr    protected function wrappedHeaderLine($key, $val){
5941d8036c2SAndreas Gohr        return wordwrap("$key: $val", 78, MAILHEADER_EOL.'  ').MAILHEADER_EOL;
595a36fc348SAndreas Gohr    }
596a36fc348SAndreas Gohr
597a36fc348SAndreas Gohr    /**
598bb01c27cSAndreas Gohr     * Create a string from the headers array
5991d045709SAndreas Gohr     *
6001d045709SAndreas Gohr     * @returns string the headers
601bb01c27cSAndreas Gohr     */
602bb01c27cSAndreas Gohr    protected function prepareHeaders() {
603bb01c27cSAndreas Gohr        $headers = '';
604bb01c27cSAndreas Gohr        foreach($this->headers as $key => $val) {
6056be717dbSMichael Hamann            if ($val === '' || is_null($val)) continue;
6061d8036c2SAndreas Gohr            $headers .= $this->wrappedHeaderLine($key, $val);
607bb01c27cSAndreas Gohr        }
608bb01c27cSAndreas Gohr        return $headers;
609bb01c27cSAndreas Gohr    }
610bb01c27cSAndreas Gohr
611bb01c27cSAndreas Gohr    /**
612bb01c27cSAndreas Gohr     * return a full email with all headers
613bb01c27cSAndreas Gohr     *
6141d045709SAndreas Gohr     * This is mainly intended for debugging and testing but could also be
6151d045709SAndreas Gohr     * used for MHT exports
6161d045709SAndreas Gohr     *
6171d045709SAndreas Gohr     * @return string the mail, false on errors
618bb01c27cSAndreas Gohr     */
619bb01c27cSAndreas Gohr    public function dump() {
620a36fc348SAndreas Gohr        $this->cleanHeaders();
621bb01c27cSAndreas Gohr        $body = $this->prepareBody();
6224d18e936SAndreas Gohr        if($body === false) return false;
6231d045709SAndreas Gohr        $headers = $this->prepareHeaders();
624bb01c27cSAndreas Gohr
625bb01c27cSAndreas Gohr        return $headers.MAILHEADER_EOL.$body;
626bb01c27cSAndreas Gohr    }
6271d045709SAndreas Gohr
6281d045709SAndreas Gohr    /**
6291d045709SAndreas Gohr     * Send the mail
6301d045709SAndreas Gohr     *
6311d045709SAndreas Gohr     * Call this after all data was set
6321d045709SAndreas Gohr     *
63328d2ad80SAndreas Gohr     * @triggers MAIL_MESSAGE_SEND
6341d045709SAndreas Gohr     * @return bool true if the mail was successfully passed to the MTA
6351d045709SAndreas Gohr     */
6361d045709SAndreas Gohr    public function send() {
63728d2ad80SAndreas Gohr        $success = false;
638a36fc348SAndreas Gohr
63928d2ad80SAndreas Gohr        // prepare hook data
64028d2ad80SAndreas Gohr        $data = array(
64128d2ad80SAndreas Gohr            // pass the whole mail class to plugin
64228d2ad80SAndreas Gohr            'mail'    => $this,
64328d2ad80SAndreas Gohr            // pass references for backward compatibility
64428d2ad80SAndreas Gohr            'to'      => &$this->headers['To'],
64528d2ad80SAndreas Gohr            'cc'      => &$this->headers['Cc'],
64628d2ad80SAndreas Gohr            'bcc'     => &$this->headers['Bcc'],
64728d2ad80SAndreas Gohr            'from'    => &$this->headers['From'],
64828d2ad80SAndreas Gohr            'subject' => &$this->headers['Subject'],
64928d2ad80SAndreas Gohr            'body'    => &$this->text,
650a89c75afSAndreas Gohr            'params'  => &$this->sendparam,
65128d2ad80SAndreas Gohr            'headers' => '', // plugins shouldn't use this
65228d2ad80SAndreas Gohr            // signal if we mailed successfully to AFTER event
65328d2ad80SAndreas Gohr            'success' => &$success,
65428d2ad80SAndreas Gohr        );
65528d2ad80SAndreas Gohr
65628d2ad80SAndreas Gohr        // do our thing if BEFORE hook approves
65728d2ad80SAndreas Gohr        $evt = new Doku_Event('MAIL_MESSAGE_SEND', $data);
65828d2ad80SAndreas Gohr        if($evt->advise_before(true)) {
65928d2ad80SAndreas Gohr            // clean up before using the headers
660a36fc348SAndreas Gohr            $this->cleanHeaders();
661a36fc348SAndreas Gohr
6621d045709SAndreas Gohr            // any recipients?
6631d045709SAndreas Gohr            if(trim($this->headers['To']) === '' &&
6641d045709SAndreas Gohr                trim($this->headers['Cc']) === '' &&
665a89c75afSAndreas Gohr                trim($this->headers['Bcc']) === ''
666a89c75afSAndreas Gohr            ) return false;
6671d045709SAndreas Gohr
6681d045709SAndreas Gohr            // The To: header is special
6696be717dbSMichael Hamann            if(array_key_exists('To', $this->headers)) {
6706be717dbSMichael Hamann                $to = (string)$this->headers['To'];
6711d045709SAndreas Gohr                unset($this->headers['To']);
6721d045709SAndreas Gohr            } else {
6731d045709SAndreas Gohr                $to = '';
6741d045709SAndreas Gohr            }
6751d045709SAndreas Gohr
6761d045709SAndreas Gohr            // so is the subject
6776be717dbSMichael Hamann            if(array_key_exists('Subject', $this->headers)) {
6786be717dbSMichael Hamann                $subject = (string)$this->headers['Subject'];
6791d045709SAndreas Gohr                unset($this->headers['Subject']);
6801d045709SAndreas Gohr            } else {
6811d045709SAndreas Gohr                $subject = '';
6821d045709SAndreas Gohr            }
6831d045709SAndreas Gohr
6841d045709SAndreas Gohr            // make the body
6851d045709SAndreas Gohr            $body = $this->prepareBody();
6864c89a7f6SAndreas Gohr            if($body === false) return false;
6871d045709SAndreas Gohr
6881d045709SAndreas Gohr            // cook the headers
6891d045709SAndreas Gohr            $headers = $this->prepareHeaders();
69028d2ad80SAndreas Gohr            // add any headers set by legacy plugins
69128d2ad80SAndreas Gohr            if(trim($data['headers'])) {
69228d2ad80SAndreas Gohr                $headers .= MAILHEADER_EOL.trim($data['headers']);
69328d2ad80SAndreas Gohr            }
6941d045709SAndreas Gohr
6951d045709SAndreas Gohr            // send the thing
6961d045709SAndreas Gohr            if(is_null($this->sendparam)) {
69728d2ad80SAndreas Gohr                $success = @mail($to, $subject, $body, $headers);
6981d045709SAndreas Gohr            } else {
69928d2ad80SAndreas Gohr                $success = @mail($to, $subject, $body, $headers, $this->sendparam);
7001d045709SAndreas Gohr            }
7011d045709SAndreas Gohr        }
70228d2ad80SAndreas Gohr        // any AFTER actions?
70328d2ad80SAndreas Gohr        $evt->advise_after();
70428d2ad80SAndreas Gohr        return $success;
70528d2ad80SAndreas Gohr    }
706bb01c27cSAndreas Gohr}
707