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