<?php
$locale->setSection("Admin: Users");
if (is_array($_REQUEST['uid'])) {
	$uids = array();
	foreach ($_REQUEST['uid'] as $uid) {
		$uids[] = $str->fromHTML($uid);
	}
} else {
	$uids = array($str->fromHTML($_REQUEST['uid']));
}

if ($config['misc']['demoMode']) {
	jsonFeedback(false, "Action unavailable in this demo version of the software!");
} else {
	$msg = array();
	$success = false;
	foreach ($uids as $userId) {
		$stop = false;
		if ($userId == "1") {
			$msg[] = "The superuser account cannot be deleted!";
		} else if ($userId == $auth->currentUserInfo['id']) {
			$msg[] = "You cannot delete your own account!";
		} else {
			$userInfo = $users->selectOne("*", array("id", "=", "'".$userId."'"));
			if (!$userInfo) {
				$msg[] = "User not found";
			} else {
				$userInfo['perms'] = $users->userPerms->getPerms($userInfo['id']);
				$userInfo['groups'] = $groups->selectOneUsersGroups($userInfo['id']);
				if (!$users->userPerms->canManageUser($userInfo, $userInfo['perms'], $userInfo['groups'])) {
					$msg[] = "You are not allowed to manage this user.";
				} else {
					if ($_POST['deleteHomeFolder']) {
						if (!$config['app']['admin']['users']['delete']['skipHomeFolderSubCheck']) {
							$otherUsersInPath = $fileman->findUsersWithHomeFoldersUnderPath($userInfo['perms']['homefolder']);
							$otherUsersInPath = array_diff($otherUsersInPath, array($userInfo['id']));
							if (sizeof($otherUsersInPath) > 0) {
								$stop = true;
								$msg[] = "The user's home folder cannot be deleted as other users have home folders located inside!";
							}
						}
					}
					if (!$stop) {
						$rs = $users->deleteUser($userId);
						if ($rs) {
							$log->add(false, "user_deleted", array(
								"user_info" => $userInfo,
								"deleteHomeFolder" => ($_POST['deleteHomeFolder'] ? true : false)
							));
							if ($_POST['deleteHomeFolder']) {
								if (is_dir($userInfo['perms']['homefolder'])) {
									$rs = $fm->deleteDir($userInfo['perms']['homefolder']);
									if ($rs) {
										$fileman->clearDBPath($userInfo['perms']['homefolder']);
									}
								}
							}
							$success = true;
							$msg[] = $locale->get("User \"%1\" succcessfuly deleted!", false, array($userInfo['name']));
						} else {
							$msg[] = $locale->get("Failed to delete user \"%1\"!", false, array($userInfo['name']));
						}
					}
				}
			}
		}
	}
	jsonFeedback($success, implode("<br>", $msg));
}
