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