#!/usr/bin/perl -wT

#----------------------------------------------------------------------
# heading     : Administration
# description : Web statistics
# navigation  : 4000 4350
#
# copyright (C) 2001 neddix !!
#
# contributor: stephen noble <support@dungog.net>
#              option to delegate single domain viewable at /user-manager
#
# This program is part of the AWstats package for the e-smith Server and Gateway
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
#
#----------------------------------------------------------------------

package esmith;

use strict;
use CGI ':all';
#use CGI::Carp qw(fatalsToBrowser);

use esmith::cgi;
use esmith::config;
use esmith::util;
use esmith::db;

sub showInitial ($$);
sub displayStats ($);
sub confAWStats ($);
sub deleteStats ($);
sub performDeleteStats ($);
sub saveConfig ($);

sub modifyOptions ($$);                 #authority and options
sub performModifyOptions ($);

BEGIN
{
    # Clear PATH and related environment variables so that calls to
    # external programs do not cause results to be tainted. See
    # "perlsec" manual page for details.

    $ENV {'PATH'} = '';
    $ENV {'SHELL'} = '/bin/bash';
    delete $ENV {'ENV'};
}

esmith::util::setRealToEffective ();

$CGI::POST_MAX=1024 * 100;  # max 100K posts
$CGI::DISABLE_UPLOADS = 1;  # no uploads

my %conf;
tie %conf, 'esmith::config';

my %domains;
tie %domains, 'esmith::config', '/home/e-smith/db/domains';

my %accounts;
tie %accounts, 'esmith::config', '/home/e-smith/db/accounts';

my $version;
open (IN, "/etc/e-smith/web/panels/manager/cgi-bin/.awstats/version");
$version = "Version ".<IN>." based on AWStats ".<IN>;
close (IN);

#------------------------------------------------------------
# examine state parameter and display the appropriate form
#------------------------------------------------------------

my $q = new CGI;
if ( grep (/^site$/, $q->param)) {
    displayStats ($q);
}

if (! grep (/^state$/, $q->param))
{
    showInitial ($q, '');
}

elsif ($q->param ('state') eq 'displaystats' )
{
    displayStats ($q);
}

elsif ($q->param ('state') eq 'confawstats' )
{
    confAWStats ($q);
}

elsif ($q->param ('state') eq "delete")
{
    deleteStats ($q);
}

elsif ($q->param ('state') eq "performDelete")
{
    performDeleteStats ($q);
}

elsif ($q->param ('state') eq 'saveconfig' )
{
    saveConfig ($q);
}

elsif ($q->param ('state') eq "modifyOptions")
{
    modifyOptions ($q, '');
}

elsif ($q->param ('state') eq "performModifyOptions")
{
    performModifyOptions ($q);
}

else
{
    esmith::cgi::genStateError ($q, \%conf);
}

exit (0);

#------------------------------------------------------------
# subroutine to display initial form
#------------------------------------------------------------

sub showInitial ($$)
{
    my ($q, $msg) = @_;
    my $domain;
    my %Stats;
    my $dirdata="/home/e-smith/files/users/admin/home/awstats";

    #------------------------------------------------------------
    # db init
    #------------------------------------------------------------
    if (not defined db_get(\%conf, "AWStats")) {
            my %default_db=(
                    'status' => 'disabled',
                    'Debug' => 'no',
            );
            db_set(\%conf, "AWStats","service",\%default_db);
    }

    #------------------------------------------------------------
    # If there's a message, we just finished an operation so show the
    # status report. If no message, this is a new list of domains.
    #------------------------------------------------------------

    if ($msg eq '') {
                esmith::cgi::genHeaderNonCacheable
                ($q, \%conf, 'Show or Configure Web Statistics ');
    } else {
        esmith::cgi::genHeaderNonCacheable
            ($q, \%conf, 'Operation status report');

        print $q->p ($msg);
        print $q->hr;
    }

      # find domains that this user can edit, store in @mydom
      my $acctName = $ENV{'REMOTE_USER'};
      my $owner = '';
      
      my @mydom = ();
      my @alldom = ();
      
      if ($acctName ne 'admin')
      {
        #A. user must be set as owner
        #1. include all virtual domains + primary
        foreach (keys %domains)
        {
            push (@alldom, $_)
                if (db_get_type(\%domains, $_) eq "domain");
        }

        #2. only retain this users domains
        foreach my $vd (@alldom)
        {
          if ($vd eq db_get(\%conf, 'DomainName'))
          {
            $owner = db_get_prop(\%conf, "AWStats", "owner") || 'admin';
          }
          else
          {
            $owner = db_get_prop(\%domains, $vd, "owner") || 'admin';
          }

          #is owner a group ?
          my $userlist = db_get_prop(\%accounts, $owner, 'Members') || 'notgroup';
          if ($userlist eq 'notgroup')
          {
            #then is it a user or everyone ?
            if (($owner eq $acctName) || ($owner eq 'everyone'))
            {
              push (@mydom, $vd);
            }
          }
          else
          {
            #it is a group
            my @selected = split (/,/, $userlist);
            foreach my $grpmem (@selected)
            {
              if ($grpmem eq $acctName)
              {
                push (@mydom, $vd);
              }
            }
          }
        }
      }
      else
      {
        #B. admin gets all domains
        foreach (keys %domains)
        {
            push (@mydom, $_)
                if (db_get_type(\%domains, $_) eq "domain");
        }
      }


      print $q->startform (-method => 'POST', -action => $q->url (-absolute => 1));

      my $mydom = @mydom;
      if ($mydom == 0)
      {
        print $q->p ($q->b ("There are no domains in the system delegated to $acctName."));
      }
      else
      {
        if ($acctName eq 'admin')
        {
          print $q->p ($q->a ({href => $q->url (-absolute => 1) . "?state=confawstats"},
                        'Click here'),
                 'to configure AWStats.');
        }

        if (db_get_prop(\%conf, "AWStats", "status") ne "enabled")
        {
          print $q->h4 ('AWStats is disabled!');
        }
        else
        {

          print $q->h4 ("List of Domains viewable by $acctName");

          print "Note: A Domain is not shown in the list below until after midnight on the day <br>".
                "statistics are available. To force the display sooner, browse to the website to <br>".
                "create some stats, then resave awstats settings.<br>";
 
          print "<table border=1 cellspacing=1 cellpadding=4>";

          if ($acctName eq 'admin')
          {
            print $q->Tr (esmith::cgi::genSmallCell ($q, $q->b ('Domain')),
                        esmith::cgi::genSmallCell ($q, $q->b ('Description')),
                        esmith::cgi::genSmallCell ($q, $q->b ('Content')),
                        esmith::cgi::genSmallCell ($q, $q->b ('AWStats')),
                        esmith::cgi::genSmallCell ($q, $q->b ('State')),
                        esmith::cgi::genSmallCell ($q, $q->b ('Delegation')));
            } else {
            print $q->Tr (esmith::cgi::genSmallCell ($q, $q->b ('Domain')),
                        esmith::cgi::genSmallCell ($q, $q->b ('Description')),
                        esmith::cgi::genSmallCell ($q, $q->b ('Content')),
                        esmith::cgi::genSmallCell ($q, $q->b ('AWStats')),
                        esmith::cgi::genSmallCell ($q, $q->b ('State')));
          }

          # build a list of domains for which a AWStats history is available
          opendir (DIR, "$dirdata") or die "Could not open directory $dirdata\n";
          while (defined($domain=readdir(DIR)))
          {
                  next if $domain=~ /^\.\.?$/ or not -d "$dirdata/$domain";
                  $Stats{$domain}="empty";
                  opendir (SUBDIR, "$dirdata/$domain") or die "Could not open directory $dirdata/$domain\n";
                  while (defined(my $stat=readdir(SUBDIR)))
                  {
                          next if $stat=~ /^\.\.?$/ or -z "$dirdata/$domain/$stat";
                          $Stats{$domain}="ok";
                          last;
                  }
                  closedir (SUBDIR);

          }
          closedir (DIR);

          foreach $domain (reverse sort keys %Stats)
          {
            my ($d, $value,$content,$active, $description, $type, %properties);
            my $d2 = $d;
            ($d=$domain)=~s/(?:(?:www\.)|(?:secure\.))(.*)/$1/;
            $value = $domains {$d};
            $active=1;
            if (defined $value) {
                    ($type, %properties) = split (/\|/, $value, -1);
                    if ($properties{'Content'} eq 'wwwpublic') {
                            $content = "primary site";
                    } else {
                            $content = $properties{'Content'} . " i-bay";
                    }
                    $description=$properties{'Description'};
            } else {
                    if ($d eq db_get(\%conf, "DomainName")) {
                            $content="primary site";
                            $description="primary site";
                    } else {
                            $active=0;
                            $content="unkown";
                            $description="unkown";
                    }
            }

            #show matches for this user
            foreach (@mydom)
            { 
              #=domain name so skip ??
              if ($_ eq $d) 
              {
                #admin see all
                if ($acctName eq 'admin') 
                {
                 #set owner
                 if ($_ eq db_get(\%conf, 'DomainName')) 
                 {
                  $owner = db_get_prop(\%conf, "AWStats", "owner") || 'admin';
                 } else {
                  $owner = db_get_prop(\%domains, $_, "owner") || 'admin';
                 }
                  my $desc = db_get_prop(\%domains, $_, "Description") || '';
                  my $cont = db_get_prop(\%domains, $_, "Content") || '';

                  print $q->Tr (esmith::cgi::genSmallCell ($q, $_),
                          esmith::cgi::genSmallCell ($q, $desc),
                          esmith::cgi::genSmallCell ($q, $cont),
                          esmith::cgi::genSmallCell ($q,
                          $Stats{$domain} eq "ok"
                          ?  $q->a ({href => ".awstats/awstats.pl"
                               . "?config=" . $_
                               . "&lang=" . db_get_prop(\%conf, "AWStats", "Language")},
                               'Show...')
                               : '<i>empty</i>'),
                          esmith::cgi::genSmallCell ($q,
                          !$active
                          ?  $q->a ({href => $q->url (-absolute => 1)
                                 . "?state=delete&domain=" . $_ },
                                 'Delete...')
                                 : 'active',
                                 ),
                          esmith::cgi::genSmallCell ($q,
                                  $q->a ({href => $q->url (-absolute => 1)
                                    . "?state=modifyOptions&d="
                                    . $_}, $owner)));
                  } else {
                  print $q->Tr (esmith::cgi::genSmallCell ($q, $domain),
                          esmith::cgi::genSmallCell ($q, $description),
                          esmith::cgi::genSmallCell ($q, $content),
                          esmith::cgi::genSmallCell ($q,
                          $Stats{$domain} eq "ok"
                          ?  $q->a ({href => ".awstats/awstats.pl"
                               . "?config=" . $domain
                               . "&lang=" . db_get_prop(\%conf, "AWStats", "Language")},
                               'Show...')
                               : '<i>empty</i>'),
                          esmith::cgi::genSmallCell ($q,
                          !$active
                          ?  $q->a ({href => $q->url (-absolute => 1)
                                 . "?state=delete&domain=" . $domain },
                                 'Delete...')
                                 : 'active',
                                 ));
                  }
              }#
            }
          }

        }#awstats is enabled
        print '</table>';

        print "<br>No statistics available.<br>" if not %Stats;

        if (open (ST, "/var/log/httpd/awstats_lr"))
        {
           print "<br><font size=-1>" . <ST> . "</font>";
          close (ST);
        }

    }
    #mydom>0


    neddixFooter ($q);
}

sub displayStats ($)
{
    my ($q) = @_;
        my $dirdata="/home/e-smith/files/users/admin/home/awstats";
        my $site=$q->param('site');
        $site=~s/.*//;
        $site=$1;

        system ("/etc/awstats/awstats.pl -h $site");

    neddixFooter ($q);
}

sub confAWStats ($)
{
    my ($q) = @_;
        my $Freq=db_get_prop(\%conf, "AWStats", "Freq");
        $Freq="5m" if not defined $Freq;

        my $SkipLocalIP=db_get_prop(\%conf, "AWStats", "SkipLocalIP");
        $SkipLocalIP="yes" if not defined $SkipLocalIP or $SkipLocalIP ne "no"; # in Beta1 SkipLocalIP="mask" was possible
        my $SkipExternalIP=db_get_prop(\%conf, "AWStats", "SkipExternalIP");
        $SkipExternalIP="yes" if not defined $SkipExternalIP;
        my $SkipLocalNetworks=db_get_prop(\%conf, "AWStats", "SkipLocalNetworks");
        $SkipLocalNetworks="no" if not defined $SkipLocalNetworks;

        my $UseFramesWhenCGI=db_get_prop(\%conf, "AWStats", "UseFramesWhenCGI") || "no";
        my $Language=db_get_prop(\%conf, "AWStats", "Language");
#        $Language=0 if not defined $Language;
        $Language='auto' if not defined $Language;

        my $Hostinfo=db_get_prop(\%conf, "AWStats", "Hostinfo");
        my $Rawlog=db_get_prop(\%conf, "AWStats", "Rawlog");

        my $BarSize=db_get_prop(\%conf, "AWStats", "BarSize");
        $BarSize="medium" if not defined $BarSize;

        my $MaxNbOfDomain = db_get_prop(\%conf, "AWStats", "MaxNbOfDomain");
        $MaxNbOfDomain=50 if not defined $MaxNbOfDomain;

        my $MaxNbOfHostsShown = db_get_prop(\%conf, "AWStats", "MaxNbOfHostsShown");
        $MaxNbOfHostsShown=100 if not defined $MaxNbOfHostsShown;
        my $MinHitHost = db_get_prop(\%conf, "AWStats", "MinHitHost");
        $MinHitHost=1 if not defined $MinHitHost;

        my $MaxNbOfPageShown = db_get_prop(\%conf, "AWStats", "MaxNbOfPageShown");
        $MaxNbOfPageShown=200 if not defined $MaxNbOfPageShown;
        my $MinHitFile = db_get_prop(\%conf, "AWStats", "MinHitFile");
        $MinHitFile=1 if not defined $MinHitFile;

        my $MaxNbOfRobotShown = db_get_prop(\%conf, "AWStats", "MaxNbOfRobotShown");
        $MaxNbOfRobotShown=25 if not defined $MaxNbOfRobotShown;
        my $MinHitRobot = db_get_prop(\%conf, "AWStats", "MinHitRobot");
        $MinHitRobot=1 if not defined $MinHitRobot;

        my $MaxNbOfRefererShown = db_get_prop(\%conf, "AWStats", "MaxNbOfRefererShown");
        $MaxNbOfRefererShown=50 if not defined $MaxNbOfRefererShown;
        my $MinHitRefer = db_get_prop(\%conf, "AWStats", "MinHitRefer");
        $MinHitRefer=1 if not defined $MinHitRefer;

        my $MaxNbOfKeywordsShown = db_get_prop(\%conf, "AWStats", "MaxNbOfKeywordsShown");
        $MaxNbOfKeywordsShown=50 if not defined $MaxNbOfKeywordsShown;
        my $MinHitKeyword = db_get_prop(\%conf, "AWStats", "MinHitKeyword");
        $MinHitKeyword=1 if not defined $MinHitKeyword;


        my @status=('disabled','enabled');
        my %noyes = ('no' => 'No',
                                  'yes' => 'Yes');
        my %ipskip = ('no' => 'No',
                                  'yes' => 'Yes, external IP',
                                  'mask' => 'Yes, external IP/Netmask');

     my %langlables = ('auto' => 'Auto Detect',
                        'en' => 'English',
                        'fr' => 'French',
                        'nl' => 'Dutch',
                        'es' => 'Spanish',
                        'it' => 'Italian',
                        'de' => 'German',
                        'pl' => 'Polish',
                        'gr' => 'Greek',
                        'cz' => 'Czech',
                        'pt' => 'Portuguese');

    my %freqlables = ('5m' => '5 minutes',
                                '10m' => '10 minutes',
                                '15m' => '15 minutes',
                    '30m' => '30 minutes',
                                '1h'  => '1 hour',
                                '2h'  => '2 hours',
                                '4h'  => '4 hours',
                                '8h'  => '8 hours',
                                '12h' => '12 hours');

    esmith::cgi::genHeaderNonCacheable ($q, \%conf, 'Configure AWStats'.$version);

    print $q->startform (-method => 'POST',
                         -action => $q->url (-absolute => 1));

        print $q->table ({border => 0, cellspacing => 0, cellpadding => 0},

        # enable/disable
        #
        esmith::cgi::genWidgetRow ($q,
                             "AWStats status",
                              $q->popup_menu (-name    => 'status',
                                              -default => db_get_prop(\%conf, "AWStats", "status"),
                                              -values  =>  \@status)),
        esmith::cgi::genTextRow($q, $q->p('&nbsp;')),

        esmith::cgi::genWidgetRow ($q, "Launch frequency",
          $q->popup_menu (-name => 'Freq',
                                                    -values => ['5m','10m','15m','30m','1h','2h','4h','8h','12h'],
                                                    -default => $Freq,
                                                    -labels => \%freqlables)),

        esmith::cgi::genTextRow($q, $q->p('&nbsp;')),

        # skip local IP
        #
        esmith::cgi::genWidgetRow ($q,
                             "Ignore hits from your local network",
                              $q->popup_menu (-name    => 'skiplocalip',
                                              -values  =>  ['no','yes'],
                                              -default => $SkipLocalIP,
                                                                          -labels => \%noyes)),
        esmith::cgi::genTextRow($q, $q->p('&nbsp;')),

        # skip external IP
        #
        esmith::cgi::genWidgetRow ($q,
                             "Ignore hits from your external IP or network",
                              $q->popup_menu (-name    => 'skipexternalip',
                                              -values  =>  ['no','yes','mask'],
                                              -default => $SkipExternalIP,
                                                                          -labels => \%ipskip)),
        esmith::cgi::genTextRow($q, $q->p('&nbsp;')),

        # skip external networks
        #
        esmith::cgi::genWidgetRow ($q,
                             "Ignore hits from local networks as<br>defined in the 'Local networks' panel",
                              $q->popup_menu (-name    => 'skiplocalnets',
                                              -values  =>  ['no','yes'],
                                              -default => $SkipLocalNetworks,
                                                                          -labels => \%noyes)),
        esmith::cgi::genTextRow($q, $q->p('&nbsp;')),

        # UseFramesWhenCGI
        #
        esmith::cgi::genWidgetRow ($q,
                             "Show report in HTML frames",
                              $q->popup_menu (-name    => 'UseFramesWhenCGI',
                                              -values  =>  ['no','yes'],
                                              -default => $UseFramesWhenCGI,
                                                                          -labels => \%noyes)),
        esmith::cgi::genTextRow($q, $q->p('&nbsp;')),


        # default language
        #
        esmith::cgi::genWidgetRow ($q, "Default language",
          $q->popup_menu (-name => 'Language',
                                                    -values => ['auto','en','fr','es','it','de','pl','gr','cz','pt'],
                                                    -default => $Language,
                                                    -labels => \%langlables)),

        esmith::cgi::genTextRow($q, $q->p('&nbsp;')),

        # hostinfo plugin
        # disbled by default as it requires perl-Net-XWhois-0.90-1.0.rh7.dag.noarch.rpm or similar
        # to enable
        # /sbin/e-smith/db configuration setprop AWStats Hostinfo yes
        # and install perl-Net-XWhois rpm
        #
        #esmith::cgi::genWidgetRow ($q,
        #                     "Enable plugin 'Hostinfo'",
        #                      $q->popup_menu (-name    => 'Hostinfo',
        #                                      -values  =>  ['no','yes'],
        #                                      -default => $Hostinfo,
        #                                      -labels => \%noyes)),
        #esmith::cgi::genTextRow($q, $q->p('&nbsp;')),

        # hostinfo rawlog
        #
        esmith::cgi::genWidgetRow ($q,
                             "Enable plugin 'Rawlog'",
                              $q->popup_menu (-name    => 'Rawlog',
                                              -values  =>  ['no','yes'],
                                              -default => $Rawlog,
                                                                          -labels => \%noyes)),
        esmith::cgi::genTextRow($q, $q->p('&nbsp;')),


        #
        #
        esmith::cgi::genCell ($q, "Max. number of domains shown:"),
        esmith::cgi::genCell ($q, $q->textfield (-name     => 'MaxNbOfDomain',
                                                           -override  => 1,
                                                           -default   => $MaxNbOfDomain,
                                                           -maxlength => 5,
                                                           -size      => 6)),

        esmith::cgi::genTextRow($q, $q->p('&nbsp;')),
        esmith::cgi::genCell ($q, "Max. number of hosts shown:"),
        esmith::cgi::genCell ($q, $q->textfield (-name     => 'MaxNbOfHostsShown',
                                                           -override  => 1,
                                                           -default   => $MaxNbOfHostsShown,
                                                           -maxlength => 5,
                                                           -size      => 6)),

        esmith::cgi::genTextRow($q, $q->p('')),
        esmith::cgi::genCell ($q, "Only show hosts with at least"),
        esmith::cgi::genCell ($q, $q->textfield (-name     => 'MinHitHost',
                                                           -override  => 1,
                                                           -default   => $MinHitHost,
                                                           -maxlength => 5,
                                                           -size      => 6)." hits"),

        esmith::cgi::genTextRow($q, $q->p('&nbsp;')),
        esmith::cgi::genCell ($q, "Max. number of pages shown:"),
        esmith::cgi::genCell ($q, $q->textfield (-name     => 'MaxNbOfPageShown',
                                                           -override  => 1,
                                                           -default   => $MaxNbOfPageShown,
                                                           -maxlength => 5,
                                                           -size      => 6)),

        esmith::cgi::genTextRow($q, $q->p('')),
        esmith::cgi::genCell ($q, "Only show pages with at least"),
        esmith::cgi::genCell ($q, $q->textfield (-name     => 'MinHitFile',
                                                           -override  => 1,
                                                           -default   => $MinHitFile,
                                                           -maxlength => 5,
                                                           -size      => 6)." hits"),

        esmith::cgi::genTextRow($q, $q->p('&nbsp;')),
        esmith::cgi::genCell ($q, "Max. number of robots shown:"),
        esmith::cgi::genCell ($q, $q->textfield (-name     => 'MaxNbOfRobotShown',
                                                           -override  => 1,
                                                           -default   => $MaxNbOfRobotShown,
                                                           -maxlength => 5,
                                                           -size      => 6)),

        esmith::cgi::genTextRow($q, $q->p('')),
        esmith::cgi::genCell ($q, "Only show robots with at least"),
        esmith::cgi::genCell ($q, $q->textfield (-name     => 'MinHitRobot',
                                                           -override  => 1,
                                                           -default   => $MinHitRobot,
                                                           -maxlength => 5,
                                                           -size      => 6)." hits"),

        esmith::cgi::genTextRow($q, $q->p('&nbsp;')),
        esmith::cgi::genCell ($q, "Max. number of referrers shown:"),
        esmith::cgi::genCell ($q, $q->textfield (-name     => 'MaxNbOfRefererShown',
                                                           -override  => 1,
                                                           -default   => $MaxNbOfRefererShown,
                                                           -maxlength => 5,
                                                           -size      => 6)),

        esmith::cgi::genTextRow($q, $q->p('')),
        esmith::cgi::genCell ($q, "Only show referrers with at least"),
        esmith::cgi::genCell ($q, $q->textfield (-name     => 'MinHitRefer',
                                                           -override  => 1,
                                                           -default   => $MinHitRefer,
                                                           -maxlength => 5,
                                                           -size      => 6)." hits"),

        esmith::cgi::genTextRow($q, $q->p('&nbsp;')),
        esmith::cgi::genCell ($q, "Max. number of keywords shown:"),
        esmith::cgi::genCell ($q, $q->textfield (-name     => 'MaxNbOfKeywordsShown',
                                                           -override  => 1,
                                                           -default   => $MaxNbOfKeywordsShown,
                                                           -maxlength => 5,
                                                           -size      => 6)),

        esmith::cgi::genTextRow($q, $q->p('')),
        esmith::cgi::genCell ($q, "Only show keywords with at least"),
        esmith::cgi::genCell ($q, $q->textfield (-name     => 'MinHitKeyword',
                                                           -override  => 1,
                                                           -default   => $MinHitKeyword,
                                                           -maxlength => 5,
                                                           -size      => 6)." hits"),

        esmith::cgi::genTextRow($q, $q->p('&nbsp;')),

        # bar size
        #
        esmith::cgi::genWidgetRow ($q, "Graphics bar size",
          $q->popup_menu (-name => 'BarSize',
                                                    -values => ['small','medium','large'],
                                                    -default => $BarSize)),

        esmith::cgi::genTextRow($q, $q->p('&nbsp;')),

        esmith::cgi::genButtonRow ($q,
                 $q->submit (-name => 'action',
                    -value => 'Save settings')),

    $q->hidden (-name => 'state',
                      -override => 1,
                      -default => 'saveconfig'),

    );

    neddixFooter ($q);
}

sub saveConfig ($)
{
    my ($q) = @_;
        my $status=$q->param('status');
        my $Freq=$q->param('Freq');
        my $skiplocalip=$q->param('skiplocalip');
        my $skipexternalip=$q->param('skipexternalip');
        my $skiplocalnets=$q->param('skiplocalnets');

        my $UseFramesWhenCGI=$q->param('UseFramesWhenCGI');
        my $Language=$q->param('Language');
        my $Hostinfo=$q->param('Hostinfo');
        my $Rawlog=$q->param('Rawlog');
        my $MaxNbOfDomain=$q->param('MaxNbOfDomain');
        $MaxNbOfDomain=1 if $MaxNbOfDomain<1;
        my $MaxNbOfHostsShown=$q->param('MaxNbOfHostsShown');
        $MaxNbOfHostsShown=1 if $MaxNbOfHostsShown<1;
        my $MinHitHost=$q->param('MinHitHost');
        $MinHitHost=1 if $MinHitHost<1;
        my $MaxNbOfPageShown=$q->param('MaxNbOfPageShown');
        $MaxNbOfPageShown=1 if $MaxNbOfPageShown<1;
        my $MinHitFile=$q->param('MinHitFile');
        $MinHitFile=1 if $MinHitFile<1;
        my $MaxNbOfRobotShown=$q->param('MaxNbOfRobotShown');
        $MaxNbOfRobotShown=1 if $MaxNbOfRobotShown<1;
        my $MinHitRobot=$q->param('MinHitRobot');
        $MinHitRobot=1 if $MinHitRobot<1;
        my $MaxNbOfRefererShown=$q->param('MaxNbOfRefererShown');
        $MaxNbOfRefererShown=1 if $MaxNbOfRefererShown<1;
        my $MinHitRefer=$q->param('MinHitRefer');
        $MinHitRefer=1 if $MinHitRefer<1;
        my $MaxNbOfKeywordsShown=$q->param('MaxNbOfKeywordsShown');
        $MaxNbOfKeywordsShown=1 if $MaxNbOfKeywordsShown<1;
        my $MinHitKeyword=$q->param('MinHitKeyword');
        $MinHitKeyword=1 if $MinHitKeyword<1;
        my $BarSize=$q->param('BarSize');

        db_set_prop(\%conf, "AWStats", "status",$status);
        db_set_prop(\%conf, "AWStats", "Freq",$Freq);
        db_set_prop(\%conf, "AWStats", "SkipLocalIP",$skiplocalip);
        db_set_prop(\%conf, "AWStats", "SkipExternalIP",$skipexternalip);
        db_set_prop(\%conf, "AWStats", "SkipLocalNetworks",$skiplocalnets);
        db_set_prop(\%conf, "AWStats", "UseFramesWhenCGI",$UseFramesWhenCGI);
        db_set_prop(\%conf, "AWStats", "Language",$Language);
        #db_set_prop(\%conf, "AWStats", "Hostinfo",$Hostinfo);
        db_set_prop(\%conf, "AWStats", "Rawlog",$Rawlog);
        db_set_prop(\%conf, "AWStats", "MaxNbOfDomain",$MaxNbOfDomain);
        db_set_prop(\%conf, "AWStats", "MaxNbOfHostsShown",$MaxNbOfHostsShown);
        db_set_prop(\%conf, "AWStats", "MinHitHost",$MinHitHost);
        db_set_prop(\%conf, "AWStats", "MaxNbOfPageShown",$MaxNbOfPageShown);
        db_set_prop(\%conf, "AWStats", "MinHitFile",$MinHitFile);
        db_set_prop(\%conf, "AWStats", "MaxNbOfRobotShown",$MaxNbOfRobotShown);
        db_set_prop(\%conf, "AWStats", "MinHitRobot",$MinHitRobot);
        db_set_prop(\%conf, "AWStats", "MaxNbOfRefererShown",$MaxNbOfRefererShown);
        db_set_prop(\%conf, "AWStats", "MinHitRefer",$MinHitRefer);
        db_set_prop(\%conf, "AWStats", "MaxNbOfKeywordsShown",$MaxNbOfKeywordsShown);
        db_set_prop(\%conf, "AWStats", "MinHitKeyword",$MinHitKeyword);
        db_set_prop(\%conf, "AWStats", "BarSize",$BarSize);

        system ("/sbin/e-smith/signal-event awstats-update &");
        sleep (2);
        showInitial ($q,
                'Configuration has been saved.<br>' .
                'Please note, that changed ignore-rules will only effect processing of future logs.<br>');

        return;
}

sub deleteStats ($)
{
    my ($q) = @_;

    esmith::cgi::genHeaderNonCacheable ($q, \%conf, 'Delete statistics');

    print $q->startform
        (-method => 'POST', -action => $q->url (-absolute => 1));

    my $domain = $q->param ('domain');


        print $q->p ('You are about to delete the statistics for domain "' . $domain . '"');

        print $q->p ($q->b ('Are you sure you wish to delete these statistics?'));

        print $q->submit (-name => 'action', -value => 'Remove');
        print $q->hidden (-name => 'domain', -override => 1, -default => $domain);

        print $q->hidden (-name     => 'state',
                          -override => 1,
                          -default  => 'performDelete');

    print $q->endform;
    esmith::cgi::genFooter ($q);
    return;
}

sub performDeleteStats ($)
{
    my ($q) = @_;
    my $domain = $q->param ('domain');
        my $dirdata="/home/e-smith/files/users/admin/home/awstats";
        opendir (DIR, "$dirdata/$domain") or die "Could not open directory $dirdata/$domain\n";
        while (defined(my $file=readdir(DIR))) {
                next if $file =~ /^\./;
                $file="$dirdata/$domain/$file";
                $file=~ s/(.*)//;
                unlink($1) or die "Could not delete $1\n";
        }
        closedir (DIR);
        my $dir="$dirdata/$domain";
        $dir =~ s/(.*)//;
        rmdir($1) or die "Could not delete $1\n";
    showInitial ($q, "Successfully deleted statistics of domain \"$domain\".");
}


sub neddixFooter ($)
{
    my ($q) = @_;

    print $q->p ($q->hr, $q->font ({size => "-1"},
        "<br>Copyright neddix.de, Stuttgart<BR>" )
        );

    print '</FONT>';
    print '</DIV>';
    print $q->end_html;
}
sub dungogFooter ($)
{
    my ($q) = @_;

    print $q->p ($q->hr, $q->font ({size => "-1"},
        "<br>dungog.net<br>" )
        );

    print '</FONT>';
    print '</DIV>';
    print $q->end_html;
}

#options
sub modifyOptions ($$)
{
    my ($q, $msg) = @_;
    my $domain    = $q->param ('d');
    my $owner     = '';

    if ($msg eq '')
    {
          esmith::cgi::genHeaderNonCacheable
            ($q, \%conf, "Modify domain - Options");
    }
    else
    {
        esmith::cgi::genHeaderNonCacheable
            ($q, \%conf, 'Modify domain - Options.');

        print $q->h4 ('Operation status report');
        print $q->p ($msg);
        print $q->hr;
    }

    print $q->startform (-method => 'POST', -action => $q->url (-absolute => 1));

    # find system users
    my @userlist = ('admin','everyone');
    push (@userlist, '-- groups --');
    foreach (sort keys %accounts)
    {
       push (@userlist, $_)
           if (db_get_type(\%accounts, $_) eq 'group');
    }
    push (@userlist, '-- users --');
    foreach (sort keys %accounts)
    {
       push (@userlist, $_)
           if (db_get_type(\%accounts, $_) eq 'user');
    }

    if ($domain eq db_get(\%conf, 'DomainName'))
    {
        $owner = db_get_prop(\%conf, "AWStats", "owner") || 'admin';
    }
    else
    {
        $owner = db_get_prop(\%domains, $domain, "owner") || 'admin';
    }

    print $q->table ({border => 0, cellspacing => 0, cellpadding => 4},

          $q->Tr (esmith::cgi::genCell ($q, "Domain name:"),
                 esmith::cgi::genCell ($q, $domain)),

          esmith::cgi::genWidgetRow ($q, "This user or users may view $domain awstats at /user-manager",
               $q->popup_menu (-name    => "owner",
                               -values  => [ @userlist ],
                               -default => $owner)),

          esmith::cgi::genButtonRow ($q,
                                    $q->submit (-name => 'action',
                                                -value => 'Modify')));

    print $q->hidden (-name => 'domain', -override => 1, -default => $domain);
    print $q->hidden (-name => 'state',  -override => 1, -default => 'performModifyOptions');

    dungogFooter ($q);
}

sub performModifyOptions ($)
{
    my ($q) = @_;

    my $domain = $q->param ('domain');
    my $owner  = $q->param ('owner');

    #------------------------------------------------------------
    # Validate parameters and untaint them
    #------------------------------------------------------------

    unless (exists $accounts {$owner})
    {
        modifyOptions ($q, "Error: account \"$owner\" is not an existing account.");
        return;
    }

    #------------------------------------------------------------
    # Update domain database
    #------------------------------------------------------------

    if ($domain eq db_get(\%conf, 'DomainName'))
    {
        db_set_prop(\%conf, "AWStats", "owner", $owner);
    }
    else
    {
        db_set_prop(\%domains, $domain, 'owner',  $owner);
    }

    showInitial ($q, "Successfully modified Options for domain <b>$domain</b>.");
}

