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