Location: PHPKode > projects > Blandware AtLeap Lite - CMS on PHP > atleaplite/include/actions/role.php
<?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 roles.
 *
 * @package     AtleapLite
 * @author      Roman Puchkovskiy
 * @license     http://www.apache.org/licenses/LICENSE-2.0  Apache License, Version 2.0
 */

// ~ DAO functions

/**
 * Loads roles from DB.
 *
 * @param array $queryInfo optional query info
 * @see loadObjects()
 * @return array objects
 */
function loadRoles($queryInfo = array())
{
    return loadObjects('role', getRoleDescriptor(), 'rolesGrid', $queryInfo);
}

/**
 * Creates or updates a role.
 *
 * @param int $id               ID of role to update (ignored when creating)
 * @param object $form          form object
 * @param bool $create          if true, role is created, else it's updated
 * @param array $permissions    array of permissions to give to this role
 * @return bool|object false if failed or object
 */
function addOrUpdateRole($id, &$form, $create, $permissions)
{
    if ($create) {
        $dao =& getDao('role');
    } else {
        $dao =& staticGet('role', $id);
        if (!$dao) {
            // no such object
            return false;
        }
    }

    formToDao($form, $dao, getRoleDescriptor());

    if ($create) {
        $r = $dao->insert();
    } else {
        $dao->update();
    }

    // deal with permissions
    $permIds = $dao->getPermissionIds();
    foreach ($permissions as $permission) {
        $id = $permission->id;
        $elem =& $form->getElement("perm[$id]");
        $newSet = $elem->getChecked();
        $oldSet = array_search($id, $permIds) !== false;
        if ($oldSet != $newSet) {
            $rp =& getDao('role_permission');
            $rp->role_id = $dao->id;
            $rp->permission_id = $id;
            if ($newSet) {
                // added
                $rp->insert();
            } else {
                // removed
                $rp->delete();
            }
        }
    }

    return $dao;
}

// ~ Actions

/**
 * Shows a page with list of roles.
 */
function listRoles()
{
    global $smarty, $perPage, $pagerDelta, $bottomLinks;

    processGridParams('rolesGrid');
    $partial = loadRoles(buildDefaultQueryInfo());
    $total = $partial['total'];
    $roles = $partial['rows'];
    $pager = getPager(array('totalItems' => $total));
    exportPagerData($pager, $smarty, $roles);
    assignSortDirs('rolesGrid', $smarty, getRoleDescriptor());
    assignFilters($smarty, 'rolesGrid');

    $smarty->assign('template', 'role/list.tpl');
    $smarty->assign('title', getMessage('role.list.title'));

    $smarty->assign('allowedViewRole', allowed('viewRole'));
    $smarty->assign('allowedUpdateRole', allowed('updateRole'));
    $smarty->assign('allowedDeleteRole', allowed('deleteRole'));
    $smarty->assign('isAdmin', isAdmin());
    $smarty->assign('deletePermId', 'deleteRole');

    $smarty->initGrid('rolesGrid', getRoleDescriptor(), $_GET['action']);

    setSystemMenuItemBold('manageRoles');

    $bottomLinks[] = array('link' => buildUrl('callCreateRole'),
                           'text' => getMessage('common.button.create'), 
                           'permId' => 'createRole',
                           'button' => true);
}

/**
 * Allows to view role properties.
 */
function viewRole()
{
    global $smarty, $bottomLinks;

    $bottomLinks[] = array('link' => getRoleListUrl('identifier'),
                           'text' => getMessage('common.button.ok'),
                           'permId' => 'listRoles',
                           'button' => true);

    $dao =& staticGet('role', $_GET['id']);
    $smarty->assign('viewed', $dao);

    $checked = array();
    $permissionIds = $dao->getPermissionIds();
    foreach ($permissionIds as $id) {
        $checked[$id] = true;
    }
    $allPermissions = getAllPermissions();
    $smarty->assign('checked', $checked);
    $smarty->assign('allPermissions', $allPermissions);

    $smarty->assign('template', 'role/view.tpl');
    $smarty->assign('title', getMessage('role.view.title'));
}

/**
 * Creates a role form.
 *
 * @param array $permissions    all permissions
 * @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      role ID (for updating)
 * @return object created form
 */
function &createRoleForm(&$permissions, $name, $method, $action, $create, $init,
        $id = null) {
    $params = array();
    if (!$create) {
        $params['id'] = $id;
    }

    $form = new FormBase($name, $method, buildUrl($action, $params));

    $form->addTextElement('identifier', getMessage('role.form.identifier'), array('maxlength' => 20));
    $form->addTextElement('title', getMessage('role.form.title'));
    $form->addTextElement('description', getMessage('role.form.description'));
    $form->addCheckboxElement('admin', getMessage('role.form.admin'));
    if (!isAdmin) {
        $adminElem =& $form->getElement('admin');
        if ($create) {
            $adminElem->setChecked(false);
        }
        $adminElem->freeze();
    }

    $form->addProceedElement($create ? getMessage('common.button.create') : getMessage('common.button.update'));
    $form->addCancelElement(getMessage('common.button.cancel'));

    foreach ($permissions as $permission) {
        $form->addCheckboxElement('perm[' . $permission->id . ']', $permission->title);
    }

    $dao = null;
    if (!$create && $init) {
        $dao =& staticGet('role', $id);
        daoToForm($dao, $form, getRoleDescriptor());
        $rolePermissionIds = $dao->getPermissionIds();
        foreach ($permissions as $permission) {
            if (array_search($permission->id, $rolePermissionIds) !== false) {
                $elem =& $form->getElement('perm[' . $permission->id . ']');
                $elem->setChecked(true);
            }
        }
    }
    
    $form->addRequiredRule('identifier', getMessage('role.error.identifier.required'));
    $form->addIdentifierRule('identifier', getMessage('role.error.identifier.identifier'));
    $form->addRequiredRule('title', getMessage('role.error.title.required'));
    $form->addFormRule($create ? 'validateCreateRoleForm' : 'validateUpdateRoleForm');

    return $form;
}

/**
 * Shows a page with form to create a role.
 */
function callCreateRole()
{
    global $smarty, $bottomLinks;

    setSystemMenuItemBold('manageRoles');

    $permissions = getAllPermissions();
    $smarty->assign('permissions', $permissions);

    $form =& createRoleForm($permissions, 'createRole', 'POST', 'createRole', true, false);

    showForm($smarty, $form, 'role/createUpdate.tpl', getMessage('role.create.title'));
}

/**
 * Creates a role.
 */
function createRole()
{
    global $smarty, $bottomLinks;

    if (isCancelled()) {
        redirect(getRoleListUrl('identifier'));
    }

    setSystemMenuItemBold('manageRoles');

    $permissions = getAllPermissions();
    $smarty->assign('permissions', $permissions);

    $form =& createRoleForm($permissions, 'createRole', 'POST', 'createRole', true, false);

    if ($form->validate()) {
        addOrUpdateRole(null, $form, true, $permissions);
        redirect(getRoleListUrl());
    } else {
        showForm($smarty, $form, 'role/createUpdate.tpl', getMessage('role.create.title'));
    }
}

/**
 * Shows a page with form to update a role.
 */
function callUpdateRole()
{
    global $smarty, $bottomLinks;

    setSystemMenuItemBold('manageRoles');

    $permissions = getAllPermissions();
    $smarty->assign('permissions', $permissions);

    $form =& createRoleForm($permissions, 'updateRole', 'POST', 'updateRole', false, true, $_GET['id']);

    showForm($smarty, $form, 'role/createUpdate.tpl', getMessage('role.update.title'));
}

/**
 * Updates a role.
 */
function updateRole()
{
    global $smarty, $bottomLinks;

    if (isCancelled()) {
        redirect(getRoleListUrl('identifier'));
    }

    setSystemMenuItemBold('manageRoles');

    $permissions = getAllPermissions();
    $smarty->assign('permissions', $permissions);

    $form =& createRoleForm($permissions, 'updateRole', 'POST', 'updateRole', false, false, $_GET['id']);

    if ($form->validate()) {
        addOrUpdateRole($_GET['id'], $form, false, $permissions);
        redirect(getRoleListUrl());
    } else {
        showForm($smarty, $form, 'role/createUpdate.tpl', getMessage('role.update.title'));
    }
}

/**
 * Validates a form which is used to create a role.
 *
 * @param array $fields assoc array from field names to values
 * @return bool|array true if form is valid or assoc array with errors
 */
function validateCreateRoleForm($fields) {
    return validateRoleForm($fields, true);
}

/**
 * Validates a form which is used to update a role.
 *
 * @param array $fields assoc array from field names to values
 * @return bool|array true if form is valid or assoc array with errors
 */
function validateUpdateRoleForm($fields) {
    return validateRoleForm($fields, false);
}

/**
 * Validates a role 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 validateRoleForm($fields, $create)
{
    if (!isAdmin()) {
        if ($create) {
            if ($fields['admin'] == 1) {
                return array('admin' => getMessage('role.error.createAdmin'));
            }
        } else {
            $role =& staticGet('role', $_GET['id']);
            if ($role->isAdmin) {
                return array('admin' => getMessage('role.error.updateAdmin'));
            }
        }
    }

    if (roleHasDuplicates($fields, $create)) {
        return array('identifier' => getMessage('role.error.duplicate.titleOrIdentifier'));
    }

    return true;
}

/**
 * Returns whether role 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 roleHasDuplicates($fields, $create) {
    $id = $_GET['id'];
    $identifier = $fields['identifier'];
    $title = $fields['title'];
    $dao =& getDao('role');
    $escapedIdentifier = $dao->escape($identifier);
    $escapedTitle = $dao->escape($title);

    $dao->selectAdd();
    $dao->selectAdd('count(*) as _c');

    $dao->whereAdd();
    $dao->whereAdd("(identifier = '$escapedIdentifier' OR title = '$escapedTitle')");
    if (!$create) {
        $dao->whereAdd("(id != $id)");
    }
    $dao->find(true);
    return $dao->_c > 0;
}

/**
 * Deletes a role.
 */
function deleteRole()
{
    global $smarty, $bottomLinks;

    setSystemMenuItemBold('manageRoles');

    $dao =& staticGet('role', $_GET['id']);

    if (tryDeleteRole($dao)) {
        redirect(getRoleListUrl());
    } else {
        $smarty->assign('template', 'error.tpl');
        $smarty->assign('reason', getMessage('role.error.cannotDelete'));
        $smarty->assign('link', getRoleListUrl());
    }
}

/**
 * Deletes several roles.
 */
function massDeleteRoles()
{
    if (isset($_GET['checked'])) {
        foreach ($_GET['checked'] as $id => $on) {
            $dao =& staticGet('role', $id);
            tryDeleteRole($dao);
        }
    }
    redirect(getRoleListUrl());
}

/**
 * Tryies to delete a role.
 *
 * @param object $dao   object to delete
 * @return true if deletion was successful
 */
function tryDeleteRole($dao) {
    if ($dao->isAdmin() && !isAdmin()) {
        return false;
    }
    if ($dao->isInUse()) {
        return false;
    }
    $dao->deleteCascadedObjects();
    return $dao->delete();
}

/**
 * Returns URL to list of roles.
 *
 * @param string $colon optional    colon by which to sort
 * @return URL
 */
function getRoleListUrl($colon = null) {
    if (empty($colon)) {
        $colon = $_SESSION['sortColon'];
    }
    return buildUrl('listRoles'/*, array('sortColon' => $colon)*/);
}


?>
Return current item: Blandware AtLeap Lite - CMS on PHP