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