Admidio/admidio

View on GitHub
adm_program/modules/groups-roles/groups_roles_new.php

Summary

Maintainability
A
3 hrs
Test Coverage
<?php
/**
 ***********************************************************************************************
 * Create and edit roles
 *
 * @copyright The Admidio Team
 * @see https://www.admidio.org/
 * @license https://www.gnu.org/licenses/gpl-2.0.html GNU General Public License v2.0 only
 *
 * Parameters:
 *
 * role_uuid: UUID of role, that should be edited
 ***********************************************************************************************
 */
use Admidio\Exception;
use Admidio\UserInterface\Form;

try {
    require_once(__DIR__ . '/../../system/common.php');
    require(__DIR__ . '/../../system/login_valid.php');

    // Initialize and check the parameters
    $getRoleUuid = admFuncVariableIsValid($_GET, 'role_uuid', 'uuid');

    // Initialize local parameters
    $showSystemCategory = false;
    $eventRole = false;

    // only users with the special right are allowed to manage roles
    if (!$gCurrentUser->manageRoles()) {
        throw new Exception('SYS_NO_RIGHTS');
    }

    if ($getRoleUuid !== '') {
        $headline = $gL10n->get('SYS_EDIT_ROLE');
    } else {
        $headline = $gL10n->get('SYS_CREATE_ROLE');
    }

    $gNavigation->addUrl(CURRENT_URL, $headline);

    // create role object
    $role = new TableRoles($gDb);

    if ($getRoleUuid !== '') {
        $role->readDataByUuid($getRoleUuid);
        $eventRole = $role->getValue('cat_name_intern') === 'EVENTS';

        // check if the role belongs to the current organization
        if ((int)$role->getValue('cat_org_id') !== $gCurrentOrgId && $role->getValue('cat_org_id') > 0) {
            throw new Exception('SYS_NO_RIGHTS');
        }

        // administrator role could only be created or edited by administrators
        if ($role->getValue('rol_administrator') == 1 && !$gCurrentUser->isAdministrator()) {
            throw new Exception('SYS_NO_RIGHTS');
        }

        // hidden roles can also see hidden categories
        if ($role->getValue('cat_system') == 1) {
            $showSystemCategory = true;
        }
    }

    // get all dependent roles of this role
    $childRoles = RoleDependency::getChildRoles($gDb, $role->getValue('rol_id'));

    $childRoleObjects = array();

    // create html page object
    $page = new HtmlPage('admidio-groups-roles-edit', $headline);

    $page->addJavascript(
        '
    checkMaxMemberCount();
    $("#rol_assign_roles").change(function() {
        markRoleRight("rol_assign_roles", "rol_all_lists_view", true);
    });
    $("#rol_all_lists_view").change(function() {
        markRoleRight("rol_all_lists_view", "rol_assign_roles", false);
    });
    $("#rol_max_members").change(function() {
        checkMaxMemberCount();
    });',
        true
    );

    $page->addJavascript('
    /**
     * show/hide role dependencies if max count members will be changed
     */
    function checkMaxMemberCount() {
        // If a maximum number of members has been specified, no role dependencies may exist
        if ($("#rol_max_members").val() > 0) {
            $("#gb_dependencies").hide();

            // All dependent roles are marked and set to independent
            $("#dependent_roles").val("");
        } else {
            $("#gb_dependencies").show();
        }
    }

    /**
     * Set dependent role right if another role right changed
     * @param {string} srcRight  ID of the right that triggers the event
     * @param {string} destRight ID of the right that is to be adapted
     * @param {bool}   checked   true destRight is set to checked
     *                           false destRight is set to unchecked
     */
    function markRoleRight(srcRight, destRight, checked) {
        if (document.getElementById(srcRight).checked && checked) {
            document.getElementById(destRight).checked = true;
        }
        if (!document.getElementById(srcRight).checked && !checked) {
            document.getElementById(destRight).checked = false;
        }
    }
');

    $form = new Form(
        'roles_edit_form',
        'modules/groups-roles.edit.tpl',
        SecurityUtils::encodeUrl(ADMIDIO_URL . FOLDER_MODULES . '/groups-roles/groups_roles_function.php', array('role_uuid' => $getRoleUuid, 'mode' => 'edit')),
        $page
    );

    if ($role->getValue('rol_administrator') === 1 || $eventRole) {
        $fieldProperty = Form::FIELD_READONLY;
    } else {
        $fieldProperty = Form::FIELD_REQUIRED;
    }
    $form->addInput(
        'rol_name',
        $gL10n->get('SYS_NAME'),
        $role->getValue('rol_name'),
        array('maxLength' => 100, 'property' => $fieldProperty)
    );
    $form->addMultilineTextInput(
        'rol_description',
        $gL10n->get('SYS_DESCRIPTION'),
        $role->getValue('rol_description'),
        3,
        array('property' => ($eventRole ? Form::FIELD_READONLY : Form::FIELD_DEFAULT), 'maxLength' => 4000)
    );
    $form->addSelectBoxForCategories(
        'rol_cat_id',
        $gL10n->get('SYS_CATEGORY'),
        $gDb,
        ($eventRole ? 'ROL_EVENT' : 'ROL'),
        Form::SELECT_BOX_MODUS_EDIT,
        array('property' => ($eventRole ? Form::FIELD_READONLY : Form::FIELD_REQUIRED), 'defaultValue' => $role->getValue('cat_uuid'))
    );
    if ($gSettingsManager->getBool('enable_mail_module')) {
        $selectBoxEntries = array(0 => $gL10n->get('SYS_NOBODY'), 1 => $gL10n->get('SYS_ROLE_MEMBERS'), 2 => $gL10n->get('ORG_REGISTERED_USERS'), 3 => $gL10n->get('SYS_ALSO_VISITORS'));
        $form->addSelectBox(
            'rol_mail_this_role',
            $gL10n->get('SYS_SEND_MAILS'),
            $selectBoxEntries,
            array(
                'defaultValue' => $role->getValue('rol_mail_this_role'),
                'showContextDependentFirstEntry' => false,
                'helpTextId' => $gL10n->get('SYS_RIGHT_MAIL_THIS_ROLE_DESC', array('SYS_RIGHT_MAIL_TO_ALL'))
            )
        );
    }
    $selectBoxEntries = array(0 => $gL10n->get('SYS_NOBODY'), 3 => $gL10n->get('SYS_LEADERS'), 1 => $gL10n->get('SYS_ROLE_MEMBERS'), 2 => $gL10n->get('ORG_REGISTERED_USERS'));
    $form->addSelectBox(
        'rol_view_memberships',
        $gL10n->get('SYS_VIEW_ROLE_MEMBERSHIPS'),
        $selectBoxEntries,
        array(
            'defaultValue' => $role->getValue('rol_view_memberships'),
            'showContextDependentFirstEntry' => false,
            'helpTextId' => $gL10n->get('SYS_VIEW_ROLE_MEMBERSHIPS_DESC', array('SYS_RIGHT_ALL_LISTS_VIEW'))
        )
    );
    $form->addSelectBox(
        'rol_view_members_profiles',
        $gL10n->get('SYS_VIEW_PROFILES_OF_ROLE_MEMBERS'),
        $selectBoxEntries,
        array(
            'defaultValue' => $role->getValue('rol_view_members_profiles'),
            'showContextDependentFirstEntry' => false,
            'helpTextId' => $gL10n->get('SYS_VIEW_PROFILES_OF_ROLE_MEMBERS_DESC', array('SYS_RIGHT_ALL_LISTS_VIEW'))
        )
    );
    $selectBoxEntries = array(0 => $gL10n->get('SYS_NO_ADDITIONAL_RIGHTS'), 1 => $gL10n->get('SYS_ASSIGN_MEMBERS'), 2 => $gL10n->get('SYS_EDIT_MEMBERS'), 3 => $gL10n->get('SYS_ASSIGN_EDIT_MEMBERS'));
    $form->addSelectBox(
        'rol_leader_rights',
        $gL10n->get('SYS_LEADER'),
        $selectBoxEntries,
        array(
            'defaultValue' => $role->getValue('rol_leader_rights'),
            'showContextDependentFirstEntry' => false,
            'helpTextId' => 'SYS_LEADER_RIGHTS_DESC'
        )
    );

    $selectBoxEntries = array(0 => $gL10n->get('SYS_SYSTEM_DEFAULT_LIST'));
    // Prepare SQL statement for all list configurations to be displayed
    $sql = 'SELECT lst_id, lst_name
          FROM ' . TBL_LISTS . '
         WHERE lst_org_id = ? -- $gCurrentOrgId
           AND lst_global = true
           AND lst_name IS NOT NULL
      ORDER BY lst_global, lst_name';
    $pdoStatement = $gDb->queryPrepared($sql, array($gCurrentOrgId));

    while ($row = $pdoStatement->fetch()) {
        $selectBoxEntries[$row['lst_id']] = $row['lst_name'];
    }
    $form->addSelectBox(
        'rol_lst_id',
        $gL10n->get('SYS_DEFAULT_LIST'),
        $selectBoxEntries,
        array('defaultValue' => (int)$role->getValue('rol_lst_id'), 'showContextDependentFirstEntry' => false, 'helpTextId' => 'SYS_DEFAULT_LIST_DESC')
    );

    if (!$eventRole) {
        $form->addCheckbox(
            'rol_default_registration',
            $gL10n->get('SYS_DEFAULT_ASSIGNMENT_REGISTRATION'),
            (bool)$role->getValue('rol_default_registration'),
            array('helpTextId' => 'SYS_DEFAULT_ASSIGNMENT_REGISTRATION_DESC')
        );
        $form->addInput(
            'rol_max_members',
            $gL10n->get('SYS_MAX_PARTICIPANTS') . '<br />(' . $gL10n->get('SYS_NO_LEADER') . ')',
            (int)$role->getValue('rol_max_members'),
            array('type' => 'number', 'minNumber' => 0, 'maxNumber' => 99999, 'step' => 1)
        );
        $form->addInput(
            'rol_cost',
            $gL10n->get('SYS_CONTRIBUTION') . ' ' . $gSettingsManager->getString('system_currency'),
            (string)$role->getValue('rol_cost'),
            array('type' => 'number', 'minNumber' => 0, 'maxNumber' => 99999, 'step' => '0.01')
        );
        $form->addSelectBox(
            'rol_cost_period',
            $gL10n->get('SYS_CONTRIBUTION_PERIOD'),
            TableRoles::getCostPeriods(),
            array('defaultValue' => $role->getValue('rol_cost_period'), 'class' => 'form-control-small')
        );
    }

    // event roles should not set rights, events meetings and dependencies
    if (!$eventRole) {
        $form->addCheckbox(
            'rol_assign_roles',
            $gL10n->get('SYS_RIGHT_ASSIGN_ROLES'),
            (bool)$role->getValue('rol_assign_roles'),
            array('helpTextId' => 'SYS_RIGHT_ASSIGN_ROLES_DESC', 'icon' => 'bi-people-fill')
        );
        $form->addCheckbox(
            'rol_all_lists_view',
            $gL10n->get('SYS_RIGHT_ALL_LISTS_VIEW'),
            (bool)$role->getValue('rol_all_lists_view'),
            array('icon' => 'bi-list-task')
        );
        $form->addCheckbox(
            'rol_approve_users',
            $gL10n->get('SYS_RIGHT_APPROVE_USERS'),
            (bool)$role->getValue('rol_approve_users'),
            array('icon' => 'bi-card-checklist')
        );
        if ($gSettingsManager->getBool('enable_mail_module')) {
            $form->addCheckbox(
                'rol_mail_to_all',
                $gL10n->get('SYS_RIGHT_MAIL_TO_ALL'),
                (bool)$role->getValue('rol_mail_to_all'),
                array('icon' => 'bi-envelope-fill')
            );
        }
        $form->addCheckbox(
            'rol_edit_user',
            $gL10n->get('SYS_RIGHT_EDIT_USER'),
            (bool)$role->getValue('rol_edit_user'),
            array('helpTextId' => 'SYS_RIGHT_EDIT_USER_DESC', 'icon' => 'bi-person-fill-gear')
        );
        $form->addCheckbox(
            'rol_profile',
            $gL10n->get('SYS_RIGHT_PROFILE'),
            (bool)$role->getValue('rol_profile'),
            array('icon' => 'bi-person-fill')
        );
        if ((int)$gSettingsManager->get('announcements_module_enabled') > 0) {
            $form->addCheckbox(
                'rol_announcements',
                $gL10n->get('SYS_RIGHT_ANNOUNCEMENTS'),
                (bool)$role->getValue('rol_announcements'),
                array('helpTextId' => 'SYS_ROLES_MODULE_ADMINISTRATORS_DESC', 'icon' => 'bi-newspaper')
            );
        }
        if ((int)$gSettingsManager->get('events_module_enabled') > 0) {
            $form->addCheckbox(
                'rol_events',
                $gL10n->get('SYS_RIGHT_DATES'),
                (bool)$role->getValue('rol_events'),
                array('helpTextId' => 'SYS_ROLES_MODULE_ADMINISTRATORS_DESC', 'icon' => 'bi-calendar-week-fill')
            );
        }
        if ((int)$gSettingsManager->get('photo_module_enabled') > 0) {
            $form->addCheckbox(
                'rol_photo',
                $gL10n->get('SYS_RIGHT_PHOTOS'),
                (bool)$role->getValue('rol_photo'),
                array('icon' => 'bi-image-fill')
            );
        }
        if ($gSettingsManager->getBool('documents_files_module_enabled')) {
            $form->addCheckbox(
                'rol_documents_files',
                $gL10n->get('SYS_RIGHT_DOCUMENTS_FILES'),
                (bool)$role->getValue('rol_documents_files'),
                array('helpTextId' => 'SYS_RIGHT_DOCUMENTS_FILES_DESC', 'icon' => 'bi-file-earmark-arrow-down-fill')
            );
        }
        if ((int)$gSettingsManager->get('enable_guestbook_module') > 0) {
            $form->addCheckbox(
                'rol_guestbook',
                $gL10n->get('SYS_RIGHT_GUESTBOOK'),
                (bool)$role->getValue('rol_guestbook'),
                array('icon' => 'bi-book-half')
            );
            // if not registered users can set comments than there is no need to set a role dependent right
            if (!$gSettingsManager->getBool('enable_gbook_comments4all')) {
                $form->addCheckbox(
                    'rol_guestbook_comments',
                    $gL10n->get('SYS_RIGHT_GUESTBOOK_COMMENTS'),
                    (bool)$role->getValue('rol_guestbook_comments'),
                    array('icon' => 'bi-chat-fill')
                );
            }
        }
        if ((int)$gSettingsManager->get('enable_weblinks_module') > 0) {
            $form->addCheckbox(
                'rol_weblinks',
                $gL10n->get('SYS_RIGHT_WEBLINKS'),
                (bool)$role->getValue('rol_weblinks'),
                array('helpTextId' => 'SYS_ROLES_MODULE_ADMINISTRATORS_DESC', 'icon' => 'bi-link-45deg')
            );
        }
        $form->addInput('rol_start_date', $gL10n->get('SYS_VALID_FROM'), $role->getValue('rol_start_date'), array('type' => 'date'));
        $form->addInput('rol_end_date', $gL10n->get('SYS_VALID_TO'), $role->getValue('rol_end_date'), array('type' => 'date'));
        $form->addInput('rol_start_time', $gL10n->get('SYS_TIME_FROM'), $role->getValue('rol_start_time'), array('type' => 'time'));
        $form->addInput('rol_end_time', $gL10n->get('SYS_TIME_TO'), $role->getValue('rol_end_time'), array('type' => 'time'));
        $form->addSelectBox('rol_weekday', $gL10n->get('SYS_WEEKDAY'), DateTimeExtended::getWeekdays(), array('defaultValue' => $role->getValue('rol_weekday'), 'class' => 'form-control-small'));
        $form->addInput('rol_location', $gL10n->get('SYS_MEETING_POINT'), $role->getValue('rol_location'), array('maxLength' => 100));

        $roleName = $gL10n->get('SYS_NEW_ROLE');
        if ($role->getValue('rol_name') !== '') {
            $roleName = $gL10n->get('SYS_ROLE') . ' <strong>' . $role->getValue('rol_name') . '</strong>';
        }

        //  list all roles that the user is allowed to see
        $sqlData['query'] = 'SELECT rol_id, rol_name, cat_name
                           FROM ' . TBL_ROLES . '
                     INNER JOIN ' . TBL_CATEGORIES . '
                             ON cat_id = rol_cat_id
                          WHERE rol_valid   = true
                            AND cat_name_intern <> \'EVENTS\'
                            AND (  cat_org_id  = ? -- $gCurrentOrgId
                                OR cat_org_id IS NULL )
                       ORDER BY cat_sequence, rol_name';
        $sqlData['params'] = array($gCurrentOrgId);

        $form->addSelectBoxFromSql(
            'dependent_roles',
            $gL10n->get('SYS_DEPENDENT'),
            $gDb,
            $sqlData,
            array('defaultValue' => $childRoles, 'multiselect' => true)
        );
    }

    $form->addSubmitButton('btn_save', $gL10n->get('SYS_SAVE'), array('icon' => 'bi-check-lg'));

    $page->assignSmartyVariable('eventRole', $eventRole);
    $page->assignSmartyVariable('roleName', $roleName);
    $page->assignSmartyVariable('nameUserCreated', $role->getNameOfCreatingUser());
    $page->assignSmartyVariable('timestampUserCreated', $role->getValue('rol_timestamp_create'));
    $page->assignSmartyVariable('nameLastUserEdited', $role->getNameOfLastEditingUser());
    $page->assignSmartyVariable('timestampLastUserEdited', $role->getValue('rol_timestamp_change'));
    $form->addToHtmlPage();
    $gCurrentSession->addFormObject($form);

    $page->show();
} catch (Exception $e) {
    $gMessage->show($e->getMessage());
}