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