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