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