xref: /dokuwiki/inc/mail.php (revision ba6984cf400bde3cbdd7e1f203602cb0d04eb7d2)
1<?php
2/**
3 * Mail functions
4 *
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author     Andreas Gohr <andi@splitbrain.org>
7 */
8
9if(!defined('DOKU_INC')) die('meh.');
10
11// end of line for mail lines - RFC822 says CRLF but postfix (and other MTAs?)
12// think different
13if(!defined('MAILHEADER_EOL')) define('MAILHEADER_EOL',"\n");
14if(!defined('QUOTEDPRINTABLE_EOL')) define('QUOTEDPRINTABLE_EOL',"\015\012");
15#define('MAILHEADER_ASCIIONLY',1);
16
17/**
18 * Patterns for use in email detection and validation
19 *
20 * NOTE: there is an unquoted '/' in RFC2822_ATEXT, it must remain unquoted to be used in the parser
21 * the pattern uses non-capturing groups as captured groups aren't allowed in the parser
22 * select pattern delimiters with care!
23 *
24 * May not be completly RFC conform!
25 * @link http://www.faqs.org/rfcs/rfc2822.html (paras 3.4.1 & 3.2.4)
26 *
27 * @author Chris Smith <chris@jalakai.co.uk>
28 * Check if a given mail address is valid
29 */
30if (!defined('RFC2822_ATEXT')) define('RFC2822_ATEXT',"0-9a-zA-Z!#$%&'*+/=?^_`{|}~-");
31if (!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)');
32
33/**
34 * Prepare mailfrom replacement patterns
35 *
36 * @author Andreas Gohr <andi@splitbrain.org>
37 */
38function mail_setup(){
39    global $conf;
40    global $INFO;
41
42    $replace = array();
43
44    if(!empty($INFO['userinfo']['mail'])){
45        $replace['@MAIL@'] = $INFO['userinfo']['mail'];
46    }else{
47        $replace['@MAIL@'] = 'noreply@'.parse_url(DOKU_URL,PHP_URL_HOST);
48    }
49
50    if(!empty($_SERVER['REMOTE_USER'])){
51        $replace['@USER@'] = $_SERVER['REMOTE_USER'];
52    }else{
53        $replace['@USER@'] = 'noreply';
54    }
55
56    if(!empty($INFO['userinfo']['name'])){
57        $replace['@NAME@'] = $INFO['userinfo']['name'];
58    }else{
59        $replace['@NAME@'] = '';
60    }
61
62    $conf['mailfrom'] = str_replace(array_keys($replace),
63                                    array_values($replace),
64                                    $conf['mailfrom']);
65}
66
67/**
68 * UTF-8 autoencoding replacement for PHPs mail function
69 *
70 * Email address fields (To, From, Cc, Bcc can contain a textpart and an address
71 * like this: 'Andreas Gohr <andi@splitbrain.org>' - the text part is encoded
72 * automatically. You can seperate receivers by commas.
73 *
74 * @param string $to      Receiver of the mail (multiple seperated by commas)
75 * @param string $subject Mailsubject
76 * @param string $body    Messagebody
77 * @param string $from    Sender address
78 * @param string $cc      CarbonCopy receiver (multiple seperated by commas)
79 * @param string $bcc     BlindCarbonCopy receiver (multiple seperated by commas)
80 * @param string $headers Additional Headers (seperated by MAILHEADER_EOL
81 * @param string $params  Additonal Sendmail params (passed to mail())
82 *
83 * @author Andreas Gohr <andi@splitbrain.org>
84 * @see    mail()
85 */
86function mail_send($to, $subject, $body, $from='', $cc='', $bcc='', $headers=null, $params=null){
87
88    $message = compact('to','subject','body','from','cc','bcc','headers','params');
89    return trigger_event('MAIL_MESSAGE_SEND',$message,'_mail_send_action');
90}
91
92function _mail_send_action($data) {
93
94    // retrieve parameters from event data, $to, $subject, $body, $from, $cc, $bcc, $headers, $params
95    $to = $data['to'];
96    $subject = $data['subject'];
97    $body = $data['body'];
98
99    // add robustness in case plugin removes any of these optional values
100    $from = isset($data['from']) ? $data['from'] : '';
101    $cc = isset($data['cc']) ? $data['cc'] : '';
102    $bcc = isset($data['bcc']) ? $data['bcc'] : '';
103    $headers = isset($data['headers']) ? $data['headers'] : null;
104    $params = isset($data['params']) ? $data['params'] : null;
105
106    // end additional code to support event ... original mail_send() code from here
107
108    if(defined('MAILHEADER_ASCIIONLY')){
109        $subject = utf8_deaccent($subject);
110        $subject = utf8_strip($subject);
111    }
112
113    if(!utf8_isASCII($subject)) {
114        $subject = '=?UTF-8?Q?'.mail_quotedprintable_encode($subject,0).'?=';
115        // Spaces must be encoded according to rfc2047. Use the "_" shorthand
116        $subject = preg_replace('/ /', '_', $subject);
117    }
118
119    $header  = '';
120
121    // No named recipients for To: in Windows (see FS#652)
122    $usenames = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? false : true;
123
124    $to = mail_encode_address($to,'',$usenames);
125    $header .= mail_encode_address($from,'From');
126    $header .= mail_encode_address($cc,'Cc');
127    $header .= mail_encode_address($bcc,'Bcc');
128    $header .= 'MIME-Version: 1.0'.MAILHEADER_EOL;
129    $header .= 'Content-Type: text/plain; charset=UTF-8'.MAILHEADER_EOL;
130    $header .= 'Content-Transfer-Encoding: quoted-printable'.MAILHEADER_EOL;
131    $header .= $headers;
132    $header  = trim($header);
133
134    $body = mail_quotedprintable_encode($body);
135
136    if($params == null){
137        return @mail($to,$subject,$body,$header);
138    }else{
139        return @mail($to,$subject,$body,$header,$params);
140    }
141}
142
143/**
144 * Encodes an email address header
145 *
146 * Unicode characters will be deaccented and encoded
147 * quoted_printable for headers.
148 * Addresses may not contain Non-ASCII data!
149 *
150 * Example:
151 *   mail_encode_address("föö <foo@bar.com>, me@somewhere.com","TBcc");
152 *
153 * @param string  $string Multiple adresses separated by commas
154 * @param string  $header Name of the header (To,Bcc,Cc,...)
155 * @param boolean $names  Allow named Recipients?
156 */
157function mail_encode_address($string,$header='',$names=true){
158    $headers = '';
159    $parts = explode(',',$string);
160    foreach ($parts as $part){
161        $part = trim($part);
162
163        // parse address
164        if(preg_match('#(.*?)<(.*?)>#',$part,$matches)){
165            $text = trim($matches[1]);
166            $addr = $matches[2];
167        }else{
168            $addr = $part;
169        }
170
171        // skip empty ones
172        if(empty($addr)){
173            continue;
174        }
175
176        // FIXME: is there a way to encode the localpart of a emailaddress?
177        if(!utf8_isASCII($addr)){
178            msg(htmlspecialchars("E-Mail address <$addr> is not ASCII"),-1);
179            continue;
180        }
181
182        if(!mail_isvalid($addr)){
183            msg(htmlspecialchars("E-Mail address <$addr> is not valid"),-1);
184            continue;
185        }
186
187        // text was given
188        if(!empty($text) && $names){
189            // add address quotes
190            $addr = "<$addr>";
191
192            if(defined('MAILHEADER_ASCIIONLY')){
193                $text = utf8_deaccent($text);
194                $text = utf8_strip($text);
195            }
196
197            if(!utf8_isASCII($text)){
198                $text = '=?UTF-8?Q?'.mail_quotedprintable_encode($text,0).'?=';
199            }
200        }else{
201            $text = '';
202        }
203
204        // add to header comma seperated
205        if($headers != ''){
206            $headers .= ',';
207            if($header) $headers .= MAILHEADER_EOL.' '; // avoid overlong mail headers
208        }
209        $headers .= $text.' '.$addr;
210    }
211
212    if(empty($headers)) return null;
213
214    //if headername was given add it and close correctly
215    if($header) $headers = $header.': '.$headers.MAILHEADER_EOL;
216
217    return $headers;
218}
219
220/**
221 * Check if a given mail address is valid
222 *
223 * @param   string $email the address to check
224 * @return  bool          true if address is valid
225 */
226function mail_isvalid($email){
227    $validator = new EmailAddressValidator;
228    return $validator->check_email_address($email);
229}
230
231/**
232 * Quoted printable encoding
233 *
234 * @author umu <umuAThrz.tu-chemnitz.de>
235 * @link   http://www.php.net/manual/en/function.imap-8bit.php#61216
236 */
237function mail_quotedprintable_encode($sText,$maxlen=74,$bEmulate_imap_8bit=true) {
238    // split text into lines
239    $aLines= preg_split("/(?:\r\n|\r|\n)/", $sText);
240    $cnt = count($aLines);
241
242    for ($i=0;$i<$cnt;$i++) {
243        $sLine =& $aLines[$i];
244        if (strlen($sLine)===0) continue; // do nothing, if empty
245
246        $sRegExp = '/[^\x09\x20\x21-\x3C\x3E-\x7E]/e';
247
248        // imap_8bit encodes x09 everywhere, not only at lineends,
249        // for EBCDIC safeness encode !"#$@[\]^`{|}~,
250        // for complete safeness encode every character :)
251        if ($bEmulate_imap_8bit)
252            $sRegExp = '/[^\x20\x21-\x3C\x3E-\x7E]/e';
253
254        $sReplmt = 'sprintf( "=%02X", ord ( "$0" ) ) ;';
255        $sLine = preg_replace( $sRegExp, $sReplmt, $sLine );
256
257        // encode x09,x20 at lineends
258        {
259            $iLength = strlen($sLine);
260            $iLastChar = ord($sLine{$iLength-1});
261
262            //              !!!!!!!!
263            // imap_8_bit does not encode x20 at the very end of a text,
264            // here is, where I don't agree with imap_8_bit,
265            // please correct me, if I'm wrong,
266            // or comment next line for RFC2045 conformance, if you like
267            if (!($bEmulate_imap_8bit && ($i==count($aLines)-1))){
268                if (($iLastChar==0x09)||($iLastChar==0x20)) {
269                    $sLine{$iLength-1}='=';
270                    $sLine .= ($iLastChar==0x09)?'09':'20';
271                }
272            }
273        }    // imap_8bit encodes x20 before chr(13), too
274        // although IMHO not requested by RFC2045, why not do it safer :)
275        // and why not encode any x20 around chr(10) or chr(13)
276        if ($bEmulate_imap_8bit) {
277            $sLine=str_replace(' =0D','=20=0D',$sLine);
278            //$sLine=str_replace(' =0A','=20=0A',$sLine);
279            //$sLine=str_replace('=0D ','=0D=20',$sLine);
280            //$sLine=str_replace('=0A ','=0A=20',$sLine);
281        }
282
283        // finally split into softlines no longer than $maxlen chars,
284        // for even more safeness one could encode x09,x20
285        // at the very first character of the line
286        // and after soft linebreaks, as well,
287        // but this wouldn't be caught by such an easy RegExp
288        if($maxlen){
289            preg_match_all( '/.{1,'.($maxlen - 2).'}([^=]{0,2})?/', $sLine, $aMatch );
290            $sLine = implode( '=' . QUOTEDPRINTABLE_EOL, $aMatch[0] ); // add soft crlf's
291        }
292    }
293
294    // join lines into text
295    return implode(QUOTEDPRINTABLE_EOL,$aLines);
296}
297
298