Added a hook for the priority plugin.
[squirrelmail.git] / functions / smtp.php
1 <?php
2 /** smtp.php
3 **
4 ** This contains all the functions needed to send messages through
5 ** an smtp server or sendmail.
6 **
7 ** $Id$
8 **/
9
10 if (defined('smtp_php'))
11 return;
12 define('smtp_php', true);
13
14 include('../functions/addressbook.php');
15 include('../functions/plugin.php');
16
17 global $username, $popuser, $domain;
18
19 // This should most probably go to some initialization...
20 if (ereg("^([^@%/]+)[@%/](.+)$", $username, $usernamedata)) {
21 $popuser = $usernamedata[1];
22 $domain = $usernamedata[2];
23 unset($usernamedata);
24 } else {
25 $popuser = $username;
26 }
27 // We need domain for smtp
28 if (!$domain)
29 $domain = getenv('HOSTNAME');
30
31 // Returns true only if this message is multipart
32 function isMultipart () {
33 global $attachments;
34
35 if (count($attachments)>0)
36 return true;
37 else
38 return false;
39 }
40
41 // looks up aliases in the addressbook and expands them to
42 // the full address.
43 // Adds @$domain if it wasn't in the address book and if it
44 // doesn't have an @ symbol in it
45 function expandAddrs ($array) {
46 global $domain;
47
48 // don't show errors -- kinda critical that we don't see
49 // them here since the redirect won't work if we do show them
50 $abook = addressbook_init(false);
51 for ($i=0; $i < count($array); $i++) {
52 $result = $abook->lookup($array[$i]);
53 $ret = "";
54 if (isset($result['email'])) {
55 if (isset($result['name'])) {
56 $ret = '"'.$result['name'].'" ';
57 }
58 $ret .= '<'.$result['email'].'>';
59 $array[$i] = $ret;
60 }
61 else
62 {
63 if (strpos($array[$i], '@') === false)
64 $array[$i] .= '@' . $domain;
65 $array[$i] = '<' . $array[$i] . '>';
66 }
67 }
68 return $array;
69 }
70
71 // Attach the files that are due to be attached
72 function attachFiles ($fp) {
73 global $attachments, $attachment_dir;
74
75 $length = 0;
76
77 if (isMultipart()) {
78 foreach ($attachments as $info)
79 {
80 if (isset($info['type']))
81 $filetype = $info['type'];
82 else
83 $filetype = 'application/octet-stream';
84
85 $header = '--'.mimeBoundary()."\r\n";
86 $header .= "Content-Type: $filetype; name=\"" .
87 $info['remotefilename'] . "\"\r\n";
88 $header .= "Content-Disposition: attachment; filename=\"" .
89 $info['remotefilename'] . "\"\r\n";
90
91 // Use 'rb' for NT systems -- read binary
92 // Unix doesn't care -- everything's binary! :-)
93 $file = fopen ($attachment_dir . $info['localfilename'], 'rb');
94 if (substr($filetype, 0, 5) == 'text/' ||
95 $filetype == 'message/rfc822') {
96 $header .= "\r\n";
97 fputs ($fp, $header);
98 $length += strlen($header);
99 while ($tmp = fgets($file, 4096)) {
100 $tmp = str_replace("\r\n", "\n", $tmp);
101 $tmp = str_replace("\r", "\n", $tmp);
102 $tmp = str_replace("\n", "\r\n", $tmp);
103 if (feof($fp) && substr($tmp, -2) != "\r\n")
104 $tmp .= "\r\n";
105 fputs($fp, $tmp);
106 $length += strlen($tmp);
107 }
108 } else {
109 $header .= "Content-Transfer-Encoding: base64\r\n\r\n";
110 fputs ($fp, $header);
111 $length += strlen($header);
112 while ($tmp = fread($file, 570)) {
113 $encoded = chunk_split(base64_encode($tmp));
114 $length += strlen($encoded);
115 fputs ($fp, $encoded);
116 }
117 }
118 fclose ($file);
119 }
120 }
121
122 return $length;
123 }
124
125 // Delete files that are uploaded for attaching
126 function deleteAttachments() {
127 global $attachments, $attachment_dir;
128
129 if (isMultipart()) {
130 reset($attachments);
131 while (list($localname, $remotename) = each($attachments)) {
132 if (!ereg ("\\/", $localname)) {
133 unlink ($attachment_dir.$localname);
134 unlink ($attachment_dir.$localname.'.info');
135 }
136 }
137 }
138 }
139
140 // Return a nice MIME-boundary
141 function mimeBoundary () {
142 static $mimeBoundaryString;
143
144 if ($mimeBoundaryString == "") {
145 $mimeBoundaryString = "----=_" .
146 GenerateRandomString(60, '\'()+,-./:=?_', 7);
147 }
148
149 return $mimeBoundaryString;
150 }
151
152 /* Time offset for correct timezone */
153 function timezone () {
154 global $invert_time;
155
156 $diff_second = date('Z');
157 if ($invert_time)
158 $diff_second = - $diff_second;
159 if ($diff_second > 0)
160 $sign = '+';
161 else
162 $sign = '-';
163
164 $diff_second = abs($diff_second);
165
166 $diff_hour = floor ($diff_second / 3600);
167 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
168
169 $zonename = '('.strftime('%Z').')';
170 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute, $zonename);
171 return ($result);
172 }
173
174 /* Print all the needed RFC822 headers */
175 function write822Header ($fp, $t, $c, $b, $subject, $more_headers) {
176 global $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
177 global $data_dir, $username, $popuser, $domain, $version, $useSendmail;
178 global $default_charset, $HTTP_VIA, $HTTP_X_FORWARDED_FOR;
179 global $REMOTE_HOST, $identity;
180
181 // Storing the header to make sure the header is the same
182 // everytime the header is printed.
183 static $header, $headerlength;
184
185 if ($header == '') {
186 $to = expandAddrs(parseAddrs($t));
187 $cc = expandAddrs(parseAddrs($c));
188 $bcc = expandAddrs(parseAddrs($b));
189 if (isset($identity) && $identity != 'default')
190 {
191 $reply_to = getPref($data_dir, $username, 'reply_to' . $identity);
192 $from = getPref($data_dir, $username, 'full_name' . $identity);
193 $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
194 }
195 else
196 {
197 $reply_to = getPref($data_dir, $username, 'reply_to');
198 $from = getPref($data_dir, $username, 'full_name');
199 $from_addr = getPref($data_dir, $username, 'email_address');
200 }
201
202 if ($from_addr == '')
203 $from_addr = $popuser.'@'.$domain;
204
205 $to_list = getLineOfAddrs($to);
206 $cc_list = getLineOfAddrs($cc);
207 $bcc_list = getLineOfAddrs($bcc);
208
209 /* Encoding 8-bit characters and making from line */
210 $subject = encodeHeader($subject);
211 if ($from == '')
212 $from = "<$from_addr>";
213 else
214 $from = '"' . encodeHeader($from) . "\" <$from_addr>";
215
216 /* This creates an RFC 822 date */
217 $date = date("D, j M Y H:i:s ", mktime()) . timezone();
218
219 /* Create a message-id */
220 $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
221 $message_id .= time() . '.squirrel@' . $SERVER_NAME .'>';
222
223 /* Make an RFC822 Received: line */
224 if (isset($REMOTE_HOST))
225 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
226 else
227 $received_from = $REMOTE_ADDR;
228
229 if (isset($HTTP_VIA) || isset ($HTTP_X_FORWARDED_FOR)) {
230 if ($HTTP_X_FORWARDED_FOR == '')
231 $HTTP_X_FORWARDED_FOR = 'unknown';
232 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
233 }
234
235 $header = "Received: from $received_from\r\n";
236 $header .= " (SquirrelMail authenticated user $username)\r\n";
237 $header .= " by $SERVER_NAME with HTTP;\r\n";
238 $header .= " $date\r\n";
239
240 /* Insert the rest of the header fields */
241 $header .= "Message-ID: $message_id\r\n";
242 $header .= "Date: $date\r\n";
243 $header .= "Subject: $subject\r\n";
244 $header .= "From: $from\r\n";
245 $header .= "To: $to_list\r\n"; // Who it's TO
246
247 /* Insert headers from the $more_headers array */
248 if(is_array($more_headers)) {
249 reset($more_headers);
250 while(list($h_name, $h_val) = each($more_headers)) {
251 $header .= sprintf("%s: %s\r\n", $h_name, $h_val);
252 }
253 }
254
255 if ($cc_list) {
256 $header .= "Cc: $cc_list\r\n"; // Who the CCs are
257 }
258
259 if ($reply_to != '')
260 $header .= "Reply-To: $reply_to\r\n";
261
262 if ($useSendmail) {
263 if ($bcc_list) {
264 // BCCs is removed from header by sendmail
265 $header .= "Bcc: $bcc_list\r\n";
266 }
267 }
268
269 $header .= "X-Mailer: SquirrelMail (version $version)\r\n"; // Identify SquirrelMail
270
271 // Do the MIME-stuff
272 $header .= "MIME-Version: 1.0\r\n";
273
274 if (isMultipart()) {
275 $header .= 'Content-Type: multipart/mixed; boundary="';
276 $header .= mimeBoundary();
277 $header .= "\"\r\n";
278 } else {
279 if ($default_charset != '')
280 $header .= "Content-Type: text/plain; charset=$default_charset\r\n";
281 else
282 $header .= "Content-Type: text/plain;\r\n";
283 $header .= "Content-Transfer-Encoding: 8bit\r\n";
284 }
285 $header .= "\r\n"; // One blank line to separate header and body
286
287 $headerlength = strlen($header);
288 }
289
290 // Write the header
291 fputs ($fp, $header);
292
293 return $headerlength;
294 }
295
296 // Send the body
297 function writeBody ($fp, $passedBody) {
298 global $default_charset;
299
300 $attachmentlength = 0;
301
302 if (isMultipart()) {
303 $body = '--'.mimeBoundary()."\r\n";
304
305 if ($default_charset != "")
306 $body .= "Content-Type: text/plain; charset=$default_charset\r\n";
307 else
308 $body .= "Content-Type: text/plain\r\n";
309
310 $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
311 $body .= $passedBody . "\r\n\r\n";
312 fputs ($fp, $body);
313
314 $attachmentlength = attachFiles($fp);
315
316 if (!isset($postbody)) $postbody = "";
317 $postbody .= "\r\n--".mimeBoundary()."--\r\n\r\n";
318 fputs ($fp, $postbody);
319 } else {
320 $body = $passedBody . "\r\n";
321 fputs ($fp, $body);
322 $postbody = "\r\n";
323 fputs ($fp, $postbody);
324 }
325
326 return (strlen($body) + strlen($postbody) + $attachmentlength);
327 }
328
329 // Send mail using the sendmail command
330 function sendSendmail($t, $c, $b, $subject, $body, $more_headers) {
331 global $sendmail_path, $popuser, $username, $domain;
332
333 // Build envelope sender address. Make sure it doesn't contain
334 // spaces or other "weird" chars that would allow a user to
335 // exploit the shell/pipe it is used in.
336 $envelopefrom = "$popuser@$domain";
337 $envelopefrom = ereg_replace("[[:blank:]]",'', $envelopefrom);
338 $envelopefrom = ereg_replace("[[:space:]]",'', $envelopefrom);
339 $envelopefrom = ereg_replace("[[:cntrl:]]",'', $envelopefrom);
340
341 // open pipe to sendmail
342 $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), 'w');
343
344 $headerlength = write822Header ($fp, $t, $c, $b, $subject, $more_headers);
345 $bodylength = writeBody($fp, $body);
346
347 pclose($fp);
348
349 return ($headerlength + $bodylength);
350 }
351
352 function smtpReadData($smtpConnection) {
353 $read = fgets($smtpConnection, 1024);
354 $counter = 0;
355 while ($read) {
356 echo $read . '<BR>';
357 $data[$counter] = $read;
358 $read = fgets($smtpConnection, 1024);
359 $counter++;
360 }
361 }
362
363 function sendSMTP($t, $c, $b, $subject, $body, $more_headers) {
364 global $username, $popuser, $domain, $version, $smtpServerAddress,
365 $smtpPort, $data_dir, $color, $use_authenticated_smtp, $identity,
366 $key, $onetimepad;
367
368 $to = expandAddrs(parseAddrs($t));
369 $cc = expandAddrs(parseAddrs($c));
370 $bcc = expandAddrs(parseAddrs($b));
371 if (isset($identity) && $identity != 'default')
372 $from_addr = getPref($data_dir, $username, 'email_address' . $identity);
373 else
374 $from_addr = getPref($data_dir, $username, 'email_address');
375
376 if (!$from_addr)
377 $from_addr = "$popuser@$domain";
378
379 $smtpConnection = fsockopen($smtpServerAddress, $smtpPort, $errorNumber, $errorString);
380 if (!$smtpConnection) {
381 echo 'Error connecting to SMTP Server.<br>';
382 echo "$errorNumber : $errorString<br>";
383 exit;
384 }
385 $tmp = fgets($smtpConnection, 1024);
386 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
387
388 $to_list = getLineOfAddrs($to);
389 $cc_list = getLineOfAddrs($cc);
390
391 /** Lets introduce ourselves */
392 if (! isset ($use_authenticated_smtp) || $use_authenticated_smtp == false) {
393 fputs($smtpConnection, "HELO $domain\r\n");
394 $tmp = fgets($smtpConnection, 1024);
395 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
396 } else {
397 fputs($smtpConnection, "EHLO $domain\r\n");
398 $tmp = fgets($smtpConnection, 1024);
399 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
400
401 fputs($smtpConnection, "AUTH LOGIN\r\n");
402 $tmp = fgets($smtpConnection, 1024);
403 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
404
405 fputs($smtpConnection, base64_encode ($username) . "\r\n");
406 $tmp = fgets($smtpConnection, 1024);
407 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
408
409 fputs($smtpConnection, base64_encode (OneTimePadDecrypt($key, $onetimepad)) . "\r\n");
410 $tmp = fgets($smtpConnection, 1024);
411 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
412 }
413
414 /** Ok, who is sending the message? */
415 fputs($smtpConnection, "MAIL FROM: <$from_addr>\r\n");
416 $tmp = fgets($smtpConnection, 1024);
417 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
418
419 /** send who the recipients are */
420 for ($i = 0; $i < count($to); $i++) {
421 fputs($smtpConnection, "RCPT TO: $to[$i]\r\n");
422 $tmp = fgets($smtpConnection, 1024);
423 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
424 }
425 for ($i = 0; $i < count($cc); $i++) {
426 fputs($smtpConnection, "RCPT TO: $cc[$i]\r\n");
427 $tmp = fgets($smtpConnection, 1024);
428 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
429 }
430 for ($i = 0; $i < count($bcc); $i++) {
431 fputs($smtpConnection, "RCPT TO: $bcc[$i]\r\n");
432 $tmp = fgets($smtpConnection, 1024);
433 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
434 }
435
436 /** Lets start sending the actual message */
437 fputs($smtpConnection, "DATA\r\n");
438 $tmp = fgets($smtpConnection, 1024);
439 if (errorCheck($tmp, $smtpConnection)!=5) return(0);
440
441 // Send the message
442 $headerlength = write822Header ($smtpConnection, $t, $c, $b, $subject, $more_headers);
443 $bodylength = writeBody($smtpConnection, $body);
444
445 fputs($smtpConnection, ".\r\n"); // end the DATA part
446 $tmp = fgets($smtpConnection, 1024);
447 $num = errorCheck($tmp, $smtpConnection, true);
448 if ($num != 250) {
449 $tmp = nl2br(htmlspecialchars($tmp));
450 displayPageHeader($color, 'None');
451 include ("../functions/display_messages.php");
452 $msg = "Message not sent!<br>\nReason given: $tmp";
453 plain_error_message($msg, $color);
454 return(0);
455 }
456
457 fputs($smtpConnection, "QUIT\r\n"); // log off
458
459 fclose($smtpConnection);
460
461 return ($headerlength + $bodylength);
462 }
463
464
465 function errorCheck($line, $smtpConnection, $verbose = false) {
466 global $color;
467
468 // Read new lines on a multiline response
469 $lines = $line;
470 while(ereg("^[0-9]+-", $line)) {
471 $line = fgets($smtpConnection, 1024);
472 $lines .= $line;
473 }
474
475 // Status: 0 = fatal
476 // 5 = ok
477
478 $err_num = substr($line, 0, strpos($line, " "));
479 switch ($err_num) {
480 case 500: $message = 'Syntax error; command not recognized';
481 $status = 0;
482 break;
483 case 501: $message = 'Syntax error in parameters or arguments';
484 $status = 0;
485 break;
486 case 502: $message = 'Command not implemented';
487 $status = 0;
488 break;
489 case 503: $message = 'Bad sequence of commands';
490 $status = 0;
491 break;
492 case 504: $message = 'Command parameter not implemented';
493 $status = 0;
494 break;
495
496
497 case 211: $message = 'System status, or system help reply';
498 $status = 5;
499 break;
500 case 214: $message = 'Help message';
501 $status = 5;
502 break;
503
504
505 case 220: $message = 'Service ready';
506 $status = 5;
507 break;
508 case 221: $message = 'Service closing transmission channel';
509 $status = 5;
510 break;
511 case 421: $message = 'Service not available, closing chanel';
512 $status = 0;
513 break;
514
515 case 235: return(5); break;
516 case 250: $message = 'Requested mail action okay, completed';
517 $status = 5;
518 break;
519 case 251: $message = 'User not local; will forward';
520 $status = 5;
521 break;
522 case 334: return(5); break;
523 case 450: $message = 'Requested mail action not taken: mailbox unavailable';
524 $status = 0;
525 break;
526 case 550: $message = 'Requested action not taken: mailbox unavailable';
527 $status = 0;
528 break;
529 case 451: $message = 'Requested action aborted: error in processing';
530 $status = 0;
531 break;
532 case 551: $message = 'User not local; please try forwarding';
533 $status = 0;
534 break;
535 case 452: $message = 'Requested action not taken: insufficient system storage';
536 $status = 0;
537 break;
538 case 552: $message = 'Requested mail action aborted: exceeding storage allocation';
539 $status = 0;
540 break;
541 case 553: $message = 'Requested action not taken: mailbox name not allowed';
542 $status = 0;
543 break;
544 case 354: $message = 'Start mail input; end with .';
545 $status = 5;
546 break;
547 case 554: $message = 'Transaction failed';
548 $status = 0;
549 break;
550 default: $message = 'Unknown response: '. nl2br(htmlspecialchars($lines));
551 $status = 0;
552 $error_num = '001';
553 break;
554 }
555
556 if ($status == 0) {
557 include '../functions/page_header.php';
558 displayPageHeader($color, 'None');
559 include ("../functions/display_messages.php");
560 $lines = nl2br(htmlspecialchars($lines));
561 $msg = $message . "<br>\nServer replied: $lines";
562 plain_error_message($msg, $color);
563 }
564 if (! $verbose) return $status;
565 return $err_num;
566 }
567
568 function sendMessage($t, $c, $b, $subject, $body, $reply_id) {
569 global $useSendmail, $msg_id, $is_reply, $mailbox, $onetimepad;
570 global $data_dir, $username, $domain, $key, $version, $sent_folder, $imapServerAddress, $imapPort;
571 global $more_headers;
572 $more_headers = Array();
573
574 do_hook("smtp_send");
575
576 $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 1);
577
578 if (isset($reply_id) && $reply_id) {
579 sqimap_mailbox_select ($imap_stream, $mailbox);
580 sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, 'Answered');
581
582 // Insert In-Reply-To and References headers if the
583 // message-id of the message we reply to is set (longer than "<>")
584 // The References header should really be the old Referenced header
585 // with the message ID appended, but it can be only the message ID too.
586 $hdr = sqimap_get_small_header ($imap_stream, $reply_id, false);
587 if(strlen($hdr->message_id) > 2) {
588 $more_headers['In-Reply-To'] = $hdr->message_id;
589 $more_headers['References'] = $hdr->message_id;
590 }
591 }
592
593 // In order to remove the problem of users not able to create
594 // messages with "." on a blank line, RFC821 has made provision
595 // in section 4.5.2 (Transparency).
596 $body = ereg_replace("\n\\.", "\n..", $body);
597 $body = ereg_replace("^\\.", "..", $body);
598
599 // this is to catch all plain \n instances and
600 // replace them with \r\n. All newlines were converted
601 // into just \n inside the compose.php file.
602 $body = ereg_replace("\n", "\r\n", $body);
603
604 if ($useSendmail) {
605 $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers);
606 } else {
607 $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers);
608 }
609
610 if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
611 sqimap_append ($imap_stream, $sent_folder, $length);
612 write822Header ($imap_stream, $t, $c, $b, $subject, $more_headers);
613 writeBody ($imap_stream, $body);
614 sqimap_append_done ($imap_stream);
615 }
616 sqimap_logout($imap_stream);
617 // Delete the files uploaded for attaching (if any).
618 // only if $length != 0 (if there was no error)
619 if ($length)
620 ClearAttachments();
621
622 return $length;
623 }
624
625 ?>