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