# All rights reserved (c) 2002;  Author: Daniel Dinev;  http://chatologica.com

package MTS4::ADMIN::HTACCESS;                          # MANIPULATE .htaccess AND .htpasswd FILES

use strict;
use MTS4::STD::Common;
use MTS4::STD::CGI_Response;
use MTS4::STD::Files;



sub run                                                 # THE LOGIC OF THIS NAVIGATION DESTINATION
{
    my ($class) = @_;
    my $me = {}; bless $me, $class;                             # setting standard object variables:
    my $P = $$me{'P'} = ${$UNIVERSAL::MTS4}{'Parameters'};
    my $E = $$me{'E'} = ${$UNIVERSAL::MTS4}{'ENV'};
    my $in = $$me{'in'} = $$E{'CGI_INPUT_HASH'};
    my $R = $$me{'R'} = new MTS4::STD::CGI_Response;
    my $out = $$me{'out'} = $$R{'out'};                         # init input fields:
    &init_keys($in,[qw(pass pass1)],1);
    if ($ENV{'SERVER_SOFTWARE'} =~ /IIS|MS|Microsoft|nformation/){
        $R->DieMsg('MS IIServer does not understand <I>.htaccess</I> or <I>.nsconfig</I> files. Try other authorization method!');
    };
    if($$in{'pass'} && $$in{'pass1'}){                          # passwords provided ->  have to setup
        if($$in{'pass'} ne $$in{'pass1'}) {
            $R->DieMsg("Passwords does not match!");
        } else {
            my $error = $me->set_user('admin',$$in{'pass'});    # setup the password
            if ($error) {
                $R->DieMsg($error);                             # exit on error
            } else {
                print "Location: $$out{'real_script_url'}\n\n"; # use redirection to avoid display of
            };                                                  # multiple authorization boxes
        };
    } else {
        $R->send_page('HTACCESS.htm');                          # show the request form
    };
};



sub set_user                                        # SETUP USERNAME/PASSWORD FOR ADMIN DIRECTORY ACCESS
{
    my($me,$user,$pass) = @_;
    my $error = '';
    if(!$user || !$pass){
        return ' Username/password pair invalid!';
    };
    my $cwd = ${$$me{'E'}}{'CWD'};
    if($cwd eq './'){
        return ' Unable to get full path to the current working directory! Use manual password setting.';
    };
    $pass =~ s/\"//sg;
    &untaint(\$pass);
    my $crypted_pass = $pass;
    if($^O !~ /win(16|32|dows)|NetWare|TPF/i){                  # skip encryption for these platforms
        my $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./";
        my $salt = '';
        for (1..2){                                 # creating random salt string for the crypt function
            $salt .= substr($chars,int rand(length($chars)),1);
        };
        local $SIG{__DIE__} = sub {};
        local $^W = 0;
        eval("\$crypted_pass = crypt(\$pass, \$salt);");                # to avoid unimplemented errors
        $crypted_pass = $pass if !$crypted_pass;
    };
    $error .= &save_file('admin/.htpasswd',"$user\:$crypted_pass\n");
    $cwd = &end_path($cwd . 'admin');
    my $mod_auth_pam_line = '';
    if($ENV{'SERVER_SOFTWARE'} =~ m{mod_auth_pam}i){
        $mod_auth_pam_line = "\nAuthPAM_Enabled off";
    };
    if(!$error){                                                        # if .htpasswd file is OK
        my $htaccess_file = <<"EOD";
AuthUserFile "$cwd\.htpasswd"
AuthGroupFile /dev/null
AuthName "Admin Panel"
AuthType Basic
require valid-user$mod_auth_pam_line
EOD
        my $nsconfig_file = <<"EOD";
<Files *>
RequireAuth userfile="$cwd\.htpasswd" realm="Admin Panel" userlist="$user"
</Files>
EOD
        $error = &save_file("admin/.htaccess", $htaccess_file);         # save .htaccess file
        $error .= &save_file("admin/.nsconfig", $nsconfig_file);        # save .nsconfig file
        if($error){
            $error .= " Check if this file is chmoded to 666 and you have enough write permissions.";
        };
    };
    return $error;
}



1; # must return TRUE


