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