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