xref: /dokuwiki/inc/Mailer.class.php (revision b6c97c7072748fa573d54a91c1be14e496fd9990)
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;
429f3eca0bSAndreas Gohr
439f3eca0bSAndreas Gohr        $server = parse_url(DOKU_URL, PHP_URL_HOST);
441d045709SAndreas Gohr
451d045709SAndreas Gohr        $this->partid   = md5(uniqid(rand(), true)).'@'.$server;
46bb01c27cSAndreas Gohr        $this->boundary = '----------'.md5(uniqid(rand(), true));
479f3eca0bSAndreas Gohr
489f3eca0bSAndreas Gohr        $listid = join('.', array_reverse(explode('/', DOKU_BASE))).$server;
499f3eca0bSAndreas Gohr        $listid = strtolower(trim($listid, '.'));
509f3eca0bSAndreas Gohr
512398a2b5SAndreas Gohr        $this->allowhtml = (bool)$conf['htmlmail'];
522398a2b5SAndreas Gohr
539f3eca0bSAndreas Gohr        // add some default headers for mailfiltering FS#2247
546a1f928fSAndreas Gohr        $this->setHeader('X-Mailer', 'DokuWiki');
559f3eca0bSAndreas Gohr        $this->setHeader('X-DokuWiki-User', $_SERVER['REMOTE_USER']);
569f3eca0bSAndreas Gohr        $this->setHeader('X-DokuWiki-Title', $conf['title']);
579f3eca0bSAndreas Gohr        $this->setHeader('X-DokuWiki-Server', $server);
589f3eca0bSAndreas Gohr        $this->setHeader('X-Auto-Response-Suppress', 'OOF');
599f3eca0bSAndreas Gohr        $this->setHeader('List-Id', $conf['title'].' <'.$listid.'>');
60bb01c27cSAndreas Gohr    }
61bb01c27cSAndreas Gohr
62bb01c27cSAndreas Gohr    /**
63bb01c27cSAndreas Gohr     * Attach a file
64bb01c27cSAndreas Gohr     *
65a89c75afSAndreas Gohr     * @param string $path  Path to the file to attach
66a89c75afSAndreas Gohr     * @param string $mime  Mimetype of the attached file
67a89c75afSAndreas Gohr     * @param string $name The filename to use
68a89c75afSAndreas Gohr     * @param string $embed Unique key to reference this file from the HTML part
69bb01c27cSAndreas Gohr     */
70bb01c27cSAndreas Gohr    public function attachFile($path, $mime, $name = '', $embed = '') {
71bb01c27cSAndreas Gohr        if(!$name) {
723009a773SAndreas Gohr            $name = utf8_basename($path);
73bb01c27cSAndreas Gohr        }
74bb01c27cSAndreas Gohr
75bb01c27cSAndreas Gohr        $this->attach[] = array(
76bb01c27cSAndreas Gohr            'data'  => file_get_contents($path),
77bb01c27cSAndreas Gohr            'mime'  => $mime,
78bb01c27cSAndreas Gohr            'name'  => $name,
79bb01c27cSAndreas Gohr            'embed' => $embed
80bb01c27cSAndreas Gohr        );
81bb01c27cSAndreas Gohr    }
82bb01c27cSAndreas Gohr
83bb01c27cSAndreas Gohr    /**
84bb01c27cSAndreas Gohr     * Attach a file
85bb01c27cSAndreas Gohr     *
86a89c75afSAndreas Gohr     * @param string $data  The file contents to attach
87a89c75afSAndreas Gohr     * @param string $mime  Mimetype of the attached file
88a89c75afSAndreas Gohr     * @param string $name  The filename to use
89a89c75afSAndreas Gohr     * @param string $embed Unique key to reference this file from the HTML part
90bb01c27cSAndreas Gohr     */
91bb01c27cSAndreas Gohr    public function attachContent($data, $mime, $name = '', $embed = '') {
92bb01c27cSAndreas Gohr        if(!$name) {
93a89c75afSAndreas Gohr            list(, $ext) = explode('/', $mime);
94bb01c27cSAndreas Gohr            $name = count($this->attach).".$ext";
95bb01c27cSAndreas Gohr        }
96bb01c27cSAndreas Gohr
97bb01c27cSAndreas Gohr        $this->attach[] = array(
98bb01c27cSAndreas Gohr            'data'  => $data,
99bb01c27cSAndreas Gohr            'mime'  => $mime,
100bb01c27cSAndreas Gohr            'name'  => $name,
101bb01c27cSAndreas Gohr            'embed' => $embed
102bb01c27cSAndreas Gohr        );
103bb01c27cSAndreas Gohr    }
104bb01c27cSAndreas Gohr
105bb01c27cSAndreas Gohr    /**
106850dbf1fSAndreas Gohr     * Callback function to automatically embed images referenced in HTML templates
107850dbf1fSAndreas Gohr     */
108850dbf1fSAndreas Gohr    protected function autoembed_cb($matches) {
109850dbf1fSAndreas Gohr        static $embeds = 0;
110850dbf1fSAndreas Gohr        $embeds++;
111850dbf1fSAndreas Gohr
112850dbf1fSAndreas Gohr        // get file and mime type
113850dbf1fSAndreas Gohr        $media = cleanID($matches[1]);
114a89c75afSAndreas Gohr        list(, $mime) = mimetype($media);
115850dbf1fSAndreas Gohr        $file = mediaFN($media);
116850dbf1fSAndreas Gohr        if(!file_exists($file)) return $matches[0]; //bad reference, keep as is
117850dbf1fSAndreas Gohr
118850dbf1fSAndreas Gohr        // attach it and set placeholder
119850dbf1fSAndreas Gohr        $this->attachFile($file, $mime, '', 'autoembed'.$embeds);
120850dbf1fSAndreas Gohr        return '%%autoembed'.$embeds.'%%';
121850dbf1fSAndreas Gohr    }
122850dbf1fSAndreas Gohr
123850dbf1fSAndreas Gohr    /**
1241d045709SAndreas Gohr     * Add an arbitrary header to the mail
1251d045709SAndreas Gohr     *
126a36fc348SAndreas Gohr     * If an empy value is passed, the header is removed
127a36fc348SAndreas Gohr     *
1281d045709SAndreas Gohr     * @param string $header the header name (no trailing colon!)
1291d045709SAndreas Gohr     * @param string $value  the value of the header
1301d045709SAndreas Gohr     * @param bool   $clean  remove all non-ASCII chars and line feeds?
1311d045709SAndreas Gohr     */
1321d045709SAndreas Gohr    public function setHeader($header, $value, $clean = true) {
1339f3eca0bSAndreas Gohr        $header = str_replace(' ', '-', ucwords(strtolower(str_replace('-', ' ', $header)))); // streamline casing
1341d045709SAndreas Gohr        if($clean) {
135578b2c23SAndreas Gohr            $header = preg_replace('/[^a-zA-Z0-9_ \-\.\+\@]+/', '', $header);
136578b2c23SAndreas Gohr            $value  = preg_replace('/[^a-zA-Z0-9_ \-\.\+\@<>]+/', '', $value);
1371d045709SAndreas Gohr        }
138a36fc348SAndreas Gohr
139a36fc348SAndreas Gohr        // empty value deletes
140*b6c97c70SAndreas Gohr        if(is_array($value)){
141*b6c97c70SAndreas Gohr            $value = array_map('trim', $value);
142*b6c97c70SAndreas Gohr            $value = array_filter($value);
143*b6c97c70SAndreas Gohr            if(!$value) $value = '';
144*b6c97c70SAndreas Gohr        }else{
145a36fc348SAndreas Gohr            $value = trim($value);
146*b6c97c70SAndreas Gohr        }
147a36fc348SAndreas Gohr        if($value === '') {
148a36fc348SAndreas Gohr            if(isset($this->headers[$header])) unset($this->headers[$header]);
149a36fc348SAndreas Gohr        } else {
1501d045709SAndreas Gohr            $this->headers[$header] = $value;
1511d045709SAndreas Gohr        }
152a36fc348SAndreas Gohr    }
1531d045709SAndreas Gohr
1541d045709SAndreas Gohr    /**
1551d045709SAndreas Gohr     * Set additional parameters to be passed to sendmail
1561d045709SAndreas Gohr     *
1571d045709SAndreas Gohr     * Whatever is set here is directly passed to PHP's mail() command as last
1581d045709SAndreas Gohr     * parameter. Depending on the PHP setup this might break mailing alltogether
1591d045709SAndreas Gohr     */
1601d045709SAndreas Gohr    public function setParameters($param) {
1611d045709SAndreas Gohr        $this->sendparam = $param;
1621d045709SAndreas Gohr    }
1631d045709SAndreas Gohr
1641d045709SAndreas Gohr    /**
165abbf0890SAndreas Gohr     * Set the text and HTML body and apply replacements
166abbf0890SAndreas Gohr     *
167abbf0890SAndreas Gohr     * This function applies a whole bunch of default replacements in addition
168abbf0890SAndreas Gohr     * to the ones specidifed as parameters
169abbf0890SAndreas Gohr     *
170abbf0890SAndreas Gohr     * If you pass the HTML part or HTML replacements yourself you have to make
171abbf0890SAndreas Gohr     * sure you encode all HTML special chars correctly
172abbf0890SAndreas Gohr     *
173abbf0890SAndreas Gohr     * @param string $text     plain text body
174abbf0890SAndreas Gohr     * @param array  $textrep  replacements to apply on the text part
175abbf0890SAndreas Gohr     * @param array  $htmlrep  replacements to apply on the HTML part, leave null to use $textrep
176abbf0890SAndreas Gohr     * @param array  $html     the HTML body, leave null to create it from $text
177f08086ecSAndreas Gohr     * @param bool   $wrap     wrap the HTML in the default header/Footer
178abbf0890SAndreas Gohr     */
179f08086ecSAndreas Gohr    public function setBody($text, $textrep = null, $htmlrep = null, $html = null, $wrap = true) {
180abbf0890SAndreas Gohr        global $INFO;
181abbf0890SAndreas Gohr        global $conf;
18276efd6d0SAndreas Gohr        $htmlrep = (array)$htmlrep;
18376efd6d0SAndreas Gohr        $textrep = (array)$textrep;
184abbf0890SAndreas Gohr
185abbf0890SAndreas Gohr        // create HTML from text if not given
186abbf0890SAndreas Gohr        if(is_null($html)) {
187ba9c057bSAndreas Gohr            $html = $text;
188ba9c057bSAndreas Gohr            $html = hsc($html);
189ba9c057bSAndreas Gohr            $html = preg_replace('/^-----*$/m', '<hr >', $html);
190ba9c057bSAndreas Gohr            $html = nl2br($html);
191abbf0890SAndreas Gohr        }
192f08086ecSAndreas Gohr        if($wrap) {
193f08086ecSAndreas Gohr            $wrap = rawLocale('mailwrap', 'html');
194a4c4a73dSAndreas Gohr            $html = preg_replace('/\n-- <br \/>.*$/s', '', $html); //strip signature
195f08086ecSAndreas Gohr            $html = str_replace('@HTMLBODY@', $html, $wrap);
196f08086ecSAndreas Gohr        }
197f08086ecSAndreas Gohr
19876efd6d0SAndreas Gohr        // copy over all replacements missing for HTML (autolink URLs)
19976efd6d0SAndreas Gohr        foreach($textrep as $key => $value) {
20076efd6d0SAndreas Gohr            if(isset($htmlrep[$key])) continue;
2013e7e6067SKlap-in            if(media_isexternal($value)) {
20276efd6d0SAndreas Gohr                $htmlrep[$key] = '<a href="'.hsc($value).'">'.hsc($value).'</a>';
20376efd6d0SAndreas Gohr            } else {
20476efd6d0SAndreas Gohr                $htmlrep[$key] = hsc($value);
20576efd6d0SAndreas Gohr            }
206abbf0890SAndreas Gohr        }
207abbf0890SAndreas Gohr
208850dbf1fSAndreas Gohr        // embed media from templates
209a89c75afSAndreas Gohr        $html = preg_replace_callback(
210a89c75afSAndreas Gohr            '/@MEDIA\(([^\)]+)\)@/',
211a89c75afSAndreas Gohr            array($this, 'autoembed_cb'), $html
212a89c75afSAndreas Gohr        );
213850dbf1fSAndreas Gohr
214abbf0890SAndreas Gohr        // prepare default replacements
215abbf0890SAndreas Gohr        $ip   = clientIP();
216f08086ecSAndreas Gohr        $cip  = gethostsbyaddrs($ip);
217abbf0890SAndreas Gohr        $trep = array(
218abbf0890SAndreas Gohr            'DATE'        => dformat(),
219abbf0890SAndreas Gohr            'BROWSER'     => $_SERVER['HTTP_USER_AGENT'],
220abbf0890SAndreas Gohr            'IPADDRESS'   => $ip,
221f08086ecSAndreas Gohr            'HOSTNAME'    => $cip,
222abbf0890SAndreas Gohr            'TITLE'       => $conf['title'],
223abbf0890SAndreas Gohr            'DOKUWIKIURL' => DOKU_URL,
224abbf0890SAndreas Gohr            'USER'        => $_SERVER['REMOTE_USER'],
225abbf0890SAndreas Gohr            'NAME'        => $INFO['userinfo']['name'],
226abbf0890SAndreas Gohr            'MAIL'        => $INFO['userinfo']['mail'],
227abbf0890SAndreas Gohr        );
228abbf0890SAndreas Gohr        $trep = array_merge($trep, (array)$textrep);
229abbf0890SAndreas Gohr        $hrep = array(
230abbf0890SAndreas Gohr            'DATE'        => '<i>'.hsc(dformat()).'</i>',
231abbf0890SAndreas Gohr            'BROWSER'     => hsc($_SERVER['HTTP_USER_AGENT']),
232abbf0890SAndreas Gohr            'IPADDRESS'   => '<code>'.hsc($ip).'</code>',
233f08086ecSAndreas Gohr            'HOSTNAME'    => '<code>'.hsc($cip).'</code>',
234abbf0890SAndreas Gohr            'TITLE'       => hsc($conf['title']),
235abbf0890SAndreas Gohr            'DOKUWIKIURL' => '<a href="'.DOKU_URL.'">'.DOKU_URL.'</a>',
236abbf0890SAndreas Gohr            'USER'        => hsc($_SERVER['REMOTE_USER']),
237abbf0890SAndreas Gohr            'NAME'        => hsc($INFO['userinfo']['name']),
238abbf0890SAndreas Gohr            'MAIL'        => '<a href="mailto:"'.hsc($INFO['userinfo']['mail']).'">'.
239abbf0890SAndreas Gohr                hsc($INFO['userinfo']['mail']).'</a>',
240abbf0890SAndreas Gohr        );
241abbf0890SAndreas Gohr        $hrep = array_merge($hrep, (array)$htmlrep);
242abbf0890SAndreas Gohr
243abbf0890SAndreas Gohr        // Apply replacements
244abbf0890SAndreas Gohr        foreach($trep as $key => $substitution) {
245abbf0890SAndreas Gohr            $text = str_replace('@'.strtoupper($key).'@', $substitution, $text);
246abbf0890SAndreas Gohr        }
247abbf0890SAndreas Gohr        foreach($hrep as $key => $substitution) {
248abbf0890SAndreas Gohr            $html = str_replace('@'.strtoupper($key).'@', $substitution, $html);
249abbf0890SAndreas Gohr        }
250abbf0890SAndreas Gohr
251abbf0890SAndreas Gohr        $this->setHTML($html);
252abbf0890SAndreas Gohr        $this->setText($text);
253abbf0890SAndreas Gohr    }
254abbf0890SAndreas Gohr
255abbf0890SAndreas Gohr    /**
256bb01c27cSAndreas Gohr     * Set the HTML part of the mail
257bb01c27cSAndreas Gohr     *
258bb01c27cSAndreas Gohr     * Placeholders can be used to reference embedded attachments
259abbf0890SAndreas Gohr     *
260abbf0890SAndreas Gohr     * You probably want to use setBody() instead
261bb01c27cSAndreas Gohr     */
2621d045709SAndreas Gohr    public function setHTML($html) {
263bb01c27cSAndreas Gohr        $this->html = $html;
264bb01c27cSAndreas Gohr    }
265bb01c27cSAndreas Gohr
266bb01c27cSAndreas Gohr    /**
267bb01c27cSAndreas Gohr     * Set the plain text part of the mail
268abbf0890SAndreas Gohr     *
269abbf0890SAndreas Gohr     * You probably want to use setBody() instead
270bb01c27cSAndreas Gohr     */
2711d045709SAndreas Gohr    public function setText($text) {
272bb01c27cSAndreas Gohr        $this->text = $text;
273bb01c27cSAndreas Gohr    }
274bb01c27cSAndreas Gohr
275bb01c27cSAndreas Gohr    /**
276a36fc348SAndreas Gohr     * Add the To: recipients
277a36fc348SAndreas Gohr     *
278a36fc348SAndreas Gohr     * @see setAddress
279*b6c97c70SAndreas Gohr     * @param string|array  $address Multiple adresses separated by commas or as array
280a36fc348SAndreas Gohr     */
281a36fc348SAndreas Gohr    public function to($address) {
282a36fc348SAndreas Gohr        $this->setHeader('To', $address, false);
283a36fc348SAndreas Gohr    }
284a36fc348SAndreas Gohr
285a36fc348SAndreas Gohr    /**
286a36fc348SAndreas Gohr     * Add the Cc: recipients
287a36fc348SAndreas Gohr     *
288a36fc348SAndreas Gohr     * @see setAddress
289*b6c97c70SAndreas Gohr     * @param string|array  $address Multiple adresses separated by commas or as array
290a36fc348SAndreas Gohr     */
291a36fc348SAndreas Gohr    public function cc($address) {
292a36fc348SAndreas Gohr        $this->setHeader('Cc', $address, false);
293a36fc348SAndreas Gohr    }
294a36fc348SAndreas Gohr
295a36fc348SAndreas Gohr    /**
296a36fc348SAndreas Gohr     * Add the Bcc: recipients
297a36fc348SAndreas Gohr     *
298a36fc348SAndreas Gohr     * @see setAddress
299*b6c97c70SAndreas Gohr     * @param string|array  $address Multiple adresses separated by commas or as array
300a36fc348SAndreas Gohr     */
301a36fc348SAndreas Gohr    public function bcc($address) {
302a36fc348SAndreas Gohr        $this->setHeader('Bcc', $address, false);
303a36fc348SAndreas Gohr    }
304a36fc348SAndreas Gohr
305a36fc348SAndreas Gohr    /**
306a36fc348SAndreas Gohr     * Add the From: address
307a36fc348SAndreas Gohr     *
308a36fc348SAndreas Gohr     * This is set to $conf['mailfrom'] when not specified so you shouldn't need
309a36fc348SAndreas Gohr     * to call this function
310a36fc348SAndreas Gohr     *
311a36fc348SAndreas Gohr     * @see setAddress
312a36fc348SAndreas Gohr     * @param string  $address from address
313a36fc348SAndreas Gohr     */
314a36fc348SAndreas Gohr    public function from($address) {
315a36fc348SAndreas Gohr        $this->setHeader('From', $address, false);
316a36fc348SAndreas Gohr    }
317a36fc348SAndreas Gohr
318a36fc348SAndreas Gohr    /**
319a36fc348SAndreas Gohr     * Add the mail's Subject: header
320a36fc348SAndreas Gohr     *
321a36fc348SAndreas Gohr     * @param string $subject the mail subject
322a36fc348SAndreas Gohr     */
323a36fc348SAndreas Gohr    public function subject($subject) {
324a36fc348SAndreas Gohr        $this->headers['Subject'] = $subject;
325a36fc348SAndreas Gohr    }
326a36fc348SAndreas Gohr
327a36fc348SAndreas Gohr    /**
3281d045709SAndreas Gohr     * Sets an email address header with correct encoding
329bb01c27cSAndreas Gohr     *
330bb01c27cSAndreas Gohr     * Unicode characters will be deaccented and encoded base64
331bb01c27cSAndreas Gohr     * for headers. Addresses may not contain Non-ASCII data!
332bb01c27cSAndreas Gohr     *
333bb01c27cSAndreas Gohr     * Example:
334bb01c27cSAndreas Gohr     *   setAddress("föö <foo@bar.com>, me@somewhere.com","TBcc");
335bb01c27cSAndreas Gohr     *
336*b6c97c70SAndreas Gohr     * @param string|array  $address Multiple adresses separated by commas or as array
337a89c75afSAndreas Gohr     * @return bool|string  the prepared header (can contain multiple lines)
338bb01c27cSAndreas Gohr     */
339*b6c97c70SAndreas Gohr    public function cleanAddress($addresses) {
340bb01c27cSAndreas Gohr        // No named recipients for To: in Windows (see FS#652)
341bb01c27cSAndreas Gohr        $names = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? false : true;
342bb01c27cSAndreas Gohr
343bb01c27cSAndreas Gohr        $headers = '';
344*b6c97c70SAndreas Gohr        if(!is_array($addresses)){
345*b6c97c70SAndreas Gohr            $addresses = explode(',', $addresses);
346*b6c97c70SAndreas Gohr        }
347*b6c97c70SAndreas Gohr
348*b6c97c70SAndreas Gohr        foreach($addresses as $part) {
349*b6c97c70SAndreas Gohr            $part = preg_replace('/[\r\n\0]+/', ' ', $part); // remove attack vectors
350bb01c27cSAndreas Gohr            $part = trim($part);
351bb01c27cSAndreas Gohr
352bb01c27cSAndreas Gohr            // parse address
353bb01c27cSAndreas Gohr            if(preg_match('#(.*?)<(.*?)>#', $part, $matches)) {
354bb01c27cSAndreas Gohr                $text = trim($matches[1]);
355bb01c27cSAndreas Gohr                $addr = $matches[2];
356bb01c27cSAndreas Gohr            } else {
357bb01c27cSAndreas Gohr                $addr = $part;
358bb01c27cSAndreas Gohr            }
359bb01c27cSAndreas Gohr            // skip empty ones
360bb01c27cSAndreas Gohr            if(empty($addr)) {
361bb01c27cSAndreas Gohr                continue;
362bb01c27cSAndreas Gohr            }
363bb01c27cSAndreas Gohr
364bb01c27cSAndreas Gohr            // FIXME: is there a way to encode the localpart of a emailaddress?
365bb01c27cSAndreas Gohr            if(!utf8_isASCII($addr)) {
366bb01c27cSAndreas Gohr                msg(htmlspecialchars("E-Mail address <$addr> is not ASCII"), -1);
367bb01c27cSAndreas Gohr                continue;
368bb01c27cSAndreas Gohr            }
369bb01c27cSAndreas Gohr
3701d045709SAndreas Gohr            if(is_null($this->validator)) {
3711d045709SAndreas Gohr                $this->validator                      = new EmailAddressValidator();
3721d045709SAndreas Gohr                $this->validator->allowLocalAddresses = true;
3731d045709SAndreas Gohr            }
3741d045709SAndreas Gohr            if(!$this->validator->check_email_address($addr)) {
375bb01c27cSAndreas Gohr                msg(htmlspecialchars("E-Mail address <$addr> is not valid"), -1);
376bb01c27cSAndreas Gohr                continue;
377bb01c27cSAndreas Gohr            }
378bb01c27cSAndreas Gohr
379bb01c27cSAndreas Gohr            // text was given
380bb01c27cSAndreas Gohr            if(!empty($text) && $names) {
381bb01c27cSAndreas Gohr                // add address quotes
382bb01c27cSAndreas Gohr                $addr = "<$addr>";
383bb01c27cSAndreas Gohr
384bb01c27cSAndreas Gohr                if(defined('MAILHEADER_ASCIIONLY')) {
385bb01c27cSAndreas Gohr                    $text = utf8_deaccent($text);
386bb01c27cSAndreas Gohr                    $text = utf8_strip($text);
387bb01c27cSAndreas Gohr                }
388bb01c27cSAndreas Gohr
389*b6c97c70SAndreas Gohr                if(strpos($text, ',') !== false || !utf8_isASCII($text)) {
390bb01c27cSAndreas Gohr                    $text = '=?UTF-8?B?'.base64_encode($text).'?=';
391bb01c27cSAndreas Gohr                }
392bb01c27cSAndreas Gohr            } else {
393bb01c27cSAndreas Gohr                $text = '';
394bb01c27cSAndreas Gohr            }
395bb01c27cSAndreas Gohr
396bb01c27cSAndreas Gohr            // add to header comma seperated
397bb01c27cSAndreas Gohr            if($headers != '') {
398bb01c27cSAndreas Gohr                $headers .= ', ';
399bb01c27cSAndreas Gohr            }
400bb01c27cSAndreas Gohr            $headers .= $text.' '.$addr;
401bb01c27cSAndreas Gohr        }
402bb01c27cSAndreas Gohr
403*b6c97c70SAndreas Gohr        $headers = trim($headers);
404bb01c27cSAndreas Gohr        if(empty($headers)) return false;
405bb01c27cSAndreas Gohr
406bb01c27cSAndreas Gohr        return $headers;
407bb01c27cSAndreas Gohr    }
408bb01c27cSAndreas Gohr
409bb01c27cSAndreas Gohr
410bb01c27cSAndreas Gohr    /**
411bb01c27cSAndreas Gohr     * Prepare the mime multiparts for all attachments
412bb01c27cSAndreas Gohr     *
413bb01c27cSAndreas Gohr     * Replaces placeholders in the HTML with the correct CIDs
414bb01c27cSAndreas Gohr     */
415bb01c27cSAndreas Gohr    protected function prepareAttachments() {
416bb01c27cSAndreas Gohr        $mime = '';
417bb01c27cSAndreas Gohr        $part = 1;
418bb01c27cSAndreas Gohr        // embedded attachments
419bb01c27cSAndreas Gohr        foreach($this->attach as $media) {
420bb01c27cSAndreas Gohr            // create content id
421bb01c27cSAndreas Gohr            $cid = 'part'.$part.'.'.$this->partid;
422bb01c27cSAndreas Gohr
423bb01c27cSAndreas Gohr            // replace wildcards
424bb01c27cSAndreas Gohr            if($media['embed']) {
425bb01c27cSAndreas Gohr                $this->html = str_replace('%%'.$media['embed'].'%%', 'cid:'.$cid, $this->html);
426bb01c27cSAndreas Gohr            }
427bb01c27cSAndreas Gohr
428bb01c27cSAndreas Gohr            $mime .= '--'.$this->boundary.MAILHEADER_EOL;
429bb01c27cSAndreas Gohr            $mime .= 'Content-Type: '.$media['mime'].';'.MAILHEADER_EOL;
430bb01c27cSAndreas Gohr            $mime .= 'Content-Transfer-Encoding: base64'.MAILHEADER_EOL;
431bb01c27cSAndreas Gohr            $mime .= "Content-ID: <$cid>".MAILHEADER_EOL;
432bb01c27cSAndreas Gohr            if($media['embed']) {
433bb01c27cSAndreas Gohr                $mime .= 'Content-Disposition: inline; filename="'.$media['name'].'"'.MAILHEADER_EOL;
434bb01c27cSAndreas Gohr            } else {
435bb01c27cSAndreas Gohr                $mime .= 'Content-Disposition: attachment; filename="'.$media['name'].'"'.MAILHEADER_EOL;
436bb01c27cSAndreas Gohr            }
437bb01c27cSAndreas Gohr            $mime .= MAILHEADER_EOL; //end of headers
438bb01c27cSAndreas Gohr            $mime .= chunk_split(base64_encode($media['data']), 74, MAILHEADER_EOL);
439bb01c27cSAndreas Gohr
440bb01c27cSAndreas Gohr            $part++;
441bb01c27cSAndreas Gohr        }
442bb01c27cSAndreas Gohr        return $mime;
443bb01c27cSAndreas Gohr    }
444bb01c27cSAndreas Gohr
4451d045709SAndreas Gohr    /**
4461d045709SAndreas Gohr     * Build the body and handles multi part mails
4471d045709SAndreas Gohr     *
4481d045709SAndreas Gohr     * Needs to be called before prepareHeaders!
4491d045709SAndreas Gohr     *
4501d045709SAndreas Gohr     * @return string the prepared mail body, false on errors
4511d045709SAndreas Gohr     */
4521d045709SAndreas Gohr    protected function prepareBody() {
4531d045709SAndreas Gohr
4542398a2b5SAndreas Gohr        // no HTML mails allowed? remove HTML body
4552398a2b5SAndreas Gohr        if(!$this->allowhtml) {
4562398a2b5SAndreas Gohr            $this->html = '';
4572398a2b5SAndreas Gohr        }
4582398a2b5SAndreas Gohr
459bb01c27cSAndreas Gohr        // check for body
460bb01c27cSAndreas Gohr        if(!$this->text && !$this->html) {
461bb01c27cSAndreas Gohr            return false;
462bb01c27cSAndreas Gohr        }
463bb01c27cSAndreas Gohr
464bb01c27cSAndreas Gohr        // add general headers
465bb01c27cSAndreas Gohr        $this->headers['MIME-Version'] = '1.0';
466bb01c27cSAndreas Gohr
4671d045709SAndreas Gohr        $body = '';
4681d045709SAndreas Gohr
469bb01c27cSAndreas Gohr        if(!$this->html && !count($this->attach)) { // we can send a simple single part message
470bb01c27cSAndreas Gohr            $this->headers['Content-Type']              = 'text/plain; charset=UTF-8';
471bb01c27cSAndreas Gohr            $this->headers['Content-Transfer-Encoding'] = 'base64';
4721d045709SAndreas Gohr            $body .= chunk_split(base64_encode($this->text), 74, MAILHEADER_EOL);
473bb01c27cSAndreas Gohr        } else { // multi part it is
4741d045709SAndreas Gohr            $body .= "This is a multi-part message in MIME format.".MAILHEADER_EOL;
475bb01c27cSAndreas Gohr
476bb01c27cSAndreas Gohr            // prepare the attachments
477bb01c27cSAndreas Gohr            $attachments = $this->prepareAttachments();
478bb01c27cSAndreas Gohr
479bb01c27cSAndreas Gohr            // do we have alternative text content?
480bb01c27cSAndreas Gohr            if($this->text && $this->html) {
481a36fc348SAndreas Gohr                $this->headers['Content-Type'] = 'multipart/alternative;'.MAILHEADER_EOL.
482a36fc348SAndreas Gohr                    '  boundary="'.$this->boundary.'XX"';
483bb01c27cSAndreas Gohr                $body .= '--'.$this->boundary.'XX'.MAILHEADER_EOL;
4841d045709SAndreas Gohr                $body .= 'Content-Type: text/plain; charset=UTF-8'.MAILHEADER_EOL;
4851d045709SAndreas Gohr                $body .= 'Content-Transfer-Encoding: base64'.MAILHEADER_EOL;
486bb01c27cSAndreas Gohr                $body .= MAILHEADER_EOL;
487bb01c27cSAndreas Gohr                $body .= chunk_split(base64_encode($this->text), 74, MAILHEADER_EOL);
488bb01c27cSAndreas Gohr                $body .= '--'.$this->boundary.'XX'.MAILHEADER_EOL;
489a36fc348SAndreas Gohr                $body .= 'Content-Type: multipart/related;'.MAILHEADER_EOL.
490a36fc348SAndreas Gohr                    '  boundary="'.$this->boundary.'"'.MAILHEADER_EOL;
491bb01c27cSAndreas Gohr                $body .= MAILHEADER_EOL;
492bb01c27cSAndreas Gohr            }
493bb01c27cSAndreas Gohr
4941d045709SAndreas Gohr            $body .= '--'.$this->boundary.MAILHEADER_EOL;
4951d045709SAndreas Gohr            $body .= 'Content-Type: text/html; charset=UTF-8'.MAILHEADER_EOL;
4961d045709SAndreas Gohr            $body .= 'Content-Transfer-Encoding: base64'.MAILHEADER_EOL;
497bb01c27cSAndreas Gohr            $body .= MAILHEADER_EOL;
4981d045709SAndreas Gohr            $body .= chunk_split(base64_encode($this->html), 74, MAILHEADER_EOL);
499bb01c27cSAndreas Gohr            $body .= MAILHEADER_EOL;
500bb01c27cSAndreas Gohr            $body .= $attachments;
501bb01c27cSAndreas Gohr            $body .= '--'.$this->boundary.'--'.MAILHEADER_EOL;
502bb01c27cSAndreas Gohr
503bb01c27cSAndreas Gohr            // close open multipart/alternative boundary
504bb01c27cSAndreas Gohr            if($this->text && $this->html) {
505bb01c27cSAndreas Gohr                $body .= '--'.$this->boundary.'XX--'.MAILHEADER_EOL;
506bb01c27cSAndreas Gohr            }
507bb01c27cSAndreas Gohr        }
508bb01c27cSAndreas Gohr
509bb01c27cSAndreas Gohr        return $body;
510bb01c27cSAndreas Gohr    }
511bb01c27cSAndreas Gohr
512bb01c27cSAndreas Gohr    /**
513a36fc348SAndreas Gohr     * Cleanup and encode the headers array
514a36fc348SAndreas Gohr     */
515a36fc348SAndreas Gohr    protected function cleanHeaders() {
516a36fc348SAndreas Gohr        global $conf;
517a36fc348SAndreas Gohr
518a36fc348SAndreas Gohr        // clean up addresses
519a36fc348SAndreas Gohr        if(empty($this->headers['From'])) $this->from($conf['mailfrom']);
520a36fc348SAndreas Gohr        $addrs = array('To', 'From', 'Cc', 'Bcc');
521a36fc348SAndreas Gohr        foreach($addrs as $addr) {
522a36fc348SAndreas Gohr            if(isset($this->headers[$addr])) {
523a36fc348SAndreas Gohr                $this->headers[$addr] = $this->cleanAddress($this->headers[$addr]);
524a36fc348SAndreas Gohr            }
525a36fc348SAndreas Gohr        }
526a36fc348SAndreas Gohr
52745992a63SAndreas Gohr        if(isset($this->headers['Subject'])) {
528a36fc348SAndreas Gohr            // add prefix to subject
52954f30755SAndreas Gohr            if(empty($conf['mailprefix'])) {
5308a215f09SAndreas Gohr                if(utf8_strlen($conf['title']) < 20) {
53154f30755SAndreas Gohr                    $prefix = '['.$conf['title'].']';
53254f30755SAndreas Gohr                } else {
5338a215f09SAndreas Gohr                    $prefix = '['.utf8_substr($conf['title'], 0, 20).'...]';
5348a215f09SAndreas Gohr                }
5358a215f09SAndreas Gohr            } else {
536a36fc348SAndreas Gohr                $prefix = '['.$conf['mailprefix'].']';
53754f30755SAndreas Gohr            }
538a36fc348SAndreas Gohr            $len = strlen($prefix);
53945992a63SAndreas Gohr            if(substr($this->headers['Subject'], 0, $len) != $prefix) {
54045992a63SAndreas Gohr                $this->headers['Subject'] = $prefix.' '.$this->headers['Subject'];
541a36fc348SAndreas Gohr            }
542a36fc348SAndreas Gohr
543a36fc348SAndreas Gohr            // encode subject
544a36fc348SAndreas Gohr            if(defined('MAILHEADER_ASCIIONLY')) {
54545992a63SAndreas Gohr                $this->headers['Subject'] = utf8_deaccent($this->headers['Subject']);
54645992a63SAndreas Gohr                $this->headers['Subject'] = utf8_strip($this->headers['Subject']);
547a36fc348SAndreas Gohr            }
548a36fc348SAndreas Gohr            if(!utf8_isASCII($this->headers['Subject'])) {
54945992a63SAndreas Gohr                $this->headers['Subject'] = '=?UTF-8?B?'.base64_encode($this->headers['Subject']).'?=';
550a36fc348SAndreas Gohr            }
551a36fc348SAndreas Gohr        }
552a36fc348SAndreas Gohr
553a36fc348SAndreas Gohr        // wrap headers
554a36fc348SAndreas Gohr        foreach($this->headers as $key => $val) {
555a36fc348SAndreas Gohr            $this->headers[$key] = wordwrap($val, 78, MAILHEADER_EOL.'  ');
556a36fc348SAndreas Gohr        }
557a36fc348SAndreas Gohr    }
558a36fc348SAndreas Gohr
559a36fc348SAndreas Gohr    /**
560bb01c27cSAndreas Gohr     * Create a string from the headers array
5611d045709SAndreas Gohr     *
5621d045709SAndreas Gohr     * @returns string the headers
563bb01c27cSAndreas Gohr     */
564bb01c27cSAndreas Gohr    protected function prepareHeaders() {
565bb01c27cSAndreas Gohr        $headers = '';
566bb01c27cSAndreas Gohr        foreach($this->headers as $key => $val) {
56791effd8dSDominik Eckelmann            if ($val === '') continue;
568bb01c27cSAndreas Gohr            $headers .= "$key: $val".MAILHEADER_EOL;
569bb01c27cSAndreas Gohr        }
570bb01c27cSAndreas Gohr        return $headers;
571bb01c27cSAndreas Gohr    }
572bb01c27cSAndreas Gohr
573bb01c27cSAndreas Gohr    /**
574bb01c27cSAndreas Gohr     * return a full email with all headers
575bb01c27cSAndreas Gohr     *
5761d045709SAndreas Gohr     * This is mainly intended for debugging and testing but could also be
5771d045709SAndreas Gohr     * used for MHT exports
5781d045709SAndreas Gohr     *
5791d045709SAndreas Gohr     * @return string the mail, false on errors
580bb01c27cSAndreas Gohr     */
581bb01c27cSAndreas Gohr    public function dump() {
582a36fc348SAndreas Gohr        $this->cleanHeaders();
583bb01c27cSAndreas Gohr        $body = $this->prepareBody();
5844d18e936SAndreas Gohr        if($body === false) return false;
5851d045709SAndreas Gohr        $headers = $this->prepareHeaders();
586bb01c27cSAndreas Gohr
587bb01c27cSAndreas Gohr        return $headers.MAILHEADER_EOL.$body;
588bb01c27cSAndreas Gohr    }
5891d045709SAndreas Gohr
5901d045709SAndreas Gohr    /**
5911d045709SAndreas Gohr     * Send the mail
5921d045709SAndreas Gohr     *
5931d045709SAndreas Gohr     * Call this after all data was set
5941d045709SAndreas Gohr     *
59528d2ad80SAndreas Gohr     * @triggers MAIL_MESSAGE_SEND
5961d045709SAndreas Gohr     * @return bool true if the mail was successfully passed to the MTA
5971d045709SAndreas Gohr     */
5981d045709SAndreas Gohr    public function send() {
59928d2ad80SAndreas Gohr        $success = false;
600a36fc348SAndreas Gohr
60128d2ad80SAndreas Gohr        // prepare hook data
60228d2ad80SAndreas Gohr        $data = array(
60328d2ad80SAndreas Gohr            // pass the whole mail class to plugin
60428d2ad80SAndreas Gohr            'mail'    => $this,
60528d2ad80SAndreas Gohr            // pass references for backward compatibility
60628d2ad80SAndreas Gohr            'to'      => &$this->headers['To'],
60728d2ad80SAndreas Gohr            'cc'      => &$this->headers['Cc'],
60828d2ad80SAndreas Gohr            'bcc'     => &$this->headers['Bcc'],
60928d2ad80SAndreas Gohr            'from'    => &$this->headers['From'],
61028d2ad80SAndreas Gohr            'subject' => &$this->headers['Subject'],
61128d2ad80SAndreas Gohr            'body'    => &$this->text,
612a89c75afSAndreas Gohr            'params'  => &$this->sendparam,
61328d2ad80SAndreas Gohr            'headers' => '', // plugins shouldn't use this
61428d2ad80SAndreas Gohr            // signal if we mailed successfully to AFTER event
61528d2ad80SAndreas Gohr            'success' => &$success,
61628d2ad80SAndreas Gohr        );
61728d2ad80SAndreas Gohr
61828d2ad80SAndreas Gohr        // do our thing if BEFORE hook approves
61928d2ad80SAndreas Gohr        $evt = new Doku_Event('MAIL_MESSAGE_SEND', $data);
62028d2ad80SAndreas Gohr        if($evt->advise_before(true)) {
62128d2ad80SAndreas Gohr            // clean up before using the headers
622a36fc348SAndreas Gohr            $this->cleanHeaders();
623a36fc348SAndreas Gohr
6241d045709SAndreas Gohr            // any recipients?
6251d045709SAndreas Gohr            if(trim($this->headers['To']) === '' &&
6261d045709SAndreas Gohr                trim($this->headers['Cc']) === '' &&
627a89c75afSAndreas Gohr                trim($this->headers['Bcc']) === ''
628a89c75afSAndreas Gohr            ) return false;
6291d045709SAndreas Gohr
6301d045709SAndreas Gohr            // The To: header is special
6311d045709SAndreas Gohr            if(isset($this->headers['To'])) {
6321d045709SAndreas Gohr                $to = $this->headers['To'];
6331d045709SAndreas Gohr                unset($this->headers['To']);
6341d045709SAndreas Gohr            } else {
6351d045709SAndreas Gohr                $to = '';
6361d045709SAndreas Gohr            }
6371d045709SAndreas Gohr
6381d045709SAndreas Gohr            // so is the subject
6391d045709SAndreas Gohr            if(isset($this->headers['Subject'])) {
6401d045709SAndreas Gohr                $subject = $this->headers['Subject'];
6411d045709SAndreas Gohr                unset($this->headers['Subject']);
6421d045709SAndreas Gohr            } else {
6431d045709SAndreas Gohr                $subject = '';
6441d045709SAndreas Gohr            }
6451d045709SAndreas Gohr
6461d045709SAndreas Gohr            // make the body
6471d045709SAndreas Gohr            $body = $this->prepareBody();
6484c89a7f6SAndreas Gohr            if($body === false) return false;
6491d045709SAndreas Gohr
6501d045709SAndreas Gohr            // cook the headers
6511d045709SAndreas Gohr            $headers = $this->prepareHeaders();
65228d2ad80SAndreas Gohr            // add any headers set by legacy plugins
65328d2ad80SAndreas Gohr            if(trim($data['headers'])) {
65428d2ad80SAndreas Gohr                $headers .= MAILHEADER_EOL.trim($data['headers']);
65528d2ad80SAndreas Gohr            }
6561d045709SAndreas Gohr
6571d045709SAndreas Gohr            // send the thing
6581d045709SAndreas Gohr            if(is_null($this->sendparam)) {
65928d2ad80SAndreas Gohr                $success = @mail($to, $subject, $body, $headers);
6601d045709SAndreas Gohr            } else {
66128d2ad80SAndreas Gohr                $success = @mail($to, $subject, $body, $headers, $this->sendparam);
6621d045709SAndreas Gohr            }
6631d045709SAndreas Gohr        }
66428d2ad80SAndreas Gohr        // any AFTER actions?
66528d2ad80SAndreas Gohr        $evt->advise_after();
66628d2ad80SAndreas Gohr        return $success;
66728d2ad80SAndreas Gohr    }
668bb01c27cSAndreas Gohr}
669