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