added patch from feature request to use getFrom function.
[squirrelmail.git] / functions / smtp.php
CommitLineData
59177427 1<?php
2ba13803 2
35586184 3/**
4 * smtp.php
5 *
15e6162e 6 * Copyright (c) 1999-2002 The SquirrelMail Project Team
35586184 7 * Licensed under the GNU GPL. For full terms see the file COPYING.
8 *
9 * This contains all the functions needed to send messages through
10 * an smtp server or sendmail.
11 *
12 * $Id$
13 */
b8ea4ed6 14
35586184 15require_once('../functions/addressbook.php');
16require_once('../functions/plugin.php');
3392dc86 17require_once('../functions/prefs.php');
35586184 18
19global $username, $popuser, $domain;
465db5d7 20
a1e937bb 21/* This should most probably go to some initialization... */
e25c2bd3 22if (ereg("^([^@%/]+)[@%/](.+)$", $username, $usernamedata)) {
23 $popuser = $usernamedata[1];
24 $domain = $usernamedata[2];
25 unset($usernamedata);
26} else {
27 $popuser = $username;
28}
a1e937bb 29/* We need domain for smtp */
30if (!$domain) {
e25c2bd3 31 $domain = getenv('HOSTNAME');
a1e937bb 32}
e25c2bd3 33
a1e937bb 34/* Returns true only if this message is multipart */
dd7766e0 35function isMultipart ($session) {
e25c2bd3 36 global $attachments;
7622a204 37
38 foreach ($attachments as $info) {
a3fbf5a4 39 if ($info['session'] == $session) {
40 return true;
41 }
a1e937bb 42 }
7622a204 43 return false;
e25c2bd3 44}
45
a1e937bb 46/* looks up aliases in the addressbook and expands them to
47 * the full address.
48 *
49 * Adds @$domain if it wasn't in the address book and if it
50 * doesn't have an @ symbol in it
51 */
e25c2bd3 52function expandAddrs ($array) {
53 global $domain;
54
a1e937bb 55 /* don't show errors -- kinda critical that we don't see
56 * them here since the redirect won't work if we do show them
57 */
68444892 58 $abook = addressbook_init(false, true);
e25c2bd3 59 for ($i=0; $i < count($array); $i++) {
60 $result = $abook->lookup($array[$i]);
61 $ret = "";
62 if (isset($result['email'])) {
a4102fd7 63 if (isset($result['name'])) {
e25c2bd3 64 $ret = '"'.$result['name'].'" ';
a4102fd7 65 }
66 $ret .= '<'.$result['email'].'>';
67 $array[$i] = $ret;
e25c2bd3 68 }
69 else
a1e937bb 70 {
71 if (strpos($array[$i], '@') === false) {
72 $array[$i] .= '@' . $domain;
e25c2bd3 73 }
a1e937bb 74 $array[$i] = '<' . $array[$i] . '>';
75 }
e25c2bd3 76 }
77 return $array;
78}
93555af8 79
93555af8 80
a1e937bb 81/* looks up aliases in the addressbook and expands them to
82 * the RFC 821 valid RCPT address. ie <user@example.com>
83 * Adds @$domain if it wasn't in the address book and if it
84 * doesn't have an @ symbol in it
85 */
e25c2bd3 86function expandRcptAddrs ($array) {
87 global $domain;
88
a1e937bb 89 /* don't show errors -- kinda critical that we don't see
90 * them here since the redirect won't work if we do show them
91 */
68444892 92 $abook = addressbook_init(false, true);
e25c2bd3 93 for ($i=0; $i < count($array); $i++) {
94 $result = $abook->lookup($array[$i]);
95 $ret = "";
96 if (isset($result['email'])) {
93555af8 97 $ret = '<'.$result['email'].'>';
98 $array[$i] = $ret;
e25c2bd3 99 }
100 else {
a1e937bb 101 if (strpos($array[$i], '@') === false) {
e25c2bd3 102 $array[$i] .= '@' . $domain;
a1e937bb 103 }
93555af8 104 $array[$i] = '<' . $array[$i] . '>';
e25c2bd3 105 }
106 }
107 return $array;
108}
93555af8 109
4ba45d11 110
77b88425 111/* Attach the files that are due to be attached
a1e937bb 112 */
721a6cac 113function attachFiles ($fp, $session, $rn="\r\n") {
e25c2bd3 114 global $attachments, $attachment_dir, $username;
77b88425 115
e25c2bd3 116 $length = 0;
77b88425 117
e25c2bd3 118 $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
dd7766e0 119 if (isMultipart($session)) {
e25c2bd3 120 foreach ($attachments as $info) {
a3fbf5a4 121 if ($info['session'] == $session) {
122 if (isset($info['type'])) {
123 $filetype = $info['type'];
124 }
125 else {
126 $filetype = 'application/octet-stream';
127 }
128
129 $header = '--' . mimeBoundary() . "$rn";
130 if ( isset($info['remotefilename'])
131 && $info['remotefilename'] != '') {
132 $header .= "Content-Type: $filetype; name=\"" .
133 $info['remotefilename'] . "\"$rn";
134 $header .= "Content-Disposition: attachment; filename=\""
135 . $info['remotefilename'] . "\"$rn";
136 } else {
30e08236 137 $header .= "Content-Type: $filetype$rn";
a3fbf5a4 138 }
77b88425 139
a3fbf5a4 140
141 /* Use 'rb' for NT systems -- read binary
142 * Unix doesn't care -- everything's binary! :-)
143 */
144
145 $filename = $hashed_attachment_dir . '/'
146 . $info['localfilename'];
147 $file = fopen ($filename, 'rb');
148 if (substr($filetype, 0, 5) == 'text/' ||
149 substr($filetype, 0, 8) == 'message/' ) {
150 $header .= "$rn";
151 fputs ($fp, $header);
152 $length += strlen($header);
153 while ($tmp = fgets($file, 4096)) {
154 $tmp = str_replace("\r\n", "\n", $tmp);
155 $tmp = str_replace("\r", "\n", $tmp);
156 if ($rn == "\r\n"){
157 $tmp = str_replace("\n", "\r\n", $tmp);
158 }
159 /**
160 * Check if the last line has newline ($rn) in it
161 * and append if it doesn't.
162 */
163 if (feof($fp) && !strstr($tmp, "$rn")){
164 $tmp .= "$rn";
165 }
166 fputs($fp, $tmp);
167 $length += strlen($tmp);
168 }
169 } else {
170 $header .= "Content-Transfer-Encoding: base64"
171 . "$rn" . "$rn";
172 fputs ($fp, $header);
173 $length += strlen($header);
174 while ($tmp = fread($file, 570)) {
175 $encoded = chunk_split(base64_encode($tmp));
176 $length += strlen($encoded);
177 fputs ($fp, $encoded);
a1e937bb 178 }
e25c2bd3 179 }
a3fbf5a4 180 fclose ($file);
e25c2bd3 181 }
e25c2bd3 182 }
183 }
184 return $length;
185}
186
a1e937bb 187/* Delete files that are uploaded for attaching
188 */
dd7766e0 189function deleteAttachments($session) {
190 global $username, $attachments, $attachment_dir;
e25c2bd3 191 $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
dd7766e0 192
193 $rem_attachments = array();
194 foreach ($attachments as $info) {
a3fbf5a4 195 if ($info['session'] == $session) {
dd7766e0 196 $attached_file = "$hashed_attachment_dir/$info[localfilename]";
197 if (file_exists($attached_file)) {
a3fbf5a4 198 unlink($attached_file);
dd7766e0 199 }
a3fbf5a4 200 } else {
201 $rem_attachments[] = $info;
202 }
dd7766e0 203 }
204 $attachments = $rem_attachments;
e25c2bd3 205}
a7d75834 206
a1e937bb 207/* Return a nice MIME-boundary
208 */
e25c2bd3 209function mimeBoundary () {
210 static $mimeBoundaryString;
77b88425 211
212 if ( !isset( $mimeBoundaryString ) ||
213 $mimeBoundaryString == '') {
214 $mimeBoundaryString = '----=_' . date( 'YmdHis' ) . '_' .
a3fbf5a4 215 mt_rand( 10000, 99999 );
e25c2bd3 216 }
77b88425 217
e25c2bd3 218 return $mimeBoundaryString;
219}
7b67334e 220
e25c2bd3 221/* Time offset for correct timezone */
222function timezone () {
223 global $invert_time;
224
225 $diff_second = date('Z');
a1e937bb 226 if ($invert_time) {
e25c2bd3 227 $diff_second = - $diff_second;
a1e937bb 228 }
229 if ($diff_second > 0) {
e25c2bd3 230 $sign = '+';
a1e937bb 231 }
232 else {
e25c2bd3 233 $sign = '-';
a1e937bb 234 }
235
e25c2bd3 236 $diff_second = abs($diff_second);
237
238 $diff_hour = floor ($diff_second / 3600);
239 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
240
241 $zonename = '('.strftime('%Z').')';
a3fbf5a4 242 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute,
243 $zonename);
e25c2bd3 244 return ($result);
245}
246
247/* Print all the needed RFC822 headers */
721a6cac 248function write822Header ($fp, $t, $c, $b, $subject, $more_headers, $session, $rn="\r\n") {
e25c2bd3 249 global $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
250 global $data_dir, $username, $popuser, $domain, $version, $useSendmail;
251 global $default_charset, $HTTP_VIA, $HTTP_X_FORWARDED_FOR;
252 global $REMOTE_HOST, $identity;
721a6cac 253
a1e937bb 254 /* Storing the header to make sure the header is the same
255 * everytime the header is printed.
256 */
e25c2bd3 257 static $header, $headerlength;
258
259 if ($header == '') {
260 $to = expandAddrs(parseAddrs($t));
261 $cc = expandAddrs(parseAddrs($c));
262 $bcc = expandAddrs(parseAddrs($b));
263 if (isset($identity) && $identity != 'default') {
264 $reply_to = getPref($data_dir, $username, 'reply_to' . $identity);
265 $from = getPref($data_dir, $username, 'full_name' . $identity);
e1225604 266 $from_addr = getFrom();
e25c2bd3 267 } else {
aaf9abef 268 $reply_to = getPref($data_dir, $username, 'reply_to');
269 $from = getPref($data_dir, $username, 'full_name');
e1225604 270 $from_addr = getFrom();
a1e937bb 271 }
e25c2bd3 272
273 $to_list = getLineOfAddrs($to);
274 $cc_list = getLineOfAddrs($cc);
275 $bcc_list = getLineOfAddrs($bcc);
276
277 /* Encoding 8-bit characters and making from line */
278 $subject = encodeHeader($subject);
a1e937bb 279 if ($from == '') {
7b67334e 280 $from = "<$from_addr>";
a1e937bb 281 }
282 else {
ec9f1c41 283 $from = '"' . encodeHeader($from) . "\" <$from_addr>";
a1e937bb 284 }
e25c2bd3 285
286 /* This creates an RFC 822 date */
287 $date = date("D, j M Y H:i:s ", mktime()) . timezone();
288
289 /* Create a message-id */
290 $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
291 $message_id .= time() . '.squirrel@' . $SERVER_NAME .'>';
292
293 /* Make an RFC822 Received: line */
a1e937bb 294 if (isset($REMOTE_HOST)) {
8a2848f0 295 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
a1e937bb 296 }
297 else {
8a2848f0 298 $received_from = $REMOTE_ADDR;
a1e937bb 299 }
77b88425 300
e25c2bd3 301 if (isset($HTTP_VIA) || isset ($HTTP_X_FORWARDED_FOR)) {
a1e937bb 302 if ($HTTP_X_FORWARDED_FOR == '') {
e25c2bd3 303 $HTTP_X_FORWARDED_FOR = 'unknown';
a1e937bb 304 }
9949206d 305 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
7e235a1a 306 }
307
a3fbf5a4 308 $header = "Received: from $received_from" . $rn;
309 $header .= " (SquirrelMail authenticated user $username)" . $rn;
310 $header .= " by $SERVER_NAME with HTTP;" . $rn;
311 $header .= " $date" . $rn;
7e235a1a 312
e25c2bd3 313 /* Insert the rest of the header fields */
a3fbf5a4 314 $header .= "Message-ID: $message_id" . $rn;
315 $header .= "Date: $date" . $rn;
316 $header .= "Subject: $subject" . $rn;
317 $header .= "From: $from" . $rn;
318 $header .= "To: $to_list" . $rn; // Who it's TO
7e235a1a 319
604e2c03 320 if (isset($more_headers["Content-Type"])) {
7e235a1a 321 $contentType = $more_headers["Content-Type"];
322 unset($more_headers["Content-Type"]);
323 }
604e2c03 324 else {
dd7766e0 325 if (isMultipart($session)) {
7e235a1a 326 $contentType = "multipart/mixed;";
604e2c03 327 }
328 else {
7e235a1a 329 if ($default_charset != '') {
330 $contentType = 'text/plain; charset='.$default_charset;
331 }
332 else {
333 $contentType = 'text/plain;';
334 }
335 }
77b88425 336 }
7e235a1a 337
338 /* Insert headers from the $more_headers array */
339 if(is_array($more_headers)) {
e25c2bd3 340 reset($more_headers);
341 while(list($h_name, $h_val) = each($more_headers)) {
721a6cac 342 if ($h_name == 'References') {
343 $h_val = str_replace(' ', "$rn ", $h_val);
344 }
a3fbf5a4 345 $header .= sprintf("%s: %s%s", $h_name, $h_val, $rn);
e25c2bd3 346 }
347 }
7e235a1a 348
e25c2bd3 349 if ($cc_list) {
a3fbf5a4 350 $header .= "Cc: $cc_list" . $rn; // Who the CCs are
e25c2bd3 351 }
7e235a1a 352
a1e937bb 353 if ($reply_to != '') {
a3fbf5a4 354 $header .= "Reply-To: $reply_to" . $rn;
a1e937bb 355 }
7e235a1a 356
e25c2bd3 357 if ($useSendmail) {
7b67334e 358 if ($bcc_list) {
e25c2bd3 359 // BCCs is removed from header by sendmail
a3fbf5a4 360 $header .= "Bcc: $bcc_list" . $rn;
7b67334e 361 }
e25c2bd3 362 }
7e235a1a 363
a3fbf5a4 364 /* Identify SquirrelMail */
365 $header .= "X-Mailer: SquirrelMail (version $version)" . $rn;
77b88425 366
a1e937bb 367 /* Do the MIME-stuff */
a3fbf5a4 368 $header .= "MIME-Version: 1.0" . $rn;
7e235a1a 369
dd7766e0 370 if (isMultipart($session)) {
604e2c03 371 $header .= 'Content-Type: '.$contentType.' boundary="';
372 $header .= mimeBoundary();
a3fbf5a4 373 $header .= "\"$rn";
e25c2bd3 374 } else {
a3fbf5a4 375 $header .= 'Content-Type: ' . $contentType . $rn;
376 $header .= "Content-Transfer-Encoding: 8bit" . $rn;
e25c2bd3 377 }
a3fbf5a4 378 $header .= $rn; // One blank line to separate header and body
e25c2bd3 379
380 $headerlength = strlen($header);
381 }
382
a1e937bb 383 /* Write the header */
e25c2bd3 384 fputs ($fp, $header);
385
386 return $headerlength;
387}
17ce8467 388
a1e937bb 389/* Send the body
390 */
721a6cac 391function writeBody ($fp, $passedBody, $session, $rn="\r\n") {
e25c2bd3 392 global $default_charset;
a3fbf5a4 393
e25c2bd3 394 $attachmentlength = 0;
395
dd7766e0 396 if (isMultipart($session)) {
a3fbf5a4 397 $body = '--'.mimeBoundary() . $rn;
e25c2bd3 398
a1e937bb 399 if ($default_charset != "") {
a3fbf5a4 400 $body .= "Content-Type: text/plain; charset=$default_charset".$rn;
a1e937bb 401 }
402 else {
a3fbf5a4 403 $body .= "Content-Type: text/plain" . $rn;
a1e937bb 404 }
e25c2bd3 405
a3fbf5a4 406 $body .= "Content-Transfer-Encoding: 8bit" . $rn . $rn;
407 $body .= $passedBody . $rn . $rn;
e25c2bd3 408 fputs ($fp, $body);
409
721a6cac 410 $attachmentlength = attachFiles($fp, $session, $rn);
e25c2bd3 411
a1e937bb 412 if (!isset($postbody)) {
413 $postbody = "";
414 }
a3fbf5a4 415 $postbody .= $rn . "--" . mimeBoundary() . "--" . $rn . $rn;
e25c2bd3 416 fputs ($fp, $postbody);
417 } else {
a3fbf5a4 418 $body = $passedBody . $rn;
e25c2bd3 419 fputs ($fp, $body);
a3fbf5a4 420 $postbody = $rn;
e25c2bd3 421 fputs ($fp, $postbody);
422 }
7e235a1a 423
e25c2bd3 424 return (strlen($body) + strlen($postbody) + $attachmentlength);
425}
17ce8467 426
a1e937bb 427/* Send mail using the sendmail command
428 */
dd7766e0 429function sendSendmail($t, $c, $b, $subject, $body, $more_headers, $session) {
e25c2bd3 430 global $sendmail_path, $popuser, $username, $domain;
431
a1e937bb 432 /* Build envelope sender address. Make sure it doesn't contain
433 * spaces or other "weird" chars that would allow a user to
434 * exploit the shell/pipe it is used in.
435 */
e1225604 436 $envelopefrom = getFrom();
e25c2bd3 437 $envelopefrom = ereg_replace("[[:blank:]]",'', $envelopefrom);
438 $envelopefrom = ereg_replace("[[:space:]]",'', $envelopefrom);
439 $envelopefrom = ereg_replace("[[:cntrl:]]",'', $envelopefrom);
440
a3fbf5a4 441 /**
442 * open pipe to sendmail or qmail-inject
443 * (qmail-inject doesn't accept -t param)
444 */
e25c2bd3 445 if (strstr($sendmail_path, "qmail-inject")) {
446 $fp = popen (escapeshellcmd("$sendmail_path -f$envelopefrom"), "w");
447 } else {
448 $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), "w");
449 }
450
a3fbf5a4 451 $headerlength = write822Header ($fp, $t, $c, $b, $subject,
721a6cac 452 $more_headers, $session, "\n");
453 $bodylength = writeBody($fp, $body, $session, "\n");
e25c2bd3 454
455 pclose($fp);
e1225604 456
e25c2bd3 457 return ($headerlength + $bodylength);
458}
459
460function smtpReadData($smtpConnection) {
461 $read = fgets($smtpConnection, 1024);
462 $counter = 0;
463 while ($read) {
464 echo $read . '<BR>';
465 $data[$counter] = $read;
466 $read = fgets($smtpConnection, 1024);
467 $counter++;
468 }
469}
470
dd7766e0 471function sendSMTP($t, $c, $b, $subject, $body, $more_headers, $session) {
e25c2bd3 472 global $username, $popuser, $domain, $version, $smtpServerAddress,
473 $smtpPort, $data_dir, $color, $use_authenticated_smtp, $identity,
474 $key, $onetimepad;
475
476 $to = expandRcptAddrs(parseAddrs($t));
477 $cc = expandRcptAddrs(parseAddrs($c));
478 $bcc = expandRcptAddrs(parseAddrs($b));
a1e937bb 479 if (isset($identity) && $identity != 'default') {
a3fbf5a4 480 $from_addr = getPref($data_dir, $username,
481 'email_address' . $identity);
a1e937bb 482 }
483 else {
e25c2bd3 484 $from_addr = getPref($data_dir, $username, 'email_address');
a1e937bb 485 }
e25c2bd3 486
a1e937bb 487 if (!$from_addr) {
e25c2bd3 488 $from_addr = "$popuser@$domain";
a1e937bb 489 }
2044f95a 490
491 /* POP3 BEFORE SMTP CODE HERE */
492 global $pop_before_smtp;
493 if (isset($pop_before_smtp) && $pop_before_smtp === true) {
494 if (!isset($pop_port)) {
495 $pop_port = 110;
496 }
497 if (!isset($pop_server)) {
498 $pop_server = $smtpServerAddress; /* usually the same host! */
499 }
500 $popConnection = fsockopen($pop_server, $pop_port, $err_no, $err_str);
501 if (!$popConnection) {
502 error_log("Error connecting to POP Server ($pop_server:$pop_port)"
503 . " $err_no : $err_str");
504 } else {
505 $tmp = fgets($popConnection, 1024); /* banner */
506 if (!eregi("^\+OK", $tmp, $regs)) {
507 return(0);
508 }
509 fputs($popConnection, "USER $username\r\n");
510 $tmp = fgets($popConnection, 1024);
511 if (!eregi("^\+OK", $tmp, $regs)) {
512 return(0);
513 }
514 fputs($popConnection, 'PASS ' . OneTimePadDecrypt($key, $onetimepad) . "\r\n");
515 $tmp = fgets($popConnection, 1024);
516 if (!eregi("^\+OK", $tmp, $regs)) {
517 return(0);
518 }
519 fputs($popConnection, "QUIT\r\n"); /* log off */
520 fclose($popConnection);
521 }
522 }
e25c2bd3 523
a3fbf5a4 524 $smtpConnection = fsockopen($smtpServerAddress, $smtpPort,
525 $errorNumber, $errorString);
e25c2bd3 526 if (!$smtpConnection) {
527 echo 'Error connecting to SMTP Server.<br>';
528 echo "$errorNumber : $errorString<br>";
529 exit;
530 }
531 $tmp = fgets($smtpConnection, 1024);
14c62c12 532 if (errorCheck($tmp, $smtpConnection)!=5) {
533 return(0);
534 }
e25c2bd3 535
536 $to_list = getLineOfAddrs($to);
537 $cc_list = getLineOfAddrs($cc);
538
a1e937bb 539 /* Lets introduce ourselves */
a3fbf5a4 540 if (! isset ($use_authenticated_smtp)
541 || $use_authenticated_smtp == false) {
e25c2bd3 542 fputs($smtpConnection, "HELO $domain\r\n");
543 $tmp = fgets($smtpConnection, 1024);
544 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
545 } else {
546 fputs($smtpConnection, "EHLO $domain\r\n");
547 $tmp = fgets($smtpConnection, 1024);
548 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
549
550 fputs($smtpConnection, "AUTH LOGIN\r\n");
551 $tmp = fgets($smtpConnection, 1024);
a1e937bb 552 if (errorCheck($tmp, $smtpConnection)!=5) {
553 return(0);
554 }
77b88425 555
e25c2bd3 556 fputs($smtpConnection, base64_encode ($username) . "\r\n");
557 $tmp = fgets($smtpConnection, 1024);
a1e937bb 558 if (errorCheck($tmp, $smtpConnection)!=5) {
559 return(0);
560 }
e25c2bd3 561
a3fbf5a4 562 fputs($smtpConnection, base64_encode
563 (OneTimePadDecrypt($key, $onetimepad)) . "\r\n");
e25c2bd3 564 $tmp = fgets($smtpConnection, 1024);
a1e937bb 565 if (errorCheck($tmp, $smtpConnection)!=5) {
566 return(0);
567 }
e25c2bd3 568 }
569
a1e937bb 570 /* Ok, who is sending the message? */
e25c2bd3 571 fputs($smtpConnection, "MAIL FROM: <$from_addr>\r\n");
572 $tmp = fgets($smtpConnection, 1024);
a1e937bb 573 if (errorCheck($tmp, $smtpConnection)!=5) {
574 return(0);
575 }
e25c2bd3 576
a1e937bb 577 /* send who the recipients are */
e25c2bd3 578 for ($i = 0; $i < count($to); $i++) {
579 fputs($smtpConnection, "RCPT TO: $to[$i]\r\n");
580 $tmp = fgets($smtpConnection, 1024);
a1e937bb 581 if (errorCheck($tmp, $smtpConnection)!=5) {
582 return(0);
583 }
e25c2bd3 584 }
585 for ($i = 0; $i < count($cc); $i++) {
586 fputs($smtpConnection, "RCPT TO: $cc[$i]\r\n");
587 $tmp = fgets($smtpConnection, 1024);
a1e937bb 588 if (errorCheck($tmp, $smtpConnection)!=5) {
589 return(0);
590 }
e25c2bd3 591 }
592 for ($i = 0; $i < count($bcc); $i++) {
593 fputs($smtpConnection, "RCPT TO: $bcc[$i]\r\n");
594 $tmp = fgets($smtpConnection, 1024);
77b88425 595 if (errorCheck($tmp, $smtpConnection)!=5) {
a1e937bb 596 return(0);
597 }
e25c2bd3 598 }
77b88425 599
a1e937bb 600 /* Lets start sending the actual message */
e25c2bd3 601 fputs($smtpConnection, "DATA\r\n");
602 $tmp = fgets($smtpConnection, 1024);
a1e937bb 603 if (errorCheck($tmp, $smtpConnection)!=5) {
604 return(0);
605 }
77b88425 606
a1e937bb 607 /* Send the message */
a3fbf5a4 608 $headerlength = write822Header ($smtpConnection, $t, $c, $b,
609 $subject, $more_headers, $session);
dd7766e0 610 $bodylength = writeBody($smtpConnection, $body, $session);
e25c2bd3 611
a1e937bb 612 fputs($smtpConnection, ".\r\n"); /* end the DATA part */
e25c2bd3 613 $tmp = fgets($smtpConnection, 1024);
614 $num = errorCheck($tmp, $smtpConnection, true);
615 if ($num != 250) {
e25c2bd3 616 return(0);
617 }
618
a1e937bb 619 fputs($smtpConnection, "QUIT\r\n"); /* log off */
e25c2bd3 620
621 fclose($smtpConnection);
622
623 return ($headerlength + $bodylength);
624}
60994e13 625
60994e13 626
e25c2bd3 627function errorCheck($line, $smtpConnection, $verbose = false) {
8f8f3a4e 628 global $color, $compose_new_win;
e25c2bd3 629
a1e937bb 630 /* Read new lines on a multiline response */
e25c2bd3 631 $lines = $line;
632 while(ereg("^[0-9]+-", $line)) {
633 $line = fgets($smtpConnection, 1024);
634 $lines .= $line;
635 }
636
a1e937bb 637 /* Status: 0 = fatal
638 * 5 = ok
639 */
e25c2bd3 640 $err_num = substr($line, 0, strpos($line, " "));
641 switch ($err_num) {
642 case 500: $message = 'Syntax error; command not recognized';
643 $status = 0;
644 break;
645 case 501: $message = 'Syntax error in parameters or arguments';
646 $status = 0;
647 break;
648 case 502: $message = 'Command not implemented';
649 $status = 0;
650 break;
651 case 503: $message = 'Bad sequence of commands';
652 $status = 0;
653 break;
654 case 504: $message = 'Command parameter not implemented';
655 $status = 0;
a1e937bb 656 break;
e25c2bd3 657
658 case 211: $message = 'System status, or system help reply';
659 $status = 5;
660 break;
661 case 214: $message = 'Help message';
662 $status = 5;
663 break;
664
e25c2bd3 665 case 220: $message = 'Service ready';
666 $status = 5;
667 break;
668 case 221: $message = 'Service closing transmission channel';
669 $status = 5;
670 break;
a1e937bb 671
e25c2bd3 672 case 421: $message = 'Service not available, closing chanel';
673 $status = 0;
674 break;
675
a1e937bb 676 case 235: return(5);
677 break;
e25c2bd3 678 case 250: $message = 'Requested mail action okay, completed';
679 $status = 5;
680 break;
681 case 251: $message = 'User not local; will forward';
682 $status = 5;
683 break;
684 case 334: return(5); break;
685 case 450: $message = 'Requested mail action not taken: mailbox unavailable';
686 $status = 0;
687 break;
688 case 550: $message = 'Requested action not taken: mailbox unavailable';
689 $status = 0;
690 break;
691 case 451: $message = 'Requested action aborted: error in processing';
692 $status = 0;
693 break;
694 case 551: $message = 'User not local; please try forwarding';
695 $status = 0;
696 break;
697 case 452: $message = 'Requested action not taken: insufficient system storage';
698 $status = 0;
699 break;
700 case 552: $message = 'Requested mail action aborted: exceeding storage allocation';
701 $status = 0;
702 break;
703 case 553: $message = 'Requested action not taken: mailbox name not allowed';
704 $status = 0;
705 break;
706 case 354: $message = 'Start mail input; end with .';
707 $status = 5;
708 break;
709 case 554: $message = 'Transaction failed';
710 $status = 0;
711 break;
712 default: $message = 'Unknown response: '. nl2br(htmlspecialchars($lines));
713 $status = 0;
714 $error_num = '001';
715 break;
716 }
7e235a1a 717
e25c2bd3 718 if ($status == 0) {
719 include_once('../functions/page_header.php');
8f8f3a4e 720 if ($compose_new_win == '1') {
721 compose_Header($color, 'None');
722 }
7e235a1a 723 else {
8f8f3a4e 724 displayPageHeader($color, 'None');
725 }
e25c2bd3 726 include_once('../functions/display_messages.php');
727 $lines = nl2br(htmlspecialchars($lines));
728 $msg = $message . "<br>\nServer replied: $lines";
729 plain_error_message($msg, $color);
730 }
731 if (! $verbose) return $status;
732 return $err_num;
733}
734
67c2f5ea 735/* create new reference header per rfc2822 */
736
737function calculate_references($refs, $inreplyto, $old_reply_to) {
721a6cac 738
67c2f5ea 739 $refer = "";
740 for ($i=1;$i<count($refs[0]);$i++) {
741 if (!empty($refs[0][$i])) {
742 if (preg_match("/^References:(.+)$/", $refs[0][$i], $regs)) {
743 $refer = trim($regs[1]);
744 }
745 else {
746 $refer .= ' ' . trim($refs[0][$i]);
747 }
748 }
749 }
750 $refer = trim($refer);
751 if (strlen($refer) > 2) {
752 $refer .= ' ' . $inreplyto;
753 }
754 else {
755 if (!empty($old_reply_to)) {
756 $refer .= $old_reply_to . ' ' . $inreplyto;
757 }
758 else {
759 $refer .= $inreplyto;
2044f95a 760 }
67c2f5ea 761 }
762 trim($refer);
67c2f5ea 763 return $refer;
764}
765
a3fbf5a4 766function sendMessage($t, $c, $b, $subject, $body, $reply_id, $MDN,
767 $prio = 3, $session) {
77b88425 768 global $useSendmail, $msg_id, $is_reply, $mailbox, $onetimepad,
a3fbf5a4 769 $data_dir, $username, $domain, $key, $version, $sent_folder,
770 $imapServerAddress, $imapPort, $default_use_priority, $more_headers,
771 $request_mdn, $request_dr;
77b88425 772
e25c2bd3 773 $more_headers = Array();
774
77b88425 775 do_hook('smtp_send');
776
a3fbf5a4 777 $imap_stream = sqimap_login($username, $key, $imapServerAddress,
778 $imapPort, 1);
77b88425 779
e25c2bd3 780 if (isset($reply_id) && $reply_id) {
781 sqimap_mailbox_select ($imap_stream, $mailbox);
782 sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, 'Answered');
77b88425 783
784 /* Insert In-Reply-To and References headers if the
a1e937bb 785 * message-id of the message we reply to is set (longer than "<>")
786 * The References header should really be the old Referenced header
67c2f5ea 787 * with the message ID appended, and now it is (jmunro)
a1e937bb 788 */
41336c5f 789 $sid = sqimap_session_id();
790 $query = "$sid FETCH $reply_id (BODY.PEEK[HEADER.FIELDS (Message-Id In-Reply-To)])\r\n";
791 fputs ($imap_stream, $query);
721a6cac 792 $read = sqimap_read_data($imap_stream, $sid, true, $response, $message);
41336c5f 793 $message_id = '';
794 $in_reply_to = '';
721a6cac 795
796 foreach ($read as $r) {
41336c5f 797 if (preg_match("/^message-id:(.*)/iA", $r, $regs)) {
798 $message_id = trim($regs[1]);
799 }
800 if (preg_match("/^in-reply-to:(.*)/iA", $r, $regs)) {
801 $in_reply_to = trim($regs[1]);
802 }
41336c5f 803 }
721a6cac 804
41336c5f 805 if(strlen($message_id) > 2) {
67c2f5ea 806 $refs = get_reference_header ($imap_stream, $reply_id);
41336c5f 807 $inreplyto = $message_id;
808 $old_reply_to = $in_reply_to;
67c2f5ea 809 $refer = calculate_references ($refs, $inreplyto, $old_reply_to);
810 $more_headers['In-Reply-To'] = $inreplyto;
811 $more_headers['References'] = $refer;
e25c2bd3 812 }
41336c5f 813
e25c2bd3 814 }
815 if ($default_use_priority) {
816 $more_headers = array_merge($more_headers, createPriorityHeaders($prio));
817 }
77b88425 818
604e2c03 819 $requestRecipt = 0;
820 if (isset($request_dr)) {
821 $requestRecipt += 1;
822 }
823 if (isset($request_mdn)) {
824 $requestRecipt += 2;
825 }
826 if ( $requestRecipt > 0) {
827 $more_headers = array_merge($more_headers, createReceiptHeaders($requestRecipt));
828 }
829
a1e937bb 830 /* In order to remove the problem of users not able to create
831 * messages with "." on a blank line, RFC821 has made provision
832 * in section 4.5.2 (Transparency).
833 */
e25c2bd3 834 $body = ereg_replace("\n\\.", "\n..", $body);
835 $body = ereg_replace("^\\.", "..", $body);
77b88425 836
a1e937bb 837 /* this is to catch all plain \n instances and
838 * replace them with \r\n. All newlines were converted
839 * into just \n inside the compose.php file.
a3fbf5a4 840 * But only if delimiter is, in fact, \r\n.
a1e937bb 841 */
604e2c03 842
843 if ($MDN) {
844 $more_headers["Content-Type"] = "multipart/report; ".
845 "report-type=disposition-notification;";
846 }
77b88425 847
e25c2bd3 848 if ($useSendmail) {
a3fbf5a4 849 $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers,
850 $session);
e25c2bd3 851 } else {
721a6cac 852 $body = ereg_replace("\n", "\r\n", $body);
a3fbf5a4 853 $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers,
854 $session);
e25c2bd3 855 }
e25c2bd3 856 if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
721a6cac 857 if ($useSendmail) $body = ereg_replace("\n", "\r\n", $body);
e25c2bd3 858 sqimap_append ($imap_stream, $sent_folder, $length);
a3fbf5a4 859 write822Header ($imap_stream, $t, $c, $b, $subject, $more_headers,
860 $session);
dd7766e0 861 writeBody ($imap_stream, $body, $session);
e25c2bd3 862 sqimap_append_done ($imap_stream);
863 }
864 sqimap_logout($imap_stream);
a1e937bb 865 /* Delete the files uploaded for attaching (if any).
866 * only if $length != 0 (if there was no error)
867 */
77b88425 868 if ($length) {
dd7766e0 869 ClearAttachments($session);
77b88425 870 }
871
e25c2bd3 872 return $length;
873}
d1b8b679 874
e25c2bd3 875function createPriorityHeaders($prio) {
876 $prio_headers = Array();
77b88425 877 $prio_headers['X-Priority'] = $prio;
878
e25c2bd3 879 switch($prio) {
77b88425 880 case 1: $prio_headers['Importance'] = 'High';
881 $prio_headers['X-MSMail-Priority'] = 'High';
e25c2bd3 882 break;
77b88425 883
884 case 3: $prio_headers['Importance'] = 'Normal';
885 $prio_headers['X-MSMail-Priority'] = 'Normal';
e25c2bd3 886 break;
77b88425 887
e25c2bd3 888 case 5:
77b88425 889 $prio_headers['Importance'] = 'Low';
890 $prio_headers['X-MSMail-Priority'] = 'Low';
e25c2bd3 891 break;
892 }
893 return $prio_headers;
894}
020abcf3 895
604e2c03 896function createReceiptHeaders($receipt) {
0804c276 897
a250d021 898 GLOBAL $data_dir, $username, $identity, $popuser, $domain;
0804c276 899
900 $receipt_headers = Array();
7aaa1434 901 if (isset($identity) && $identity != 'default') {
902 $from = getPref($data_dir, $username, 'full_name' . $identity);
903 $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
904 } else {
905 $from = getPref($data_dir, $username, 'full_name');
906 $from_addr = getPref($data_dir, $username, 'email_address');
907 }
908 if ($from_addr == '') {
909 $from_addr = $popuser.'@'.$domain;
910 }
0804c276 911
912 if ($from == '') {
913 $from = "<$from_addr>";
914 }
915 else {
916 $from = '"' . encodeHeader($from) . "\" <$from_addr>";
917 }
918
919 /* On Delivery */
920 if ( $receipt == 1
921 || $receipt == 3 ) {
922 $receipt_headers["Return-Receipt-To"] = $from;
923 }
924 /* On Read */
925 if ($receipt == 2
926 || $receipt == 3 ) {
927 /* Pegasus Mail */
928 $receipt_headers["X-Confirm-Reading-To"] = $from;
929 /* RFC 2298 */
930 $receipt_headers["Disposition-Notification-To"] = $from;
931 }
932 return $receipt_headers;
933}
604e2c03 934
e1225604 935/* Figure out what the 'From:' address is
936 */
937
938function getFrom() {
939 global $username, $popuser, $domain, $data_dir, $identity;
940 if (isset($identity) && $identity != 'default') {
941 $from_addr = getPref($data_dir, $username,
942 'email_address' . $identity);
943 }
944 else {
945 $from_addr = getPref($data_dir, $username, 'email_address');
946 }
947
948 if (!$from_addr) {
949 $from_addr = "$popuser@$domain";
950 }
951 return $from_addr;
952}
953
604e2c03 954
020abcf3 955?>