Explained how hooks now can get data, documented attachment hook and data
[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");
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
df15de21 111 /* Print all the needed RFC822 headers */
60994e13 112 function write822Header ($fp, $t, $c, $b, $subject, $more_headers) {
a7d75834 113 global $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
df15de21 114 global $data_dir, $username, $domain, $version, $useSendmail;
9949206d 115 global $default_charset, $HTTP_VIA, $HTTP_X_FORWARDED_FOR;
a5363806 116 global $REMOTE_HOST;
465db5d7 117
7b67334e 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
78e230b7 137 /* Encoding 8-bit characters and making from line */
7aaa81fc 138 $subject = sqStripSlashes(encodeHeader($subject));
7b67334e 139 if ($from == "")
140 $from = "<$from_addr>";
141 else
95de6c91 142 $from = "\"" . encodeHeader($from) . "\" <$from_addr>";
7b67334e 143
a7d75834 144 /* This creates an RFC 822 date */
7b67334e 145 $date = date("D, j M Y H:i:s ", mktime()) . timezone();
a7d75834 146
147 /* Create a message-id */
148 $message_id = "<" . $REMOTE_PORT . "." . $REMOTE_ADDR . ".";
a5363806 149 $message_id .= time() . ".squirrel@" . $SERVER_NAME .">";
7b67334e 150
151 /* Make an RFC822 Received: line */
a5363806 152 if (isset($REMOTE_HOST))
8a2848f0 153 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
a5363806 154 else
8a2848f0 155 $received_from = $REMOTE_ADDR;
a5363806 156
9949206d 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 }
a5363806 162
8a2848f0 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";
7b67334e 167
a7d75834 168 /* Insert the rest of the header fields */
169 $header .= "Message-ID: $message_id\r\n";
7b67334e 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
60994e13 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
7b67334e 183 if ($cc_list) {
184 $header .= "Cc: $cc_list\r\n"; // Who the CCs are
df15de21 185 }
7b67334e 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
f8308f16 200 $header .= "MIME-Version: 1.0\r\n";
7b67334e 201
202 if (isMultipart()) {
203 $header .= "Content-Type: multipart/mixed; boundary=\"";
204 $header .= mimeBoundary();
205 $header .= "\"\r\n";
206 } else {
17ce8467 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";
7b67334e 211 $header .= "Content-Transfer-Encoding: 8bit\r\n";
212 }
213 $header .= "\r\n"; // One blank line to separate header and body
df15de21 214
7b67334e 215 $headerlength = strlen($header);
216 }
217
218 // Write the header
219 fputs ($fp, $header);
df15de21 220
7b67334e 221 return $headerlength;
222 }
df15de21 223
7b67334e 224 // Send the body
225 function writeBody ($fp, $passedBody) {
17ce8467 226 global $default_charset;
227
7b67334e 228 $attachmentlength = 0;
229
df15de21 230 if (isMultipart()) {
7b67334e 231 $body = "--".mimeBoundary()."\r\n";
17ce8467 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
7b67334e 238 $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
7aaa81fc 239 $body .= sqStripSlashes($passedBody) . "\r\n";
7b67334e 240 fputs ($fp, $body);
241
6441f7c6 242 $attachmentlength = attachFiles($fp);
7b67334e 243
244 $postbody .= "\r\n--".mimeBoundary()."--\r\n\r\n";
245 fputs ($fp, $postbody);
df15de21 246 } else {
7aaa81fc 247 $body = sqStripSlashes($passedBody) . "\r\n";
7b67334e 248 fputs ($fp, $body);
249 $postbody = "\r\n";
250 fputs ($fp, $postbody);
df15de21 251 }
df15de21 252
7b67334e 253 return (strlen($body) + strlen($postbody) + $attachmentlength);
c99c5b31 254 }
465db5d7 255
c99c5b31 256 // Send mail using the sendmail command
60994e13 257 function sendSendmail($t, $c, $b, $subject, $body, $more_headers) {
c99c5b31 258 global $sendmail_path, $username, $domain;
7b67334e 259
6ebf8b30 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
c99c5b31 268 // open pipe to sendmail
6ebf8b30 269 $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), "w");
c99c5b31 270
60994e13 271 $headerlength = write822Header ($fp, $t, $c, $b, $subject, $more_headers);
7b67334e 272 $bodylength = writeBody($fp, $body);
465db5d7 273
274 pclose($fp);
7b67334e 275
0775b17f 276 return ($headerlength + $bodylength);
465db5d7 277 }
278
b8ea4ed6 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
60994e13 290 function sendSMTP($t, $c, $b, $subject, $body, $more_headers) {
356d7825 291 global $username, $domain, $version, $smtpServerAddress, $smtpPort,
28010579 292 $data_dir, $color;
7831268e 293
40ee9452 294 $to = parseAddrs($t);
295 $cc = parseAddrs($c);
296 $bcc = parseAddrs($b);
356d7825 297 $from_addr = getPref($data_dir, $username, "email_address");
298
3ed2faff 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
d3cdb279 328
c175e2e4 329 $smtpConnection = fsockopen($smtpServerAddress, $smtpPort, $errorNumber, $errorString);
b8ea4ed6 330 if (!$smtpConnection) {
331 echo "Error connecting to SMTP Server.<br>";
332 echo "$errorNumber : $errorString<br>";
333 exit;
334 }
f8a9394d 335 $tmp = fgets($smtpConnection, 1024);
336 errorCheck($tmp, $smtpConnection);
b8ea4ed6 337
40ee9452 338 $to_list = getLineOfAddrs($to);
339 $cc_list = getLineOfAddrs($cc);
340
341 /** Lets introduce ourselves */
3379d740 342 fputs($smtpConnection, "HELO $domain\r\n");
f8a9394d 343 $tmp = fgets($smtpConnection, 1024);
344 errorCheck($tmp, $smtpConnection);
7831268e 345
40ee9452 346 /** Ok, who is sending the message? */
3379d740 347 fputs($smtpConnection, "MAIL FROM:<$from_addr>\r\n");
f8a9394d 348 $tmp = fgets($smtpConnection, 1024);
349 errorCheck($tmp, $smtpConnection);
b8ea4ed6 350
40ee9452 351 /** send who the recipients are */
352 for ($i = 0; $i < count($to); $i++) {
3379d740 353 fputs($smtpConnection, "RCPT TO:<$to[$i]>\r\n");
f8a9394d 354 $tmp = fgets($smtpConnection, 1024);
355 errorCheck($tmp, $smtpConnection);
40ee9452 356 }
357 for ($i = 0; $i < count($cc); $i++) {
3379d740 358 fputs($smtpConnection, "RCPT TO:<$cc[$i]>\r\n");
f8a9394d 359 $tmp = fgets($smtpConnection, 1024);
360 errorCheck($tmp, $smtpConnection);
40ee9452 361 }
362 for ($i = 0; $i < count($bcc); $i++) {
3379d740 363 fputs($smtpConnection, "RCPT TO:<$bcc[$i]>\r\n");
f8a9394d 364 $tmp = fgets($smtpConnection, 1024);
365 errorCheck($tmp, $smtpConnection);
40ee9452 366 }
b8ea4ed6 367
40ee9452 368 /** Lets start sending the actual message */
3379d740 369 fputs($smtpConnection, "DATA\r\n");
f8a9394d 370 $tmp = fgets($smtpConnection, 1024);
371 errorCheck($tmp, $smtpConnection);
7831268e 372
7b67334e 373 // Send the message
60994e13 374 $headerlength = write822Header ($smtpConnection, $t, $c, $b, $subject, $more_headers);
7b67334e 375 $bodylength = writeBody($smtpConnection, $body);
7831268e 376
3379d740 377 fputs($smtpConnection, ".\r\n"); // end the DATA part
f8a9394d 378 $tmp = fgets($smtpConnection, 1024);
379 $num = errorCheck($tmp, $smtpConnection);
3021b626 380 if ($num != 250) {
f8a9394d 381 $tmp = nl2br(htmlspecialchars($tmp));
28010579 382 echo "ERROR<BR>Message not sent!<BR>Reason given: $tmp<BR></BODY></HTML>";
3021b626 383 }
d3cdb279 384
3379d740 385 fputs($smtpConnection, "QUIT\r\n"); // log off
78509c54 386
387 fclose($smtpConnection);
7b67334e 388
389 return ($headerlength + $bodylength);
b8ea4ed6 390 }
3021b626 391
392
f8a9394d 393 function errorCheck($line, $smtpConnection) {
776c7431 394 global $page_header_php;
28010579 395 global $color;
776c7431 396 if (!isset($page_header_php)) {
397 include "../functions/page_header.php";
398 }
399
f8a9394d 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
3021b626 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;
f8a9394d 481 default: $message = "Unknown response: ". nl2br(htmlspecialchars($lines));
3021b626 482 $status = 0;
483 $error_num = "001";
484 break;
485 }
486
487 if ($status == 0) {
776c7431 488 displayPageHeader($color, "None");
3021b626 489 echo "<TT>";
776c7431 490 echo "<br><b><font color=\"$color[1]\">ERROR</font></b><br><br>";
3021b626 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>";
f8a9394d 493 $lines = nl2br(htmlspecialchars($lines));
494 echo "<B>Server Response: </B>$lines<BR>";
3021b626 495 echo "<BR>MAIL NOT SENT";
496 echo "</TT></BODY></HTML>";
497 exit;
498 }
499 return $err_num;
500 }
df15de21 501
966286ae 502 function sendMessage($t, $c, $b, $subject, $body, $reply_id) {
503 global $useSendmail, $msg_id, $is_reply, $mailbox;
6441f7c6 504 global $data_dir, $username, $domain, $key, $version, $sent_folder, $imapServerAddress, $imapPort;
60994e13 505 $more_headers = Array();
d1b8b679 506
966286ae 507 $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 1);
60994e13 508
966286ae 509 if ($reply_id) {
510 sqimap_mailbox_select ($imap_stream, $mailbox);
511 sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, "Answered");
60994e13 512
c95df380 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);
966286ae 523 }
524
df15de21 525 if ($useSendmail==true) {
60994e13 526 $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers);
df15de21 527 } else {
60994e13 528 $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers);
df15de21 529 }
d1b8b679 530
2966f172 531 if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
532 sqimap_append ($imap_stream, $sent_folder, $length);
60994e13 533 write822Header ($imap_stream, $t, $c, $b, $subject, $more_headers);
2966f172 534 writeBody ($imap_stream, $body);
535 sqimap_append_done ($imap_stream);
536 }
1195c340 537 sqimap_logout($imap_stream);
a7d75834 538 // Delete the files uploaded for attaching (if any).
539 deleteAttachments();
df15de21 540 }
465db5d7 541?>