#!/usr/bin/perl

# ispCP ω (OMEGA) a Virtual Hosting Control Panel
# Copyright (C) 2001-2006 by moleSoftware GmbH - http://www.molesoftware.com
# Copyright (C) 2006-2010 by isp Control Panel - http://ispcp.net
#
# Version: $Id: ispcp-htaccess-mngr 2700 2010-03-19 10:21:57Z nuxwin $
#
# The contents of this file are subject to the Mozilla Public License
# Version 1.1 (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
# License for the specific language governing rights and limitations
# under the License.
#
# The Original Code is "VHCS - Virtual Hosting Control System".
#
# The Initial Developer of the Original Code is moleSoftware GmbH.
# Portions created by Initial Developer are Copyright (C) 2001-2006
# by moleSoftware GmbH. All Rights Reserved.
# Portions created by the ispCP Team are Copyright (C) 2006-2010 by
# isp Control Panel. All Rights Reserved.
#
# The ispCP ω Home Page is:
#
#    http://isp-control.net
#

################################################################################
## Program Short Desciption:                                                  ##
##  htaccess Manager - Create, Update or Delete a protected area              ##
################################################################################

use strict;
use warnings;

# Ignore the warning of this kind:
# Name "varname" used only once: possible typo at ...
no warnings 'once';

use FindBin;
use lib "$FindBin::Bin/";
require 'ispcp_common_code.pl';

# Unique identifier of a database record related to a protected area
$main::htuser_task_id = undef;

################################################################################
##                                SUBROUTINES                                 ##
################################################################################

################################################################################
##
## Start Up!
##
sub htaccess_mngr_start_up {

	push_el(\@main::el, 'htaccess_mngr_start_up()', 'Starting...');

	my ($rs, $rdata) = (undef, undef);

	# Checking for master process;
	$rs = check_master();
	return $rs if ($rs != 0);

	# Let's clear Execution Logs, if any.
	if (-e $main::ispcp_htaccess_mngr_el) {
		$rs = del_file($main::ispcp_htaccess_mngr_el);
		return $rs if ($rs != 0);
	}

	# Sql check:
	# FIXME Really required ?
	my $sql = "
		SELECT
			`admin_id`
		FROM
			`admin`
		WHERE
			`admin_id` = 1
		;
	";

	($rs, $rdata) = doSQL($sql);
	return $rs if ($rs != 0);

	# Getting task id
	$main::htuser_task_id = $ARGV[0];

	push_el(\@main::el, 'htaccess_mngr_start_up()', 'Ending...');

	0;
}

################################################################################
##
## Shut Down!
##
sub htaccess_mngr_shut_down {

	push_el(\@main::el, 'htaccess_mngr_shut_down()', 'Starting...');

	# Nothing todo here !

	push_el(\@main::el, 'htaccess_mngr_shut_down()', 'Ending...');

	0;
}

################################################################################
##
## Create a protected area where the authentication is made by user
##
## Here, a protected area is represented by an directory wich contain a
## `.htaccess` file. The `.htaccess` file must contain the following data:
##
## - The type of authentication - Only Basic authentication is supported
## - The name of the protected area
## - The file path wich contain the users authentication data (login/password)
## - A list of one or more valid users
##
## See rfc 2617 for more information about http authentication specifications
##
sub htaccess_add_user_system_data {

	push_el(\@main::el, 'htuser_add_user_system_data()', 'Starting...');

	my ($htuser_data) = @_;

	if (!defined($htuser_data) || $htuser_data eq '') {
		push_el(
			\@main::el,
			'htaccess_add_user_system_data()',
			'ERROR: Undefined Input Data...'
		);

		return -1;
	}

	my ($rs, $rdata, $sql) = (undef, undef, undef);

	my (
		$dmn_name,
		$user_ids,
		undef,
		$auth_type,
		$auth_name,
		$path,
		$status,
		$domain_uid,
		$domain_gid
	) = @$htuser_data;

	my $www_dir = $main::cfg{'APACHE_WWW_DIR'};
	my $htaccess_users_file_name = $main::cfg{'HTACCESS_USERS_FILE_NAME'};
	my $htaccess_users_file = "$www_dir/$dmn_name/$htaccess_users_file_name";

	# See ticket #2265 for the reason of this!
	if(-e "$www_dir/$dmn_name/htdocs.disabled" && $path =~ m@^/htdocs(/.*)?$@) {
		$path = defined $1 ? "/htdocs.disabled$1" : '/htdocs.disabled';
	}
	
	my $htaccess_file = "$www_dir/$dmn_name$path/.htaccess";

	my $unames = '';

	foreach (split(',', $user_ids)) {
		$sql = "
			SELECT
				`uname`
			FROM
				`htaccess_users`
			WHERE
				`id` = $_
			;
		";

		($rs, $rdata) = doSQL($sql);
		return $rs if ($rs != 0);

		$unames .= $rdata->[0]->[0] . ' ';
	}

	# Remove trailing space
	$unames =~ s/\s$//;

	if(-e $htaccess_file) {
		($rs, $rdata) = get_file($htaccess_file);
		return $rs if($rs !=0);
	} else {
		$rdata = '';
	}

	$rdata = set_zone(
		$rdata,
		"\t\tAuthType $auth_type
		AuthName \"$auth_name\"
		AuthUserFile $htaccess_users_file
		Require user $unames",
		'PROTECTION',
		'#'
	);

	if (-e "$www_dir/$dmn_name/$path") {
		$rs = store_file(
			$htaccess_file, $rdata, $domain_uid, $domain_gid, 0644
		);

		return $rs if ($rs != 0);
	} else {
		push_el(
			\@main::el,
			'htaccess_add_user_system_data()',
			"ERROR: The path $www_dir/$dmn_name/$path doesn't exists!"
		);

		return -1;
	}

	push_el(\@main::el, 'htaccess_add_user_system_data()', 'Ending...');

	0;
}

################################################################################
##
## Create a protected area where the authentication is made by group
##
## Here, a protected area is represented by an directory wich contain a
## `.htaccess` file. The `.htaccess` file must contain the following data:
##
## - The type of authentication - Only Basic authentication is supported
## - The name of the protected area
## - The file path wich contain the users authentication data
## - The file path wich contain the groups authentication data
## - A list of one or more valid groups
##
## See rfc 2617 for more information about http authentication specifications
##
sub htaccess_add_group_system_data {

	push_el(\@main::el, 'htuser_add_group_system_data()', 'Starting...');

	my ($htgroup_data) = @_;

	if (!defined($htgroup_data) || $htgroup_data eq '') {
		push_el(
				\@main::el,
				'htaccess_add_group_system_data()',
				'ERROR: Undefined Input Data...'
		);

		return -1;
	}

	my ($rs, $rdata, $sql) = (undef, undef, undef);

	my (
		$dmn_name,
		undef,
		$group_ids,
		$auth_type,
		$auth_name,
		$path,
		$status,
		$domain_uid,
		$domain_gid
	) = @$htgroup_data;

	my $www_dir = $main::cfg{'APACHE_WWW_DIR'};
	my $htaccess_users_file_name = $main::cfg{'HTACCESS_USERS_FILE_NAME'};
	my $htaccess_groups_file_name = $main::cfg{'HTACCESS_GROUPS_FILE_NAME'};
	my $htaccess_users_file = "$www_dir/$dmn_name/$htaccess_users_file_name";
	my $htaccess_groups_file = "$www_dir/$dmn_name/$htaccess_groups_file_name";

	# See ticket #2265 for the reason of this!
	if(-e "$www_dir/$dmn_name/htdocs.disabled" && $path =~ m@^/htdocs(/.*)?$@) {
		$path = defined $1 ? "/htdocs.disabled$1" : '/htdocs.disabled';
	}
	
	my $htaccess_file = "$www_dir/$dmn_name$path/.htaccess";

	my $ugroups = '';

	foreach (split(',', $group_ids)) {
		$sql = "
			SELECT
				`ugroup`
			FROM
				`htaccess_groups`
			WHERE
				`id` = $_
			;
		";

		($rs, $rdata) = doSQL($sql);
		return $rs if($rs != 0);

		$ugroups .= $rdata->[0]->[0] . ' ';
	}
	
	# Remove trailing space
	$ugroups =~ s/\s$//;

	if(-e $htaccess_file) {
		($rs, $rdata) = get_file($htaccess_file);
		return $rs if($rs != 0);
	} else {
		$rdata = '';
	}

	$rdata = set_zone(
		$rdata,
		"\t\tAuthType $auth_type
		AuthName \"$auth_name\"
		AuthUserFile $htaccess_users_file
		AuthGroupFile $htaccess_groups_file
		Require group $ugroups",
		'PROTECTION',
		'#'
	);

	if (-e "$www_dir/$dmn_name/$path") {
		$rs = store_file($htaccess_file, $rdata, $domain_uid, $domain_gid, 0644);
		return $rs if ($rs != 0);
	} else {
		push_el(
			\@main::el,
			'htaccess_add_user_system_data()',
			"ERROR: The path $www_dir/$dmn_name/$path doesn't exists!"
		);

		return -1;
	}

	push_el(\@main::el, 'htaccess_add_group_system_data()', 'Ending...');

	0;
}

################################################################################
##
## Delete a protected area
##
sub htaccess_del_protected_area_data {

	push_el(\@main::el, 'htaccess_del_protected_area_data()', 'Starting...');

	if (!@_) {
		push_el(
			\@main::el,
			'htaccess_del_protected_area_data()',
			'ERROR: Undefined Input Data...'
		);

		return -1;
	}

	my ($rs, $rdata) = (undef, undef);
	my($dmn_name, $path, $domain_uid, $domain_gid) = @_;
	my $www_dir = $main::cfg{'APACHE_WWW_DIR'};
	my $htaccess_file = "$www_dir/$dmn_name/$path/.htaccess";

	if(-e $htaccess_file) {
		($rs, $rdata) = get_file($htaccess_file);
		return $rs if($rs != 0);

		$rdata = del_zone($rdata, 'PROTECTION', '#');

		if(length $rdata < 2) {
			$rs = del_file($htaccess_file);
			return $rs if($rs != 0);
		} else {
			$rs = store_file(
				$htaccess_file, $rdata, $domain_uid, $domain_gid, 0644
			);

			return $rs if ($rs != 0);
		}
	}

	push_el(\@main::el, 'htaccess_del_protected_area_data()', 'Ending...');

	0;
}

################################################################################
## Create a protected area
##
## A protected area is represented by a directory that contain a `.htaccess`
## file. The authentification can be made by user or group.
##
## See htuser_add_user_system_data() and htuser_add_group_system_data()
## subroutines for more information about the possible content of the `.htaccess`
## file.
##
sub htaccess_mngr_engine {

	push_el(\@main::el, 'htaccess_mngr_engine()', 'Starting...');

	my ($rs, $rows) = (undef, undef);

	#
	# Get needed data from the database - Begin
	#

	my $sql = "
		SELECT
			`domain_name`,
			`user_id`,
			`group_id`,
			`auth_type`,
			`auth_name`,
			`path`,
			`status`,
			`domain_uid`,
			`domain_gid`
		FROM
			`domain`
		LEFT JOIN
			`htaccess` ON `id` =  $main::htuser_task_id
		WHERE
			`domain_id` = `dmn_id`
		;
	";

	($rs, $rows) = doSQL($sql);
	return $rs if ($rs != 0);

	#
	# Get needed data from the database - End
	#

	# The record exists in the database ?
	if (scalar(@$rows) != 0) {
		my $entries = @$rows[0];

		my $action = undef;
		# Protected area by user(s)
		if(@$entries[1] ne '0') {
			$action = \&htaccess_add_user_system_data;
		# protected area by group(s)
		} elsif(@$entries[2] ne '0') {
			$action = \&htaccess_add_group_system_data;
		} else {
			push_el(
				\@main::el,
				'htaccess_mngr_engine()',
				'ERROR: The data are corrupted...'
			);

			return -1;
		}

		#
		# Perform needed action - Begin
		#

		# Add or update a protected area
		if(@$entries[6] eq 'toadd' || @$entries[6] eq 'change') {
			$rs = &$action($entries);
		# Deleting a protected area
		} elsif(@$entries[6] eq 'delete') {
			$rs = htaccess_del_protected_area_data(
				@$entries[0], @$entries[5], @$entries[7], @$entries[8]
			);
		} else {
				push_el(
					\@main::el,
					'htaccess_mngr_engine()',
					'ERROR: Unknown action requested...'
				);

			return -1;
		}

		#
		# Perform needed action - End
		#

		#
		# Update database - Begin
		#

		if($rs == 0) {
			if(@$entries[6] ne 'delete') {
				$sql = "
					UPDATE
						`htaccess`
					SET
						`status` = 'ok'
					WHERE
						`id` = $main::htuser_task_id
					;
				";
			} else {
				$sql = "
					DELETE FROM
						`htaccess`
					WHERE
						`id` = $main::htuser_task_id
					;
				";
			}
		# An error was occured during action process
		} else {
			my ($sub_name, $msg) = split(/$main::el_sep/, pop_el(\@main::el));
			$msg =~ s/\'/\\\'/g;

			$sql = "
				UPDATE
					`htaccess`
				SET
					`status` = '$sub_name | $msg'
				WHERE
					`id` = $main::htuser_task_id
				;
			";
		}

		# Execute SQL statement now
		($rs, undef) = doSQL($sql);
		return $rs if ($rs != 0);

		#
		# Update database - End
		#

	} else {
		push_el(
			\@main::el,
			'htaccess_mngr_engine()',
			"ERROR: No data found for task $main::htuser_task_id ..."
		);

		return -1;
	}

	push_el(\@main::el, 'htaccess_mngr_engine()', 'Ending...');

	0;
}

################################################################################
##                               MAIN PROGRAM                                 ##
################################################################################

my $rs = htaccess_mngr_start_up();

if ($rs != 0) {
	pop_el(\@main::el, $main::ispcp_htaccess_mngr_el);
	htaccess_mngr_shut_down();
	exit 1;
}

$rs = htaccess_mngr_engine();

if ($rs != 0) {
	pop_el(\@main::el, $main::ispcp_htaccess_mngr_el);
	htaccess_mngr_shut_down();
	exit 1;
}

$rs = htaccess_mngr_shut_down();

if ($rs != 0) {
	pop_el(\@main::el, $main::ispcp_htaccess_mngr_el);
	exit 1;
}

exit 0;
