[x]
Posted via EE Mobile

Search, ask, and monitor your questions on the go with EE Mobile. Visit Experts Exchange from your mobile device and never be out of touch again.

04/03/2003 at 04:26AM PST, ID: 20572879
[x]
Attachment Details
[x]
The Solution Rating System

With so many solutions, how can you tell which solutions are most likely to help you and which ones are not? To provide you with a tool to use, we rate our solutions based on various elements that most accurately determine if a solution is a quality solution. To explain what factors affect the solution rating, here are the elements we take into consideration when formulating our solution rating.

  • The Grade of the Solution
  • The Zone Rank of the Expert Providing the Solution
  • The Number of Author and Expert Comments
  • The Number of Experts Contributing
  • The Feedback of the Community

Your Input Matters
Because of the way the system is set up, the most important variable in this equation is you. As a member of Experts Exchange, you are able to cast your vote on the quality of the solutions in regard to how complete, accurate, helpful and easy to understand each solution is. When you provide your feedback, each rating is adjusted accordingly. So, if you see a solution that has a poor rating that you think is a good solution, let us know by rating it. As you do, the rating will be adjusted and will become more accurate for other members of our site.

If you have any suggestions that you would like to make for our rating system, please ask a question in the Suggestions Zone of Community Support.

Thank you!

5.8

Premature end of script headers: URGENT HELP PLZ

Asked by sohaib69 in Perl Programming Language

Tags: end, premature, script, headers

Sir, Everything is working fine on my server just only admin.pl never work, when ever I run that script on my server I always got Premature end of script headers: the reason not known I will appreciate if u plz kindly help me also that script work fine on my other server but when I wanted to run that script onto some other server of mine that give me some problem so plz plz help, the script are as follows :-

=====
#!/usr/bin/perl
use strict;
use lib "/home/www/libs/"; # Change to your path
use lib "../libs";

no strict "refs";

$|++;

eval "use Myownemail::SQL;";

use Myownemail::Config;
use Myownemail::Global;
use Myownemail::Log;
use Time::CTime;
use Myownemail::SendMsg;
use Crypt::PasswdMD5;


use vars qw($sql @ISA);

if ( $pref{sql_type} ) {
    $sql = new Myownemail::SQL;
}
else {
    $sql = new Myownemail::Flat;
}

my %var;

# Default table colour
$var{class} = "even";

my $myownemail = new Myownemail::Global();

print $myownemail->header();

$var{func}   = $myownemail->param('func');
$var{delete} = $myownemail->param('delete');

if ( $var{delete} ) {

    # Just in case ...
    $var{delete} =~ s/\.\.//g;

    if ( $pref{sql_type} ) {
        &deleteuser_sql( $var{delete} );
    }
    else {
        &deleteuser_flat( $var{delete} );
    }

}

if ( $var{func} eq "adduser" ) {
    $var{domainbox} = $myownemail->domains();
    $var{langbox}   = $myownemail->languages();
    $var{langbox} =~ s/<select/<select class='option'/g;
    print $myownemail->parse("html/adminheader.html");
    print $myownemail->parse( "html/newuser.html", %var );
    exit;
}

# A message composition screen
elsif ( $var{func} eq "compose" ) {

    my (@id);

    # Search users via the SQL database
    if ( $pref{sql_type} ) {

        $var{query} = makesql_query();

      # Make a default query, if the user selected nothing
      $var{query} = "select id from Users where Account is not null" if($var{query} eq
"select id from Users where ");

        # If viewing the email addresses

        $var{query} =~ s/select id/select Account/g;
        @id = $sql->idquery( $var{query}, "Account" );

    }
    else {

        # Search for users in the flat-file database.

        $var{query} = makeflat_query();

        # List all usera matching @ if 'All Users' selected
        $var{Account} = "\@" if ( $var{query} );

        @id = searchusers_flat( $var{query} );
    }

    # If we are showing all the users
    if ( $myownemail->param('all') ) {

        foreach (@id) {

            # Loop through and print
            $var{class}        = ( $var{class} eq "odd" ) ? "even" : "odd";
            $var{massmailuser} = "$_";
            $var{massmailuserlist} .=
              $myownemail->parse( "html/massmailuser_entry.html", %var );
        }

        $var{title} = "Massmail Userlist";
        print $myownemail->parse( "html/adminheader.html",      %var );
        print $myownemail->parse( "html/massmailuserlist.html", %var );

        # Then print the final template
        # myownemail->parse('showusertomail.html')

    }
    else {

        $var{count} = scalar(@id);

        $myownemail->{PrimaryColor}   = "#E8E9FD";
        $myownemail->{SecondaryColor} = "#F5F7BF";

        #$myownemail->{HeaderColor} = "gray";
        $myownemail->{FontStyle} = "Verdana";

        $var{myownemailstyle} = $myownemail->parse("css/myownemailstyle.css");

        $var{title} = "Mass Mail $var{count} users";
        print $myownemail->parse( "html/adminheader.html", %var );
        $var{editor} = $myownemail->param("Editor");

        # print $var{editor};

        if ( $var{editor} eq "html" && $ENV{HTTP_USER_AGENT} !~ /Mac/ ) {
            print $myownemail->parse( "html/composehtml.html", %var );
        }
        if ( $var{editor} eq "txt" ) {
            print $myownemail->parse( "html/composetext.html", %var );
        }

    }

}
# Change the users quota
elsif ( $var{func} eq "changequota" )      {

   # Load the CGI vars
   my $account = $myownemail->param('Account');
   my $quota   = $myownemail->param('quota');

   if ( $pref{sql_type} )      {

      # Find the SQL table for the user account
      $sql->table_names($account);

      # Escape any special characters
      $quota   = $sql->quote($quota);
      $account = $sql->quote($account);

      # Execute the SQL query to update the UserQuota field
      $sql->sqlquery("update $sql->{UserSettings} set UserQuota=$quota where Account=$account");

      #print "update $sql->{UserSettings} set UserQuota=$quota where Account=$account<BR>";
      print "Updated account $account - $quota";

      }

}

elsif ( $var{func} eq "sendmail" ) {

    my (@id);

    # Search users via the SQL database
    if ( $pref{sql_type} ) {

        $var{query} = makesql_query();
        $var{query} =~ s/select id/select Account/g;
        @id = $sql->idquery( $var{query}, "Account" );

        # print $var{query};
        # foreach(@id)      { print "$_ -"; }

    }
    else {

        $var{query} = makeflat_query();

        # List all usera matching @ if 'All Users' selected
        $var{Account} = "\@" if ( $var{query} );

        @id = searchusers_flat( $var{query} );

    }

    # Load our email message vars
    $var{emailto}       = $myownemail->param('emailto');
    $var{From}          = $myownemail->param('From');
    $var{emailsubject}  = $myownemail->param('emailsubject');
    $var{emailpriority} = $myownemail->param('emailpriority');
    $var{contype}       = $myownemail->param('contype');
    $var{unique}        = $myownemail->param('unique');
    $var{UIDL}          = $myownemail->param('UIDL');
    $var{type}          = $myownemail->param('type');

    foreach (@id) {
        my $to = $_;

        # Make a new UIDL if one does not exist
        if ( !$var{UIDL} ) {
            $var{UIDL} = time() . $$ . rand(9000) . $myownemail->genkey();
            $var{UIDL} =~ s/\..*//g;
        }

        $var{count} = scalar(@id);

        # Build the message to send . Add the headers, message body and UIDL
        my $sendmsg = Myownemail::SendMsg->new(
          Account       => "$var{From}",
          EmailTo       => $to,
          EmailFrom     => "$var{From}",
          EmailSubject  => $var{emailsubject},
          EmailPriority => $var{emailpriority},
          ContentType   => $var{contype},
          XMailer    => "Myownemail $myownemail->{version} - http://myownemail.info/",
          EmailBox   => $var{msgbox},
          EmailUIDL  => $var{UIDL},
          Unique     => $var{unique},
          'X-Origin' => $ENV{REMOTE_ADDR},
          EmailMessage => $myownemail->param('emailmessage')

        );

        my $top = $sendmsg->buildmsg();

        $sendmsg->deliver($top);

      # Print something to the browser, so it does not time out
      print "<>";
      sleep 1;

    }
    print $myownemail->parse("html/adminheader.html");
    $var{status} = "Massmailing complete, emailed $var{count} user(s)<br><br>";
    print $myownemail->parse( "html/massmail.html", %var );
}

# The user is registering the software      
elsif ( $var{func} eq "register" ) {

    use Net::Domain qw(hostname);
    $var{hostname} = hostname();

    if ( $myownemail->param('write') ) {

        $reg{ID} = $myownemail->param('ID');
        $reg{expiry}     = $myownemail->param('expiry');
        $reg{serial}     = $myownemail->param('serial');

        #checksum("$reg{ID}$hostname$reg{company}$reg{URL}");

        &write_conf();
    }

    $reg{URL} = $ENV{HTTP_REFERER} if ( !$reg{URL} );
    $reg{URL} =~ s/(.*)\/webadmin.*/$1/g;

    print $myownemail->parse("html/adminheader.html");
    print $myownemail->parse( "html/registration.html", %var );

    $myownemail->cleanup();

}
elsif ( $var{func} eq "splash" ) {

    print $myownemail->parse("html/adminheader.html");
    print $myownemail->parse( "html/splash.html", %var );

}
elsif ( $var{func} eq "modifyuser" ) {

    print $myownemail->parse("html/adminheader.html");
    print $myownemail->parse( "html/modifyuser.html", %var );

}

elsif ( $var{func} eq "deleteuser" ) {
    print $myownemail->parse("html/adminheader.html");

    $var{user} = $myownemail->param("user");

    if ( $var{user} ) {
        my %user;

        if ( $pref{sql_type} ) {
            %user =
              $sql->doquery("select * from Users where Account='$var{user}'");
        }
        else {
            %user =
              Myownemail::Flat->gethash( "$pref{user_dir}/users/$var{user}/login.db"
            );
        }

        if ( $user{Account} ) {
            $var{status} = "Deleted user: $var{user}";

            &deleteuser_sql("$var{user}") if ( $pref{sql_type} );
            &deleteuser_flat("$var{user}") if ( !$pref{sql_type} );

        }
        else {
            $var{status} =
              "No such user exists on the system. Please try again.";

        }

    }
    print $myownemail->parse( "html/deleteuser.html", %var );
}

elsif ( $var{func} eq "searchusers" ) {

    print $myownemail->parse("html/adminheader.html");
      
      $var{Groups} = group_options();
    $var{domainbox} = $myownemail->domains();
    print $myownemail->parse( "html/searchusers.html", %var );

}

elsif ( $var{func} eq "massmail" ) {

    print $myownemail->parse("html/adminheader.html");

      $var{Groups} = group_options();
    $var{domainbox} = $myownemail->domains();
    print $myownemail->parse( "html/massmail.html", %var );

}

elsif ( $var{func} eq "cds" ) {

    # Open the install_size SQL query
    open( F, "../db/$pref{install_size}.sql" );
    my $f;

    # Load the SQL statments into a temp var
    while (<F>) {

        # Skip comments
        next if ( $_ =~ /^#/ );
        $f .= $_;
    }

    # Split each SQL query into bits
    my @sql = split ( ";", $f );

    my @tables = $sql->func('_ListTables');
    my %tbl;

    # Load table names into a hash
    foreach (@tables) { $tbl{$_}++ }

    foreach my $query (@sql) {

        # Get the Create table name
        my $name = $1 if ( $query =~ /CREATE TABLE (.*) \(/i );

        print "<b>.</b>";

        next if ( !$name );

        if ( !$tbl{$name} ) {

            # Creating the structure
            $sql->sqlquery($query);
            $var{db} .= "$name created<BR>";
        }
        else {
            $var{db} .= "$name already exists <br>";
        }
    }
    $var{title} = "Create Database Structure";
    print $myownemail->parse( "html/adminheader.html", %var );
    print $myownemail->parse( "html/cds.html",         %var );

}
elsif ( $var{func} eq "migrate" ) {

    print $myownemail->parse("html/adminheader.html");

    $var{migratefile} = $myownemail->param('migratefile');

    if ( $myownemail->param('Add') ) {

        open( F, "$pref{user_dir}/tmp/migrate.txt" );

        # check for file

        while (<F>) {
            my $line = $_;
            my ( $user, $pass, $domain );

            # Take away the last \n
            chomp($line);

            #$line =~ s/ //g;
            $line =~ s/$/,/g;

            my @user = split ( /\s?,\s?/, $line );

            # Skip if migrate file is invalid
            next if ( !$user[1] || !$user[2] );

            my $auth = new Myownemail::Auth;

            $auth->{Account}  = $user[0] . "\@" . $user[2];
            $auth->{pop3host} = $user[2];
            $auth->{password} = $user[1];

          # Lowercase input
          $auth->{Account} = lc($auth->{Account});
          $auth->{pop3host} = lc($auth->{pop3host});

      # Take away the last training space, if it exists
      foreach('Account', 'password' , 'pop3host')      {
          $auth->{$_} =~ s/ $//g;      
      }

my %users;
 $users{FirstName} = ucfirst($user[3]);
 $users{LastName} = ucfirst($user[4]);
 $users{PasswordQuestion} = $user[5];
 $users{OtherEmail} = $user[6];
 $users{BirthDay} = $user[7];
 $users{BirthMonth} = $user[8];
 $users{BirthYear} = $user[9];
 $users{Gender} = uc($user[10]);
 $users{Industry} = $user[11];
 $users{Occupation} = $user[12];
$users{Address} = $user[13];
 $users{City} = $user[14];
 $users{State} = $user[15];
 $users{PostCode} = $user[16];
 $users{Country} = $user[17];
 $users{LoginType} = $user[18] || 'blue_pane';
 $users{Service} = $user[19];

            $var{status} = $auth->newuser(1, %users);

            $var{Account} = $user[0] . "\@" . $user[2];
            $var{status}  = "OK" if ( $var{status} == 0 );
            $var{status}  = "Already Exists" if ( $var{status} == 2 );

            $var{migratelist} .=
              $myownemail->parse( "html/migrate_entry_run.html", %var, %user);

        }

        print $myownemail->parse( "html/migraterun.html", %var );

        # Delete the old migrate.txt file

        unlink("$pref{user_dir}/tmp/migrate.txt");
    }

    # Upload the file to the server
    elsif ( $var{migratefile} ) {

        attach("migratefile");

        open( F, "$pref{user_dir}/tmp/migrate.txt" );

        # check for file

        while (<F>) {
            my $line = $_;
            my ( $user, $pass, $domain );

            # Create an array of our usernames
            my @user = split ( ",", $line );
            $var{migratecount}++;

my %users;
 $users{Account} = $user[0];
 $users{password} = $user[1];
 $users{pop3host} = $user[2];
 $users{FirstName} = $user[3];
 $users{LastName} = $user[4];
 $users{PasswordQuestion} = $user[5];
 $users{OtherEmail} = $user[6];
 $users{BirthDay} = $user[7];
 $users{BirthMonth} = $user[8];
 $users{BirthYear} = $user[9];
 $users{Gender} = $user[10];
 $users{Industry} = $user[11];
 $users{Occupation} = $user[12];
$users{Address} = $user[13];
 $users{City} = $user[14];
 $users{State} = $user[15];
 $users{PostCode} = $user[16];
 $users{Country} = $user[17];
 $users{LoginType} = $user[18] || 'blue_pane';
 $users{Service} = $user[19];

            $var{migratelist} .= $myownemail->parse(
              "html/migrate_entry.html", %users
            );

        }

        if ( !$var{migratelist} ) {
            $var{status} = "File contained no valid information";
            print $myownemail->parse( "html/migrate.html", %var );
        }
        else {
            print $myownemail->parse( "html/migrateconfirm.html", %var );
        }
    }

    else {
        print $myownemail->parse( "html/migrate.html", %var );
    }
}

elsif ( $var{func} eq "searchinguser" ) {

    # Search users via the SQL database
    if ( $pref{sql_type} ) {

        $var{query} = makesql_query();

        #print "<font color='red'>$var{query}-</font>";

        # If the SQL query is empty
        if ( $var{query} =~ /where $/ ) {
            $var{status} = "No query specified";
            $var{query}  = "select id from Users";
        }

    }
    else {

        $var{query} = makeflat_query();

        # Search user via the flat-file databases
    }

    $var{userlist} = searchusers( $var{query} );

    print $myownemail->parse( "html/adminheader.html", %var );
    print $myownemail->parse( "html/users.html",       %var );

}

elsif ( $var{func} eq "who" ) {

    if ( $pref{sql_type} ) {

        my $time = time();
        my $userlist;

        $time = $time - 3600;

        $var{status} = <<_EOF;

Users Online <a href="javascript:adminhelp('who')"><img src="imgs/help_small.gif" border="0" alt="Show Help for Who is Online"></a>
            
_EOF

        $var{comment} =
"This is a list of users currently logged into \Myownemail in the last 60 minutes.
        Click 'Edit' to change users account details, or choose to delete the user.";

        my @id =
          $sql->idquery(
"select Account from UserSession where LastLogin > $time GROUP by LastLogin",
          "Account" );

        foreach (@id) {
          my $user = $_;

            my %db =
              $sql->doquery(
              "select Account,DateCreate from Users where Account='$_'");
            

            $var{time} = $sql->getvalue( "select LastLogin from UserSession
                        where Account='$db{Account}'" );

            $var{time} = strftime( "%a %D %R", localtime( $var{time} ) );

              # Parse the date into a more reabable format
            $db{DateCreate} =~ /(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/;
            $db{DateCreate} = "$3/$2/$1 $4:$5:$6";

            $var{userlist} .=
              $myownemail->parse( "html/user_entry.html", %db, %var );
        }

        print $myownemail->parse( "html/adminheader.html", %var );
        print $myownemail->parse( "html/users.html",       %var );

    }
    else {
        print $myownemail->parse( "html/adminheader.html", %var );
        print $myownemail->parse("html/notyet.html");
    }

}

elsif ( $var{func} eq "stats" ) {

    # Get today's date in mySQL format
    get_date();

    $var{type} = $myownemail->param('type');

    # Load the system's name
    $var{system} = $^O;

    my $day     = 86400;
    my $week    = 604800;
    my $timenow = time();

      # Check if the WebServer is running under Mod_Perl
      if($ENV{SERVER_SOFTWARE} =~ /mod_perl/)      {
      $var{mod_perl} = "<font class='sw'>Installed</a></font>";
      } else      {
      $var{mod_perl} = "<font class='sw'>Not Installed</a></font>";
      }

    # Get the date in mySQL format, seven days ago.
    $var{WeekDate} = calc_week( time() );

    if ( !$var{type} && $pref{sql_type} ) {

        $var{UserCount} = $sql->getvalue("select count(id) from Users");
        $var{UserToday} =
          $sql->getvalue(
          "select count(id) from Users where DateCreate like '$var{time}%'");
        $var{UserWeek} =
          $sql->getvalue(
          "select count(id) from Users where DateCreate > $var{WeekDate}");

        $var{LoginCount} = $sql->getvalue("select count(id) from Log_Login");
        $var{LoginToday} =
          $sql->getvalue(
          "select count(id) from Log_Login where LogDate like '$var{time}%'");
        $var{LoginWeek} =
          $sql->getvalue(
          "select count(id) from Log_Login where LogDate > $var{WeekDate}");

        $var{SentCount} = $sql->getvalue("select count(id) from Log_SendMail");
        $var{SentToday} =
          $sql->getvalue(
          "select count(id) from Log_SendMail where LogDate like '$var{time}%'"
        );
        $var{SentWeek} =
          $sql->getvalue(
          "select count(id) from Log_SendMail where LogDate > $var{WeekDate}");

        $var{MsgCount} = $sql->getvalue("select count(id) from Log_RecvMail");
        $var{MsgToday} =
          $sql->getvalue(
          "select count(id) from Log_RecvMail where LogDate like '$var{time}%'"
        );
        $var{MsgWeek} =
          $sql->getvalue(
          "select count(id) from Log_RecvMail where LogDate > $var{WeekDate}");

        $var{ErrorCount} = $sql->getvalue("select count(id) from Log_Error");
        $var{ErrorToday} =
          $sql->getvalue(
          "select count(id) from Log_Error where LogDate like '$var{time}%'");
        $var{ErrorWeek} =
          $sql->getvalue(
          "select count(id) from Log_Error where LogDate > $var{WeekDate}");

        print $myownemail->parse("html/adminheader.html");
        print $myownemail->parse( "html/stats.html", %var );

        $myownemail->cleanup();
    }
    elsif ( !$var{type} ) {

        use Time::ParseDate;

        # $var{UserCount} = $sql->getvalue("select count(id) from Users");
        # $var{UserToday} =
        #   $sql->getvalue(
        #   "select count(id) from Users where DateCreate like '$var{time}%'");
# $var{UserWeek} = $sql->getvalue("select count(id) from Users where DateCreate > $var{WeekDate}");

        # Open the user directory
        opendir( DIR, "$pref{user_dir}/users/" )
          || print "Cannot open $pref{user_dir}/users/ : $!";
        my @fol = readdir(DIR);
        my @id;

        # Loop through each user, and check their last login date
        foreach (@fol) {
            my $fol = $_;
            next if ( $fol !~ /@/ );
            push ( @id, "$fol" );
        }

        $var{UserCount} = scalar(@id);

        foreach (@id) {
            my $user = $_;

            my $time = ( ( stat("$pref{user_dir}/users/$user/user.db") )[9] );

            my $now = $timenow - $day;
            $var{UserToday}++ if ( $time > $now );

            my $now = $timenow - $week;
            $var{UserWeek}++ if ( $time > $now );

        }

        open( F, "$pref{user_dir}/Login.log" );
        while (<F>) {
            my $line = $_;
            my ( $now, $log );

            my $time = $1 if ( $line =~ /(.*? \d{4}):/ );

            $time = parsedate($time);
            $var{LoginCount}++;

            my $now = $timenow - $day;
            $var{LoginToday}++ if ( $time > $now );

            my $now = $timenow - $week;
            $var{LoginWeek}++ if ( $time > $now );

        }
        close(F);

        open( F, "$pref{user_dir}/Error.log" );
        while (<F>) {
            my $line = $_;
            my ( $now, $log );

            my $time = $1 if ( $line =~ /(.*? \d{4}):/ );

            $time = parsedate($time);
            $var{ErrorCount}++;

            my $now = $timenow - $day;
            $var{ErrorToday}++ if ( $time > $now );

            my $now = $timenow - $week;
            $var{ErrorWeek}++ if ( $time > $now );

        }
        close(F);

        open( F, "$pref{user_dir}/RecvMail.log" );
        while (<F>) {
            my $line = $_;
            my ( $now, $log );

            my $time = $1 if ( $line =~ /(.*? \d{4}):/ );

            $time = parsedate($time);
            $var{MsgCount}++;

            my $now = $timenow - $day;
            $var{MsgToday}++ if ( $time > $now );

            my $now = $timenow - $week;
            $var{MsgWeek}++ if ( $time > $now );

        }
        close(F);

        open( F, "$pref{user_dir}/SendMail.log" );
        while (<F>) {
            my $line = $_;
            my ( $now, $log );

            my $time = $1 if ( $line =~ /(.*? \d{4}):/ );

            $time = parsedate($time);
            $var{SentCount}++;

            my $now = $timenow - $day;
            $var{SentToday}++ if ( $time > $now );

            my $now = $timenow - $week;
            $var{SentWeek}++ if ( $time > $now );

        }
        close(F);

        print $myownemail->parse("html/adminheader.html");
        print $myownemail->parse( "html/stats.html", %var );

        $myownemail->cleanup();

    }

    # Specified a log file to expand
    if ( $var{type} && $pref{sql_type} ) {

        #            $var{db} = "Log_SendMail" if ( $var{type} eq "SentCount" );
        #        $var{db} = "Log_Login" if ( $var{type} eq "LoginCount" );
        #        $var{db} = "Log_RecvMail" if ( $var{type} eq "MsgCount" );
        #        $var{db} = "Log_Error" if ( $var{type} eq "ErrorCount" );

        $var{WeekDate} = calc_week( time() );

        $var{db} = "Log_SendMail" if ( $var{type} =~ /^Sent/ );
        $var{db} = "Log_Login" if ( $var{type}    =~ /^Login/ );
        $var{db} = "Log_RecvMail" if ( $var{type} =~ /^Msg/ );
        $var{db} = "Log_Error" if ( $var{type}    =~ /^Error/ );
        $var{db} = "Log_Virus" if ( $var{type}    =~ /^Virus/ );

        $var{db} = "Users" if ( $var{type} =~ /User/ );

        if ( $var{type} =~ /User/ ) {
            $var{options} =
              "where DateCreate like '$var{year}$var{month}$var{day}%'"
              if ( $var{type} =~ /Today/ );

            $var{options} = "where DateCreate  > $var{WeekDate}"
              if ( $var{type} =~ /Week/ );

            $var{sql} = "select id from Users $var{options} order by id";
        }

        else {
            $var{options} =
              "where LogDate like '$var{year}$var{month}$var{day}%'"
              if ( $var{type} =~ /Today/ );

            $var{options} = "where LogDate  > $var{WeekDate}"
              if ( $var{type} =~ /Week/ );

            $var{sql} = "select id from $var{db} $var{options} order by id";
        }

        my @id = $sql->idquery( $var{sql}, "id" );

        # The total number of log entrys
        $var{total}   = scalar(@id);
        $var{num}     = 100 if ( !$var{num} );
        $var{msg_pos} = $myownemail->param('start') || $var{total} - $var{num};

        # Create the next / prev buttons if nessasary
        if ( $var{msg_pos} + $var{num} < $var{total} ) {
            my $next_pos = $var{msg_pos} + $var{num};

            $var{next} = <<_EOF;
<a href="admin.pl?func=stats&type=$var{type}&start=$next_pos">
<img src="imgs/next.gif" border=0 alt="Next messages">
</a>
_EOF
        }

        if ( $var{total} - $var{num} >= 0 && $var{msg_pos} != 1 ) {
            my $prev_pos = $var{msg_pos} - $var{num};
            $prev_pos = 1 if ( $prev_pos <= 0 );

            $var{prev} = <<_EOF;
<a href="admin.pl?func=stats&type=$var{type}&start=$prev_pos">
<img src="imgs/previous.gif" border=0 alt="Previous messages">
</a>
_EOF
        }

# Find which messages to display, depending if the user clicked 'next/prev' buttons
        $var{msg_pos} = $var{total} - $var{num}
          if ( $var{msg_pos} + $var{num} > $var{total} );
        $var{msg_pos} = 0 if ( $var{msg_pos} <= 1 );

        $var{total} = $var{msg_pos} + $var{num}
          if ( $var{msg_pos} + $var{num} <= $var{total} );

        # List messages from the newest to oldest
        for ( my $i = $var{total} ; $i >= $var{msg_pos} ; $i-- ) {
            $var{id} = $id[$i];
            next if ( !$var{id} );

            my %db =
              $sql->doquery("select * from $var{db} where id='$var{id}'");

            if ( $var{db} eq "Users" ) {
                $db{LogDate} = $db{DateCreate};
                $db{LogMsg}  = "Created new user";
            }

            # Parse the date into a more reabable format
            $db{LogDate} =~ /(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/;
            $db{LogDate} = "$3/$2/$1 $4:$5:$6";
            $var{class} = ( $var{class} eq "odd" ) ? "even" : "odd";
            $var{log} .= $myownemail->parse( "html/stats_entry.html", %db, %var );
        }

        print $myownemail->parse("html/adminheader.html");
        print $myownemail->parse( "html/stats_expand.html", %var );

        $myownemail->cleanup();
    }
    elsif ( $var{type} ) {

        # FLAT FILE VERSION
        my $type;

        $var{db} = "SendMail" if ( $var{type} =~ /^Sent/ );
        $var{db} = "Login" if ( $var{type}    =~ /^Login/ );
        $var{db} = "RecvMail" if ( $var{type} =~ /^Msg/ );
        $var{db} = "Error" if ( $var{type}    =~ /^Error/ );

        if ( $var{type} =~ /User/ ) {

            # Open the user directory
            opendir( DIR, "$pref{user_dir}/users/" )
              || print "Cannot open $pref{user_dir} : $!";
            my @fol = readdir(DIR);
            my @id;

            # Loop through each user, and check their last login date
            foreach (@fol) {
                my $fol = $_;
                next if ( $fol !~ /@/ );
                push ( @id, "$fol" );
            }

            foreach (@id) {
                my $user = $_;
                $var{id}++;
                $var{Account} = $user;
                $var{LogDate} = "";
                $var{LogMsg}  = "New User";

                my $time =
                  ( ( stat("$pref{user_dir}/users/$user/user.db") )[9] );

                if ( $var{type} =~ /Today/ && $time > ( $timenow - $day ) ) {
                    $var{LogDate} = $time;
                }
                elsif ( $var{type} =~ /Week/ && $time > ( $timenow - $week ) ) {
                    $var{LogDate} = $time;
                }
                else {
                    $var{LogDate} = $time;
                }

                $var{log} .= $myownemail->parse( "html/stats_entry.html", %var )
                  if ( $var{LogDate} );

            }

        }
        else {

            # Open the specified log file
            open( F, "$pref{user_dir}/$var{db}.log" )
              || print "Cannot open $pref{user_dir}/$var{db}.log : $!";
            while (<F>) {
                my $line = $_;
                $var{id}++;

                $line =~ /(.*?\d{4}):(.*):(.*)/;

                $var{LogDate} = $1;
                $var{Account} = $2;
                $var{LogMsg}  = $3;

                my $time = $1 if ( $line =~ /(.*? \d{4}):/ );

                $time = parsedate($time);

                if ( $var{type} =~ /Week/ ) {
                    my $now = $timenow - $week;

                    if ( $time > $now ) {
                        $var{log} .=
                          $myownemail->parse( "html/stats_entry.html", %var );
                        $var{total}++;
                    }

                }
                elsif ( $var{type} =~ /Today/ ) {
                    my $now = $timenow - $day;

                    if ( $time > $now ) {
                        $var{log} .=
                          $myownemail->parse( "html/stats_entry.html", %var );
                        $var{total}++;
                    }

                }
                else {
                    $var{log} .=
                      $myownemail->parse( "html/stats_entry.html", %var );
                    $var{total}++;
                }

            }

        }

        print $myownemail->parse("html/adminheader.html");
        print $myownemail->parse( "html/stats_expand.html", %var );

        $myownemail->cleanup();

    }

}

elsif ( $var{func} eq "purgeusers" ) {

    $var{days}    = $myownemail->param('days');
    $var{secs}    = 86400 * $var{days};
    $var{time}    = time() - $var{secs};
    $var{confirm} = $myownemail->param('confirm');
    my (@id);

    if ( $pref{sql_type} ) {
        @id =
          $sql->idquery(
          "select Account from UserSession where LastLogin < $var{time}",
          "Account" );
    }

    else {

        # FLAT FILE
        use Myownemail::Flat;
        my $f = new Myownemail::Flat;

        # Open the user directory
        opendir( DIR, "$pref{user_dir}/users/" )
          || print "Cannot open $pref{user_dir} : $!";
        my @fol = readdir(DIR);

        # Loop through each user, and check their last login date
        foreach (@fol) {
            my $fol = $_;
            next if ( $fol !~ /@/ );

            # Find the lastlgon
            my %db = $f->gethash("$pref{user_dir}/users/$fol/login.db");

# Add the user to the array, if their time lastlogin < time - (x * days)
            push ( @id, "$fol" ) if ( $db{LastLogin} < $var{time} );

        }

    }

    # If we are confirming the deletion
    if ( $var{confirm} ) {

        $var{status} = "- Deleted " . scalar(@id) . " user accounts";

        foreach (@id) {
            &deleteuser_sql("$_") if ( $pref{sql_type} );
            &deleteuser_flat("$_") if ( !$pref{sql_type} );
        }

        print $myownemail->parse('html/adminheader.html');
        print $myownemail->parse( 'html/purgeusers.html', %var );

        # List the users to delete
    }
    elsif ( $var{days} && $id[0] ) {
        $var{ucount} = scalar(@id);
        print $myownemail->parse("html/adminheader.html");
        print $myownemail->parse( "html/purgeusersalert.html", %var );

        foreach (@id) {
            $var{user} = $_;
            print $myownemail->parse( "html/purgeusers_entry.html", %var );
        }
    }

    else {
        print $myownemail->parse("html/adminheader.html");
        print $myownemail->parse("html/purgeusers.html");
    }

}
elsif ( $var{func} eq "purgemessages" ) {

    print $myownemail->parse("html/adminheader.html");

    if ( !$pref{sql_type} ) {
        print $myownemail->parse("html/notyet.html");
        $myownemail->cleanup();
    }
    else {

        $var{search} = $myownemail->param('search');

        if ( $var{search} ) {

            $var{extra} = "where ";

            $var{EmailBody} = $myownemail->param('EmailBody');

            # Loop through each field
            foreach ( 'EmailSubject', 'EmailFrom', 'EmailTo', 'EmailBody',
              'Size', 'EmailBox', 'unread', 'received' )
            {
                my $name = $_;

                # Load the field search type
                my $search = $name . "_o";

                # Load the value of the search field
                my $value = $myownemail->param($name);

                $var{$search} = $myownemail->param($search);

                $var{hidden} .=
                  "<input type='hidden' name='$name' value='$value'>\n";
                $var{hidden} .=
                 "<input type='hidden' name='$search' value='$var{$search}'>\n";

                # Add in % for like querys
                if ( $var{$search} eq "like" || $var{$search} eq "not like" ) {
                    next if ( !$value );
                    $value = "%" . $value . "%";
                }

                if ( $myownemail->param('pop3host') && $name eq "Account" ) {
                    $value = "$value\@" . $myownemail->param("pop3host");
                }

                next
                  if ( !$var{$search} || $name eq "EmailBody" || $name eq "Size"
                  || $name eq "EmailBox" && !$value || $name eq "unread"
                  || $name eq "received" );

                # SQL quote the query
                $var{$name} = $sql->quote($value);

                # Create our extended SQL query
                $var{extra} .= "$name $var{$search} $var{$name} and "
                  if ( $var{$name} );

            }

            $var{extra} =~ s/and $//g;
            $var{confirm} = $myownemail->param('confirm');
            if ( $pref{sql_type} ) {

                # If we are SQL

                # If we use the 'normal' size SQL tables
                if ( $pref{install_size} eq "normal" ) {

                    my $cnt;
                    for ( 'a' .. 'z' ) {
                        my @id;
                        my $db = $_;
                        my $extra;
                        my $q;

                        # Create a default SQL query
                        $var{extra} = "where id is not null"
                          if ( $var{extra} eq "where " );

                        # Search the message by Received date
                        if ( $myownemail->param('received') ) {
                            my $type = $myownemail->param('received_o');

# If the user is searching for records older/newer/like the current date
                            my $t =
                              time() - ( 86400 * ( $myownemail->param('received') *
                              $myownemail->param('received_p') ) );
                            $t = get_date($t);
                            $t .= "000000";    # Append Minutes / Seconds
                            $q = "and EmailDatabase_$db.EmailDate $type $t";
                        }

                        if ( $myownemail->param('Size') ) {

                        }

                        # Search the EmailMessage table if required
                        if ( $var{EmailBody} ) {
                            $var{sql} =
"select EmailDatabase_$_.id from  EmailDatabase_$_, EmailMessage_$_ $var{extra} and
                        EmailMessage_$_.EmailMessage like '%$var{EmailBody}%' and EmailMessage_$_.id = EmailDatabase_$_.id $q";
                        }
                        else {
                            $var{sql} =
"select EmailDatabase_$db.id from EmailDatabase_$db $extra $var{extra} $q ";

                            #print $var{sql};
                        }

                        #print $var{sql} .  "<BR>";

                        @id = $sql->idquery( $var{sql}, "id" );

# If the user is searching if the message is unread , read or unread for X amount of time.
                        my @tmp;
                        $var{'unread_o'} = $myownemail->param('unread_o');

                        if ( $var{'unread_o'} ne "irrelevant" ) {
                            my $extra;

# If the user is searching for records older/newer/like the current date
                            my $t =
                              time() - ( 86400 * ( $myownemail->param('unread') *
                              $myownemail->param('unread_p') ) );

                            #print "Time Now: " . time();
                            #print "<BR>Time Sel: $t<BR>";
                            #print "Localtime: " . localtime(time);
                            #print "<BR>MyTime: " . localtime($t) . "<BR>";
                            #print "<BR>MySQLTime: " . get_date("$t") . "<BR>";

                            $t = get_date($t);
                            $t .= "000000";    # Append Minutes / Seconds

                            if ( $var{'unread_o'} =~ /<|>|like/ ) {
                                $extra =
"and EmailDatabase_$db.EmailDate $var{'unread_o'} $t";
                            }

                            foreach (@id) {
                                my $i = $_;

# Add new entrys to the array, that match our query
                                push ( @tmp, $sql->getvalue(
"select EmailDatabase_$db.id from EmailDatabase_$db, EmailUIDL_$db where EmailDatabase_$db.id='$i' and EmailDatabase_$db.EmailUIDL $var{'unread_o'} EmailUIDL_$db.EmailUIDL $extra"
                                  ) );
                            }

                            # Load our temp array into the @id
                            @id = @tmp if ( $tmp[0] );

                        }

                        # If we are searching by the Unread tags
                        # if($myownemail

                        $var{mcount} = scalar(@id) + $var{mcount};
                        $var{mcount} = "$var{mcount} (listing only 300 emails)"
                          if ( $var{mcount} > 100 && !$var{confirm} );

                        foreach (@id) {
                            $var{message} = "$_";
                            my %db =
                              $sql->doquery(
                              "select * from EmailDatabase_$db where id='$_'");

                            # If we have confirmed, delete the message
                            if ( $var{confirm} ) {

                                $sql->sqlquery(
                                  "delete from EmailDatabase_$db where id='$_'"
                                );
                                $sql->sqlquery(
                                  "delete from EmailMessage_$db where id='$_'");

                            }
                            elsif ( $cnt < 300 ) {
                                $cnt++;
                                $var{class} =
                                  ( $var{class} eq "odd" ) ? "even" : "odd";

                                # print "$cnt<br>";
                                $var{messagelist} .=
                                  $myownemail->parse( "html/message_entry.html",
                                  %var, %db );
                            }

                        }
                    }

                    $var{status} = " - $var{mcount} messages have been deleted";

                    print $myownemail->parse( "html/purgemessagesalert.html", %var )
                      if ( !$var{confirm} );
                    print $myownemail->parse( "html/purgemessages.html", %var )
                      if ( $var{confirm} );

                }
            }

        }
        else {
            print $myownemail->parse("html/purgemessages.html");
        }
    }

}

elsif ( $var{func} eq "users" ) {

    print $myownemail->parse("html/adminheader.html");

    $var{userlist} = &searchusers();

    print $myownemail->parse( "html/users.html", %var );

}
elsif ( $var{func} eq "update" ) {
    my ( %user, %user2, %user3 );

    $var{user}   = $myownemail->param('user') || $var{Account};
      $var{domain} = $1 if($var{user} =~ /\@(.*)/);            # Find the users domain
    $var{status} = "Viewing Record Sheet" if ( !$var{status} );

    if ( $myownemail->param('update') ) {

        $var{Account} = $sql->quote( $myownemail->param('Account') );
        $var{PasswordQuestion} =
          $sql->quote( $myownemail->param('PasswordQuestion') );
        $var{OtherEmail} = $sql->quote( $myownemail->param('OtherEmail') );
        $var{FirstName}  = $sql->quote( $myownemail->param('FirstName') );
        $var{LastName}   = $sql->quote( $myownemail->param('LastName') );
        $var{BirthDay}   = $sql->quote( $myownemail->param('BirthDay') );
        $var{BirthMonth} = $sql->quote( $myownemail->param('BirthMonth') );
        $var{BirthYear}  = $sql->quote( $myownemail->param('BirthYear') );
        $var{Gender}     = $sql->quote( $myownemail->param('Gender') );
        $var{Industry}   = $sql->quote( $myownemail->param('Industry') );
        $var{Occupation} = $sql->quote( $myownemail->param('Occupation') );
            $var{TelHome}    = $sql->quote( $myownemail->param('TelHome') );
        $var{FaxHome}    = $sql->quote( $myownemail->param('FaxHome') );
        $var{TelWork}    = $sql->quote( $myownemail->param('TelWork') );
        $var{FaxWork}    = $sql->quote( $myownemail->param('FaxWork') );
        $var{TelMobile}  = $sql->quote( $myownemail->param('TelMobile') );
        $var{TelPager}   = $sql->quote( $myownemail->param('TelPager') );
        $var{Address}    = $sql->quote( $myownemail->param('Address') );
        $var{City}       = $sql->quote( $myownemail->param('City') );
        $var{PostCode}   = $sql->quote( $myownemail->param('PostCode') );
        $var{State}      = $sql->quote( $myownemail->param('State') );
        $var{Country}    = $sql->quote( $myownemail->param('Country') );

        $var{UserQuota}  = $sql->quote( $myownemail->param('UserQuota') );
            $var{RealName}   = $sql->quote( $myownemail->param('RealName') );
            $var{ReplyTo}    = $sql->quote( $myownemail->param('ReplyTo') );
            $var{Group}      = $sql->quote( $myownemail->param('Group') );
            $var{UserStatus} = $sql->quote( $myownemail->param('UserStatus') );

            $var{Password}   = $sql->quote( $myownemail->param('Password') );

            # Jumple the password, if using the non-crypt() function
            if(!$pref{crypt} || !$domains{$var{domain}} )      {
        $var{Password}   =~ tr/a-zA-Z/n-za-mN-ZA-M/;
            } elsif($var{Password} eq "'Specify new password'")      {
            # Keep the existing crypt() version
            $var{Password} = $sql->quote ( $myownemail->param('PasswordCrypt') );
            } else      {
            # Crypt the user password , escape the SQL from above
            $var{Password} =~ s/'//g;
            $var{Password} = $sql->quote ( crypt( $var{Password} , $myownemail->salt() ) );
            }

    }

    # SQL Function to update a user
    if ( $pref{sql_type} ) {

        # Load our table names
        $sql->table_names( $myownemail->param('Account') ) if ( $myownemail->param('Account') );
        $sql->table_names( $myownemail->param('user') ) if ( $myownemail->param('user') );

        if ( $myownemail->param('update') ) {

            # Update the Users database table
            $sql->sqlquery( "UPDATE Users SET PasswordQuestion = $var{PasswordQuestion}, OtherEmail = $var{OtherEmail}, FirstName = $var{FirstName}, LastName = $var{LastName}, BirthDay = $var{BirthDay}, BirthMonth = $var{BirthMonth}, BirthYear = $var{BirthYear}, Gender = $var{Gender}, Industry = $var{Industry}, Occupation = $var{Occupation}, TelHome = $var{TelHome}, FaxHome = $var{FaxHome}, TelWork = $var{TelWork}, FaxWork = $var{FaxWork}, TelMobile = $var{TelMobile}, TelPager = $var{TelPager}, Address = $var{Address}, City = $var{City}, PostCode = $var{PostCode}, State = $var{State}, Country = $var{Country}, Ugroup = $var{Group}, UserStatus = $var{UserStatus} where Account=$var{Account}" );


            # Update the users password in the UserSession table
            $sql->sqlquery( "UPDATE UserSession SET Password = $var{Password} where Account = $var{Account}" );

            # Update the UserQuota, Fullname and ReplyTo in the UserSettings table
            $sql->sqlquery( "UPDATE $sql->{UserSettings} SET UserQuota = $var{UserQuota}, RealName = $var{RealName}, ReplyTo = $var{ReplyTo} where Account = $var{Account}" );
            $var{status} = "Updated Record Sheet";
        }

        # Query the database for the users details
        %user =
          $sql->doquery( "select * from Users,UserSession,$sql->{UserSettings}
      where Users.Account='$var{user}' and
      UserSession.Account='$var{user}' and
      $sql->{UserSettings}.Account='$var{user}'
      " );

        # Change the password into something we can read      
            # Jumple the password, if using the non-crypt() function
            if(!$pref{crypt} || !$domains{$var{domain}} )      {
        $var{Password}   =~ tr/a-zA-Z/n-za-mN-ZA-M/;
        $user{Password}   =~ tr/a-zA-Z/n-za-mN-ZA-M/;

            } else      {
            # Crypt the user password
            $var{PasswordCrypt} = $user{Password};
            $var{Password} = "Specify new password";
            $user{Password} = "Specify new password";
            }
            
        # Parse the date into a more reabable format
        $user{DateCreate} =~ /(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/;
        $user{DateCreate} = "$3/$2/$1 $4:$5:$6";

        # Flat file function to update a user
    }
    else {

        if ( $myownemail->param('update') ) {

      my $time = localtime();

            # Update the users, user.db
            Myownemail::Flat->updatehash(
              "$pref{user_dir}/users/$var{user}/user.db",
            DateCreate      => $time,
              PasswordQuestion => $var{PasswordQuestion},
              OtherEmail       => $var{OtherEmail},
              FirstName        => $var{FirstName},
              LastName         => $var{LastName},
              BirthDay         => $var{BirthDay},
              BirthMonth       => $var{BirthMonth},
              BirthYear        => $var{BirthYear},
              Gender           => $var{Gender},
              Industry         => $var{Industry},
              Occupation       => $var{Occupation},
                    TelHome          => $var{TelHome},
                    FaxHome          => $var{FaxHome},
                    TelWork          => $var{TelWork},
                    FaxWork          => $var{FaxWork},
                    TelMobile        => $var{TelMobile},
                    TelPager         => $var{TelPager},
              Address          => $var{Address},
              City             => $var{City},
              PostCode         => $var{PostCode},
              State            => $var{State},
              Country          => $var{Country},
                  Ugroup           => $var{Group},
                    UserStatus       => $var{UserStatus}
            );

            # Update the users password
            my %db =
              Myownemail::Flat->gethash( "$pref{user_dir}/users/$var{user}/login.db"
            );
            $db{Password} = $var{Password};
            Myownemail::Flat->updatehash(
              "$pref{user_dir}/users/$var{user}/login.db", %db );

            # Update the users quota
            my %db =
              Myownemail::Flat->gethash(
              "$pref{user_dir}/users/$var{user}/settings.db");
            $db{UserQuota} = $var{UserQuota};
                  $db{ReplyTo} = $var{ReplyTo};
                  $db{RealName} = $var{RealName};
            Myownemail::Flat->updatehash(
              "$pref{user_dir}/users/$var{user}/settings.db", %db );

        }

        %user =
          Myownemail::Flat->gethash("$pref{user_dir}/users/$var{user}/user.db");
        %user2 =
          Myownemail::Flat->gethash("$pref{user_dir}/users/$var{user}/login.db");
        %user3 =
          Myownemail::Flat->gethash("$pref{user_dir}/users/$var{user}/settings.db");

            # Jumple the password, if using the non-crypt() function
            if(!$pref{crypt} || !$domains{$var{domain}} )      {
        $user2{Password} =~ tr/a-zA-Z/n-za-mN-ZA-M/;
            } else      {
            # Crypt the user password
            $var{PasswordCrypt} = $user2{Password};
            $var{Password} = "Specify new password";
            $user2{Password} = "Specify new password";
            }

    }

    # Print the header and the update page
    print $myownemail->parse("html/adminheader.html");

      $var{Groups} = group_options();

    if ( $user{Account} || $user2{Account} ) {
        $var{user} =
          $myownemail->parse( "html/update.html", %var, %user, %user2, %user3 );

        # Escape the ()'s in the Industry + Occupation value
        $user{Industry}   =~ s/([()\\])/\\$1/g;
        $user{Occupation} =~ s/([()\\])/\\$1/g;

        # Build the Country Industry and Occupation select boxes and more

        $var{user} =~ s/name="BirthDay"(.*?)<option value="$user{BirthDay}"/name="BirthDay" $1 <option value="$user{BirthDay}" selected/smg;
        $var{user} =~ s/name="BirthMonth"(.*?)<option value="$user{BirthMonth}"/name="BirthMonth" $1 <option value="$user{BirthMonth}" selected/smg;

            $var{user} =~ s/name="UserStatus"(.*?)<option value="$user{UserStatus}"/name="UserStatus" $1 <option value="$user{UserStatus}" selected/smg;

            $var{user} =~ s/<option value="$user{Gender}"/<option value="$user{Gender}" selected/g;
            $var{user} =~ s/<option value="$user{Country}"/<option value="$user{Country}" selected/gi;
        $var{user} =~ s/<option value="$user{Industry}"/<option value="$user{Industry}" selected/gi;
        $var{user} =~ s/<option value="$user{Occupation}"/<option value="$user{Occupation}" selected/ig;
            $var{user} =~ s/<option value="$user{Ugroup}"/<option value="$user{Ugroup}" selected/ig;

        print $var{user};

    }
    else {
        print $myownemail->parse("html/nouser.html");
    }

}

if ( $var{func} eq "settings" ) {

    if ( $myownemail->param('save') ) {

        $pref{'test_exist'}      = $myownemail->param('test_exist');
        $pref{'install_dir'}     = $myownemail->param('install_dir');
        $pref{'user_dir'}        = $myownemail->param('user_dir');
        $pref{'ispell_dir'}      = $myownemail->param('ispell_dir');
        $pref{'session_timeout'} = $myownemail->param('session_timeout');
        $pref{'admin_email'}     = $myownemail->param('admin_email');
        $pref{'version'}         = $myownemail->param('version');
        $pref{'error_message'}       = $myownemail->param('error_message');
        $pref{'builddate'}       = $myownemail->param('builddate');
        $pref{'version'}         = $myownemail->param('version');

        &write_conf();

        $var{status} = "<br>Configuration Updated";

        use Myownemail::Config;

    }

    $var{error} = &check_errors();

    print $myownemail->parse("html/adminheader.html");

    $var{settings} = $myownemail->parse( "html/settings.html", %var );

    $var{settings} =~
s/<option value="$pref{install_size}"/<option value="$pref{install_size}" selected/g;

    print $var{settings};

}

# Restore Default Configuration (factory defaults)
if ( $var{func} eq "RestoreConf" ) {

    # Move Config.pm to Config.previous
    rename( "../libs/Myownemail/Config.pm", "../libs/Myownemail/Config.previous.pm" );

    # Copy Config.default to Config.pm
    open( F, "../libs/Myownemail/Config.default.pm" )
      || print "Cannot read Config.default.pm : $!";
    open( F2, ">../libs/Myownemail/Config.pm" )
      || print "Cannot write Config.pm : $!";

    while (<F>) {
        print F2 $_;
    }

    close(F);
    close(F2);

    $var{status} = "<br>Default Configuration Restored";
    $var{error}  = &check_errors();

    print $myownemail->parse("html/adminheader.html");

    $var{settings} = $myownemail->parse( "html/settings.html", %var );

    $var{settings} =~
s/<option value="$pref{install_size}"/<option value="$pref{install_size}" selected/g;

    print $var{settings};

}

if ( $var{func} eq "settings_db" ) {

    # Check if the user is creating the DB structure
    $var{Create} = $myownemail->param('Create');

    if ( $myownemail->param('save') ) {
        $pref{'sql_type'}     = $myownemail->param('sql_type');
        $pref{'install_size'} = $myownemail->param('install_size');
        $pref{'sql_user'}     = $myownemail->param('sql_user');
        $pref{'sql_pass'}     = $myownemail->param('sql_pass');
        $pref{'sql_host'}     = $myownemail->param('sql_host');
        $pref{'sql_table'}    = $myownemail->param('sql_table');

        $var{status} = "<br>Updated your \Myownemail Configuration</br>";
        Myownemail::Config->writeconf();

        # Create the database structure if nessasary
        if ( $pref{'sql_type'} eq "mysql" ) {
            my $drh = DBI->install_driver("mysql");
            my $rc =
              $drh->func( 'createdb', $pref{'sql_table'}, $pref{'sql_host'},
              $pref{'sql_user'}, $pref{'sql_pass'}, 'admin' );
        }

    }

    $var{error} = &check_errors();

    print $myownemail->parse("html/adminheader.html");
    $var{mysqlversion} = mysqlversion();
    $var{settings} = $myownemail->parse( "html/settings_db.html", %var );
    $var{settings} =~
s/<option value="$pref{sql_type}"/<option value="$pref{sql_type}" selected/g;
    $var{settings} =~
s/<option value="$pref{install_size}"/<option value="$pref{install_size}" selected/g;
    print $var{settings};

}
if ( $var{func} eq "settings_sendmail" ) {

    if ( $myownemail->param('Save') ) {
        $pref{'install_type'} = $myownemail->param('install_type');
        $pref{'sendmode'}     = $myownemail->param('sendmode');
        $pref{'sendmail'}     = $myownemail->param('sendmail');
        $pref{'smtphost'}     = $myownemail->param('smtphost');
        $pref{'smtp_type'}    = $myownemail->param('smtp_type');
        $pref{'max_msg_size'} = $myownemail->param('max_msg_size');
        $pref{'mail_type'}    = $myownemail->param('mail_type');
            $pref{'mailserver_auth'} = $myownemail->param('mailserver_auth');
            $pref{'imap_folders'} = $myownemail->param('imap_folders');
            $pref{'imap_subdirectory'} = $myownemail->param('imap_subdirectory');
        $var{status} = "<br>Updated your \Myownemail Configuration<br>";
        Myownemail::Config->writeconf();
    }

    use Myownemail::Config;

    $var{error} = &check_errors();

    $var{install_type} = install_type();

    # Append the Jscript check
    $var{install_type} =~
s/<select/<select onchange="javascript:check_type\(this.options[this.selectedIndex].value\)"/g;

    $var{smtp_type} = smtp_type();

    $var{sendmode} = sendmode();

    $var{mysqlversion} = mysqlversion();

    $var{mail_type} = mail_type();

      $var{mailserver_auth} = '<input type=checkbox name="mailserver_auth" value="1">';
      $var{mailserver_auth} =~ s/value="1"/value="1" checked/g if($pref{mailserver_auth});

      $var{imap_folders} = '<input type=checkbox name="imap_folders" value="1">';
      $var{imap_folders} =~ s/value="1"/value="1" checked/g if($pref{imap_folders});

      $var{imap_subdirectory} = '<input type=checkbox name="imap_subdirectory" value="1">';
      $var{imap_subdirectory} =~ s/value="1"/value="1" checked/g if($pref{imap_subdirectory});

    print $myownemail->parse("html/adminheader.html");
    print $myownemail->parse( "html/settings_sendmail.html", %var );
}

if ( $var{func} eq "settings_defaults" ) {

    if ( $myownemail->param('save') ) {

        # Default Settings

        $settings{'UserQuota'}            = $myownemail->param('UserQuota');
            $settings{'LeaveMsgs'}            = $myownemail->param('LeaveMsgs');
            $settings{'MboxOrder'}            = $myownemail->param('MboxOrder');
        $settings{'FontStyle'}            = $myownemail->param('FontStyle');
        $settings{'Language'}             = $myownemail->param('Language');
        $settings{'MsgNum'}               = $myownemail->param('MsgNum');
        $settings{'TimeZone'}             = $myownemail->param('TimeZone');
        $settings{'Advanced'}             = $myownemail->param('Advanced');
        $settings{'AutoTrash'}            = $myownemail->param('AutoTrash');
          $settings{'EmptyTrash'}           = $myownemail->param('EmptyTrash');
        $settings{'HtmlEditor'}           = $myownemail->param('HtmlEditor');
        $settings{'LoginType'}            = $myownemail->param('LoginType');

        # Colors & TopBg

        $settings{'PrimaryColor'}     = $myownemail->param('PrimaryColor');
        $settings{'SecondaryColor'}   = $myownemail->param('SecondaryColor');
        $settings{'ThirdColor'}       = $myownemail->param('ThirdColor');
        $settings{'HeaderColor'}      = $myownemail->param('HeaderColor');
        $settings{'HeadColor'}        = $myownemail->param('HeadColor');
        $settings{'BgColor'}          = $myownemail->param('BgColor');
        $settings{'TextColor'}        = $myownemail->param('TextColor');
        $settings{'TextHeadColor'}    = $myownemail->param('TextHeadColor');
        $settings{'VlinkColor'}       = $myownemail->param('VlinkColor');
        $settings{'LinkColor'}        = $myownemail->param('LinkColor');
        $settings{'OnColor'}          = $myownemail->param('OnColor');
        $settings{'OffColor'}         = $myownemail->param('OffColor');
        $settings{'SelectColor'}      = $myownemail->param('SelectColor');
        $settings{'TopBg'}            = $myownemail->param('TopBg');

        $var{status} = "<br>Updated your \Myownemail Configuration</br>";
        Myownemail::Config->writeconf();

    }

    $var{error} = &check_errors();

    print $myownemail->parse("html/adminheader.html");

    #      $var{mysqlversion} = mysqlversion();

    $var{langbox} = $myownemail->languages();
    $var{langbox} =~ s/<select/<select class='option'/g;
    $var{langbox} =~ s/<option value="$pref{Language}"/<option value="$pref{Language}" selected/g;

    $var{settings} = $myownemail->parse( "html/settings_defaults.html", %var );

      $var{settings} =~ s/<option value="$settings{LoginType}"/<option value="$settings{LoginType}" selected/g;
    $var{settings} =~ s/<option value="$settings{MboxOrder}"/<option value="$settings{MboxOrder}" selected/g;
    $var{settings} =~ s/<option value="$settings{TimeZone}"/<option value="$settings{TimeZone}" selected/g;
    $var{settings} =~ s/<option value="$settings{MsgNum}"/<option value="$settings{MsgNum}" selected/g;
    $var{settings} =~ s/<option value="$settings{FontStyle}"/<option value="$settings{FontStyle}" selected/g;

      $var{settings} =~ s/(<select name="LeaveMsgs".*)<option value="$settings{LeaveMsgs}"/$1<option value="$settings{LeaveMsgs}" selected/g;
    $var{settings} =~ s/(<select name="HtmlEditor".*)<option value="$settings{HtmlEditor}"/$1<option value="$settings{HtmlEditor}" selected/g;
    $var{settings} =~ s/(<select name="Advanced".*)<option value="$settings{Advanced}"/$1<option value="$settings{Advanced}" selected/g;
    $var{settings} =~ s/(<select name="AutoTrash".*)<option value="$settings{AutoTrash}"/$1<option value="$settings{AutoTrash}" selected/g;
      $var{settings} =~ s/(<select name="EmptyTrash".*)<option value="$settings{EmptyTrash}"/$1<option value="$settings{EmptyTrash}" selected/g;

    print $var{settings};

}

if ( $var{func} eq "settings_allow" ) {

    if ( $myownemail->param('save') ) {

      if($myownemail->param('setall') eq "allow")      {
        foreach(%pref)      {
            next if($_ !~ /p?allow_|GlobalAbook/);
            $pref{$_} = 1;
        }
      }
      elsif ($myownemail->param('setall') eq "deny")      {
        foreach(%pref)      {
        next if($_ !~ /p?allow_|GlobalAbook/);
            $pref{$_} = 0;
        }
      }
      else {

        # Allow Functions
        $pref{'allow_Signup'}            = $myownemail->param('allow_Signup');
            $pref{'allow_Passutil'}          = $myownemail->param('allow_Passutil');
        $pref{'allow_Layout'}            = $myownemail->param('allow_Layout');
        $pref{'allow_Forward'}           = $myownemail->param('allow_Forward');
        $pref{'allow_Profile'}           = $myownemail->param('allow_Profile');
        $pref{'allow_Folders'}           = $myownemail->param('allow_Folders');
        $pref{'allow_MultiAccounts'}     = $myownemail->param('allow_MultiAccounts');
        $pref{'allow_LoginHistory'}      = $myownemail->param('allow_LoginHistory');

        #$pref{'allow_Emotion'}      = $myownemail->param('allow_Emotion');
            
            # Global Addressbook
            $pref{'GlobalAbook'}             = $myownemail->param('GlobalAbook');

        # Allow Functions
        $pref{'allow_Signup'}            = $myownemail->param('allow_Signup');
        $pref{'allow_Layout'}            = $myownemail->param('allow_Layout');
        $pref{'allow_Forward'}           = $myownemail->param('allow_Forward');
        $pref{'allow_Profile'}           = $myownemail->param('allow_Profile');
        $pref{'allow_Folders'}           = $myownemail->param('allow_Folders');
        $pref{'allow_MultiAccounts'}     = $myownemail->param('allow_MultiAccounts');
            
            # Global Addressbook
            $pref{'GlobalAbook'}             = $myownemail->param('GlobalAbook');


            # Allow Settings
        $pref{'allow_FullName'}          = $myownemail->param('allow_FullName');
        $pref{'allow_ReplyTo'}           = $myownemail->param('allow_ReplyTo');
        $pref{'allow_MboxOrder'}         = $myownemail->param('allow_MboxOrder');
        $pref{'allow_FontStyle'}         = $myownemail->param('allow_FontStyle');
        $pref{'allow_LeaveMsgs'}         = $myownemail->param('allow_LeaveMsgs');
        $pref{'allow_Language'}          = $myownemail->param('allow_Language');
        $pref{'allow_MsgNum'}            = $myownemail->param('allow_MsgNum');
        $pref{'allow_TimeZone'}          = $myownemail->param('allow_TimeZone');
        $pref{'allow_Advanced'}          = $myownemail->param('allow_Advanced');
        $pref{'allow_AutoTrash'}         = $myownemail->param('allow_AutoTrash');
        $pref{'allow_EmptyTrash'}        = $myownemail->param('allow_EmptyTrash');
        $pref{'allow_HtmlEditor'}        = $myownemail->param('allow_HtmlEditor');
        $pref{'allow_Signature'}         = $myownemail->param('allow_Signature');

            # Allow User Details
            $pref{'pallow_FirstName'}        = $myownemail->param('pallow_FirstName');
            $pref{'pallow_LastName'}         = $myownemail->param('pallow_LastName');
            $pref{'pallow_DOB'}              = $myownemail->param('pallow_DOB');
            $pref{'pallow_Gender'}           = $myownemail->param('pallow_Gender');

            $pref{'pallow_TelHome'}          = $myownemail->param('pallow_TelHome');
            $pref{'pallow_FaxHome'}          = $myownemail->param('pallow_FaxHome');
            $pref{'pallow_TelWork'}          = $myownemail->param('pallow_TelWork');
            $pref{'pallow_FaxWork'}          = $myownemail->param('pallow_FaxWork');
            $pref{'pallow_TelMobile'}        = $myownemail->param('pallow_TelMobile');
            $pref{'pallow_TelPager'}         = $myownemail->param('pallow_TelPager');


            $pref{'pallow_Address'}          = $myownemail->param('pallow_Address');
            $pref{'pallow_City'}             = $myownemail->param('pallow_City');
            $pref{'pallow_PostCode'}         = $myownemail->param('pallow_PostCode');
            $pref{'pallow_State'}            = $myownemail->param('pallow_State');
            $pref{'pallow_Country'}          = $myownemail->param('pallow_Country');
            $pref{'pallow_OtherEmail'}       = $myownemail->param('pallow_OtherEmail');
            $pref{'pallow_PasswordQuestion'} = $myownemail->param('pallow_PasswordQuestion');
            $pref{'pallow_Industry'}         = $myownemail->param('pallow_Industry');
            $pref{'pallow_Occupation'}       = $myownemail->param('pallow_Occupation');

        $var{status} = "<br>Updated your \Myownemail Configuration</br>";
        Myownemail::Config->writeconf();
 }

    }


    print $myownemail->parse("html/adminheader.html");

    $var{settings} = $myownemail->parse( "html/settings_allow.html", %var );

# Allow
      $var{settings} =~ s/(<select name="allow_Signup".*)<option value="$pref{allow_Signup}"/$1<option value="$pref{allow_Signup}" selected/g;
      $var{settings} =~ s/(<select name="allow_Passutil".*)<option value="$pref{allow_Passutil}"/$1<option value="$pref{allow_Passutil}" selected/g;
      $var{settings} =~ s/(<select name="allow_FullName".*)<option value="$pref{allow_FullName}"/$1<option value="$pref{allow_FullName}" selected/g;
      $var{settings} =~ s/(<select name="allow_ReplyTo".*)<option value="$pref{allow_ReplyTo}"/$1<option value="$pref{allow_ReplyTo}" selected/g;
      $var{settings} =~ s/(<select name="allow_MboxOrder".*)<option value="$pref{allow_MboxOrder}"/$1<option value="$pref{allow_MboxOrder}" selected/g;
      $var{settings} =~ s/(<select name="allow_FontStyle".*)<option value="$pref{allow_FontStyle}"/$1<option value="$pref{allow_FontStyle}" selected/g;
      $var{settings} =~ s/(<select name="allow_LeaveMsgs".*)<option value="$pref{allow_LeaveMsgs}"/$1<option value="$pref{allow_LeaveMsgs}" selected/g;
      $var{settings} =~ s/(<select name="allow_Language".*)<option value="$pref{allow_Language}"/$1<option value="$pref{allow_Language}" selected/g;
      $var{settings} =~ s/(<select name="allow_MsgNum".*)<option value="$pref{allow_MsgNum}"/$1<option value="$pref{allow_MsgNum}" selected/g;
      $var{settings} =~ s/(<select name="allow_TimeZone".*)<option value="$pref{allow_TimeZone}"/$1<option value="$pref{allow_TimeZone}" selected/g;
      $var{settings} =~ s/(<select name="allow_Advanced".*)<option value="$pref{allow_Advanced}"/$1<option value="$pref{allow_Advanced}" selected/g;
      $var{settings} =~ s/(<select name="allow_AutoTrash".*)<option value="$pref{allow_AutoTrash}"/$1<option value="$pref{allow_AutoTrash}" selected/g;
      $var{settings} =~ s/(<select name="allow_EmptyTrash".*)<option value="$pref{allow_EmptyTrash}"/$1<option value="$pref{allow_EmptyTrash}" selected/g;
      $var{settings} =~ s/(<select name="allow_HtmlEditor".*)<option value="$pref{allow_HtmlEditor}"/$1<option value="$pref{allow_HtmlEditor}" selected/g;
      $var{settings} =~ s/(<select name="allow_Signature".*)<option value="$pref{allow_Signature}"/$1<option value="$pref{allow_Signature}" selected/g;
      $var{settings} =~ s/(<select name="allow_Layout".*)<option value="$pref{allow_Layout}"/$1<option value="$pref{allow_Layout}" selected/g;
      $var{settings} =~ s/(<select name="allow_Forward".*)<option value="$pref{allow_Forward}"/$1<option value="$pref{allow_Forward}" selected/g;
      $var{settings} =~ s/(<select name="allow_Profile".*)<option value="$pref{allow_Profile}"/$1<option value="$pref{allow_Profile}" selected/g;
      $var{settings} =~ s/(<select name="allow_Folders".*)<option value="$pref{allow_Folders}"/$1<option value="$pref{allow_Folders}" selected/g;
      $var{settings} =~ s/(<select name="allow_MultiAccounts".*)<option value="$pref{allow_MultiAccounts}"/$1<option value="$pref{allow_MultiAccounts}" selected/g;
      $var{settings} =~ s/(<select name="allow_LoginHistory".*)<option value="$pref{allow_LoginHistory}"/$1<option value="$pref{allow_LoginHistory}" selected/g;

      $var{settings} =~ s/(<select name="allow_Emotion".*)<option value="$pref{allow_Emotion}"/$1<option value="$pref{allow_Emotion}" selected/g;

      $var{settings} =~ s/(<select name="GlobalAbook".*)<option value="$pref{GlobalAbook}"/$1<option value="$pref{GlobalAbook}" selected/g;

# Pallow
      $var{settings} =~ s/(<select name="pallow_FirstName".*)<option value="$pref{pallow_FirstName}"/$1<option value="$pref{pallow_FirstName}" selected/g;
      $var{settings} =~ s/(<select name="pallow_LastName".*)<option value="$pref{pallow_LastName}"/$1<option value="$pref{pallow_LastName}" selected/g;
      $var{settings} =~ s/(<select name="pallow_DOB".*)<option value="$pref{pallow_DOB}"/$1<option value="$pref{pallow_DOB}" selected/g;
      $var{settings} =~ s/(<select name="pallow_Gender".*)<option value="$pref{pallow_Gender}"/$1<option value="$pref{pallow_Gender}" selected/g;
      $var{settings} =~ s/(<select name="pallow_TelHome".*)<option value="$pref{pallow_TelHome}"/$1<option value="$pref{pallow_TelHome}" selected/g;
      $var{settings} =~ s/(<select name="pallow_FaxHome".*)<option value="$pref{pallow_FaxHome}"/$1<option value="$pref{pallow_FaxHome}" selected/g;
      $var{settings} =~ s/(<select name="pallow_TelWork".*)<option value="$pref{pallow_TelWork}"/$1<option value="$pref{pallow_TelWork}" selected/g;
      $var{settings} =~ s/(<select name="pallow_FaxWork".*)<option value="$pref{pallow_FaxWork}"/$1<option value="$pref{pallow_FaxWork}" selected/g;
      $var{settings} =~ s/(<select name="pallow_TelMobile".*)<option value="$pref{pallow_TelMobile}"/$1<option value="$pref{pallow_TelMobile}" selected/g;
      $var{settings} =~ s/(<select name="pallow_TelPager".*)<option value="$pref{pallow_TelPager}"/$1<option value="$pref{pallow_TelPager}" selected/g;
      $var{settings} =~ s/(<select name="pallow_Address".*)<option value="$pref{pallow_Address}"/$1<option value="$pref{pallow_Address}" selected/g;
      $var{settings} =~ s/(<select name="pallow_City".*)<option value="$pref{pallow_City}"/$1<option value="$pref{pallow_City}" selected/g;
      $var{settings} =~ s/(<select name="pallow_PostCode".*)<option value="$pref{pallow_PostCode}"/$1<option value="$pref{pallow_PostCode}" selected/g;
      $var{settings} =~ s/(<select name="pallow_State".*)<option value="$pref{pallow_State}"/$1<option value="$pref{pallow_State}" selected/g;
      $var{settings} =~ s/(<select name="pallow_Country".*)<option value="$pref{pallow_Country}"/$1<option value="$pref{pallow_Country}" selected/g;
      $var{settings} =~ s/(<select name="pallow_OtherEmail".*)<option value="$pref{pallow_OtherEmail}"/$1<option value="$pref{pallow_OtherEmail}" selected/g;
      $var{settings} =~ s/(<select name="pallow_PasswordQuestion".*)<option value="$pref{pallow_PasswordQuestion}"/$1<option value="$pref{pallow_PasswordQuestion}" selected/g;
      $var{settings} =~ s/(<select name="pallow_Industry".*)<option value="$pref{pallow_Industry}"/$1<option value="$pref{pallow_Industry}" selected/g;
      $var{settings} =~ s/(<select name="pallow_Occupation".*)<option value="$pref{pallow_Occupation}"/$1<option value="$pref{pallow_Occupation}" selected/g;

    print $var{settings};

}


if ( $var{func} eq "settings_ldap" ) {

    if ( $myownemail->param('save') ) {

        #Settings

        $pref{'ldap_server'}   = $myownemail->param('ldap_server');
        $pref{'ldap_chserver'} = $myownemail->param('ldap_chserver');
        $pref{'base_dn'}       = $myownemail->param('base_dn');
        $pref{'bind_dn'}       = $myownemail->param('bind_dn');
        $pref{'ldap_passwd'}   = $myownemail->param('ldap_passwd');
        $pref{'ldap_local'}    = $myownemail->param('ldap_local');

        $var{status} = "<br>Updated your \Myownemail Configuration</br>";
        Myownemail::Config->writeconf();

    }

    print $myownemail->parse("html/adminheader.html");

    $var{settings} = $myownemail->parse( "html/settings_ldap.html", %var );
      $var{settings} =~ s/<input name="ldap_chserver"/<input name="ldap_chserver" checked/g if ($pref{ldap_chserver});
    $var{settings} =~ s/(<select name="ldap_local".*)<option value="$pref{ldap_local}"/$1<option value="$pref{ldap_local}" selected/g;

    print $var{settings};

}

# The feedback page in Myownemail
if ( $var{func} eq "feedback" ) {
    print $myownemail->parse("html/adminheader.html");
    print $myownemail->parse( "html/feedback.html", %var );
}

# The domain manager within Myownemail
if ( $var{func} eq "domains" ) {

    if ( $myownemail->param('Add') ) {
        $domains{ $myownemail->param('Domain') } = 1;
        Myownemail::Config->writeconf();

        &add_domain_sendmail( $myownemail->param('Domain') )
          if ( $myownemail->param('smtp_type') eq "Sendmail" );
        &add_domain_sendmail( $myownemail->param('Domain') )
          if ( $myownemail->param('smtp_type') eq "Sendmail Aliases" );

      my $out = &add_domain_exim( $myownemail->param('Domain') ) if($myownemail->param('smtp_type') eq "Exim");

        $var{status} = "<br>Added new domain " . $myownemail->param('Domain') . " : $out<br>";

        $var{status} .=
          " - Your Sendmail server requires a reboot to take effect"
          if ( $myownemail->param('smtp_type') eq "Sendmail" );

    }
    elsif ( $myownemail->param('Delete') ) {
        delete $domains{ $myownemail->param('Del') };
        Myownemail::Config->writeconf();
        &del_domain_sendmail( $myownemail->param('Domain') )
          if ( $pref{smtp_type} eq "Sendmail" );
            &del_domain_exim( $myownemail->param('Domain') ) if($myownemail->param('smtp_type') eq "Exim");

        $var{status} = "<br>Deleted domain " . $myownemail->param('Del');
    }

    $var{domainbox} = $myownemail->domains();
    $var{smtp_type} = smtp_type();

    # Append the Jscript check if we are using POP3 only
    $var{smtp_type} =~
s/<select/<select onchange="javascript:check_type\(this.options[this.selectedIndex].value\)"/g;

    print $myownemail->parse("html/adminheader.html");

    foreach ( keys %domains ) {
        $var{domain} = $_;
        $var{count}  = 0;

        if ( $pref{sql_type} ) {
            $var{count} =
              $sql->getvalue(
              "select count(id) from Users where Account like '%\@$var{domain}'"
            );

            $var{class} = ( $var{class} eq "odd" ) ? "even" : "odd";

            $var{domainlist} .=
              $myownemail->parse( "html/domain_entry.html", %var );

        }
        else {

            # FLAT FILE

            # Open the user directory
            opendir( DIR, "$pref{user_dir}/users/" )
              || print "Cannot open $pref{user_dir} : $!";
            my @fol = readdir(DIR);

            # Loop through each user, and check their last login date

            foreach (@fol) {
                my $fol = $_;
                next if ( $fol !~ /@/ );
                $var{count}++ if ( $fol =~ /\@$var{domain}$/ );

            }

            $var{class} = ( $var{class} eq "odd" ) ? "even" : "odd";

            $var{domainlist} .=
              $myownemail->parse( "html/domain_entry.html", %var );

            #print $myownemail->parse("html/notyet.html");
        }

    }

    print $myownemail->parse( "html/domainmanager.html", %var );

}

# The group manager within Myownemail
if ( $var{func} eq "groups" ) {

    if ( $myownemail->param('Add') ) {
        $groups{ $myownemail->param('Group') } = 1;
        Myownemail::Config->writeconf();

        $var{status} = "<br>Added new Group " . $myownemail->param('Group');

    }
    elsif ( $myownemail->param('Delete') ) {

# Ugroup = "" at all users where Ugroup = $var{Group}
# oh ja and the spamrules for $var{Group} have to be set to all. or can we catch this?!


my $Ugroup = $myownemail->param('Del');
$Ugroup = $sql->quote($Ugroup);

           $sql->sqlquery( "UPDATE Users SET Ugroup = '' where Ugroup = $Ugroup" );


        delete $groups{ $myownemail->param('Del') };
        Myownemail::Config->writeconf();

        $var{status} = "<br>Deleted Group " . $myownemail->param('Del');
    }

    print $myownemail->parse("html/adminheader.html");

    foreach ( keys %groups ) {
        $var{Group} = $_;
        $var{count}  = 0;

        if ( $pref{sql_type} ) {
            $var{count} =
              $sql->getvalue(
              "select count(id) from Users where Ugroup = '$var{Group}'"
            );

            $var{class} = ( $var{class} eq "odd" ) ? "even" : "odd";

            $var{grouplist} .= $myownemail->parse( "html/group_entry.html", %var );

        }
        else {

            # FLAT FILE

            # Open the user directory
            opendir( DIR, "$pref{user_dir}/users/" ) || print "Cannot open $pref{user_dir} : $!";
            my @fol = readdir(DIR);

            # Loop through each user, and check their last login date

            foreach (@fol) {
             my $fol = $_;
             next if ( $fol !~ /@/ );

                   my %db = Myownemail::Flat->gethash("$pref{user_dir}/users/$fol/user.db");

             $var{count}++ if ( $db{Ugroup} eq "$var{Group}" );
                   }

            $var{class} = ( $var{class} eq "odd" ) ? "even" : "odd";

                  $var{grouplist} .= $myownemail->parse( "html/group_entry.html", %var );

            #print $myownemail->parse("html/notyet.html");
        }

    }

    print $myownemail->parse( "html/groupmanager.html", %var );

}


# Reserved Usernames
if ( $var{func} eq "reserved" ) {

    if ( $myownemail->param('Add') ) {
        $reserved{ $myownemail->param('ruser') } = 1;
        Myownemail::Config->writeconf();
        $var{status} = "<br>Added reserved username " . $myownemail->param('ruser');
    }
    elsif ( $myownemail->param('Delete') ) {
        delete $reserved{ $myownemail->param('Del') };
        Myownemail::Config->writeconf();
        $var{status} = "<br>Deleted reserved username " . $myownemail->param('Del');
    }

    $var{domainbox} = $myownemail->domains();

    foreach ( sort keys %reserved ) {
        $var{class}    = ( $var{class} eq "odd" ) ? "even" : "odd";
        $var{Reserved} = $_;
        $var{reserveduserlist} .=
          $myownemail->parse( "html/reserved_entry.html", %var );
    }

    print $myownemail->parse("html/adminheader.html");

    print $myownemail->parse( "html/reservedusers.html", %var );

}

if ( $var{func} eq "newuser" ) {
    print $myownemail->parse("html/adminheader.html");
    print $myownemail->parse( "html/newuser.html", %var );
}

if ( $var{func} eq "installreport" ) {

foreach ( keys %domains ) {
my $domain = $_;
      $var{domains} .= "$domain," ;
}

$var{uname} = `uname -a`;
$var{hostname} = `hostname`;
$var{date} = localtime;
print $myownemail->parse("html/installreport.html", %var);


}


# Reserved Usernames
if ( $var{func} eq "undeliverable" ) {

    if ( $myownemail->param('Add') ) {

        $pref{error_nouser}    = $myownemail->param('error_nouser');
        $pref{error_overquota} = $myownemail->param('error_overquota');
        $pref{error_maxsize}   = $myownemail->param('error_maxsize');
        $var{status}           = "<br>Updated Undeliverable Messages<br>";
        Myownemail::Config->writeconf();
    }

    use Myownemail::Config;
    print $myownemail->parse("html/adminheader.html");
    print $myownemail->parse( "html/undeliverable.html", %var );
}

if ( $var{func} eq "branding" ) {

    if ( $myownemail->param('Add') ) {

        $pref{brandname} = $myownemail->param('brandname');
        if ( !$pref{brandname} ) { $pref{brandname} = "\Myownemail" }

        $pref{logo_big_img} = $myownemail->param('logo_big_img');
        if ( !$pref{logo_big_img} ) { $pref{logo_big_img} = "imgs/about.gif" }

        $pref{logo_big_alt} = $myownemail->param('logo_big_alt');
        if ( !$pref{logo_big_alt} ) { $pref{logo_big_alt} = "WebMail System" }

        $pref{logo_small_img} = $myownemail->param('logo_small_img');
        if ( !$pref{logo_small_img} ) {
            $pref{logo_small_img} = "imgs/about.gif";
        }

        $pref{logo_small_alt} = $myownemail->param('logo_small_alt');
        if ( !$pref{logo_small_alt} ) { $pref{logo_small_alt} = "\Myownemail" }

        $pref{company_url} = $myownemail->param('company_url');
        if ( !$pref{company_url} ) {
            $pref{company_url} = "http://myownemail.info/";
        }

        $pref{logout_url} = $myownemail->param('logout_url');
        if ( !$pref{logout_url} ) { $pref{logout_url} = "index.pl?func=logout" }

        $pref{Language} = $myownemail->param('Language');
      $settings{Language} = $myownemail->param('Language');

        if ( !$pref{Language} ) { $pref{Language} = "english" }

            $pref{disclaimer} = $myownemail->param('disclaimer');

        $pref{welcome_msg} = $myownemail->param('welcome_msg');

        $pref{footer_msg} = $myownemail->param('footer_msg');

        $var{status} = "<br>Updated your \Myownemail Configuration<br>";
        Myownemail::Config->writeconf();
    }

    use Myownemail::Config;

    $var{langbox} = $myownemail->languages();
    $var{langbox} =~ s/<select/<select class='option'/g;
    $var{langbox} =~
s/<option value="$pref{Language}"/<option value="$pref{Language}" selected/g;

    print $myownemail->parse("html/adminheader.html");
    print $myownemail->parse( "html/branding.html", %var );
}

if ( $var{func} eq "newuser" ) {
    print $myownemail->parse("html/adminheader.html");
    print $myownemail->parse( "html/newuser.html", %var );
}

if ( $var{func} eq "backup" ) {
    print $myownemail->parse("html/adminheader.html");

    $var{mysql_dir}    = mysqltable();
    $var{tar_location} = tarlocation();

    if ( $myownemail->param('save') ) {

        $var{user_dir}     = $myownemail->param('user_dir');
        $var{mysql_dir}    = $myownemail->param('mysql_dir');
        $var{backup_type}  = $myownemail->param('backup_type');
        $var{tar_location} = $myownemail->param('tar_location');
        $var{backup_dir}   = $myownemail->param('backup_dir');

        $var{t} = time();

        # CHECK FOR DATABASE BACKUP

        if ( -d "$var{mysql_dir}" ) {
            if ( $var{backup_type} eq "copy" ) {
                $var{status} =
"Copying Database<br><b>***</b> cp -vR $var{mysql_dir} $var{backup_dir}/myownemail.$var{t}.db <b>***</b><br><br>";
            }
            elsif ( $var{backup_type} eq "tar" ) {
                $var{status} =
"Tarring up Database<br><b>***</b> $var{tar_location} $var{backup_dir}/myownemail.$var{t}.db.tar.gz $var{mysql_dir} <b>***</b><br><br>";
            }
            $var{dbBackup} = 1;
        }

        elsif ( $var{mysql_dir} ) {

            # nice error message with explanation
            my $tmp = $var{mysql_dir};
            $tmp =~ s/$pref{sql_table}//g;
            my $user = $);
            $user =~ s/ (.*)//g;

            $var{status} = <<_EOF;
Database backup couldn't be backed up because permissions are not set
correctly. Backup your database manually as root, or change the ownership
of the database files. To do this:
      
<br><br>chmod 750 $tmp<br>chmod -R 750 $var{mysql_dir}<br><br>chgrp $user $tmp<br>
chgrp -R $user $var{mysql_dir}<br><br>
_EOF
        }

        else {

            #chill
        }

        #copy files
        if ( $var{backup_type} eq "copy" ) {
            $var{status} .=
"Copying User Directory<br><b>***</b> cp -vR $var{user_dir} $var{backup_dir}/myownemail.$var{t}.users <b>***</b><br>";
            print $myownemail->parse( "html/backupbusy.html", %var );
            if ( $var{dbBackup} ) {

                #BACKUP DATABASE
                print system(
                  "cp -vR $var{mysql_dir} $var{backup_dir}/myownemail.$var{t}.db");

            }
            print system(
              "cp -vR $var{user_dir} $var{backup_dir}/myownemail.$var{t}.users");
            print
             "<script language='javascript'>alert('Backup Complete');</script>";
        }

        #tar files up            
        elsif ( $var{backup_type} eq "tar" ) {
            $var{status} .=
"Tarring up User Directory<br><b>***</b> $var{tar_location} $var{backup_dir}/myownemail.$var{t}.users.tar.gz $var{user_dir} <b>***</b><br>";
            print $myownemail->parse( "html/backupbusy.html", %var );
            if ( $var{dbBackup} ) {

                #BACKUP DATABASE
                print system(
"$var{tar_location} $var{backup_dir}/myownemail.$var{t}.db.tar.gz $var{mysql_dir}"
                );
            }
            print system(
"$var{tar_location} $var{backup_dir}/myownemail.$var{t}.users.tar.gz $var{user_dir}"
            );
            print
             "<script language='javascript'>alert('Backup Complete');</script>";
        }

    }

    else {
        print $myownemail->parse( "html/backup.html", %var );
    }
}

if ( $var{func} eq "htpasswd" ) {
    print $myownemail->parse("html/adminheader.html");

    if ( $myownemail->param('save') ) {

        #$var{oldpass} = $myownemail->param('oldpass');
        $var{newpass} = $myownemail->param('newpass');

        my $pass;

        open( F, ".htpasswd" );
        while (<F>) {
            $_ =~ /admin:(.*)/;
            $pass = $1;
            last if ($pass);
        }
        close(F);

        chomp($pass);

#  See if the specified installation directory exists.
if(!-e "$pref{install_dir}/webadmin/admin.pl")      {
$var{status} = "Cannot add password. The $pref{install_dir}/webadmin/ directory does not exist. Specify the
installation directory of \Myownemail via the Configuration -> System Configuration menu.";

} else      {
# Otherwise add the new password as required.

my $newpass = apache_md5_crypt( $var{newpass} );
open( F, ">.htpasswd" ) || print "Cannot write .htpasswd : $!";
print F "admin:$newpass";
close(F);

# Add the .htaccess file if it does not exist.
if(!-e ".htaccess" && -e "$pref{install_dir}/webadmin/admin.pl")      {

open(F, ">.htaccess" ) || print "Cannot write .htaccess : $!";
print F <<_EOF;
AuthUserFile $pref{install_dir}/webadmin/.htpasswd
AuthName WebAdmin
AuthType Basic
require valid-user
_EOF
            close(F);
}

$var{status} = "Password Changed.";
}
      
      
} else {

        #$var{status} = "Old Password does not match";
    }

    #}

    print $myownemail->parse( "html/htpasswd.html", %var );
}

elsif ( $var{func} eq "notyet" ) {
    print $myownemail->parse( "html/adminheader.html", %var );
    print $myownemail->parse("html/notyet.html");
}

sub get_date {
    my $t = $_[0] || time();

    $var{year} = strftime( "%y", localtime($t) );
    $var{year} = "0$var{year}" if ( length( $var{year} ) == 1 );

    $var{month} = strftime( "%m", localtime($t) );
    $var{month} = "0$var{month}" if ( length( $var{month} ) == 1 );

    $var{day} = strftime( "%d", localtime($t) );
    $var{day} = "0$var{day}" if ( length( $var{day} ) == 1 );

    $var{time} = "$var{year}$var{month}$var{day}";

    return $var{time};
}


sub write_conf {

    Myownemail::Config->writeconf();

}

### Delete a user account      
sub deleteuser_flat {
    my $user = $_[0];

    # Return if there is no username or specified user is not a directory
    return if ( !$user || !-d "$pref{user_dir}/users/$user/" );

    # Delete the user, flat file style

    # Print some output, to the browser will not expire
    print "<b></b>";

    # We are running Windows ...
    if ( $^O =~ /Win/ ) {
        my $path = "$pref{user_dir}/users/$user/";
        $path =~ s/\//\\/g;
        `rd /s /q $path`;

    }
    else {

        # Unix style delete
        `rm -rf $pref{user_dir}/users/$user`;
    }
}

sub deleteuser_sql {
    my $user = $_[0];


    # Load the table names
    $sql->table_names("$user");

    # Print some output, to the browser will not expire
    print "<b></b>";

    # Loop through the common tables of user accounts
    foreach ( 'EmailUIDL', 'SpamDB', 'MailSort', 'Abook', 'UserSettings' ) {
        $sql->sqlquery("delete from $sql->{$_} where Account='$user'");
    }

    # Delete all the messages in the database from the specified user
    my @id =
      $sql->idquery(
      "select id from $sql->{EmailDatabase} where Account='$user'", "id" );

    foreach (@id) {
        $sql->sqlquery("delete from $sql->{EmailMessage} where id='$_'");
        $sql->sqlquery("delete from $sql->{EmailDatabase} where id='$_'");
    }

    # Delete the remaining tables
    $sql->sqlquery("delete from Users where Account='$user'");
    $sql->sqlquery("delete from UserSession where Account='$user'");
    $sql->sqlquery("delete from $sql->{Calendar} where UserTo='$user'");
    $sql->sqlquery("delete from Folders where Account='$user'");

    return;
}

sub myescape {
    my $toencode = shift;
    return undef unless defined($toencode);
    $toencode =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
    return $toencode;
}

sub searchusers {

    my $query = $myownemail->param('sql') || $_[0];
    my ($userlist);

    # Decide which mode to search in. All users or query based
    if ($query) {
        $var{status}  = "Search Results";
        $var{comment} = $myownemail->parse("msgs/comment-searchusers.html");
    }
    else {
        $var{status}  = "Listing all users";
        $var{comment} = $myownemail->parse("msgs/comment-allusers.html");
    }

    my @id;

    # Search for users flat-file, or SQL based
    if ( $pref{sql_type} ) {
        $query = "select id from Users order by id" if ( !$query );
        @id = $sql->idquery( $query, "id" );

        # Escape the SQL query
        $query = myescape($query);

    }
    else {

        # Search for the user in the flat-file database
        @id = searchusers_flat($query);
    }

    # The total number of log entrys
    $var{total} = scalar(@id);
    $var{status} .= " - $var{total} records";
    $var{num}     = 25 if ( !$var{num} );
    $var{msg_pos} = $myownemail->param('start') || $var{total} - $var{num};

    # Create the next / prev buttons if nessasary
    if ( $var{msg_pos} + $var{num} < $var{total} ) {
        my $next_pos = $var{msg_pos} + $var{num};

        $var{next} = <<_EOF;
<a href="admin.pl?func=users&type=$var{type}&start=$next_pos&sql=$query">
<img src="imgs/next.gif" border=0 alt="Next messages">
</a>
_EOF
    }

    if ( $var{total} - $var{num} >= 0 && $var{msg_pos} != 1 ) {
        my $prev_pos = $var{msg_pos} - $var{num};
        $prev_pos = 1 if ( $prev_pos <= 0 );

        $var{prev} = <<_EOF;
<a href="admin.pl?func=users&type=$var{type}&start=$prev_pos&sql=$query">
<img src="imgs/previous.gif" border=0 alt="Previous messages">
</a>
_EOF
    }

# Find which messages to display, depending if the user clicked 'next/prev' buttons
    $var{msg_pos} = $var{total} - $var{num}
      if ( $var{msg_pos} + $var{num} > $var{total} );
    $var{msg_pos} = 0 if ( $var{msg_pos} <= 1 );

    $var{total} = $var{msg_pos} + $var{num}
      if ( $var{msg_pos} + $var{num} <= $var{total} );

    # Create a temp hash containing the users details
    my (%db);

    # List messages from the newest to oldest
    for ( my $i = $var{total} ; $i >= $var{msg_pos} ; $i-- ) {
        $var{id} = $id[$i];
        next if ( !$var{id} );

        $var{class} = ( $var{class} eq "odd" ) ? "even" : "odd";

        if ( $pref{sql_type} ) {

            %db =
              $sql->doquery(
              "select Account,DateCreate from Users where id='$var{id}'");

            $var{time} = $sql->getvalue( "select LastLogin from UserSession
                        where Account='$db{Account}'" );

            $var{time} = strftime( "%a %D %R", localtime( $var{time} ) );

          $var{Account} = $db{Account};
      
      # Delete any whitespace , to avoid breaking the javascript.
            $var{Account} =~ s/\s//g;

        # Parse the date into a more reabable format
        $db{DateCreate} =~ /(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/;
        $db{DateCreate} = "$3/$2/$1 $4:$5:$6";

            $userlist .= $myownemail->parse( "html/user_entry.html", %db, %var );
        }
        else {

            # Retrieve the users details from the flat-file DB
            %db =
              Myownemail::Flat->gethash("$pref{user_dir}/users/$var{id}/login.db");

          my %tmp =
             Myownemail::Flat->gethash("$pref{user_dir}/users/$var{id}/user.db");

            $var{time} = strftime( "%a %D %R", localtime( $db{LastLogin} ) );

            $var{Account} = $db{Account};
          $var{DateCreate} = $tmp{DateCreate};

            #$var{userlist} .=
            $userlist .= $myownemail->parse( "html/user_entry.html", %db, %var );
        }

    }

    # Return the list of users in HTML table format
    return $userlist;
}

sub makesql_query {

    my ( $extra, $query );

    $extra = "where ";

    # Loop through each field
    foreach ( 'Account', 'Ugroup', 'FirstName', 'LastName', 'Address', 'City', 'State',
      'PostCode', 'Country', 'OtherEmail', 'Gender', 'OtherEmail', 'Industry',
      'Occupation', 'BirthDay', 'BirthMonth', 'BirthYear' )
    {
        my $name = $_;

        # Load the field search type
        my $search = $name . "_o";

        # Load the value of the search field
        my $value = $myownemail->param($name);

        $var{$search} = $myownemail->param($search);

        $var{hidden} .= "<input type='hidden' name='$name' value='$value'>\n";
        $var{hidden} .=
          "<input type='hidden' name='$search' value='$var{$search}'>\n";

        if ( $myownemail->param('pop3host') && !$myownemail->param('Account')
          && $name eq "Account" )
        {
            $value = '%';
        }

        # Add in % for like querys
        if ( $var{$search} eq "like" || $var{$search} eq "not like" ) {
            next if ( !$value );
            $value = "%" . $value . "%";
        }

        if ( $myownemail->param('pop3host') && $name eq "Account" ) {
            $value = "$value\@" . $myownemail->param("pop3host");
        }

        # Skip if we have no value and no search query
        next if ( !$var{$search} );
        next if ( !$value );

        # SQL quote the query
        $var{$name} = $sql->quote($value);

        # Create our extended SQL query
        $extra .= "$name $var{$search} $var{$name} and " if ( $var{$name} );

    }

    # Take away the last and statement
    $extra =~ s/and $//g;

    $query = "select id from Users $extra";

    return $query;
}

sub makeflat_query {

    my ( $extra, $query );

    # Loop through each field
    foreach ( 'Account', 'Ugroup', 'FirstName', 'LastName', 'Address', 'City', 'State',
      'PostCode', 'Country', 'OtherEmail', 'Gender', 'OtherEmail', 'Industry',
      'Occupation', 'BirthDay', 'BirthMonth', 'BirthYear' )
    {
        my $name = $_;

        # Load the field search type
        my $search = $name . "_o";

        # Load the value of the search field
        my $value = $myownemail->param($name);

        $var{$name} = $myownemail->param($name);

        $var{$search} = $myownemail->param($search);

        $var{hidden} .= "<input type='hidden' name='$name' value='$value'>\n";
        $var{hidden} .=
          "<input type='hidden' name='$search' value='$var{$search}'>\n";

        if ( $myownemail->param('pop3host') && !$myownemail->param('Account')
          && $name eq "Account" )
        {
            $value = '=~';
        }

        # Convert the SQL querys to Perl syntax
        $var{$search} = "=~" if ( $var{$search} eq "like" );
        $var{$search} = "!~" if ( $var{$search} eq "not like" );
        $var{$search} = "eq" if ( $var{$search} eq "=" );
        $var{$search} = "ne" if ( $var{$search} eq "!=" );

        if ( $myownemail->param('pop3host') && $name eq "Account" ) {
            $value = "$value" . $myownemail->param("pop3host");
        }

        # Add in % for like querys
        if ( $var{$search} eq "like" || $var{$search} eq "not like" ) {
            next if ( !$value );

            #$value = "=~" . $value . "=~";
        }

        #print "$name = $var{$search} = $search = $value<BR>";

        # Skip if we have no value and no search query
        next if ( !$var{$search} );
        next if ( !$value );

        # SQL quote the query
        #$var{$name} = $sql->quote($value);

        # Create our extended SQL query
        $extra .=
          "\$db{$name} $var{$search} \$var{$name} && ";    # if ( $var{$name} );

    }

    # Take away the last and statement
    $extra =~ s/&& $//g;

    #$query = "select id from Users $extra";

    return $extra;
}


sub group_options {
      my $txt;
      foreach ( keys %groups ) {
            $txt .= "<option value=\"$_\">$_</option>";
      }
      return $txt;
}

sub weekdate {

}

sub calc_week {
    my ($time) = @_;

    my $days = 86400 * 7;

    $time = $time - $days;

    my $newtime = strftime( "%D %r", localtime($time) );

    $newtime =~ /(\d\d)\/(\d\d)\/(\d\d) (\d\d):(\d\d):(\d\d)/;
    $newtime = "$3$1$2$4$5$6";
    return $newtime;
}

sub smtp_type {

    my $txt = <<_EOF;
        <select class="option" name="smtp_type">
          <option value="POP3">POP3 Access Only</option>
          <option value="Sendmail">Sendmail</option>
          <option value="Sendmail Aliases">Sendmail Aliases</option>
          <option value="Exim">Exim</option>
          <option value="qmail">qMail</option>
        </select>
_EOF

    $txt =~
s/option value="$pref{smtp_type}"/option value="$pref{smtp_type}" selected/g;

# For our Windows friends ...
if($^O =~ /MSWin/)      {
      $txt =~ s/Exim<\/option>/Exim (Windows)<\/option>/g;
}

    return $txt;

}

sub install_type {

    my $txt = <<_EOF;
      <select class="option" name="install_type">
      <option value="standalone">Email Client</option>
      <option value="server">Email Server</option>
      </select>
_EOF

    $txt =~
s/option value="$pref{install_type}"/option value="$pref{install_type}" selected/g;

    return $txt;
}

sub mail_type {
    my $txt = <<_EOF;
      <select class="option" name="mail_type">
      <option value="pop3imap">POP3 and IMAP</option>
      <option value="pop3">POP3 only</option>
      <option value="imap">IMAP only</option>
      <option value="none">No External Servers</option>
      </select>
_EOF

    $txt =~
s/option value="$pref{mail_type}"/option value="$pref{mail_type}" selected/g;

    return $txt;
}

sub sendmode {
    my $txt = <<_EOF;
      <select class="option" name="sendmode">
      <option value="pipe">Sendmail Binary</option>
      <option value="smtp">SMTP Server</option>
      </select>
_EOF

    $txt =~
     s/option value="$pref{sendmode}"/option value="$pref{sendmode}" selected/g;

    return $txt;
}

# Check for any errors with the Configuraiton
sub check_errors {

    # Test our Myownemail installation is functioning
    my $err;
    my $error;

      # Test the .install file exists
      if ( $^O !~ /Win/i && !-e "../.install" )      {
            $error .= "<font class=error><li> The install.pl script has not been run via the command-line. Use this
                  script to first configure the \Myownemail software.</li></font>";
      }


    # Get the users running Myownemail, only under Unix
    $var{user} = getpwuid($<) if ( $^O !~ /Win/i );

    # See if we can open to our Myownemail direcfory
    foreach ( "$pref{user_dir}", "$pref{user_dir}/tmp", "$pref{user_dir}/users/" ) {
        my $dir = $_;
        my $err;
        $err = open( F, ">$dir/.test" );

        if ( !$err ) {
            $error .=
"<font class=error><li> Cannot write to the User Directory of \Myownemail $dir . Please check the directory exists and change the ownership of the directory to your webserver user $var{user} (chown -R $var{user} $dir)</li></font>";
        }

        unlink("$dir/.test");
    }

    # Next, check our sendmail binary or SMTP server is valid
    if ( $pref{sendmode} eq "pipe" ) {

        my $sendmail = $pref{sendmail};
        $sendmail =~ s/ .*//g;

        # If we cannot see the sendmail binary, report the error
        if ( !-e "$sendmail" ) {
            $error .=
"<font class=error><li> The sendmail binary $pref{sendmail} could not be located on your system. Check you have provided the correct pathname. Otherwise, use an external SMTP server to deliver emails</li></font>";
        }

        # Check the SMTP server is valid, and can be found
    }
    else {
        use Net::SMTP;

        my $smtp = Net::SMTP->new( $pref{smtphost}, Timeout => 60 );

        if ( !$smtp ) {
            $error .=
"<font class=error><li> The SMTP server would not connect. Please check the domain-name is correct, you have access to the SMTP server and your connection to the network is active</li></font>";
        }

    }

    # Check the connection to the database server is active
    if ( $pref{sql_type} ) {

        eval "use DBI;\n";

        my $dbh =
          DBI->connect(
"DBI:$pref{sql_type}:database=$pref{sql_table};hostname=$pref{sql_host}",
          "$pref{sql_user}", "$pref{sql_pass}" );

        if ( !$dbh ) {
            $error .=
"<font class=error><li> \Myownemail could not connect to the database server. Check the database name is correct, the
database exists, and the username/password are correct to connect. Verify you are using the correct database driver for your
    system - <i>$DBI::errstr</i> </li></font>";
        }

        if ( $dbh && !$myownemail->param('Create') ) {
            my $exist;
            my @tables = $dbh->func('_ListTables');

            for (@tables) {
                $exist++
                  if ( $_ eq "Users" || $_ =~ /EmailDatabase/i
                  || $_ =~ /EmailMessage/ );
            }

            $error .=
"<font class=error><li> \Myownemail could not detect the Database Tables are created. You must create
the database tables before using the application. To create the nessasary tables use the <a href=\"admin.pl?func=settings_db\">database configuration</a> </li></font>"
              if ( !$exist );

        }

    }

    # Check that the Myownemail directory is owned by the webserver
    my $dirs = $myownemail->{Bin};
    $dirs =~ s/\/webadmin//g;

    foreach ( "$dirs/libs/Myownemail/", "$dirs" ) {
        my $dir = $_;

        my $err = open( F, ">$dir/.test" );

        if ( !$err ) {
            $error .=
"<font class=error><li> The $dir directory does not have write permissions. Change the ownership of the directory to your webserver user $var{user} . (chown -R $var{user} $dir)</li></font>";
        }

    }

    $error =
"<font class=error><ul><li><b>\Myownemail Configuration Errors</b></li>$error</ul></font>"
      if ($error);

    return $error;
}

sub mysqlversion {
    my $mysqlversion;
    foreach ( '/usr/local/mysql/bin/mysql -V', '/usr/local/bin/mysql -V',
      '/usr/bin/mysql -V', 'mysql -V' )
    {

        last if ($mysqlversion);
        $mysqlversion = `$_`;
        $mysqlversion = $1 if ( $mysqlversion =~ /Distrib (.*?),/ );
        if ($mysqlversion) {
            $mysqlversion = "<font class='option'>$mysqlversion</font>";
        }

        next if ( !$mysqlversion );

    }

      if ( !$mysqlversion && $^O =~ /Win/ ) {

            $mysqlversion = `/myownemail/mysql/bin/mysqld-nt.exe -v`;
            $mysqlversion = $1 if ( $mysqlversion =~ /Ver (.*?)\s/);

      } elsif( !$mysqlversion ) {
        $mysqlversion = "<font class='error'>not found</font>";
    }

    return $mysqlversion;
}

sub mysqltable {
    my $mysqltable;
    foreach ( '/usr/local/mysql/data', '/usr/local/var' ) {

        $mysqltable = "$_/$pref{sql_table}" if ( -d $_ );

    }
    return $mysqltable;
}

sub tarlocation {
    my $tarlocation;
    foreach ( '/usr/local/bin/tar', '/usr/bin/tar', '/bin/tar',
      '/usr/local/tar/bin/tar' )
    {

        $tarlocation = "$_ cfvz" if ( -e $_ );

    }
    return $tarlocation;
}

# Upload the migrate to the server
sub attach {
    my ($fileupload) = $_[0];
    my $fileupload = $myownemail->param("$fileupload");

    return "File not specified!" if ( !$fileupload );
    open( ATTACH, ">$pref{user_dir}/tmp/migrate.txt" )
      || die "Cannot save migrate on server: $!";
    binmode(ATTACH);

    while (<$fileupload>) {
        print ATTACH $_;
    }

    close(ATTACH);

}

sub searchusers_flat {
    my ($query) = @_[0];
    my (@id);

    opendir( DIR, "$pref{user_dir}/users/" );
    my @fol = readdir(DIR);

    #@fol = reverse(@fol);

    foreach my $f (@fol) {
        next if ( $f eq "." || $f eq ".." || $f !~ /\@/ );

        if ($query) {
            my %db = Myownemail::Flat->gethash("$pref{user_dir}/users/$f/user.db");
            $db{Account} = $f;

            # Perform the SQL query
            if ( eval("$query") ) {
                push ( @id, "$f" );
            }

        }
        else {

            # Add the user to the array
            push ( @id, $f );
        }

    }

    return @id;
}

sub logtype {
    my ( $log, $type ) = @_;
    my ($log);

    if ( $type eq "Login" || $type eq "Error" ) {
        $log = "$log$type";
    }
    elsif ( $type eq "RecvMail" ) {
        $log = "Msg" . $type;
    }
    elsif ( $type eq "SentMail" ) {
        $log = "Sent" . $type;
    }

    return $log;
}

sub add_domain_sendmail {
    my ($domain) = @_;

    $domain = lc($domain);
    my $cw = sendmail_cw();
    my $check;

    # Open the CW file, see if our domain exists
    open( F, "$cw" )
      || print "Cannot open $cw , you must edit the file manually : $!";
    while (<F>) {
        my $line = $_;
        chomp($line);
        $line =~ s/ //g;
        $line = lc($line);

        $check++ if ( $line eq $domain );
    }

    if ( !$check ) {
        open( F, ">>$cw" )
          || print
          "Cannot add new domain to $cw , you must edit the file manually : $!";
        print F "\n# Added by \Myownemail " . localtime() . "\n$domain\n";
        close(F);
    }

    my $check;

    # Open the myownemail-domains file, see if our domain exists
    open( F, "$pref{install_dir}/myownemail-domains" )
      || print
"Cannot open $pref{install_dir}/myownemail-domains , you must edit the file manually : $!";
    while (<F>) {
        my $line = $_;
        chomp($line);
        $line =~ s/ //g;
        $line = lc($line);

        $check++ if ( $line eq $domain );
    }

    if ( !$check ) {
        open( F, ">>$pref{install_dir}/myownemail-domains" )
          || print
"Cannot add new domain to $pref{install_dir}/myownemail-domains , you must edit the file manually : $!";
        print F "\n# Added by \Myownemail " . localtime() . "\n$domain\n";
        close(F);
    }

}

# Add the domain Exim style
sub add_domain_exim {
my($domain) = @_;

      my $check;
      my $out;

      # Open the myownemail-domains file, see if our domain exists
      open(F, "$pref{install_dir}/myownemail-domains")      || print "Cannot open $pref{install_dir}/myownemail-domains , you must edit the file manually : $!";
      while(<F>)      {
      my $line = $_;
      chomp($line);
      $line =~ s/ //g;
      $line = lc($line);

      $check++ if($line eq $domain);
      }

      if(!$check)      {
      open(F,">>$pref{install_dir}/myownemail-domains") || print "Cannot add new domain to $pref{install_dir}/myownemail-domains , you must edit the file manually : $!";
      print F "\n# Added by \Myownemail " . localtime() . "\n$domain\n";
      close(F);
      }

    if ( $^O =~ /Win/ ) {
      $out = `net stop atsmtp`;
      $out = `net start atsmtp`;
      }

return $out;

}

# Delete the domain

sub del_domain_exim      {
my($domain) = @_;

      # Open the myownemail-domains file
      open(F, "$pref{install_dir}/myownemail-domains")      || print "Cannot open $pref{install_dir}/myownemail-domains , you must edit the file manually : $!";

      open(F2, ">$pref{install_dir}/myownemail-domains.bak")      || print "Cannot write $pref{install_dir}/myownemail-domains.bak , you must edit the file manually : $!";

      while(<F>)      {
      my $line = $_;
      chomp($line);
      print F2 $_ if($line !~ /^$domain/);
      }

      close(F2);
      close(F);

      rename("$pref{install_dir}/myownemail-domains.bak", "$pref{install_dir}/myownemail-domains") || print "Cannot rename $pref{install_dir}/myownemail-domains to $pref{install_dir}/myownemail-domains.bak : $!";


}

sub sendmail_cw {

    my $cw;
    my $sendmailcfpath;

    $sendmailcfpath = "/etc/sendmail.cf" if ( -e "/etc/sendmail.cf" );
    $sendmailcfpath = "/etc/mail/sendmail.cf" if ( -e "/etc/mail/sendmail.cf" );

    open( F, "$sendmailcfpath" ) || print "Cannot open $sendmailcfpath : $!";
    while (<F>) {
        $cw = $1 if ( $_ =~ /^Fw(.*)/ );
    }
    close(F);

    # Delete the -o from the pathname
    $cw =~ s/.*?-o\s+//g;
    $cw =~ s/%.*//g;
    return $cw;

}

sub del_domain_sendmail {
    my ($domain) = @_;

    $domain = lc($domain);

    my $cw = sendmail_cw();

    my $check;

    # Open the CW file, see if our domain exists
    open( F, "$cw" )
      || print "Cannot open $cw , you must edit the file manually : $!";

    my $name = $1 if ( $cw =~ /.*\/(.*)/ );

    open( F2, ">$pref{install_dir}/$name.bak" )
      || print "Cannot write $cw , you must edit the file manually : $!";

    while (<F>) {
        my $line = $_;
        chomp($line);
        print F2 $_ if ( $line !~ /^$domain/ );
    }

    close(F2);
    close(F);

    # Rename has permission denied errors ...
#rename("$pref{install_dir}/$name.bak", "$cw") || print "Cannot rename $pref{install_dir}/$name.bak to $cw : $!";

    open( F,  ">$cw" ) || print "Cannot write $cw : $!";
    open( F2, "$pref{install_dir}/$name.bak" )
      || print "Cannot read $pref{install_dir}/$name.bak : $!";

    while (<F2>) {
        print F $_;
    }

    close(F);
    close(F2);

    unlink("$pref{install_dir}/$name.bak");

    # Open the myownemail-domains file
    open( F, "$pref{install_dir}/myownemail-domains" )
      || print
"Cannot open $pref{install_dir}/myownemail-domains , you must edit the file manually : $!";

    open( F2, ">$pref{install_dir}/myownemail-domains.bak" )
      || print
"Cannot write $pref{install_dir}/myownemail-domains.bak , you must edit the file manually : $!";

    while (<F>) {
        my $line = $_;
        chomp($line);
        print F2 $_ if ( $line !~ /^$domain/ );
    }

    close(F2);
    close(F);

    rename( "$pref{install_dir}/myownemail-domains.bak",
      "$pref{install_dir}/myownemail-domains" )
      || print
"Cannot rename $pref{install_dir}/myownemail-domains to $pref{install_dir}/myownemail-domains.bak : $!";

}
[+][-]04/03/03 05:08 AM, ID: 8260983

View this solution now by starting your 30-day free trial. Setting up your free trial is quick, easy, and secure. We will return you to this solution, unlocked, when you're done.

 

About this solution

Zone: Perl Programming Language
Tags: end, premature, script, headers
Sign Up Now!
Solution Provided By: rj2
Participating Experts: 6
Solution Grade: A
 
 
[+][-]04/03/03 05:08 AM, ID: 8260985

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]04/03/03 05:11 AM, ID: 8261023

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]04/03/03 05:27 AM, ID: 8261142

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]04/03/03 05:49 AM, ID: 8261328

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]04/03/03 06:21 AM, ID: 8261572

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]04/03/03 06:28 AM, ID: 8261633

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]04/03/03 06:30 AM, ID: 8261647

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]04/03/03 06:55 AM, ID: 8261854

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]04/03/03 07:34 AM, ID: 8262184

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]04/03/03 08:22 AM, ID: 8262607

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]04/03/03 08:27 AM, ID: 8262651

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]04/03/03 08:30 AM, ID: 8262679

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]04/03/03 08:32 AM, ID: 8262692

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]04/03/03 08:34 AM, ID: 8262707

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]04/03/03 08:39 AM, ID: 8262742

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]04/03/03 09:06 AM, ID: 8262952

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]04/03/03 09:11 AM, ID: 8262975

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]04/03/03 09:13 AM, ID: 8262992

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]04/03/03 09:15 AM, ID: 8262998

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]04/03/03 09:18 AM, ID: 8263014

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]04/03/03 09:24 AM, ID: 8263056

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]04/03/03 10:42 AM, ID: 8263472

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]04/03/03 10:45 AM, ID: 8263493

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]04/04/03 10:11 AM, ID: 8271305

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]04/09/03 11:51 AM, ID: 8301834

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]04/10/03 07:54 AM, ID: 8306868

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
 
Loading Advertisement...
20091111-EE-VQP-91