<?php
require_once(dirname(__FILE__).'/../../../lib/api/class.user.php');
require_once(dirname(__FILE__).'/class.adminview.php');

if (!class_exists('AKB_HELPER')) {
	include_once(dirname(__FILE__).'/class.helper.php');
}

class AKB_XMLUSER extends AdminView
{
	var $validUserAttributes = array('userid','username','firstname','lastname','email');

	function AKB_XMLUSER() {}

	/**
		* SaveNewUser
		* Create a new user in the database
		*
		* @return void
		*/
	function SaveNewUser()
	{
		if (!$_SESSION['user']->verify('user', 'edit')) {
			$errors = array(
			0 => array(
			"code" => 'XMLNoPermission',
			"message" => GetLang('XMLNoPermission')
			)
			);
			XmlShowError(GetLang('XMLUserCreatedFailed'), $errors);
			return false;
		}

		// transfer all the value from XML to $_POST
		$_POST['username'] = (isset($GLOBALS['xmlRequest']->userdetails->username)) ? strval($GLOBALS['xmlRequest']->userdetails->username) : '';
		$_POST['password'] = (isset($GLOBALS['xmlRequest']->userdetails->password)) ? strval($GLOBALS['xmlRequest']->userdetails->password) : '';
		if ($_POST['password'] == '') {
			unset($_POST['password']);
		}
		$_POST['email'] = (isset($GLOBALS['xmlRequest']->userdetails->email)) ? strval($GLOBALS['xmlRequest']->userdetails->email) : '';
		$_POST['firstname'] = (isset($GLOBALS['xmlRequest']->userdetails->firstname)) ? strval($GLOBALS['xmlRequest']->userdetails->firstname) : '';
		$_POST['lastname'] = (isset($GLOBALS['xmlRequest']->userdetails->lastname)) ? strval($GLOBALS['xmlRequest']->userdetails->lastname) : '';
		$_POST['status'] = (isset($GLOBALS['xmlRequest']->userdetails->status)) ? strval($GLOBALS['xmlRequest']->userdetails->status) : '';

		$_POST['groups'] = array();
		if (isset($GLOBALS['xmlRequest']->userdetails->groups) && isset($GLOBALS['xmlRequest']->userdetails->groups->group)) {
			for($i=0; isset($GLOBALS['xmlRequest']->userdetails->groups->group[$i]->id); $i++) {
				$_POST['groups'][] = strval($GLOBALS['xmlRequest']->userdetails->groups->group[$i]->id);
			}
		}

		if ($this->_UsernameAvailable($_POST['username'])) {
			$user = new API_USER();
			if ($user->create()) {
				if (sizeof($_POST['groups'])) {
					$user->find('username', $_POST['username']);
					$group = new API_GROUP();
					$all_groups = $group->getList();
					foreach (array_keys($all_groups) as $groupid) {
						if (in_array($groupid, $_POST['groups'])) {
							$user->join($groupid);
						}
					}
				}
				// Everything is done
				XmlShowResponse(sprintf(GetLang('UserAddedOK'), $_POST['username']));
			} else {
				// Something went wrong
				if ($GLOBALS['AKB_DB']->GetErrorMsg() != '') {
					$error = $GLOBALS['AKB_DB']->GetErrorMessage();
				} else if ($user->error != '') {
					$error = $user->error;
				} else {
					$error = GetLang('UnknownError');
				}

				// Something went wrong
				$errors = array(
				0 => array(
				"code" => 'UserCreateError',
				"message" => sprintf(GetLang('UserCreateError'), $error)
				)
				);
				XmlShowError(GetLang('XMLUserCreatedFailed'), $errors);
			}
		} else {
			// The username is already taken
			$errors = array(
			0 => array(
			"code" => 'duplicateUsername',
			"message" => sprintf(GetLang('UsernameTaken'), $_POST['username'])
			)
			);
			XmlShowError(GetLang('XMLUserCreatedFailed'), $errors);
			exit;
		}
	}

	function GetUsers() {
		if (!$_SESSION['user']->verify('user', 'edit')
		&& !$_SESSION['user']->verify('user', 'delete')) {
			$errors = array(
			0 => array(
			"code" => 'XMLNoPermission',
			"message" => GetLang('XMLNoPermission')
			)
			);
			XmlShowError(GetLang('XMLGetUsersFailed'), $errors);
			return false;
		}

		// checking if the parsed user attributes are correct
		$userAttbs = array();
		if (isset($GLOBALS['xmlRequest']->requestuserdetails) && isset($GLOBALS['xmlRequest']->requestuserdetails->value)) {
			for($i=0; isset($GLOBALS['xmlRequest']->requestuserdetails->value[$i]); $i++) {
				$userAttbs[] = strval($GLOBALS['xmlRequest']->requestuserdetails->value[$i]);
			}
		}

		if (!sizeof($userAttbs)) {
			$errors = array(
			0 => array(
			"code" => 'XMLNoUsersAttb',
			"message" => GetLang('XMLNoUsersAttb')
			)
			);
			XmlShowError(GetLang('XMLGetUsersFailed'), $errors);
			return false;
		}

		if (sizeof($this->validUserAttributes) != sizeof(array_unique(array_merge($this->validUserAttributes, $userAttbs)))) {
			$errors = array(
			0 => array(
			"code" => 'XMLBadUsersAttb',
			"message" => GetLang('XMLBadUsersAttb')
			)
			);
			XmlShowError(GetLang('XMLGetUsersFailed'), $errors);
			return false;
		}

		// Get all the users details from database.
		$query = sprintf('SELECT * FROM %susers ', $GLOBALS['tablePrefix']);
		$result = $GLOBALS['AKB_DB']->Query($query);
		$users = array();

		while($row = $GLOBALS['AKB_DB']->Fetch($result)) {
			array_push($users, $row);
		}
		$xmlResponseArray['TotalUsers'] = sizeof($users);
		foreach ($users as $eachUser) {
			$tmpUsers = array();
			foreach ($eachUser as $k=>$v) {
				if (in_array($k, $userAttbs)) {
					$tmpUsers[$k] = $v;
				}
			}
			$xmlResponseArray['UserDetails'][] = array(
			'user' => $tmpUsers
			);

		}
		XmlShowResponse(sprintf(GetLang('XMLQueryUsersOK'), $xmlResponseArray['TotalUsers']), $xmlResponseArray);
		return true;
	}

	/**
		* DeleteUser
		* Delete a user from the database and display the confirmation
		*
		* @return void
		*/
	function DeleteUser()
	{
		if (!$_SESSION['user']->verify('user', 'delete')) {
			$errors = array(
			0 => array(
			"code" => 'XMLNoPermission',
			"message" => GetLang('XMLNoPermission')
			)
			);
			XmlShowError(GetLang('XMLUserDeleteFailed'), $errors);
			return false;
		}

		if (isset($GLOBALS['xmlRequest']->targetuserdetails->userid) && $GLOBALS['xmlRequest']->targetuserdetails->userid) {
			$ids = array();
			for ($i=0; isset($GLOBALS['xmlRequest']->targetuserdetails->userid[$i]); $i++) {
				$ids[strval($GLOBALS['xmlRequest']->targetuserdetails->userid[$i])] = 'userids';
			}
			if (sizeof($ids) && $_SESSION['user']->multiDelete($ids)) {
				XmlShowResponse(GetLang('XMLUserDeletedOK'));
			} else {
				$errors = array(
				0 => array(
				"code" => 'XMLUserDeleteError',
				"message" => GetLang('XMLUserDeleteError')
				)
				);
				XmlShowError(GetLang('XMLUserDeleteFailed'), $errors);
				return false;
			}
		} else {
			$errors = array(
			0 => array(
			"code" => 'XMLNoUserId',
			"message" => GetLang('XMLNoUserId')
			)
			);
			XmlShowError(GetLang('XMLUserDeleteFailed'), $errors);
			return false;
		}
	}

	/**
		* SaveUpdatedUser
		* Save the changes made to a user to the database
		*
		* @param bool $restricted Is this user restricted to only editing some
		* fields of the user ?
		*
		* @return void
		*/
	function SaveUpdatedUser($restricted=false)
	{
		if (!$restricted && !$_SESSION['user']->verify('user', 'edit')) {
			$this->NoPermission();
			return;
		} elseif ($restricted && $_POST['userid'] != $_SESSION['user']->userid) {
			$this->NoPermission();
			return;
		}

		$user = new API_USER();
		$user->load($_POST['userid']);

		// transfer all the value from XML to $_POST
		$_POST['username'] = (isset($GLOBALS['xmlRequest']->userdetails->username) && strval($GLOBALS['xmlRequest']->userdetails->username) != '') ? strval($GLOBALS['xmlRequest']->userdetails->username) : $user->username;
		$_POST['password'] = (isset($GLOBALS['xmlRequest']->userdetails->password) && strval($GLOBALS['xmlRequest']->userdetails->password) != '') ? strval($GLOBALS['xmlRequest']->userdetails->password) : '';
		$_POST['email'] = (isset($GLOBALS['xmlRequest']->userdetails->email) && strval($GLOBALS['xmlRequest']->userdetails->email) != '') ? strval($GLOBALS['xmlRequest']->userdetails->email) : $user->email;
		$_POST['firstname'] = (isset($GLOBALS['xmlRequest']->userdetails->firstname) && strval($GLOBALS['xmlRequest']->userdetails->firstname) != '') ? strval($GLOBALS['xmlRequest']->userdetails->firstname) : $user->firstname;
		$_POST['lastname'] = (isset($GLOBALS['xmlRequest']->userdetails->lastname) && strval($GLOBALS['xmlRequest']->userdetails->lastname) != '') ? strval($GLOBALS['xmlRequest']->userdetails->lastname) : $user->lastname;
		$_POST['status'] = (isset($GLOBALS['xmlRequest']->userdetails->status) && strval($GLOBALS['xmlRequest']->userdetails->status) != '') ? strval($GLOBALS['xmlRequest']->userdetails->status) : $user->status;

		$_POST['groups'] = array();
		if ($restricted) {
			// If we are in the my account section, the user is limited
			// to only being able to updated certain fields
			$restricted_fields = array (
			'username',
			'status',
			);

			foreach ($restricted_fields as $k) {
				$_POST[$k] = $user->$k;
			}
			foreach ($user->groups as $group) {
				$_POST['groups'][] = $group->groupid;
			}

		} else {
			if (isset($GLOBALS['xmlRequest']->userdetails->groups) && isset($GLOBALS['xmlRequest']->userdetails->groups->group)) {
				for($i=0; isset($GLOBALS['xmlRequest']->userdetails->groups->group[$i]->id); $i++) {
					$_POST['groups'][] = strval($GLOBALS['xmlRequest']->userdetails->groups->group[$i]->id);
				}
			}
		}
		$old_username = $user->username;



		if (sizeof($_POST['groups'])) {
			$group = new API_GROUP();
			$all_groups = $group->getList();
			foreach (array_keys($all_groups) as $groupid) {
				if (isset($_POST['groups']) && in_array($groupid, $_POST['groups'])) {
					$user->join($groupid);
				} else {
					$user->part($groupid);
				}
			}
		}

		// If the username hasn't changed or is still available
		if (strtolower($_POST['username']) == strtolower($old_username) || $this->_UsernameAvailable($_POST['username'])) {
			if ($user->save()) {
				// Everything is done
				XmlShowResponse(GetLang('XMLUserEditOK'));
			} else {
				// Something went wrong
				if ($GLOBALS['AKB_DB']->GetErrorMsg() != '') {
					$error = $GLOBALS['AKB_DB']->GetErrorMessage();
				} else if ($user->error != '') {
					$error = $user->error;
				} else {
					$error = GetLang('UnknownError');
				}

				// Something went wrong
				$errors = array(
				0 => array(
				"code" => 'XMLUserEditError',
				"message" => sprintf(GetLang('XMLUserEditError'), $error)
				)
				);
				XmlShowError(GetLang('XMLUserEditFailed'), $errors);
			}
		} else {
			// The username is already taken
			// The username is already taken
			$errors = array(
			0 => array(
			"code" => 'duplicateUsername',
			"message" => sprintf(GetLang('UsernameTaken'), $_POST['username'])
			)
			);
			XmlShowError(GetLang('XMLUserEditFailed'), $errors);
			return false;
		}
	}

	/**
	* _UsernameAvailable
	* Check if the given username is already in use by another user
	*
	* @param string $username The username to check
	*
	* @return bool Is the username available ?
	*/
	function _UsernameAvailable($username) {
		$user = new API_USER();
		$user->find('username', $username);

		return ($user->userid == 0);
	}

}
?>