* Fixed typo when forwarding a message with attachments -- the attachment
[squirrelmail.git] / functions / smtp.php
CommitLineData
59177427 1<?php
b8ea4ed6 2 /** smtp.php
3 **
4 ** This contains all the functions needed to send messages through
36fa79c8 5 ** an smtp server or sendmail.
245a6892 6 **
7 ** $Id$
b8ea4ed6 8 **/
9
d068c0ec 10 $smtp_php = true;
a4102fd7 11 if (!isset($addressbook_php))
12 include('../functions/addressbook.php');
465db5d7 13
31afdefb 14 // This should most probably go to some initialization...
15 if (ereg("^([^@%/]+)[@%/](.+)$", $username, $usernamedata)) {
16 $popuser = $usernamedata[1];
17 $domain = $usernamedata[2];
18 unset($usernamedata);
19 } else {
20 $popuser = $username;
21 }
22 // We need domain for smtp
23 if (!$domain)
ec9f1c41 24 $domain = getenv('HOSTNAME');
31afdefb 25
df15de21 26 // Returns true only if this message is multipart
27 function isMultipart () {
4ba45d11 28 global $attachments;
29
30 if (count($attachments)>0)
31 return true;
32 else
33 return false;
df15de21 34 }
35
a4102fd7 36 // looks up aliases in the addressbook and expands them to
37 // the full address.
38 function expandAddrs ($array) {
39 $abook = addressbook_init();
40 for ($i=0; $i < count($array); $i++) {
41 $result = $abook->lookup($array[$i]);
42 $ret = "";
43 if (isset($result['email'])) {
44 if (isset($result['name'])) {
45 $ret = '"'.$result['name'].'" ';
46 }
47 $ret .= '<'.$result['email'].'>';
48 $array[$i] = $ret;
49 }
18e206dd 50 else
51 {
52 $array[$i] = '<' . $array[$i] . '>';
53 }
a4102fd7 54 }
55 return $array;
56 }
57
df15de21 58 // Attach the files that are due to be attached
4ba45d11 59 function attachFiles ($fp) {
c3c37167 60 global $attachments, $attachment_dir;
4ba45d11 61
7b67334e 62 $length = 0;
63
a7d75834 64 if (isMultipart()) {
f972eb46 65 foreach ($attachments as $info)
66 {
67 $filetype = $info['type'];
68 if ($filetype == '')
ec9f1c41 69 $filetype = 'application/octet-stream';
a7d75834 70
ec9f1c41 71 $header = '--'.mimeBoundary()."\r\n";
f972eb46 72 $header .= "Content-Type: $filetype; name=\"" .
73 $info['remotefilename'] . "\"\r\n";
74 $header .= "Content-Disposition: attachment; filename=\"" .
75 $info['remotefilename'] . "\"\r\n";
a7d75834 76 $header .= "Content-Transfer-Encoding: base64\r\n\r\n";
77 fputs ($fp, $header);
78 $length += strlen($header);
79
f972eb46 80 $file = fopen ($attachment_dir . $info['localfilename'], 'r');
a7d75834 81 while ($tmp = fread($file, 570)) {
82 $encoded = chunk_split(base64_encode($tmp));
83 $length += strlen($encoded);
84 fputs ($fp, $encoded);
85 }
86 fclose ($file);
7b67334e 87 }
4ba45d11 88 }
7b67334e 89
90 return $length;
df15de21 91 }
92
a7d75834 93 // Delete files that are uploaded for attaching
94 function deleteAttachments() {
95 global $attachments, $attachment_dir;
96
97 if (isMultipart()) {
98 reset($attachments);
99 while (list($localname, $remotename) = each($attachments)) {
100 if (!ereg ("\\/", $localname)) {
101 unlink ($attachment_dir.$localname);
ec9f1c41 102 unlink ($attachment_dir.$localname.'.info');
a7d75834 103 }
104 }
105 }
106 }
107
df15de21 108 // Return a nice MIME-boundary
109 function mimeBoundary () {
7b67334e 110 static $mimeBoundaryString;
df15de21 111
112 if ($mimeBoundaryString == "") {
ed865adf 113 $mimeBoundaryString = "----=_" .
fe53c3b9 114 GenerateRandomString(60, '\'()+,-./:=?_', 7);
465db5d7 115 }
df15de21 116
117 return $mimeBoundaryString;
465db5d7 118 }
119
24397423 120 /* Time offset for correct timezone */
121 function timezone () {
b0d1b51e 122 global $invert_time;
123
ec9f1c41 124 $diff_second = date('Z');
d47b2518 125 if ($invert_time)
126 $diff_second = - $diff_second;
24397423 127 if ($diff_second > 0)
ec9f1c41 128 $sign = '+';
24397423 129 else
ec9f1c41 130 $sign = '-';
24397423 131
132 $diff_second = abs($diff_second);
133
134 $diff_hour = floor ($diff_second / 3600);
135 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
136
ec9f1c41 137 $zonename = '('.strftime('%Z').')';
24397423 138 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute, $zonename);
139 return ($result);
140 }
141
df15de21 142 /* Print all the needed RFC822 headers */
60994e13 143 function write822Header ($fp, $t, $c, $b, $subject, $more_headers) {
a7d75834 144 global $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
31afdefb 145 global $data_dir, $username, $popuser, $domain, $version, $useSendmail;
9949206d 146 global $default_charset, $HTTP_VIA, $HTTP_X_FORWARDED_FOR;
a5363806 147 global $REMOTE_HOST;
465db5d7 148
7b67334e 149 // Storing the header to make sure the header is the same
150 // everytime the header is printed.
151 static $header, $headerlength;
152
ec9f1c41 153 if ($header == '') {
a4102fd7 154 $to = expandAddrs(parseAddrs($t));
155 $cc = expandAddrs(parseAddrs($c));
156 $bcc = expandAddrs(parseAddrs($b));
ec9f1c41 157 $reply_to = getPref($data_dir, $username, 'reply_to');
158 $from = getPref($data_dir, $username, 'full_name');
159 $from_addr = getPref($data_dir, $username, 'email_address');
31afdefb 160
ec9f1c41 161 if ($from_addr == '')
162 $from_addr = $popuser.'@'.$domain;
7b67334e 163
164 $to_list = getLineOfAddrs($to);
165 $cc_list = getLineOfAddrs($cc);
166 $bcc_list = getLineOfAddrs($bcc);
8ae331c2 167
78e230b7 168 /* Encoding 8-bit characters and making from line */
d51894be 169 $subject = encodeHeader($subject);
ec9f1c41 170 if ($from == '')
7b67334e 171 $from = "<$from_addr>";
172 else
ec9f1c41 173 $from = '"' . encodeHeader($from) . "\" <$from_addr>";
7b67334e 174
a7d75834 175 /* This creates an RFC 822 date */
7b67334e 176 $date = date("D, j M Y H:i:s ", mktime()) . timezone();
a7d75834 177
178 /* Create a message-id */
ec9f1c41 179 $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
180 $message_id .= time() . '.squirrel@' . $SERVER_NAME .'>';
7b67334e 181
182 /* Make an RFC822 Received: line */
a5363806 183 if (isset($REMOTE_HOST))
8a2848f0 184 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
a5363806 185 else
8a2848f0 186 $received_from = $REMOTE_ADDR;
a5363806 187
9949206d 188 if (isset($HTTP_VIA) || isset ($HTTP_X_FORWARDED_FOR)) {
ec9f1c41 189 if ($HTTP_X_FORWARDED_FOR == '')
190 $HTTP_X_FORWARDED_FOR = 'unknown';
9949206d 191 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
192 }
a5363806 193
8a2848f0 194 $header = "Received: from $received_from\r\n";
195 $header .= " (SquirrelMail authenticated user $username)\r\n";
196 $header .= " by $SERVER_NAME with HTTP;\r\n";
197 $header .= " $date\r\n";
7b67334e 198
a7d75834 199 /* Insert the rest of the header fields */
200 $header .= "Message-ID: $message_id\r\n";
7b67334e 201 $header .= "Date: $date\r\n";
202 $header .= "Subject: $subject\r\n";
203 $header .= "From: $from\r\n";
18e206dd 204 $header .= "To: $to_list\r\n"; // Who it's TO
60994e13 205
206 /* Insert headers from the $more_headers array */
207 if(is_array($more_headers)) {
208 reset($more_headers);
209 while(list($h_name, $h_val) = each($more_headers)) {
210 $header .= sprintf("%s: %s\r\n", $h_name, $h_val);
211 }
212 }
213
7b67334e 214 if ($cc_list) {
215 $header .= "Cc: $cc_list\r\n"; // Who the CCs are
df15de21 216 }
7b67334e 217
ec9f1c41 218 if ($reply_to != '')
7b67334e 219 $header .= "Reply-To: $reply_to\r\n";
220
221 if ($useSendmail) {
222 if ($bcc_list) {
223 // BCCs is removed from header by sendmail
224 $header .= "Bcc: $bcc_list\r\n";
225 }
226 }
227
228 $header .= "X-Mailer: SquirrelMail (version $version)\r\n"; // Identify SquirrelMail
229
230 // Do the MIME-stuff
f8308f16 231 $header .= "MIME-Version: 1.0\r\n";
7b67334e 232
233 if (isMultipart()) {
ec9f1c41 234 $header .= 'Content-Type: multipart/mixed; boundary="';
7b67334e 235 $header .= mimeBoundary();
236 $header .= "\"\r\n";
237 } else {
ec9f1c41 238 if ($default_charset != '')
17ce8467 239 $header .= "Content-Type: text/plain; charset=$default_charset\r\n";
240 else
241 $header .= "Content-Type: text/plain;\r\n";
7b67334e 242 $header .= "Content-Transfer-Encoding: 8bit\r\n";
243 }
244 $header .= "\r\n"; // One blank line to separate header and body
df15de21 245
7b67334e 246 $headerlength = strlen($header);
247 }
248
249 // Write the header
250 fputs ($fp, $header);
df15de21 251
7b67334e 252 return $headerlength;
253 }
df15de21 254
7b67334e 255 // Send the body
256 function writeBody ($fp, $passedBody) {
17ce8467 257 global $default_charset;
258
7b67334e 259 $attachmentlength = 0;
260
df15de21 261 if (isMultipart()) {
ec9f1c41 262 $body = '--'.mimeBoundary()."\r\n";
17ce8467 263
264 if ($default_charset != "")
265 $body .= "Content-Type: text/plain; charset=$default_charset\r\n";
266 else
267 $body .= "Content-Type: text/plain\r\n";
268
7b67334e 269 $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
d51894be 270 $body .= $passedBody . "\r\n\r\n";
7b67334e 271 fputs ($fp, $body);
272
6441f7c6 273 $attachmentlength = attachFiles($fp);
7b67334e 274
f8cfeb5c 275 if (!isset($postbody)) $postbody = "";
7b67334e 276 $postbody .= "\r\n--".mimeBoundary()."--\r\n\r\n";
277 fputs ($fp, $postbody);
df15de21 278 } else {
d51894be 279 $body = $passedBody . "\r\n";
7b67334e 280 fputs ($fp, $body);
281 $postbody = "\r\n";
282 fputs ($fp, $postbody);
df15de21 283 }
df15de21 284
7b67334e 285 return (strlen($body) + strlen($postbody) + $attachmentlength);
c99c5b31 286 }
465db5d7 287
c99c5b31 288 // Send mail using the sendmail command
60994e13 289 function sendSendmail($t, $c, $b, $subject, $body, $more_headers) {
31afdefb 290 global $sendmail_path, $popuser, $username, $domain;
7b67334e 291
6ebf8b30 292 // Build envelope sender address. Make sure it doesn't contain
293 // spaces or other "weird" chars that would allow a user to
294 // exploit the shell/pipe it is used in.
31afdefb 295 $envelopefrom = "$popuser@$domain";
ec9f1c41 296 $envelopefrom = ereg_replace("[[:blank:]]",'', $envelopefrom);
297 $envelopefrom = ereg_replace("[[:space:]]",'', $envelopefrom);
298 $envelopefrom = ereg_replace("[[:cntrl:]]",'', $envelopefrom);
6ebf8b30 299
c99c5b31 300 // open pipe to sendmail
ec9f1c41 301 $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), 'w');
c99c5b31 302
60994e13 303 $headerlength = write822Header ($fp, $t, $c, $b, $subject, $more_headers);
7b67334e 304 $bodylength = writeBody($fp, $body);
465db5d7 305
306 pclose($fp);
7b67334e 307
0775b17f 308 return ($headerlength + $bodylength);
465db5d7 309 }
310
b8ea4ed6 311 function smtpReadData($smtpConnection) {
312 $read = fgets($smtpConnection, 1024);
313 $counter = 0;
314 while ($read) {
ec9f1c41 315 echo $read . '<BR>';
b8ea4ed6 316 $data[$counter] = $read;
317 $read = fgets($smtpConnection, 1024);
318 $counter++;
319 }
320 }
321
60994e13 322 function sendSMTP($t, $c, $b, $subject, $body, $more_headers) {
31afdefb 323 global $username, $popuser, $domain, $version, $smtpServerAddress, $smtpPort,
28010579 324 $data_dir, $color;
7831268e 325
a4102fd7 326 $to = expandAddrs(parseAddrs($t));
327 $cc = expandAddrs(parseAddrs($c));
328 $bcc = expandAddrs(parseAddrs($b));
ec9f1c41 329 $from_addr = getPref($data_dir, $username, 'email_address');
356d7825 330
31afdefb 331 if (!$from_addr)
332 $from_addr = "$popuser@$domain";
d3cdb279 333
c175e2e4 334 $smtpConnection = fsockopen($smtpServerAddress, $smtpPort, $errorNumber, $errorString);
b8ea4ed6 335 if (!$smtpConnection) {
ec9f1c41 336 echo 'Error connecting to SMTP Server.<br>';
b8ea4ed6 337 echo "$errorNumber : $errorString<br>";
338 exit;
339 }
f8a9394d 340 $tmp = fgets($smtpConnection, 1024);
341 errorCheck($tmp, $smtpConnection);
b8ea4ed6 342
40ee9452 343 $to_list = getLineOfAddrs($to);
344 $cc_list = getLineOfAddrs($cc);
345
346 /** Lets introduce ourselves */
3379d740 347 fputs($smtpConnection, "HELO $domain\r\n");
f8a9394d 348 $tmp = fgets($smtpConnection, 1024);
349 errorCheck($tmp, $smtpConnection);
7831268e 350
40ee9452 351 /** Ok, who is sending the message? */
f89627f3 352 fputs($smtpConnection, "MAIL FROM: <$from_addr>\r\n");
f8a9394d 353 $tmp = fgets($smtpConnection, 1024);
354 errorCheck($tmp, $smtpConnection);
b8ea4ed6 355
40ee9452 356 /** send who the recipients are */
357 for ($i = 0; $i < count($to); $i++) {
18e206dd 358 fputs($smtpConnection, "RCPT TO: $to[$i]\r\n");
f8a9394d 359 $tmp = fgets($smtpConnection, 1024);
360 errorCheck($tmp, $smtpConnection);
40ee9452 361 }
362 for ($i = 0; $i < count($cc); $i++) {
b4338e67 363 fputs($smtpConnection, "RCPT TO: $cc[$i]\r\n");
f8a9394d 364 $tmp = fgets($smtpConnection, 1024);
365 errorCheck($tmp, $smtpConnection);
40ee9452 366 }
367 for ($i = 0; $i < count($bcc); $i++) {
b4338e67 368 fputs($smtpConnection, "RCPT TO: $bcc[$i]\r\n");
f8a9394d 369 $tmp = fgets($smtpConnection, 1024);
370 errorCheck($tmp, $smtpConnection);
40ee9452 371 }
b8ea4ed6 372
40ee9452 373 /** Lets start sending the actual message */
3379d740 374 fputs($smtpConnection, "DATA\r\n");
f8a9394d 375 $tmp = fgets($smtpConnection, 1024);
376 errorCheck($tmp, $smtpConnection);
7831268e 377
7b67334e 378 // Send the message
60994e13 379 $headerlength = write822Header ($smtpConnection, $t, $c, $b, $subject, $more_headers);
7b67334e 380 $bodylength = writeBody($smtpConnection, $body);
7831268e 381
3379d740 382 fputs($smtpConnection, ".\r\n"); // end the DATA part
f8a9394d 383 $tmp = fgets($smtpConnection, 1024);
384 $num = errorCheck($tmp, $smtpConnection);
3021b626 385 if ($num != 250) {
f8a9394d 386 $tmp = nl2br(htmlspecialchars($tmp));
28010579 387 echo "ERROR<BR>Message not sent!<BR>Reason given: $tmp<BR></BODY></HTML>";
3021b626 388 }
d3cdb279 389
3379d740 390 fputs($smtpConnection, "QUIT\r\n"); // log off
78509c54 391
392 fclose($smtpConnection);
7b67334e 393
394 return ($headerlength + $bodylength);
b8ea4ed6 395 }
3021b626 396
397
f8a9394d 398 function errorCheck($line, $smtpConnection) {
776c7431 399 global $page_header_php;
28010579 400 global $color;
776c7431 401 if (!isset($page_header_php)) {
ec9f1c41 402 include '../functions/page_header.php';
776c7431 403 }
404
f8a9394d 405 // Read new lines on a multiline response
406 $lines = $line;
407 while(ereg("^[0-9]+-", $line)) {
408 $line = fgets($smtpConnection, 1024);
409 $lines .= $line;
410 }
411
3021b626 412 // Status: 0 = fatal
413 // 5 = ok
414
415 $err_num = substr($line, 0, strpos($line, " "));
416 switch ($err_num) {
ec9f1c41 417 case 500: $message = 'Syntax error; command not recognized';
3021b626 418 $status = 0;
419 break;
ec9f1c41 420 case 501: $message = 'Syntax error in parameters or arguments';
3021b626 421 $status = 0;
422 break;
ec9f1c41 423 case 502: $message = 'Command not implemented';
3021b626 424 $status = 0;
425 break;
ec9f1c41 426 case 503: $message = 'Bad sequence of commands';
3021b626 427 $status = 0;
428 break;
ec9f1c41 429 case 504: $message = 'Command parameter not implemented';
3021b626 430 $status = 0;
431 break;
432
433
ec9f1c41 434 case 211: $message = 'System status, or system help reply';
3021b626 435 $status = 5;
436 break;
ec9f1c41 437 case 214: $message = 'Help message';
3021b626 438 $status = 5;
439 break;
440
441
ec9f1c41 442 case 220: $message = 'Service ready';
3021b626 443 $status = 5;
444 break;
ec9f1c41 445 case 221: $message = 'Service closing transmission channel';
3021b626 446 $status = 5;
447 break;
ec9f1c41 448 case 421: $message = 'Service not available, closing chanel';
3021b626 449 $status = 0;
450 break;
451
452
ec9f1c41 453 case 250: $message = 'Requested mail action okay, completed';
3021b626 454 $status = 5;
455 break;
ec9f1c41 456 case 251: $message = 'User not local; will forward';
3021b626 457 $status = 5;
458 break;
ec9f1c41 459 case 450: $message = 'Requested mail action not taken: mailbox unavailable';
3021b626 460 $status = 0;
461 break;
ec9f1c41 462 case 550: $message = 'Requested action not taken: mailbox unavailable';
3021b626 463 $status = 0;
464 break;
ec9f1c41 465 case 451: $message = 'Requested action aborted: error in processing';
3021b626 466 $status = 0;
467 break;
ec9f1c41 468 case 551: $message = 'User not local; please try forwarding';
3021b626 469 $status = 0;
470 break;
ec9f1c41 471 case 452: $message = 'Requested action not taken: insufficient system storage';
3021b626 472 $status = 0;
473 break;
ec9f1c41 474 case 552: $message = 'Requested mail action aborted: exceeding storage allocation';
3021b626 475 $status = 0;
476 break;
ec9f1c41 477 case 553: $message = 'Requested action not taken: mailbox name not allowed';
3021b626 478 $status = 0;
479 break;
ec9f1c41 480 case 354: $message = 'Start mail input; end with .';
3021b626 481 $status = 5;
482 break;
ec9f1c41 483 case 554: $message = 'Transaction failed';
3021b626 484 $status = 0;
485 break;
434666c7 486 default: $message = 'Unknown response: '. nl2br(htmlspecialchars($lines));
3021b626 487 $status = 0;
ec9f1c41 488 $error_num = '001';
3021b626 489 break;
490 }
491
492 if ($status == 0) {
ec9f1c41 493 displayPageHeader($color, 'None');
494 echo '<TT>';
776c7431 495 echo "<br><b><font color=\"$color[1]\">ERROR</font></b><br><br>";
3021b626 496 echo "&nbsp;&nbsp;&nbsp;<B>Error Number: </B>$err_num<BR>";
497 echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<B>Reason: </B>$message<BR>";
f8a9394d 498 $lines = nl2br(htmlspecialchars($lines));
499 echo "<B>Server Response: </B>$lines<BR>";
ec9f1c41 500 echo '<BR>MAIL NOT SENT';
501 echo '</TT></BODY></HTML>';
3021b626 502 exit;
503 }
504 return $err_num;
505 }
df15de21 506
966286ae 507 function sendMessage($t, $c, $b, $subject, $body, $reply_id) {
508 global $useSendmail, $msg_id, $is_reply, $mailbox;
6441f7c6 509 global $data_dir, $username, $domain, $key, $version, $sent_folder, $imapServerAddress, $imapPort;
60994e13 510 $more_headers = Array();
d1b8b679 511
966286ae 512 $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 1);
60994e13 513
214e1343 514 if (isset($reply_id) && $reply_id) {
966286ae 515 sqimap_mailbox_select ($imap_stream, $mailbox);
ec9f1c41 516 sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, 'Answered');
60994e13 517
c95df380 518 // Insert In-Reply-To and References headers if the
519 // message-id of the message we reply to is set (longer than "<>")
520 // The References header should really be the old Referenced header
521 // with the message ID appended, but it can be only the message ID too.
522 $hdr = sqimap_get_small_header ($imap_stream, $reply_id, false);
523 if(strlen($hdr->message_id) > 2) {
ec9f1c41 524 $more_headers['In-Reply-To'] = $hdr->message_id;
525 $more_headers['References'] = $hdr->message_id;
c95df380 526 }
966286ae 527 }
8ae331c2 528
af8eba43 529 // In order to remove the problem of users not able to create
530 // messages with "." on a blank line, RFC821 has made provision
531 // in section 4.5.2 (Transparency).
146e0c45 532 $body = ereg_replace("\n\\.", "\n..", $body);
533 $body = ereg_replace("^\\.", "..", $body);
af8eba43 534
8ae331c2 535 // this is to catch all plain \n instances and
536 // replace them with \r\n.
537 $body = ereg_replace("\r\n", "\n", $body);
538 $body = ereg_replace("\n", "\r\n", $body);
3a8c414d 539
8ae331c2 540 if ($useSendmail) {
60994e13 541 $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers);
df15de21 542 } else {
60994e13 543 $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers);
df15de21 544 }
d1b8b679 545
2966f172 546 if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
547 sqimap_append ($imap_stream, $sent_folder, $length);
60994e13 548 write822Header ($imap_stream, $t, $c, $b, $subject, $more_headers);
8ae331c2 549 writeBody ($imap_stream, $body);
2966f172 550 sqimap_append_done ($imap_stream);
8ae331c2 551 }
552 sqimap_logout($imap_stream);
a7d75834 553 // Delete the files uploaded for attaching (if any).
f972eb46 554 ClearAttachments();
df15de21 555 }
8ae331c2 556
434666c7 557?>