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