#!/usr/local/bin/perl
# save_user.cgi
# Save, create or delete a user

require './mysql-lib.pl';
&ReadParse();
$access{'perms'} == 1 || &error($text{'perms_ecannot'});

if ($in{'delete'}) {
	# Delete some user
	&execute_sql_logged($master_db,
		     "delete from user where user = '$in{'olduser'}' ".
		     "and host = '$in{'oldhost'}'");
	}
else {
	# Validate inputs
	&error_setup($text{'user_err'});
	$in{'user_def'} || $in{'user'} =~ /^\S+$/ ||
		&error($text{'user_euser'});
	$in{'host_def'} || $in{'host'} =~ /^\S+$/ ||
		&error($text{'user_ehost'});

	map { $perms[$_]++ } split(/\0/, $in{'perms'});
	if ($in{'new'}) {
		# Create a new user
		for($i=3; $i<=16; $i++) {
			push(@yesno, $perms[$i] ? "'Y'" : "'N'");
			}
		$sql = sprintf "insert into user (Host, User, Password, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Reload_priv, Shutdown_priv, Process_priv, File_priv, Grant_priv, References_priv, Index_priv, Alter_priv) values ('%s', '%s', '', %s)",
			$in{'host_def'} ? '' : $in{'host'},
			$in{'user_def'} ? '' : $in{'user'},
			join(",", @yesno);
		}
	else {
		# Update existing user
		@desc = &table_structure($master_db, 'user');
		for($i=3; $i<=16; $i++) {
			push(@yesno, $desc[$i]->{'field'}."=".
				     ($perms[$i] ? "'Y'" : "'N'"));
			}
		$sql = sprintf "update user set user = '%s', host = '%s', ".
			       "%s where user = '%s' and host = '%s'",
		    $in{'user_def'} ? '' : $in{'user'},
		    $in{'host_def'} ? '' : $in{'host'},
		    join(" , ", @yesno), $in{'olduser'}, $in{'oldhost'};
		}
	&execute_sql_logged($master_db, $sql);
	if ($in{'pass_mode'} == 0) {
		&execute_sql_logged($master_db,
			"update user set password = password('$in{'pass'}') ".
			"where user = '$in{'user'}' and host = '$in{'host'}'");
		}
	elsif ($in{'pass_mode'} == 2) {
		&execute_sql_logged($master_db,
			"update user set password = NULL ".
			"where user = '$in{'user'}' and host = '$in{'host'}'");
		}
	}
&execute_sql_logged($master_db, 'flush privileges');
if ($in{'delete'}) {
	&webmin_log("delete", "user", $in{'olduser'},
		    { 'user' => $in{'olduser'},
		      'host' => $in{'oldhost'} } );
	}
elsif ($in{'new'}) {
	&webmin_log("create", "user",
		    $in{'user_def'} ? '' : $in{'user'},
		    { 'user' => $in{'user_def'} ? '' : $in{'user'},
		      'host' => $in{'host_def'} ? '' : $in{'host'} } );
	}
else {
	&webmin_log("modify", "user",
		    $in{'user_def'} ? '' : $in{'user'},
		    { 'user' => $in{'user_def'} ? '' : $in{'user'},
		      'host' => $in{'host_def'} ? '' : $in{'host'} } );
	}
if ($in{'new'} || $in{'olduser'} ne $config{'login'}) {
	&redirect("list_users.cgi");
	}
else {
	&redirect("/$module_name/");
	}

