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