<?php
/*
* Copyright 2008 Blandware (http://www.blandware.com)
*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Actions for users.
*
* @package AtleapLite
* @author Roman Puchkovskiy
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
*/
// ~ DAO functions
/**
* Loads users from DB.
*
* @param array $queryInfo optional query info
* @see loadObjects()
* @return array objects
*/
function loadUsers($queryInfo = array())
{
return loadObjects('user', getUserDescriptor(), 'usersGrid', $queryInfo);
}
/**
* Creates or updates a user.
*
* @param int $id ID of user to update (ignored when creating)
* @param object $form form object
* @param bool $create if true, user is created, else it's updated
* @return bool|object false if failed or object
*/
function addOrUpdateUser($id, &$form, $create)
{
if ($create) {
$dao =& getDao('user');
} else {
$dao =& staticGet('user', $id);
if (!$dao) {
// no such object
return false;
}
}
formToDao($form, $dao, getUserDescriptor());
$password = $form->getElementValue('password1');
if ($create || (!empty($password))) {
$dao->setPassword($password);
}
if ($create) {
$dao->insert();
} else {
$dao->update();
}
return $dao;
}
// ~ Actions
/**
* Shows a page with list of users.
*/
function listUsers()
{
global $smarty, $perPage, $pagerDelta, $bottomLinks;
processGridParams('usersGrid', array('role_id' => -1));
$partial = loadUsers(buildDefaultQueryInfo());
$total = $partial['total'];
$users = $partial['rows'];
$pager = getPager(array('totalItems' => $total));
exportPagerData($pager, $smarty, $users);
assignSortDirs('usersGrid', $smarty, getUserDescriptor());
assignFilters($smarty, 'usersGrid');
$smarty->assign('template', 'user/list.tpl');
$smarty->assign('title', getMessage('user.list.title'));
$smarty->assign('allowedViewUser', allowed('viewUser'));
$smarty->assign('allowedUpdateUser', allowed('updateUser'));
$smarty->assign('allowedDeleteUser', allowed('deleteUser'));
$smarty->assign('isAdmin', isAdmin());
$smarty->assign('deletePermId', 'deleteUser');
$smarty->initGrid('usersGrid', getUserDescriptor(), $_GET['action']);
$roles = getRolesTitles();
$roles[-1] = getMessage('common.all');
ksort($roles);
$smarty->assign('roles', $roles);
setSystemMenuItemBold('manageUsers');
$bottomLinks[] = array('link' => buildUrl('callCreateUser'),
'text' => getMessage('common.button.create'),
'permId' => 'createUser',
'button' => true);
}
/**
* Allows to view category properties.
*/
function viewUser()
{
global $smarty, $bottomLinks;
$bottomLinks[] = array('link' => getUserListUrl('login'),
'text' => getMessage('common.button.ok'),
'permId' => 'listUsers',
'button' => true);
$dao =& staticGet('user', $_GET['id']);
$smarty->assign('viewed', $dao);
$smarty->assign('template', 'user/view.tpl');
$smarty->assign('title', getMessage('user.view.title'));
}
/**
* Creates a user form.
*
* @param string $name form name
* @param string $method HTTP method
* @param string $action action
* @param bool $create whether this is for for creation, not for updating
* @param bool $init whether form needs to be initialized from dao
* @param int $id optional user ID (for updating)
* @return object created form
*/
function &createUserForm($name, $method, $action, $create, $init, $id = null) {
$params = array();
if (!$create) {
$params['id'] = $id;
}
$form = new FormBase($name, $method, buildUrl($action, $params));
$form->addTextElement('login', getMessage('user.form.login'), array('maxlength' => 20));
if (!$create) {
$loginElement =& $form->getElement('login');
$loginElement->freeze();
}
$form->addPasswordElement('password1', getMessage('user.form.password1'));
$form->addPasswordElement('password2', getMessage('user.form.password2'));
$form->addTextElement('firstName', getMessage('user.form.firstName'));
$form->addTextElement('patronymicName', getMessage('user.form.patronymicName'));
$form->addTextElement('lastName', getMessage('user.form.lastName'));
$form->addTextElement('address', getMessage('user.form.address'));
$form->addTextElement('phone', getMessage('user.form.phone'));
$form->addTextElement('fax', getMessage('user.form.fax'));
$form->addTextElement('email', getMessage('user.form.email'));
$form->addSelectElement('roleId', getMessage('user.form.role'), getRolesTitles());
$form->addProceedElement($create ? getMessage('common.button.create') : getMessage('common.button.update'));
$form->addCancelElement(getMessage('common.button.cancel'));
if (!$create && $init) {
$dao =& staticGet('user', $id);
daoToForm($dao, $form, getUserDescriptor());
}
$form->addRequiredRule('login', getMessage('user.error.login.required'));
if ($create) {
$form->addRequiredRule('password1', getMessage('user.error.password1.required'));
$form->addRequiredRule('password2', getMessage('user.error.password2.required'));
}
$form->addRequiredRule('firstName', getMessage('user.error.firstName.required'));
$form->addRule('phone', getMessage('user.error.phone.phone'), 'regex', PHONE_REGEX, 'client');
$form->addRule('fax', getMessage('user.error.fax.phone'), 'regex', PHONE_REGEX, 'client');
$form->addRequiredRule('email', getMessage('user.error.email.required'));
$form->addRule(array('password1', 'password2'), getMessage('user.error.password.compare'), 'compare', null, 'client');
$form->addRule('password1', getMessage('user.error.password1.minlength', MIN_PWD_LEN), 'minlength', MIN_PWD_LEN, 'client');
$form->addRule('email', getMessage("user.error.email.email"), 'email', null, 'client');
$form->addFormRule($create ? 'validateCreateUserForm' : 'validateUpdateUserForm');
return $form;
}
/**
* Shows a page with form to create a user.
*/
function callCreateUser()
{
global $smarty, $bottomLinks;
setSystemMenuItemBold('manageUsers');
$form =& createUserForm('createUser', 'POST', 'createUser', true, false);
showForm($smarty, $form, 'user/createUpdate.tpl', getMessage('user.create.title'));
}
/**
* Creates a user.
*/
function createUser()
{
global $smarty, $bottomLinks;
if (isCancelled()) {
redirect(getUserListUrl('login'));
}
setSystemMenuItemBold('manageUsers');
$form =& createUserForm('createUser', 'POST', 'createUser', true, false);
if ($form->validate()) {
addOrUpdateUser(null, $form, true);
redirect(getUserListUrl());
} else {
showForm($smarty, $form, 'user/createUpdate.tpl', getMessage('user.create.title'));
}
}
/**
* Shows a page with form to update a user.
*/
function callUpdateUser()
{
global $smarty, $bottomLinks;
setSystemMenuItemBold('manageUsers');
$form =& createUserForm('updateUser', 'POST', 'updateUser', false, true, $_GET['id']);
showForm($smarty, $form, 'user/createUpdate.tpl', getMessage('user.update.title'));
}
/**
* Updates a user.
*/
function updateUser()
{
global $smarty, $bottomLinks;
if (isCancelled()) {
redirect(allowed('listUsers') ? getUserListUrl('login') : ADMIN_PAGE);
}
setSystemMenuItemBold('manageUsers');
$form =& createUserForm('updateUser', 'POST', 'updateUser', false, false, $_GET['id']);
if ($form->validate()) {
addOrUpdateUser($_GET['id'], $form, false);
redirect(allowed('listUsers') ? getUserListUrl() : ADMIN_PAGE);
} else {
showForm($smarty, $form, 'user/createUpdate.tpl', getMessage('user.update.title'));
}
}
/**
* Begins process of self-update.
*/
function updateMyself() {
$_GET['id'] = getCurrentUserId();
callUpdateUser();
}
/**
* Validates a form which is used to create a user.
*
* @param array $fields assoc array from field names to values
* @return bool|array true if form is valid or assoc array with errors
*/
function validateCreateUserForm($fields) {
return validateUserForm($fields, true);
}
/**
* Validates a form which is used to update a user.
*
* @param array $fields assoc array from field names to values
* @return bool|array true if form is valid or assoc array with errors
*/
function validateUpdateUserForm($fields) {
return validateUserForm($fields, false);
}
/**
* Validates a user form.
*
* @param array $fields assoc array from field names to values
* @param bool $create whether this is creation form
* @return bool|array true if form is valid or assoc array with errors
*/
function validateUserForm($fields, $create)
{
if (!isAdmin()) {
if ($create) {
$role = staticGet('role', $fields['roleId']);
if ($role->admin == 1) {
return array('roleId' => getMessage('user.error.createAdmin'));
}
} else {
$user =& staticGet('user', $_GET['id']);
if ($user->isAdmin()) {
return array('roleId' => getMessage('user.error.updateAdmin'));
}
}
}
$role = staticGet('role', $fields['roleId']);
if (!isAdmin() && $role->admin) {
return array('roleId' => getMessage('user.error.assignAdmin'));
}
if (userHasDuplicates($fields, $create)) {
return array('login' => getMessage('user.error.duplicate.login'));
}
return true;
}
/**
* Returns whether user has duplicates.
*
* @param array $fields assoc array from field names to values
* @param bool $create whether this is creation form being validated
* @return bool true if there are duplicates
*/
function userHasDuplicates($fields, $create) {
$id = $_GET['id'];
$login = $fields['login'];
$dao =& getDao('user');
$escapedLogin = $dao->escape($login);
$dao->selectAdd();
$dao->selectAdd('count(*) as _c');
$dao->whereAdd();
$dao->whereAdd("(login = '$escapedLogin')");
if (!$create) {
$dao->whereAdd("(id != $id)");
}
$dao->find(true);
return $dao->_c > 0;
}
/**
* Deletes a user.
*/
function deleteUser()
{
global $smarty, $bottomLinks;
setSystemMenuItemBold('manageUsers');
$dao =& staticGet('user', $_GET['id']);
if (tryDeleteUser($dao)) {
redirect(getUserListUrl());
} else {
$smarty->assign('template', 'error.tpl');
$smarty->assign('reason', getMessage('user.error.cannotDelete'));
$smarty->assign('link', getUserListUrl());
}
}
/**
* Deletes several users.
*/
function massDeleteUsers()
{
if (isset($_GET['checked'])) {
foreach ($_GET['checked'] as $id => $on) {
$dao =& staticGet('user', $id);
tryDeleteUser($dao);
}
}
redirect(getUserListUrl());
}
/**
* Tryies to delete a user.
*
* @param object $dao object to delete
* @return true if deletion was successful
*/
function tryDeleteUser($dao) {
if ($dao->me() || ($dao->isAdmin() && !isAdmin())) {
return false;
}
return $dao->delete();
}
/**
* Returns URL to list of users.
*
* @param string $colon optional colon by which to sort
* @return URL
*/
function getUserListUrl($colon = null) {
if (empty($colon)) {
$colon = $_SESSION['grids']['usersGrid']['sortColon'];
}
return buildUrl('listUsers'/*, array('sortColon' => $colon)*/);
}
?>