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