xref: /dokuwiki/inc/Mailer.class.php (revision ba9c057b0126f2c449e16adf5073920b5a663773)
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
17bb01c27cSAndreas Gohrclass Mailer {
18bb01c27cSAndreas Gohr
19bb01c27cSAndreas Gohr    private $headers = array();
20bb01c27cSAndreas Gohr    private $attach  = array();
21bb01c27cSAndreas Gohr    private $html    = '';
22bb01c27cSAndreas Gohr    private $text    = '';
23bb01c27cSAndreas Gohr
24bb01c27cSAndreas Gohr    private $boundary = '';
25bb01c27cSAndreas Gohr    private $partid   = '';
261d045709SAndreas Gohr    private $sendparam= null;
27bb01c27cSAndreas Gohr
281d045709SAndreas Gohr    private $validator = null;
291d045709SAndreas Gohr
301d045709SAndreas Gohr    /**
311d045709SAndreas Gohr     * Constructor
321d045709SAndreas Gohr     *
331d045709SAndreas Gohr     * Initializes the boundary strings and part counters
341d045709SAndreas Gohr     */
351d045709SAndreas Gohr    public function __construct(){
369f3eca0bSAndreas Gohr        global $conf;
379f3eca0bSAndreas Gohr
389f3eca0bSAndreas Gohr        $server = parse_url(DOKU_URL,PHP_URL_HOST);
391d045709SAndreas Gohr
401d045709SAndreas Gohr        $this->partid = md5(uniqid(rand(),true)).'@'.$server;
41bb01c27cSAndreas Gohr        $this->boundary = '----------'.md5(uniqid(rand(),true));
429f3eca0bSAndreas Gohr
439f3eca0bSAndreas Gohr        $listid = join('.',array_reverse(explode('/',DOKU_BASE))).$server;
449f3eca0bSAndreas Gohr        $listid = strtolower(trim($listid,'.'));
459f3eca0bSAndreas Gohr
469f3eca0bSAndreas Gohr        // add some default headers for mailfiltering FS#2247
479f3eca0bSAndreas Gohr        $this->setHeader('X-Mailer','DokuWiki '.getVersion());
489f3eca0bSAndreas Gohr        $this->setHeader('X-DokuWiki-User', $_SERVER['REMOTE_USER']);
499f3eca0bSAndreas Gohr        $this->setHeader('X-DokuWiki-Title', $conf['title']);
509f3eca0bSAndreas Gohr        $this->setHeader('X-DokuWiki-Server', $server);
519f3eca0bSAndreas Gohr        $this->setHeader('X-Auto-Response-Suppress', 'OOF');
529f3eca0bSAndreas Gohr        $this->setHeader('List-Id',$conf['title'].' <'.$listid.'>');
53bb01c27cSAndreas Gohr    }
54bb01c27cSAndreas Gohr
55bb01c27cSAndreas Gohr    /**
56bb01c27cSAndreas Gohr     * Attach a file
57bb01c27cSAndreas Gohr     *
58bb01c27cSAndreas Gohr     * @param $path  Path to the file to attach
59bb01c27cSAndreas Gohr     * @param $mime  Mimetype of the attached file
60bb01c27cSAndreas Gohr     * @param $name  The filename to use
61bb01c27cSAndreas Gohr     * @param $embed Unique key to reference this file from the HTML part
62bb01c27cSAndreas Gohr     */
63bb01c27cSAndreas Gohr    public function attachFile($path,$mime,$name='',$embed=''){
64bb01c27cSAndreas Gohr        if(!$name){
65bb01c27cSAndreas Gohr            $name = basename($path);
66bb01c27cSAndreas Gohr        }
67bb01c27cSAndreas Gohr
68bb01c27cSAndreas Gohr        $this->attach[] = array(
69bb01c27cSAndreas Gohr            'data'  => file_get_contents($path),
70bb01c27cSAndreas Gohr            'mime'  => $mime,
71bb01c27cSAndreas Gohr            'name'  => $name,
72bb01c27cSAndreas Gohr            'embed' => $embed
73bb01c27cSAndreas Gohr        );
74bb01c27cSAndreas Gohr    }
75bb01c27cSAndreas Gohr
76bb01c27cSAndreas Gohr    /**
77bb01c27cSAndreas Gohr     * Attach a file
78bb01c27cSAndreas Gohr     *
79bb01c27cSAndreas Gohr     * @param $path  The file contents to attach
80bb01c27cSAndreas Gohr     * @param $mime  Mimetype of the attached file
81bb01c27cSAndreas Gohr     * @param $name  The filename to use
82bb01c27cSAndreas Gohr     * @param $embed Unique key to reference this file from the HTML part
83bb01c27cSAndreas Gohr     */
84bb01c27cSAndreas Gohr    public function attachContent($data,$mime,$name='',$embed=''){
85bb01c27cSAndreas Gohr        if(!$name){
86bb01c27cSAndreas Gohr            list($junk,$ext) = split('/',$mime);
87bb01c27cSAndreas Gohr            $name = count($this->attach).".$ext";
88bb01c27cSAndreas Gohr        }
89bb01c27cSAndreas Gohr
90bb01c27cSAndreas Gohr        $this->attach[] = array(
91bb01c27cSAndreas Gohr            'data'  => $data,
92bb01c27cSAndreas Gohr            'mime'  => $mime,
93bb01c27cSAndreas Gohr            'name'  => $name,
94bb01c27cSAndreas Gohr            'embed' => $embed
95bb01c27cSAndreas Gohr        );
96bb01c27cSAndreas Gohr    }
97bb01c27cSAndreas Gohr
98bb01c27cSAndreas Gohr    /**
99850dbf1fSAndreas Gohr     * Callback function to automatically embed images referenced in HTML templates
100850dbf1fSAndreas Gohr     */
101850dbf1fSAndreas Gohr    protected function autoembed_cb($matches){
102850dbf1fSAndreas Gohr        static $embeds = 0;
103850dbf1fSAndreas Gohr        $embeds++;
104850dbf1fSAndreas Gohr
105850dbf1fSAndreas Gohr        // get file and mime type
106850dbf1fSAndreas Gohr        $media = cleanID($matches[1]);
107850dbf1fSAndreas Gohr        list($ext, $mime) = mimetype($media);
108850dbf1fSAndreas Gohr        $file  = mediaFN($media);
109850dbf1fSAndreas Gohr        if(!file_exists($file)) return $matches[0]; //bad reference, keep as is
110850dbf1fSAndreas Gohr
111850dbf1fSAndreas Gohr        // attach it and set placeholder
112850dbf1fSAndreas Gohr        $this->attachFile($file,$mime,'','autoembed'.$embeds);
113850dbf1fSAndreas Gohr        return '%%autoembed'.$embeds.'%%';
114850dbf1fSAndreas Gohr    }
115850dbf1fSAndreas Gohr
116850dbf1fSAndreas Gohr    /**
1171d045709SAndreas Gohr     * Add an arbitrary header to the mail
1181d045709SAndreas Gohr     *
119a36fc348SAndreas Gohr     * If an empy value is passed, the header is removed
120a36fc348SAndreas Gohr     *
1211d045709SAndreas Gohr     * @param string $header the header name (no trailing colon!)
1221d045709SAndreas Gohr     * @param string $value  the value of the header
1231d045709SAndreas Gohr     * @param bool   $clean  remove all non-ASCII chars and line feeds?
1241d045709SAndreas Gohr     */
1251d045709SAndreas Gohr    public function setHeader($header,$value,$clean=true){
1269f3eca0bSAndreas Gohr        $header = str_replace(' ','-',ucwords(strtolower(str_replace('-',' ',$header)))); // streamline casing
1271d045709SAndreas Gohr        if($clean){
1281d045709SAndreas Gohr            $header = preg_replace('/[^\w \-\.\+\@]+/','',$header);
1299f3eca0bSAndreas Gohr            $value  = preg_replace('/[^\w \-\.\+\@<>]+/','',$value);
1301d045709SAndreas Gohr        }
131a36fc348SAndreas Gohr
132a36fc348SAndreas Gohr        // empty value deletes
133a36fc348SAndreas Gohr        $value = trim($value);
134a36fc348SAndreas Gohr        if($value === ''){
135a36fc348SAndreas Gohr            if(isset($this->headers[$header])) unset($this->headers[$header]);
136a36fc348SAndreas Gohr        }else{
1371d045709SAndreas Gohr            $this->headers[$header] = $value;
1381d045709SAndreas Gohr        }
139a36fc348SAndreas Gohr    }
1401d045709SAndreas Gohr
1411d045709SAndreas Gohr    /**
1421d045709SAndreas Gohr     * Set additional parameters to be passed to sendmail
1431d045709SAndreas Gohr     *
1441d045709SAndreas Gohr     * Whatever is set here is directly passed to PHP's mail() command as last
1451d045709SAndreas Gohr     * parameter. Depending on the PHP setup this might break mailing alltogether
1461d045709SAndreas Gohr     */
1471d045709SAndreas Gohr    public function setParameters($param){
1481d045709SAndreas Gohr        $this->sendparam = $param;
1491d045709SAndreas Gohr    }
1501d045709SAndreas Gohr
1511d045709SAndreas Gohr    /**
152abbf0890SAndreas Gohr     * Set the text and HTML body and apply replacements
153abbf0890SAndreas Gohr     *
154abbf0890SAndreas Gohr     * This function applies a whole bunch of default replacements in addition
155abbf0890SAndreas Gohr     * to the ones specidifed as parameters
156abbf0890SAndreas Gohr     *
157abbf0890SAndreas Gohr     * If you pass the HTML part or HTML replacements yourself you have to make
158abbf0890SAndreas Gohr     * sure you encode all HTML special chars correctly
159abbf0890SAndreas Gohr     *
160abbf0890SAndreas Gohr     * @param string $text     plain text body
161abbf0890SAndreas Gohr     * @param array  $textrep  replacements to apply on the text part
162abbf0890SAndreas Gohr     * @param array  $htmlrep  replacements to apply on the HTML part, leave null to use $textrep
163abbf0890SAndreas Gohr     * @param array  $html     the HTML body, leave null to create it from $text
164f08086ecSAndreas Gohr     * @param bool   $wrap     wrap the HTML in the default header/Footer
165abbf0890SAndreas Gohr     */
166f08086ecSAndreas Gohr    public function setBody($text, $textrep=null, $htmlrep=null, $html=null, $wrap=true){
167abbf0890SAndreas Gohr        global $INFO;
168abbf0890SAndreas Gohr        global $conf;
16976efd6d0SAndreas Gohr        $htmlrep = (array) $htmlrep;
17076efd6d0SAndreas Gohr        $textrep = (array) $textrep;
171abbf0890SAndreas Gohr
172abbf0890SAndreas Gohr        // create HTML from text if not given
173abbf0890SAndreas Gohr        if(is_null($html)){
174*ba9c057bSAndreas Gohr            $html = $text;
175*ba9c057bSAndreas Gohr            $html = hsc($html);
176*ba9c057bSAndreas Gohr            $html = preg_replace('/^-----*$/m','<hr >',$html);
177*ba9c057bSAndreas Gohr            $html = nl2br($html);
178abbf0890SAndreas Gohr        }
179f08086ecSAndreas Gohr        if($wrap){
180f08086ecSAndreas Gohr            $wrap = rawLocale('mailwrap','html');
181a4c4a73dSAndreas Gohr            $html = preg_replace('/\n-- <br \/>.*$/s','',$html); //strip signature
182f08086ecSAndreas Gohr            $html = str_replace('@HTMLBODY@',$html,$wrap);
183f08086ecSAndreas Gohr        }
184f08086ecSAndreas Gohr
18576efd6d0SAndreas Gohr        // copy over all replacements missing for HTML (autolink URLs)
18676efd6d0SAndreas Gohr        foreach($textrep as $key => $value){
18776efd6d0SAndreas Gohr            if(isset($htmlrep[$key])) continue;
18876efd6d0SAndreas Gohr            if(preg_match('/^https?:\/\//i',$value)){
18976efd6d0SAndreas Gohr                $htmlrep[$key] = '<a href="'.hsc($value).'">'.hsc($value).'</a>';
19076efd6d0SAndreas Gohr            }else{
19176efd6d0SAndreas Gohr                $htmlrep[$key] = hsc($value);
19276efd6d0SAndreas Gohr            }
193abbf0890SAndreas Gohr        }
194abbf0890SAndreas Gohr
195850dbf1fSAndreas Gohr        // embed media from templates
196850dbf1fSAndreas Gohr        $html = preg_replace_callback('/@MEDIA\(([^\)]+)\)@/',
197850dbf1fSAndreas Gohr                                      array($this,'autoembed_cb'),$html);
198850dbf1fSAndreas Gohr
199abbf0890SAndreas Gohr        // prepare default replacements
200abbf0890SAndreas Gohr        $ip   = clientIP();
201f08086ecSAndreas Gohr        $cip  = gethostsbyaddrs($ip);
202abbf0890SAndreas Gohr        $trep = array(
203abbf0890SAndreas Gohr            'DATE'        => dformat(),
204abbf0890SAndreas Gohr            'BROWSER'     => $_SERVER['HTTP_USER_AGENT'],
205abbf0890SAndreas Gohr            'IPADDRESS'   => $ip,
206f08086ecSAndreas Gohr            'HOSTNAME'    => $cip,
207abbf0890SAndreas Gohr            'TITLE'       => $conf['title'],
208abbf0890SAndreas Gohr            'DOKUWIKIURL' => DOKU_URL,
209abbf0890SAndreas Gohr            'USER'        => $_SERVER['REMOTE_USER'],
210abbf0890SAndreas Gohr            'NAME'        => $INFO['userinfo']['name'],
211abbf0890SAndreas Gohr            'MAIL'        => $INFO['userinfo']['mail'],
212abbf0890SAndreas Gohr        );
213abbf0890SAndreas Gohr        $trep = array_merge($trep,(array) $textrep);
214abbf0890SAndreas Gohr        $hrep = array(
215abbf0890SAndreas Gohr            'DATE'        => '<i>'.hsc(dformat()).'</i>',
216abbf0890SAndreas Gohr            'BROWSER'     => hsc($_SERVER['HTTP_USER_AGENT']),
217abbf0890SAndreas Gohr            'IPADDRESS'   => '<code>'.hsc($ip).'</code>',
218f08086ecSAndreas Gohr            'HOSTNAME'    => '<code>'.hsc($cip).'</code>',
219abbf0890SAndreas Gohr            'TITLE'       => hsc($conf['title']),
220abbf0890SAndreas Gohr            'DOKUWIKIURL' => '<a href="'.DOKU_URL.'">'.DOKU_URL.'</a>',
221abbf0890SAndreas Gohr            'USER'        => hsc($_SERVER['REMOTE_USER']),
222abbf0890SAndreas Gohr            'NAME'        => hsc($INFO['userinfo']['name']),
223abbf0890SAndreas Gohr            'MAIL'        => '<a href="mailto:"'.hsc($INFO['userinfo']['mail']).'">'.
224abbf0890SAndreas Gohr                             hsc($INFO['userinfo']['mail']).'</a>',
225abbf0890SAndreas Gohr        );
226abbf0890SAndreas Gohr        $hrep = array_merge($hrep,(array) $htmlrep);
227abbf0890SAndreas Gohr
228abbf0890SAndreas Gohr        // Apply replacements
229abbf0890SAndreas Gohr        foreach ($trep as $key => $substitution) {
230abbf0890SAndreas Gohr            $text = str_replace('@'.strtoupper($key).'@',$substitution, $text);
231abbf0890SAndreas Gohr        }
232abbf0890SAndreas Gohr        foreach ($hrep as $key => $substitution) {
233abbf0890SAndreas Gohr            $html = str_replace('@'.strtoupper($key).'@',$substitution, $html);
234abbf0890SAndreas Gohr        }
235abbf0890SAndreas Gohr
236abbf0890SAndreas Gohr        $this->setHTML($html);
237abbf0890SAndreas Gohr        $this->setText($text);
238abbf0890SAndreas Gohr    }
239abbf0890SAndreas Gohr
240abbf0890SAndreas Gohr    /**
241bb01c27cSAndreas Gohr     * Set the HTML part of the mail
242bb01c27cSAndreas Gohr     *
243bb01c27cSAndreas Gohr     * Placeholders can be used to reference embedded attachments
244abbf0890SAndreas Gohr     *
245abbf0890SAndreas Gohr     * You probably want to use setBody() instead
246bb01c27cSAndreas Gohr     */
2471d045709SAndreas Gohr    public function setHTML($html){
248bb01c27cSAndreas Gohr        $this->html = $html;
249bb01c27cSAndreas Gohr    }
250bb01c27cSAndreas Gohr
251bb01c27cSAndreas Gohr    /**
252bb01c27cSAndreas Gohr     * Set the plain text part of the mail
253abbf0890SAndreas Gohr     *
254abbf0890SAndreas Gohr     * You probably want to use setBody() instead
255bb01c27cSAndreas Gohr     */
2561d045709SAndreas Gohr    public function setText($text){
257bb01c27cSAndreas Gohr        $this->text = $text;
258bb01c27cSAndreas Gohr    }
259bb01c27cSAndreas Gohr
260bb01c27cSAndreas Gohr    /**
261a36fc348SAndreas Gohr     * Add the To: recipients
262a36fc348SAndreas Gohr     *
263a36fc348SAndreas Gohr     * @see setAddress
264a36fc348SAndreas Gohr     * @param string  $address Multiple adresses separated by commas
265a36fc348SAndreas Gohr     */
266a36fc348SAndreas Gohr    public function to($address){
267a36fc348SAndreas Gohr        $this->setHeader('To', $address, false);
268a36fc348SAndreas Gohr    }
269a36fc348SAndreas Gohr
270a36fc348SAndreas Gohr    /**
271a36fc348SAndreas Gohr     * Add the Cc: recipients
272a36fc348SAndreas Gohr     *
273a36fc348SAndreas Gohr     * @see setAddress
274a36fc348SAndreas Gohr     * @param string  $address Multiple adresses separated by commas
275a36fc348SAndreas Gohr     */
276a36fc348SAndreas Gohr    public function cc($address){
277a36fc348SAndreas Gohr        $this->setHeader('Cc', $address, false);
278a36fc348SAndreas Gohr    }
279a36fc348SAndreas Gohr
280a36fc348SAndreas Gohr    /**
281a36fc348SAndreas Gohr     * Add the Bcc: recipients
282a36fc348SAndreas Gohr     *
283a36fc348SAndreas Gohr     * @see setAddress
284a36fc348SAndreas Gohr     * @param string  $address Multiple adresses separated by commas
285a36fc348SAndreas Gohr     */
286a36fc348SAndreas Gohr    public function bcc($address){
287a36fc348SAndreas Gohr        $this->setHeader('Bcc', $address, false);
288a36fc348SAndreas Gohr    }
289a36fc348SAndreas Gohr
290a36fc348SAndreas Gohr    /**
291a36fc348SAndreas Gohr     * Add the From: address
292a36fc348SAndreas Gohr     *
293a36fc348SAndreas Gohr     * This is set to $conf['mailfrom'] when not specified so you shouldn't need
294a36fc348SAndreas Gohr     * to call this function
295a36fc348SAndreas Gohr     *
296a36fc348SAndreas Gohr     * @see setAddress
297a36fc348SAndreas Gohr     * @param string  $address from address
298a36fc348SAndreas Gohr     */
299a36fc348SAndreas Gohr    public function from($address){
300a36fc348SAndreas Gohr        $this->setHeader('From', $address, false);
301a36fc348SAndreas Gohr    }
302a36fc348SAndreas Gohr
303a36fc348SAndreas Gohr    /**
304a36fc348SAndreas Gohr     * Add the mail's Subject: header
305a36fc348SAndreas Gohr     *
306a36fc348SAndreas Gohr     * @param string $subject the mail subject
307a36fc348SAndreas Gohr     */
308a36fc348SAndreas Gohr    public function subject($subject){
309a36fc348SAndreas Gohr        $this->headers['Subject'] = $subject;
310a36fc348SAndreas Gohr    }
311a36fc348SAndreas Gohr
312a36fc348SAndreas Gohr    /**
3131d045709SAndreas Gohr     * Sets an email address header with correct encoding
314bb01c27cSAndreas Gohr     *
315bb01c27cSAndreas Gohr     * Unicode characters will be deaccented and encoded base64
316bb01c27cSAndreas Gohr     * for headers. Addresses may not contain Non-ASCII data!
317bb01c27cSAndreas Gohr     *
318bb01c27cSAndreas Gohr     * Example:
319bb01c27cSAndreas Gohr     *   setAddress("föö <foo@bar.com>, me@somewhere.com","TBcc");
320bb01c27cSAndreas Gohr     *
321bb01c27cSAndreas Gohr     * @param string  $address Multiple adresses separated by commas
322a36fc348SAndreas Gohr     * @param string  returns the prepared header (can contain multiple lines)
323bb01c27cSAndreas Gohr     */
324a36fc348SAndreas Gohr    public function cleanAddress($address){
325bb01c27cSAndreas Gohr        // No named recipients for To: in Windows (see FS#652)
326bb01c27cSAndreas Gohr        $names = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? false : true;
327bb01c27cSAndreas Gohr
3281d045709SAndreas Gohr        $address = preg_replace('/[\r\n\0]+/',' ',$address); // remove attack vectors
3291d045709SAndreas Gohr
330bb01c27cSAndreas Gohr        $headers = '';
331bb01c27cSAndreas Gohr        $parts = explode(',',$address);
332bb01c27cSAndreas Gohr        foreach ($parts as $part){
333bb01c27cSAndreas Gohr            $part = trim($part);
334bb01c27cSAndreas Gohr
335bb01c27cSAndreas Gohr            // parse address
336bb01c27cSAndreas Gohr            if(preg_match('#(.*?)<(.*?)>#',$part,$matches)){
337bb01c27cSAndreas Gohr                $text = trim($matches[1]);
338bb01c27cSAndreas Gohr                $addr = $matches[2];
339bb01c27cSAndreas Gohr            }else{
340bb01c27cSAndreas Gohr                $addr = $part;
341bb01c27cSAndreas Gohr            }
342bb01c27cSAndreas Gohr            // skip empty ones
343bb01c27cSAndreas Gohr            if(empty($addr)){
344bb01c27cSAndreas Gohr                continue;
345bb01c27cSAndreas Gohr            }
346bb01c27cSAndreas Gohr
347bb01c27cSAndreas Gohr            // FIXME: is there a way to encode the localpart of a emailaddress?
348bb01c27cSAndreas Gohr            if(!utf8_isASCII($addr)){
349bb01c27cSAndreas Gohr                msg(htmlspecialchars("E-Mail address <$addr> is not ASCII"),-1);
350bb01c27cSAndreas Gohr                continue;
351bb01c27cSAndreas Gohr            }
352bb01c27cSAndreas Gohr
3531d045709SAndreas Gohr            if(is_null($this->validator)){
3541d045709SAndreas Gohr                $this->validator = new EmailAddressValidator();
3551d045709SAndreas Gohr                $this->validator->allowLocalAddresses = true;
3561d045709SAndreas Gohr            }
3571d045709SAndreas Gohr            if(!$this->validator->check_email_address($addr)){
358bb01c27cSAndreas Gohr                msg(htmlspecialchars("E-Mail address <$addr> is not valid"),-1);
359bb01c27cSAndreas Gohr                continue;
360bb01c27cSAndreas Gohr            }
361bb01c27cSAndreas Gohr
362bb01c27cSAndreas Gohr            // text was given
363bb01c27cSAndreas Gohr            if(!empty($text) && $names){
364bb01c27cSAndreas Gohr                // add address quotes
365bb01c27cSAndreas Gohr                $addr = "<$addr>";
366bb01c27cSAndreas Gohr
367bb01c27cSAndreas Gohr                if(defined('MAILHEADER_ASCIIONLY')){
368bb01c27cSAndreas Gohr                    $text = utf8_deaccent($text);
369bb01c27cSAndreas Gohr                    $text = utf8_strip($text);
370bb01c27cSAndreas Gohr                }
371bb01c27cSAndreas Gohr
372bb01c27cSAndreas Gohr                if(!utf8_isASCII($text)){
3731d045709SAndreas Gohr                    //FIXME check if this is needed for base64 too
374bb01c27cSAndreas Gohr                    // put the quotes outside as in =?UTF-8?Q?"Elan Ruusam=C3=A4e"?= vs "=?UTF-8?Q?Elan Ruusam=C3=A4e?="
375bb01c27cSAndreas Gohr                    /*
376bb01c27cSAndreas Gohr                    if (preg_match('/^"(.+)"$/', $text, $matches)) {
377bb01c27cSAndreas Gohr                      $text = '"=?UTF-8?Q?'.mail_quotedprintable_encode($matches[1], 0).'?="';
378bb01c27cSAndreas Gohr                    } else {
379bb01c27cSAndreas Gohr                      $text = '=?UTF-8?Q?'.mail_quotedprintable_encode($text, 0).'?=';
380bb01c27cSAndreas Gohr                    }
381bb01c27cSAndreas Gohr                    */
382bb01c27cSAndreas Gohr                    $text = '=?UTF-8?B?'.base64_encode($text).'?=';
383bb01c27cSAndreas Gohr                }
384bb01c27cSAndreas Gohr            }else{
385bb01c27cSAndreas Gohr                $text = '';
386bb01c27cSAndreas Gohr            }
387bb01c27cSAndreas Gohr
388bb01c27cSAndreas Gohr            // add to header comma seperated
389bb01c27cSAndreas Gohr            if($headers != ''){
390bb01c27cSAndreas Gohr                $headers .= ', ';
391bb01c27cSAndreas Gohr            }
392bb01c27cSAndreas Gohr            $headers .= $text.' '.$addr;
393bb01c27cSAndreas Gohr        }
394bb01c27cSAndreas Gohr
395bb01c27cSAndreas Gohr        if(empty($headers)) return false;
396bb01c27cSAndreas Gohr
397bb01c27cSAndreas Gohr        return $headers;
398bb01c27cSAndreas Gohr    }
399bb01c27cSAndreas Gohr
400bb01c27cSAndreas Gohr
401bb01c27cSAndreas Gohr    /**
402bb01c27cSAndreas Gohr     * Prepare the mime multiparts for all attachments
403bb01c27cSAndreas Gohr     *
404bb01c27cSAndreas Gohr     * Replaces placeholders in the HTML with the correct CIDs
405bb01c27cSAndreas Gohr     */
406bb01c27cSAndreas Gohr    protected function prepareAttachments(){
407bb01c27cSAndreas Gohr        $mime = '';
408bb01c27cSAndreas Gohr        $part = 1;
409bb01c27cSAndreas Gohr        // embedded attachments
410bb01c27cSAndreas Gohr        foreach($this->attach as $media){
411bb01c27cSAndreas Gohr            // create content id
412bb01c27cSAndreas Gohr            $cid = 'part'.$part.'.'.$this->partid;
413bb01c27cSAndreas Gohr
414bb01c27cSAndreas Gohr            // replace wildcards
415bb01c27cSAndreas Gohr            if($media['embed']){
416bb01c27cSAndreas Gohr                $this->html = str_replace('%%'.$media['embed'].'%%','cid:'.$cid,$this->html);
417bb01c27cSAndreas Gohr            }
418bb01c27cSAndreas Gohr
419bb01c27cSAndreas Gohr            $mime .= '--'.$this->boundary.MAILHEADER_EOL;
420bb01c27cSAndreas Gohr            $mime .= 'Content-Type: '.$media['mime'].';'.MAILHEADER_EOL;
421bb01c27cSAndreas Gohr            $mime .= 'Content-Transfer-Encoding: base64'.MAILHEADER_EOL;
422bb01c27cSAndreas Gohr            $mime .= "Content-ID: <$cid>".MAILHEADER_EOL;
423bb01c27cSAndreas Gohr            if($media['embed']){
424bb01c27cSAndreas Gohr                $mime .= 'Content-Disposition: inline; filename="'.$media['name'].'"'.MAILHEADER_EOL;
425bb01c27cSAndreas Gohr            }else{
426bb01c27cSAndreas Gohr                $mime .= 'Content-Disposition: attachment; filename="'.$media['name'].'"'.MAILHEADER_EOL;
427bb01c27cSAndreas Gohr            }
428bb01c27cSAndreas Gohr            $mime .= MAILHEADER_EOL; //end of headers
429bb01c27cSAndreas Gohr            $mime .= chunk_split(base64_encode($media['data']),74,MAILHEADER_EOL);
430bb01c27cSAndreas Gohr
431bb01c27cSAndreas Gohr            $part++;
432bb01c27cSAndreas Gohr        }
433bb01c27cSAndreas Gohr        return $mime;
434bb01c27cSAndreas Gohr    }
435bb01c27cSAndreas Gohr
4361d045709SAndreas Gohr    /**
4371d045709SAndreas Gohr     * Build the body and handles multi part mails
4381d045709SAndreas Gohr     *
4391d045709SAndreas Gohr     * Needs to be called before prepareHeaders!
4401d045709SAndreas Gohr     *
4411d045709SAndreas Gohr     * @return string the prepared mail body, false on errors
4421d045709SAndreas Gohr     */
4431d045709SAndreas Gohr    protected function prepareBody(){
4441d045709SAndreas Gohr        global $conf;
4451d045709SAndreas Gohr
446bb01c27cSAndreas Gohr        // check for body
447bb01c27cSAndreas Gohr        if(!$this->text && !$this->html){
448bb01c27cSAndreas Gohr            return false;
449bb01c27cSAndreas Gohr        }
450bb01c27cSAndreas Gohr
451bb01c27cSAndreas Gohr        // add general headers
452bb01c27cSAndreas Gohr        $this->headers['MIME-Version'] = '1.0';
453bb01c27cSAndreas Gohr
4541d045709SAndreas Gohr        $body = '';
4551d045709SAndreas Gohr
456bb01c27cSAndreas Gohr        if(!$this->html && !count($this->attach)){ // we can send a simple single part message
457bb01c27cSAndreas Gohr            $this->headers['Content-Type'] = 'text/plain; charset=UTF-8';
458bb01c27cSAndreas Gohr            $this->headers['Content-Transfer-Encoding'] = 'base64';
4591d045709SAndreas Gohr            $body .= chunk_split(base64_encode($this->text),74,MAILHEADER_EOL);
460bb01c27cSAndreas Gohr        }else{ // multi part it is
4611d045709SAndreas Gohr            $body .= "This is a multi-part message in MIME format.".MAILHEADER_EOL;
462bb01c27cSAndreas Gohr
463bb01c27cSAndreas Gohr            // prepare the attachments
464bb01c27cSAndreas Gohr            $attachments = $this->prepareAttachments();
465bb01c27cSAndreas Gohr
466bb01c27cSAndreas Gohr            // do we have alternative text content?
467bb01c27cSAndreas Gohr            if($this->text && $this->html){
468a36fc348SAndreas Gohr                $this->headers['Content-Type'] = 'multipart/alternative;'.MAILHEADER_EOL.
469a36fc348SAndreas Gohr                                                 '  boundary="'.$this->boundary.'XX"';
470bb01c27cSAndreas Gohr                $body .= '--'.$this->boundary.'XX'.MAILHEADER_EOL;
4711d045709SAndreas Gohr                $body .= 'Content-Type: text/plain; charset=UTF-8'.MAILHEADER_EOL;
4721d045709SAndreas Gohr                $body .= 'Content-Transfer-Encoding: base64'.MAILHEADER_EOL;
473bb01c27cSAndreas Gohr                $body .= MAILHEADER_EOL;
474bb01c27cSAndreas Gohr                $body .= chunk_split(base64_encode($this->text),74,MAILHEADER_EOL);
475bb01c27cSAndreas Gohr                $body .= '--'.$this->boundary.'XX'.MAILHEADER_EOL;
476a36fc348SAndreas Gohr                $body .= 'Content-Type: multipart/related;'.MAILHEADER_EOL.
477a36fc348SAndreas Gohr                         '  boundary="'.$this->boundary.'"'.MAILHEADER_EOL;
478bb01c27cSAndreas Gohr                $body .= MAILHEADER_EOL;
479bb01c27cSAndreas Gohr            }
480bb01c27cSAndreas Gohr
4811d045709SAndreas Gohr            $body .= '--'.$this->boundary.MAILHEADER_EOL;
4821d045709SAndreas Gohr            $body .= 'Content-Type: text/html; charset=UTF-8'.MAILHEADER_EOL;
4831d045709SAndreas Gohr            $body .= 'Content-Transfer-Encoding: base64'.MAILHEADER_EOL;
484bb01c27cSAndreas Gohr            $body .= MAILHEADER_EOL;
4851d045709SAndreas Gohr            $body .= chunk_split(base64_encode($this->html),74,MAILHEADER_EOL);
486bb01c27cSAndreas Gohr            $body .= MAILHEADER_EOL;
487bb01c27cSAndreas Gohr            $body .= $attachments;
488bb01c27cSAndreas Gohr            $body .= '--'.$this->boundary.'--'.MAILHEADER_EOL;
489bb01c27cSAndreas Gohr
490bb01c27cSAndreas Gohr            // close open multipart/alternative boundary
491bb01c27cSAndreas Gohr            if($this->text && $this->html){
492bb01c27cSAndreas Gohr                $body .= '--'.$this->boundary.'XX--'.MAILHEADER_EOL;
493bb01c27cSAndreas Gohr            }
494bb01c27cSAndreas Gohr        }
495bb01c27cSAndreas Gohr
496bb01c27cSAndreas Gohr        return $body;
497bb01c27cSAndreas Gohr    }
498bb01c27cSAndreas Gohr
499bb01c27cSAndreas Gohr    /**
500a36fc348SAndreas Gohr     * Cleanup and encode the headers array
501a36fc348SAndreas Gohr     */
502a36fc348SAndreas Gohr    protected function cleanHeaders(){
503a36fc348SAndreas Gohr        global $conf;
504a36fc348SAndreas Gohr
505a36fc348SAndreas Gohr        // clean up addresses
506a36fc348SAndreas Gohr        if(empty($this->headers['From'])) $this->from($conf['mailfrom']);
507a36fc348SAndreas Gohr        $addrs = array('To','From','Cc','Bcc');
508a36fc348SAndreas Gohr        foreach($addrs as $addr){
509a36fc348SAndreas Gohr            if(isset($this->headers[$addr])){
510a36fc348SAndreas Gohr                $this->headers[$addr] = $this->cleanAddress($this->headers[$addr]);
511a36fc348SAndreas Gohr            }
512a36fc348SAndreas Gohr        }
513a36fc348SAndreas Gohr
51445992a63SAndreas Gohr        if(isset($this->headers['Subject'])){
515a36fc348SAndreas Gohr            // add prefix to subject
51654f30755SAndreas Gohr            if(empty($conf['mailprefix'])){
5178a215f09SAndreas Gohr                if(utf8_strlen($conf['title']) < 20) {
51854f30755SAndreas Gohr                    $prefix = '['.$conf['title'].']';
51954f30755SAndreas Gohr                }else{
5208a215f09SAndreas Gohr                    $prefix = '['.utf8_substr($conf['title'], 0, 20).'...]';
5218a215f09SAndreas Gohr                }
5228a215f09SAndreas Gohr            }else{
523a36fc348SAndreas Gohr                $prefix = '['.$conf['mailprefix'].']';
52454f30755SAndreas Gohr            }
525a36fc348SAndreas Gohr            $len = strlen($prefix);
52645992a63SAndreas Gohr            if(substr($this->headers['Subject'],0,$len) != $prefix){
52745992a63SAndreas Gohr                $this->headers['Subject'] = $prefix.' '.$this->headers['Subject'];
528a36fc348SAndreas Gohr            }
529a36fc348SAndreas Gohr
530a36fc348SAndreas Gohr            // encode subject
531a36fc348SAndreas Gohr            if(defined('MAILHEADER_ASCIIONLY')){
53245992a63SAndreas Gohr                $this->headers['Subject'] = utf8_deaccent($this->headers['Subject']);
53345992a63SAndreas Gohr                $this->headers['Subject'] = utf8_strip($this->headers['Subject']);
534a36fc348SAndreas Gohr            }
535a36fc348SAndreas Gohr            if(!utf8_isASCII($this->headers['Subject'])){
53645992a63SAndreas Gohr                $this->headers['Subject'] = '=?UTF-8?B?'.base64_encode($this->headers['Subject']).'?=';
537a36fc348SAndreas Gohr            }
538a36fc348SAndreas Gohr        }
539a36fc348SAndreas Gohr
540a36fc348SAndreas Gohr        // wrap headers
541a36fc348SAndreas Gohr        foreach($this->headers as $key => $val){
542a36fc348SAndreas Gohr            $this->headers[$key] = wordwrap($val,78,MAILHEADER_EOL.'  ');
543a36fc348SAndreas Gohr        }
544a36fc348SAndreas Gohr    }
545a36fc348SAndreas Gohr
546a36fc348SAndreas Gohr    /**
547bb01c27cSAndreas Gohr     * Create a string from the headers array
5481d045709SAndreas Gohr     *
5491d045709SAndreas Gohr     * @returns string the headers
550bb01c27cSAndreas Gohr     */
551bb01c27cSAndreas Gohr    protected function prepareHeaders(){
552bb01c27cSAndreas Gohr        $headers = '';
553bb01c27cSAndreas Gohr        foreach($this->headers as $key => $val){
554bb01c27cSAndreas Gohr            $headers .= "$key: $val".MAILHEADER_EOL;
555bb01c27cSAndreas Gohr        }
556bb01c27cSAndreas Gohr        return $headers;
557bb01c27cSAndreas Gohr    }
558bb01c27cSAndreas Gohr
559bb01c27cSAndreas Gohr    /**
560bb01c27cSAndreas Gohr     * return a full email with all headers
561bb01c27cSAndreas Gohr     *
5621d045709SAndreas Gohr     * This is mainly intended for debugging and testing but could also be
5631d045709SAndreas Gohr     * used for MHT exports
5641d045709SAndreas Gohr     *
5651d045709SAndreas Gohr     * @return string the mail, false on errors
566bb01c27cSAndreas Gohr     */
567bb01c27cSAndreas Gohr    public function dump(){
568a36fc348SAndreas Gohr        $this->cleanHeaders();
569bb01c27cSAndreas Gohr        $body    = $this->prepareBody();
5701d045709SAndreas Gohr        if($body === 'false') return false;
5711d045709SAndreas Gohr        $headers = $this->prepareHeaders();
572bb01c27cSAndreas Gohr
573bb01c27cSAndreas Gohr        return $headers.MAILHEADER_EOL.$body;
574bb01c27cSAndreas Gohr    }
5751d045709SAndreas Gohr
5761d045709SAndreas Gohr    /**
5771d045709SAndreas Gohr     * Send the mail
5781d045709SAndreas Gohr     *
5791d045709SAndreas Gohr     * Call this after all data was set
5801d045709SAndreas Gohr     *
58128d2ad80SAndreas Gohr     * @triggers MAIL_MESSAGE_SEND
5821d045709SAndreas Gohr     * @return bool true if the mail was successfully passed to the MTA
5831d045709SAndreas Gohr     */
5841d045709SAndreas Gohr    public function send(){
58528d2ad80SAndreas Gohr        $success = false;
586a36fc348SAndreas Gohr
58728d2ad80SAndreas Gohr        // prepare hook data
58828d2ad80SAndreas Gohr        $data = array(
58928d2ad80SAndreas Gohr            // pass the whole mail class to plugin
59028d2ad80SAndreas Gohr            'mail' => $this,
59128d2ad80SAndreas Gohr            // pass references for backward compatibility
59228d2ad80SAndreas Gohr            'to'      => &$this->headers['To'],
59328d2ad80SAndreas Gohr            'cc'      => &$this->headers['Cc'],
59428d2ad80SAndreas Gohr            'bcc'     => &$this->headers['Bcc'],
59528d2ad80SAndreas Gohr            'from'    => &$this->headers['From'],
59628d2ad80SAndreas Gohr            'subject' => &$this->headers['Subject'],
59728d2ad80SAndreas Gohr            'body'    => &$this->text,
59828d2ad80SAndreas Gohr            'params'  => &$this->sendparams,
59928d2ad80SAndreas Gohr            'headers' => '', // plugins shouldn't use this
60028d2ad80SAndreas Gohr            // signal if we mailed successfully to AFTER event
60128d2ad80SAndreas Gohr            'success' => &$success,
60228d2ad80SAndreas Gohr        );
60328d2ad80SAndreas Gohr
60428d2ad80SAndreas Gohr        // do our thing if BEFORE hook approves
60528d2ad80SAndreas Gohr        $evt = new Doku_Event('MAIL_MESSAGE_SEND', $data);
60628d2ad80SAndreas Gohr        if ($evt->advise_before(true)) {
60728d2ad80SAndreas Gohr            // clean up before using the headers
608a36fc348SAndreas Gohr            $this->cleanHeaders();
609a36fc348SAndreas Gohr
6101d045709SAndreas Gohr            // any recipients?
6111d045709SAndreas Gohr            if(trim($this->headers['To'])  === '' &&
6121d045709SAndreas Gohr               trim($this->headers['Cc'])  === '' &&
6131d045709SAndreas Gohr               trim($this->headers['Bcc']) === '') return false;
6141d045709SAndreas Gohr
6151d045709SAndreas Gohr            // The To: header is special
6161d045709SAndreas Gohr            if(isset($this->headers['To'])){
6171d045709SAndreas Gohr                $to = $this->headers['To'];
6181d045709SAndreas Gohr                unset($this->headers['To']);
6191d045709SAndreas Gohr            }else{
6201d045709SAndreas Gohr                $to = '';
6211d045709SAndreas Gohr            }
6221d045709SAndreas Gohr
6231d045709SAndreas Gohr            // so is the subject
6241d045709SAndreas Gohr            if(isset($this->headers['Subject'])){
6251d045709SAndreas Gohr                $subject = $this->headers['Subject'];
6261d045709SAndreas Gohr                unset($this->headers['Subject']);
6271d045709SAndreas Gohr            }else{
6281d045709SAndreas Gohr                $subject = '';
6291d045709SAndreas Gohr            }
6301d045709SAndreas Gohr
6311d045709SAndreas Gohr            // make the body
6321d045709SAndreas Gohr            $body    = $this->prepareBody();
6331d045709SAndreas Gohr            if($body === 'false') return false;
6341d045709SAndreas Gohr
6351d045709SAndreas Gohr            // cook the headers
6361d045709SAndreas Gohr            $headers = $this->prepareHeaders();
63728d2ad80SAndreas Gohr            // add any headers set by legacy plugins
63828d2ad80SAndreas Gohr            if(trim($data['headers'])){
63928d2ad80SAndreas Gohr                $headers .= MAILHEADER_EOL.trim($data['headers']);
64028d2ad80SAndreas Gohr            }
6411d045709SAndreas Gohr
6421d045709SAndreas Gohr            // send the thing
6431d045709SAndreas Gohr            if(is_null($this->sendparam)){
64428d2ad80SAndreas Gohr                $success = @mail($to,$subject,$body,$headers);
6451d045709SAndreas Gohr            }else{
64628d2ad80SAndreas Gohr                $success = @mail($to,$subject,$body,$headers,$this->sendparam);
6471d045709SAndreas Gohr            }
6481d045709SAndreas Gohr        }
64928d2ad80SAndreas Gohr        // any AFTER actions?
65028d2ad80SAndreas Gohr        $evt->advise_after();
65128d2ad80SAndreas Gohr        return $success;
65228d2ad80SAndreas Gohr    }
653bb01c27cSAndreas Gohr}
654