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