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