PageRenderTime 150ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/inc/mail.php

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