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