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