#!/usr/bin/perl
#
# Copyright (c) 2000 SuSE GmbH Nuernberg, Germany.  All rights reserved.
#
#
# $Id: index.pl,v 1.56 2000/11/13 12:22:56 choeger Exp $
#

BEGIN{
    push @INC,"/usr/local/httpd/htdocs/lib"
    }

use CGI;
use imas;
use CGI::Carp qw(fatalsToBrowser);
use Net::LDAP;
use Time::Local;

my $cgi=new CGI;

my $sessionID = $cgi->param('sessionID');
my $uid       = $cgi->param('uid');
my $passwd    = $cgi->param('passwd');
my $doit     = $cgi->param('doit');
my $lang     = $cgi->param('lang');


if(!defined $lang || $lang ne "DE" && $lang ne "EN") {
    $lang = "EN";
}

my %message = get_lang_text("$lang", "LOGIN", "CREATE_USER");

if(defined $doit && $doit eq "login") {
    frameset();
} elsif (defined $uid && $uid ne "" && defined $passwd && $passwd ne ""){
    check_login();
} elsif (defined $sessionID && $sessionID ne ""){
    frameset2();
} else { 
    login();
}

1;

# -- original
sub frameset2 {
    my $LANG;
    my $res = check_sessionID($sessionID);

    if($res ne "OK") {
	print $cgi->header(-refresh=>"0; URL=$imas::confParam{cgi_path}/index.pl");
	print $cgi->start_html(-title=>"");
	print $cgi->end_html;
	exit;
    } else {
	$LANG=$imas::confParam{LANG};
    }

    print $cgi->header(); 
    print "<html> <head> <title>SuSE eMail Server</title> </head> ";
    print "<frameset cols=\"800,*\" border=0>";
    print '<frameset  rows="75,1**" cols="*" border="0" framespacing="0" frameborder="NO"> ';
    print "  <frame name=\"Title\" src=\"$imas::confParam{cgi_path}/title.pl?LANG=$LANG&sessionID=$sessionID\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\" frameborder=\"NO\" noresize>";
    print '  <frameset  cols="175,1*" frameborder="NO" border="0" framespacing="0"> ';
    print "    <frame name=\"LeftBar\" src=\"$imas::confParam{cgi_path}/menu.pl?LANG=$LANG&sessionID=$sessionID\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\" frameborder=\"NO\" noresize>";
    print "    <frame name=\"MainWindow\" src=\"$imas::confParam{cgi_path}/main.pl?sessionID=$sessionID\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"auto\" frameborder=\"NO\" noresize>";
    print '  </frameset>';
    print '</frameset><frame src="/blank.html">';
    print '</frameset>';
    print '<body> Sorry, your browser doesn´t support frames!</body></html>';
}


sub frameset {
    my ($basedn, $ldapserver, $ldapport) = parse_file("/etc/openldap/ldap.conf", "BASE", "HOST", "PORT");

    if($basedn eq "") {
	print status_site($message{error},$message{basedn_missed}, "ERR", "$imas::confParam{cgi_path}/index.pl", 3);
	exit;
    }
    if($ldapserver eq "") {
	$ldapserver = "localhost";
    }
    if($ldapport eq "") {
	$ldapport = 389;
    }

    my $ld = Net::LDAP->new($ldapserver,port=>$ldapport);
    if (!defined $ld || $ld <= 0)
    {
	$text = "LDAP-Server: $message{connection_failed}";
	print_status($ld, $text);
	exit;
    }
    
    my $status = $ld->bind; 

    if ($status->code != 0)  {
	$text = "$message{ldap} $message{bind_failed}";
	print_status($status, $text);
	exit;
    }
    
    my $filter = "preferredLanguage=*";
    $status = $ld->search(
			  base => "uid=cyrus,".$basedn,
			  scope => "base",
			  attrs => ['preferredLanguage'],
			  filter => $filter
			  );
    
    if ($status->code != 0) {
	$text = "$message{search_failed}";
	$ld->unbind;
	print_status($status, $text);
	exit;
    } else {
	my $entry = $status->entry(0);
	$lang = $entry->get_value("preferredlanguage");
	if($lang ne "DE" && $lang ne "EN") {
	    $lang = "EN";
	}
    }
    $ld->unbind;

    print $cgi->header(-target=>"_top");
    print "<html> <head> <title>SuSE eMail Server</title> </head> ";
    print "<frameset cols=\"800,*\" border=0>";
    print '<frameset  rows="75,1**" cols="*" border="0" framespacing="0" frameborder="NO"> ';
    print '<frame name="Title" src="/blank.html" marginwidth="0" marginheight="0" scrolling="no" frameborder="NO" noresize>';
    print '<frameset  cols="175,1*" frameborder="NO" border="0" framespacing="0"> ';
    print '<frame name="LeftBar" src="/blank.html" marginwidth="0" marginheight="0" scrolling="no" frameborder="NO" noresize>';
    print "<frame name=\"MainWindow\" src=\"/imap-bin/index.pl?lang=$lang\" marginwidth=0 marginheight=0 scrolling=\"auto\" frameborder=\"NO\" noresize>";
    print '</frameset>';
    print '</frameset><frame src="/blank.html">';
    print '</frameset>';
    print "<body> Sorry, your browser doesn't support frames!</body></html>";
}



sub login {

    print $cgi->header(-target=>"MainWindow");
    print $cgi->start_html( -title=>"$message{login}", -style=>{-src=>'/imas.css'});
    my $code=<<EOF;
<form method=post action=$imas::confParam{cgi_path}/index.pl target=_top>
<table border=0 cellpadding=0 cellspacing=0 align=center>
  <tr valign=top>
<td><img name=login_r1_c1 src=/images/login_r1_c1.png width=59 height=281 border=0></td>
		<td bgcolor=#ffcc00 align=center valign=top>
			<font size=+1><b>&nbsp;SuSE <font color=green>e</font>Mail Server&nbsp;</b></font>
			<table border=0 cellspacing=0 cellpadding=10 bgcolor=#ffcc00>
				<tr>
					<th colspan=2 align=center bgcolor=#ffcc00>$message{login_txt}</th>
				</tr>
				<tr>
					<td bgcolor=#ffcc00><b>$message{uid}:</b></td>
					<td bgcolor=#ffcc00><input type=text name=uid></td>
				</tr>
				<tr>
					<td bgcolor=#ffcc00><b>$message{password}:</b></td>
					<td bgcolor=#ffcc00><input type=password name=passwd></td>
				</tr>
				<tr>
					<td colspan=2 align=center bgcolor=#ffcc00>
						<font face='Arial, Helvetica, sans-serif'>
							<input type=submit name=OK value=Login>
						</font>
					</td>
				</tr>
			</table>
		</td>
		<td><img name=login_r1_c3 src=/images/login_r1_c3.png width=58 height=281 border=0></td>
	</tr>
</table>
<input type=hidden name=lang value=$lang>
</form>
EOF

    $code =~ s/\n//g;

    print "<script language=\"Javascript\">";
    print "<!--\n";
    print "document.write (\"$code\"); \n";
    print "\n//-->";
    print "</script>";
    print "<noscript>";
    print "<br><br>";
    print $cgi->h1($message{nojava});
    print "</noscript>";
#    print $code;
    print $cgi->end_html();
}

sub check_login {

    my $text       = "";
    
    my ($basedn, $ldapserver, $ldapport) = parse_file("/etc/openldap/ldap.conf", "BASE", "HOST", "PORT");

    if($basedn eq "") {
	print status_site($message{error},$message{basedn_missed}, "ERR", "$imas::confParam{cgi_path}/index.pl", 3);
	exit;
    }
    if($ldapserver eq "") {
	$ldapserver = "localhost";
    }
    if($ldapport eq "") {
	$ldapport = 389;
    }

    #-- open connection to LDAP
    my $ld = Net::LDAP->new($ldapserver,port=>$ldapport);
    if (!defined $ld || $ld <= 0)
    {
	$text = "$message{user} $uid: $message{ldap} $message{connection_failed}";
	print_status($text);
	exit;
    }
    
    #-- bind anonymous
    my $status = $ld->bind; 
    if ($status->code != 0)  {
	$text = "$message{user} $uid: $message{ldap} $message{bind_failed}";
	print_status($text, $status);
	exit;
    }
    
    #-- search for all dn´s for accounts
    my $filter = "(&(uid=$uid)(objectclass=account))";
    $status = $ld->search(
			  base => $basedn,
			  scope => "one",
			  attrs => ['dn'],
			  filter => $filter
			  );
    if ($status->code != 0) {
	$text = "$message{user} $uid: $message{ldap} $message{search_failed}";
	$ld->unbind;
	print_status($text, $status);
	exit;
    }
    #-- found more or less than one entry => error
    if ($status->count != 1) {
	$text = "$message{user} $uid: $message{not_found}";
	$ld->unbind;
	print_status($text);
	exit;
    }
    
    my $entry = $status->shift_entry;
    
    my $dn = $entry->dn;
    
    #-- bind as user
    $status = $ld->bind(
			dn => $dn,
			password => $passwd
			);
    if ($status->code != 0 || $passwd eq "" ) {
	$text = "$message{user} $uid: $message{pass_mismatch}";
	$ld->unbind;
	print_status($text);
	exit;
    }  
    
    #-- search for shadowexpire(is user deactivated?) and the preferred Language
    $filter = "objectclass=account";
    $status = $ld->search(
			  base => $dn,
			  scope => "base",
			  attrs => ['shadowexpire', 'preferredLanguage'],
			  filter => $filter
			  );
    if ($status->code != 0) {
	$text = "$message{user} $uid: $message{ldap} $message{search_failed}";
	$ld->unbind;
	print_status($text, $status);
	exit;
    }
    
    my $result = $status->as_struct;
    my %result = %$result;

    my $shadowExpire;

    if( defined $result{$dn}{shadowexpire} ) {
	$shadowExpire = join "", @{$result{$dn}{shadowexpire}};
    }

    #-- calculate if the account is expired
    my $days_since_1970 = timelocal(localtime()) / 3600 / 24;

    if( defined $shadowExpire && $shadowExpire ne "" && $shadowExpire < $days_since_1970) {
	$text = "$message{user} $uid: $message{access_denied}";
	$ld->unbind;
	print_status($text);
	exit;
    }
    my $lang = "EN";
    if(defined $result{$dn}{preferredlanguage}) {
	$lang = join "", @{$result{$dn}{preferredlanguage}};
    }

    $dn = "uid=cyrus,".$basedn;

    #-- search for imapServer and imapPort
    $status = $ld->search(
			  base => $dn,
			  scope => "base",
			  attrs => ['imapServer', 'imapPort'],
			  filter => "objectclass=account"
			  );
    if ($status->code != 0) {
	$text = "$message{user} $uid: $message{ldap} $message{search_failed}";
	$ld->unbind;
	print_status($text, $status);
	exit;
    }
    
    $result = $status->as_struct;
    %result = %$result;

    my $imapserver = "localhost"; 
    my $imapport = 143;

    if(defined $result{$dn}{imapserver}) {
	$imapserver = join "", @{$result{$dn}{imapserver}};
    }
    if(defined $result{$dn}{imapport}) {
	$imapport = join "", @{$result{$dn}{imapport}};
    }

    # --- Autentication successful

    if(!defined $lang || $lang eq "" || ($lang ne "DE" && $lang ne "EN") ) {
	$lang = "EN";
    }
    if(!defined $imapserver || $imapserver eq "") {
	$imapserver = "localhost";
    }
    if(!defined $imapport || $imapport eq "") {
	$imapport = 143;
    }
    
    #-- add data to session
    my %data = ();
    $data{uid} = $uid; 
    $data{passwd} = $passwd; 
    $data{LDAPserver} = $ldapserver; 
    $data{LDAPport} = $ldapport; 
    $data{baseDN} = $basedn;
    $data{IMAPserver} = $imapserver; 
    $data{IMAPport} = $imapport; 
    $data{LANG} = $lang; 
    
    $sessionID = new_session(%data);

    $ld->unbind;
    
#    print STDERR "sessionID:$sessionID\n";

    if($sessionID =~ /FAILED:(.*)/) {
	print status_site($message{error},
			  $message{start_session_failed}."\n".$1,
			  "ERR", "$imas::confParam{cgi_path}/index.pl?doit=login", 3);
	exit;
    }
    
    frameset2();
    exit;
}

sub print_status($){
    my $text = shift;
    my $ld = shift;

    if(defined $ld && $ld ne "") {
	$text .= LDAPerror($ld);
    }
    print status_site("$message{error}", "$text", "ERR", "/index.html", 3);
}
