xref: /dokuwiki/inc/mail.php (revision 96569d486b765a54033635135007a20bc4368868)
1ed7b5f09Sandi<?php
244f669e9Sandi/**
344f669e9Sandi * Mail functions
444f669e9Sandi *
544f669e9Sandi * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
644f669e9Sandi * @author     Andreas Gohr <andi@splitbrain.org>
744f669e9Sandi */
844f669e9Sandi
9fa8adffeSAndreas Gohrif(!defined('DOKU_INC')) die('meh.');
1044f669e9Sandi
1129f3a5faSAndreas Gohr// end of line for mail lines - RFC822 says CRLF but postfix (and other MTAs?)
1229f3a5faSAndreas Gohr// think different
1329f3a5faSAndreas Gohrif(!defined('MAILHEADER_EOL')) define('MAILHEADER_EOL',"\n");
14e1906e6eSandi#define('MAILHEADER_ASCIIONLY',1);
1544f669e9Sandi
1644f669e9Sandi/**
17d530a62aSAndreas Gohr * Patterns for use in email detection and validation
18d530a62aSAndreas Gohr *
19d530a62aSAndreas Gohr * NOTE: there is an unquoted '/' in RFC2822_ATEXT, it must remain unquoted to be used in the parser
20d530a62aSAndreas Gohr * the pattern uses non-capturing groups as captured groups aren't allowed in the parser
21d530a62aSAndreas Gohr * select pattern delimiters with care!
22d530a62aSAndreas Gohr *
23d530a62aSAndreas Gohr * May not be completly RFC conform!
24d530a62aSAndreas Gohr * @link http://www.faqs.org/rfcs/rfc2822.html (paras 3.4.1 & 3.2.4)
25d530a62aSAndreas Gohr *
26d530a62aSAndreas Gohr * @author Chris Smith <chris@jalakai.co.uk>
27d530a62aSAndreas Gohr * Check if a given mail address is valid
28d530a62aSAndreas Gohr */
29d530a62aSAndreas Gohrif (!defined('RFC2822_ATEXT')) define('RFC2822_ATEXT',"0-9a-zA-Z!#$%&'*+/=?^_`{|}~-");
30d530a62aSAndreas Gohrif (!defined('PREG_PATTERN_VALID_EMAIL')) define('PREG_PATTERN_VALID_EMAIL', '['.RFC2822_ATEXT.']+(?:\.['.RFC2822_ATEXT.']+)*@(?i:[0-9a-z][0-9a-z-]*\.)+(?i:[a-z]{2,4}|museum|travel)');
31d530a62aSAndreas Gohr
325ec3fefcSAndreas Gohr/**
335ec3fefcSAndreas Gohr * Prepare mailfrom replacement patterns
345ec3fefcSAndreas Gohr *
355ec3fefcSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
365ec3fefcSAndreas Gohr */
375ec3fefcSAndreas Gohrfunction mail_setup(){
385ec3fefcSAndreas Gohr    global $conf;
39609c41e4SElan Ruusamäe    global $USERINFO;
40d530a62aSAndreas Gohr
415ec3fefcSAndreas Gohr    $replace = array();
425ec3fefcSAndreas Gohr
43609c41e4SElan Ruusamäe    if(!empty($USERINFO['mail'])){
44609c41e4SElan Ruusamäe        $replace['@MAIL@'] = $USERINFO['mail'];
455ec3fefcSAndreas Gohr    }else{
46204d9c53SAndreas Gohr        $host = @parse_url(DOKU_URL,PHP_URL_HOST);
47204d9c53SAndreas Gohr        if(!$host) $host = 'example.com';
48204d9c53SAndreas Gohr        $replace['@MAIL@'] = 'noreply@'.$host;
495ec3fefcSAndreas Gohr    }
505ec3fefcSAndreas Gohr
515ec3fefcSAndreas Gohr    if(!empty($_SERVER['REMOTE_USER'])){
525ec3fefcSAndreas Gohr        $replace['@USER@'] = $_SERVER['REMOTE_USER'];
535ec3fefcSAndreas Gohr    }else{
545ec3fefcSAndreas Gohr        $replace['@USER@'] = 'noreply';
555ec3fefcSAndreas Gohr    }
565ec3fefcSAndreas Gohr
57609c41e4SElan Ruusamäe    if(!empty($USERINFO['name'])){
58609c41e4SElan Ruusamäe        $replace['@NAME@'] = $USERINFO['name'];
595ec3fefcSAndreas Gohr    }else{
605ec3fefcSAndreas Gohr        $replace['@NAME@'] = '';
615ec3fefcSAndreas Gohr    }
625ec3fefcSAndreas Gohr
635ec3fefcSAndreas Gohr    $conf['mailfrom'] = str_replace(array_keys($replace),
645ec3fefcSAndreas Gohr                                    array_values($replace),
655ec3fefcSAndreas Gohr                                    $conf['mailfrom']);
665ec3fefcSAndreas Gohr}
67d530a62aSAndreas Gohr
68d530a62aSAndreas Gohr/**
6944f669e9Sandi * UTF-8 autoencoding replacement for PHPs mail function
7044f669e9Sandi *
7144f669e9Sandi * Email address fields (To, From, Cc, Bcc can contain a textpart and an address
7244f669e9Sandi * like this: 'Andreas Gohr <andi@splitbrain.org>' - the text part is encoded
7344f669e9Sandi * automatically. You can seperate receivers by commas.
7444f669e9Sandi *
7544f669e9Sandi * @param string $to      Receiver of the mail (multiple seperated by commas)
7644f669e9Sandi * @param string $subject Mailsubject
7744f669e9Sandi * @param string $body    Messagebody
7844f669e9Sandi * @param string $from    Sender address
7944f669e9Sandi * @param string $cc      CarbonCopy receiver (multiple seperated by commas)
8044f669e9Sandi * @param string $bcc     BlindCarbonCopy receiver (multiple seperated by commas)
8144f669e9Sandi * @param string $headers Additional Headers (seperated by MAILHEADER_EOL
8244f669e9Sandi * @param string $params  Additonal Sendmail params (passed to mail())
8344f669e9Sandi *
8444f669e9Sandi * @author Andreas Gohr <andi@splitbrain.org>
8544f669e9Sandi * @see    mail()
8644f669e9Sandi */
8744f669e9Sandifunction mail_send($to, $subject, $body, $from='', $cc='', $bcc='', $headers=null, $params=null){
88348e3c03SChris Smith
891986aa9eSChris Smith    $message = compact('to','subject','body','from','cc','bcc','headers','params');
90348e3c03SChris Smith    return trigger_event('MAIL_MESSAGE_SEND',$message,'_mail_send_action');
911986aa9eSChris Smith}
921986aa9eSChris Smith
93348e3c03SChris Smithfunction _mail_send_action($data) {
94348e3c03SChris Smith
95348e3c03SChris Smith    // retrieve parameters from event data, $to, $subject, $body, $from, $cc, $bcc, $headers, $params
96348e3c03SChris Smith    $to = $data['to'];
97348e3c03SChris Smith    $subject = $data['subject'];
98348e3c03SChris Smith    $body = $data['body'];
99348e3c03SChris Smith
100348e3c03SChris Smith    // add robustness in case plugin removes any of these optional values
101348e3c03SChris Smith    $from = isset($data['from']) ? $data['from'] : '';
102348e3c03SChris Smith    $cc = isset($data['cc']) ? $data['cc'] : '';
103348e3c03SChris Smith    $bcc = isset($data['bcc']) ? $data['bcc'] : '';
104348e3c03SChris Smith    $headers = isset($data['headers']) ? $data['headers'] : null;
105348e3c03SChris Smith    $params = isset($data['params']) ? $data['params'] : null;
106348e3c03SChris Smith
107*96569d48SMatthias Schulte    // discard mail request if no recipients are available
108*96569d48SMatthias Schulte    if(trim($to) === '' && trim($cc) === '' && trim($bcc) === '') return false;
109*96569d48SMatthias Schulte
110348e3c03SChris Smith    // end additional code to support event ... original mail_send() code from here
111348e3c03SChris Smith
112e1906e6eSandi    if(defined('MAILHEADER_ASCIIONLY')){
113e1906e6eSandi        $subject = utf8_deaccent($subject);
114e1906e6eSandi        $subject = utf8_strip($subject);
115e1906e6eSandi    }
116e1906e6eSandi
117265f02e3SGuy Brand    if(!utf8_isASCII($subject)) {
1187e8e923fSAndreas Gohr        $enc_subj = '=?UTF-8?Q?'.mail_quotedprintable_encode($subject,0).'?=';
119265f02e3SGuy Brand        // Spaces must be encoded according to rfc2047. Use the "_" shorthand
120ddcd5ab6SKazutaka Miyasaka        $enc_subj = preg_replace('/ /', '_', $enc_subj);
1217e8e923fSAndreas Gohr
1227e8e923fSAndreas Gohr        // quoted printable has length restriction, use base64 if needed
1237e8e923fSAndreas Gohr        if(strlen($subject) > 74){
1247e8e923fSAndreas Gohr            $enc_subj = '=?UTF-8?B?'.base64_encode($subject).'?=';
1257e8e923fSAndreas Gohr        }
1267e8e923fSAndreas Gohr
1277e8e923fSAndreas Gohr        $subject = $enc_subj;
128265f02e3SGuy Brand    }
12944f669e9Sandi
13044f669e9Sandi    $header  = '';
131e1906e6eSandi
132f95e691eSAndreas Gohr    // No named recipients for To: in Windows (see FS#652)
133f95e691eSAndreas Gohr    $usenames = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? false : true;
134f95e691eSAndreas Gohr
135f95e691eSAndreas Gohr    $to = mail_encode_address($to,'',$usenames);
13644f669e9Sandi    $header .= mail_encode_address($from,'From');
13744f669e9Sandi    $header .= mail_encode_address($cc,'Cc');
13844f669e9Sandi    $header .= mail_encode_address($bcc,'Bcc');
13944f669e9Sandi    $header .= 'MIME-Version: 1.0'.MAILHEADER_EOL;
14044f669e9Sandi    $header .= 'Content-Type: text/plain; charset=UTF-8'.MAILHEADER_EOL;
14144f669e9Sandi    $header .= 'Content-Transfer-Encoding: quoted-printable'.MAILHEADER_EOL;
14244f669e9Sandi    $header .= $headers;
143e1906e6eSandi    $header  = trim($header);
14444f669e9Sandi
14544f669e9Sandi    $body = mail_quotedprintable_encode($body);
14644f669e9Sandi
147d7785cceSandi    if($params == null){
148d7785cceSandi        return @mail($to,$subject,$body,$header);
149d7785cceSandi    }else{
150e1906e6eSandi        return @mail($to,$subject,$body,$header,$params);
15144f669e9Sandi    }
152d7785cceSandi}
15344f669e9Sandi
15444f669e9Sandi/**
15544f669e9Sandi * Encodes an email address header
15644f669e9Sandi *
157e1906e6eSandi * Unicode characters will be deaccented and encoded
158e1906e6eSandi * quoted_printable for headers.
15944f669e9Sandi * Addresses may not contain Non-ASCII data!
16044f669e9Sandi *
16144f669e9Sandi * Example:
162a2021ad8Sandi *   mail_encode_address("föö <foo@bar.com>, me@somewhere.com","TBcc");
16344f669e9Sandi *
164f95e691eSAndreas Gohr * @param string  $string Multiple adresses separated by commas
165f95e691eSAndreas Gohr * @param string  $header Name of the header (To,Bcc,Cc,...)
166f95e691eSAndreas Gohr * @param boolean $names  Allow named Recipients?
16744f669e9Sandi */
168f95e691eSAndreas Gohrfunction mail_encode_address($string,$header='',$names=true){
16944f669e9Sandi    $headers = '';
1704b7f9e70STom N Harris    $parts = explode(',',$string);
17144f669e9Sandi    foreach ($parts as $part){
17244f669e9Sandi        $part = trim($part);
17344f669e9Sandi
17444f669e9Sandi        // parse address
17544f669e9Sandi        if(preg_match('#(.*?)<(.*?)>#',$part,$matches)){
17644f669e9Sandi            $text = trim($matches[1]);
17744f669e9Sandi            $addr = $matches[2];
17844f669e9Sandi        }else{
17944f669e9Sandi            $addr = $part;
18044f669e9Sandi        }
18144f669e9Sandi
18244f669e9Sandi        // skip empty ones
18344f669e9Sandi        if(empty($addr)){
18444f669e9Sandi            continue;
18544f669e9Sandi        }
18644f669e9Sandi
18744f669e9Sandi        // FIXME: is there a way to encode the localpart of a emailaddress?
18844f669e9Sandi        if(!utf8_isASCII($addr)){
18944f669e9Sandi            msg(htmlspecialchars("E-Mail address <$addr> is not ASCII"),-1);
19044f669e9Sandi            continue;
19144f669e9Sandi        }
19244f669e9Sandi
19344f669e9Sandi        if(!mail_isvalid($addr)){
19444f669e9Sandi            msg(htmlspecialchars("E-Mail address <$addr> is not valid"),-1);
19544f669e9Sandi            continue;
19644f669e9Sandi        }
19744f669e9Sandi
198a2021ad8Sandi        // text was given
199f95e691eSAndreas Gohr        if(!empty($text) && $names){
200a2021ad8Sandi            // add address quotes
201a2021ad8Sandi            $addr = "<$addr>";
20244f669e9Sandi
203e1906e6eSandi            if(defined('MAILHEADER_ASCIIONLY')){
204e1906e6eSandi                $text = utf8_deaccent($text);
205e1906e6eSandi                $text = utf8_strip($text);
206e1906e6eSandi            }
207e1906e6eSandi
20844f669e9Sandi            if(!utf8_isASCII($text)){
2090667123fSElan Ruusamäe                // put the quotes outside as in =?UTF-8?Q?"Elan Ruusam=C3=A4e"?= vs "=?UTF-8?Q?Elan Ruusam=C3=A4e?="
2100667123fSElan Ruusamäe                if (preg_match('/^"(.+)"$/', $text, $matches)) {
2110667123fSElan Ruusamäe                  $text = '"=?UTF-8?Q?'.mail_quotedprintable_encode($matches[1], 0).'?="';
2120667123fSElan Ruusamäe                } else {
21391275a65SAndreas Gohr                  $text = '=?UTF-8?Q?'.mail_quotedprintable_encode($text, 0).'?=';
21444f669e9Sandi                }
2150667123fSElan Ruusamäe                // additionally the space character should be encoded as =20 (or each
2160667123fSElan Ruusamäe                // word QP encoded separately).
2170667123fSElan Ruusamäe                // however this is needed only in mail headers, not globally in mail_quotedprintable_encode().
2180667123fSElan Ruusamäe                $text = str_replace(" ", "=20", $text);
2190667123fSElan Ruusamäe            }
220628e6ba7SAndreas Gohr        }else{
221628e6ba7SAndreas Gohr            $text = '';
22244f669e9Sandi        }
22344f669e9Sandi
2242300b3e6SAndreas Gohr        // add to header comma seperated
2252300b3e6SAndreas Gohr        if($headers != ''){
2262300b3e6SAndreas Gohr            $headers .= ',';
2272300b3e6SAndreas Gohr            if($header) $headers .= MAILHEADER_EOL.' '; // avoid overlong mail headers
2282300b3e6SAndreas Gohr        }
229ba36e50eSAndreas Gohr        $headers .= $text.' '.$addr;
230a2021ad8Sandi    }
231a2021ad8Sandi
232a2021ad8Sandi    if(empty($headers)) return null;
233a2021ad8Sandi
234a2021ad8Sandi    //if headername was given add it and close correctly
235a2021ad8Sandi    if($header) $headers = $header.': '.$headers.MAILHEADER_EOL;
236a2021ad8Sandi
23744f669e9Sandi    return $headers;
23844f669e9Sandi}
23944f669e9Sandi
24044f669e9Sandi/**
241e8f8d645SAndreas Gohr * Check if a given mail address is valid
24244f669e9Sandi *
24344f669e9Sandi * @param   string $email the address to check
24444f669e9Sandi * @return  bool          true if address is valid
24544f669e9Sandi */
24644f669e9Sandifunction mail_isvalid($email){
247e8f8d645SAndreas Gohr    $validator = new EmailAddressValidator;
24802700828SAndreas Gohr    $validator->allowLocalAddresses = true;
249e8f8d645SAndreas Gohr    return $validator->check_email_address($email);
25044f669e9Sandi}
25144f669e9Sandi
25244f669e9Sandi/**
25344f669e9Sandi * Quoted printable encoding
25444f669e9Sandi *
25591275a65SAndreas Gohr * @author umu <umuAThrz.tu-chemnitz.de>
25691275a65SAndreas Gohr * @link   http://www.php.net/manual/en/function.imap-8bit.php#61216
25744f669e9Sandi */
25891275a65SAndreas Gohrfunction mail_quotedprintable_encode($sText,$maxlen=74,$bEmulate_imap_8bit=true) {
25991275a65SAndreas Gohr    // split text into lines
26091275a65SAndreas Gohr    $aLines= preg_split("/(?:\r\n|\r|\n)/", $sText);
261db959ae3SAndreas Gohr    $cnt = count($aLines);
26291275a65SAndreas Gohr
263db959ae3SAndreas Gohr    for ($i=0;$i<$cnt;$i++) {
26491275a65SAndreas Gohr        $sLine =& $aLines[$i];
26591275a65SAndreas Gohr        if (strlen($sLine)===0) continue; // do nothing, if empty
26691275a65SAndreas Gohr
26791275a65SAndreas Gohr        $sRegExp = '/[^\x09\x20\x21-\x3C\x3E-\x7E]/e';
26891275a65SAndreas Gohr
26991275a65SAndreas Gohr        // imap_8bit encodes x09 everywhere, not only at lineends,
27091275a65SAndreas Gohr        // for EBCDIC safeness encode !"#$@[\]^`{|}~,
27191275a65SAndreas Gohr        // for complete safeness encode every character :)
27291275a65SAndreas Gohr        if ($bEmulate_imap_8bit)
27391275a65SAndreas Gohr            $sRegExp = '/[^\x20\x21-\x3C\x3E-\x7E]/e';
27491275a65SAndreas Gohr
27591275a65SAndreas Gohr        $sReplmt = 'sprintf( "=%02X", ord ( "$0" ) ) ;';
27691275a65SAndreas Gohr        $sLine = preg_replace( $sRegExp, $sReplmt, $sLine );
27791275a65SAndreas Gohr
27891275a65SAndreas Gohr        // encode x09,x20 at lineends
27991275a65SAndreas Gohr        {
28091275a65SAndreas Gohr            $iLength = strlen($sLine);
28191275a65SAndreas Gohr            $iLastChar = ord($sLine{$iLength-1});
28291275a65SAndreas Gohr
28391275a65SAndreas Gohr            //              !!!!!!!!
28491275a65SAndreas Gohr            // imap_8_bit does not encode x20 at the very end of a text,
28591275a65SAndreas Gohr            // here is, where I don't agree with imap_8_bit,
28691275a65SAndreas Gohr            // please correct me, if I'm wrong,
28791275a65SAndreas Gohr            // or comment next line for RFC2045 conformance, if you like
288db959ae3SAndreas Gohr            if (!($bEmulate_imap_8bit && ($i==count($aLines)-1))){
28991275a65SAndreas Gohr                if (($iLastChar==0x09)||($iLastChar==0x20)) {
29091275a65SAndreas Gohr                    $sLine{$iLength-1}='=';
29191275a65SAndreas Gohr                    $sLine .= ($iLastChar==0x09)?'09':'20';
29244f669e9Sandi                }
293db959ae3SAndreas Gohr            }
29491275a65SAndreas Gohr        }    // imap_8bit encodes x20 before chr(13), too
29591275a65SAndreas Gohr        // although IMHO not requested by RFC2045, why not do it safer :)
29691275a65SAndreas Gohr        // and why not encode any x20 around chr(10) or chr(13)
29791275a65SAndreas Gohr        if ($bEmulate_imap_8bit) {
29891275a65SAndreas Gohr            $sLine=str_replace(' =0D','=20=0D',$sLine);
29991275a65SAndreas Gohr            //$sLine=str_replace(' =0A','=20=0A',$sLine);
30091275a65SAndreas Gohr            //$sLine=str_replace('=0D ','=0D=20',$sLine);
30191275a65SAndreas Gohr            //$sLine=str_replace('=0A ','=0A=20',$sLine);
30244f669e9Sandi        }
30344f669e9Sandi
30491275a65SAndreas Gohr        // finally split into softlines no longer than $maxlen chars,
30591275a65SAndreas Gohr        // for even more safeness one could encode x09,x20
30691275a65SAndreas Gohr        // at the very first character of the line
30791275a65SAndreas Gohr        // and after soft linebreaks, as well,
30891275a65SAndreas Gohr        // but this wouldn't be caught by such an easy RegExp
30991275a65SAndreas Gohr        if($maxlen){
31091275a65SAndreas Gohr            preg_match_all( '/.{1,'.($maxlen - 2).'}([^=]{0,2})?/', $sLine, $aMatch );
3111a6a1c04SAndreas Gohr            $sLine = implode( '=' . MAILHEADER_EOL, $aMatch[0] ); // add soft crlf's
31291275a65SAndreas Gohr        }
31391275a65SAndreas Gohr    }
31491275a65SAndreas Gohr
31591275a65SAndreas Gohr    // join lines into text
3161a6a1c04SAndreas Gohr    return implode(MAILHEADER_EOL,$aLines);
31791275a65SAndreas Gohr}
31844f669e9Sandi
319