Example #1
0
/**
 * This function handles adding a membergroup and setting some initial properties.
 * Called by ?action=admin;area=membergroups;sa=add.
 * It requires the manage_membergroups permission.
 * Allows to use a predefined permission profile or copy one from another group.
 * Redirects to action=admin;area=membergroups;sa=edit;group=x.
 *
 * @uses the new_group sub template of ManageMembergroups.
 */
function AddMembergroup()
{
    global $context, $txt, $sourcedir, $modSettings, $smcFunc;
    // A form was submitted, we can start adding.
    if (isset($_POST['group_name']) && trim($_POST['group_name']) != '') {
        checkSession();
        validateToken('admin-mmg');
        $postCountBasedGroup = isset($_POST['min_posts']) && (!isset($_POST['postgroup_based']) || !empty($_POST['postgroup_based']));
        $_POST['group_type'] = !isset($_POST['group_type']) || $_POST['group_type'] < 0 || $_POST['group_type'] > 3 || $_POST['group_type'] == 1 && !allowedTo('admin_forum') ? 0 : (int) $_POST['group_type'];
        // @todo Check for members with same name too?
        $request = $smcFunc['db_query']('', '
			SELECT MAX(id_group)
			FROM {db_prefix}membergroups', array());
        list($id_group) = $smcFunc['db_fetch_row']($request);
        $smcFunc['db_free_result']($request);
        $id_group++;
        $smcFunc['db_insert']('', '{db_prefix}membergroups', array('id_group' => 'int', 'description' => 'string', 'group_name' => 'string-80', 'min_posts' => 'int', 'icons' => 'string', 'online_color' => 'string', 'group_type' => 'int'), array($id_group, '', $smcFunc['htmlspecialchars']($_POST['group_name'], ENT_QUOTES), $postCountBasedGroup ? (int) $_POST['min_posts'] : '-1', '1#star.png', '', $_POST['group_type']), array('id_group'));
        call_integration_hook('integrate_add_membergroup', array($id_group, $postCountBasedGroup));
        // Update the post groups now, if this is a post group!
        if (isset($_POST['min_posts'])) {
            updateStats('postgroups');
        }
        // You cannot set permissions for post groups if they are disabled.
        if ($postCountBasedGroup && empty($modSettings['permission_enable_postgroups'])) {
            $_POST['perm_type'] = '';
        }
        if ($_POST['perm_type'] == 'predefined') {
            // Set default permission level.
            require_once $sourcedir . '/ManagePermissions.php';
            setPermissionLevel($_POST['level'], $id_group, 'null');
        } elseif ($_POST['perm_type'] == 'copy' || $_POST['perm_type'] == 'inherit') {
            $copy_id = $_POST['perm_type'] == 'copy' ? (int) $_POST['copyperm'] : (int) $_POST['inheritperm'];
            // Are you a powerful admin?
            if (!allowedTo('admin_forum')) {
                $request = $smcFunc['db_query']('', '
					SELECT group_type
					FROM {db_prefix}membergroups
					WHERE id_group = {int:copy_from}
					LIMIT {int:limit}', array('copy_from' => $copy_id, 'limit' => 1));
                list($copy_type) = $smcFunc['db_fetch_row']($request);
                $smcFunc['db_free_result']($request);
                // Protected groups are... well, protected!
                if ($copy_type == 1) {
                    fatal_lang_error('membergroup_does_not_exist');
                }
            }
            // Don't allow copying of a real priviledged person!
            require_once $sourcedir . '/ManagePermissions.php';
            loadIllegalPermissions();
            $request = $smcFunc['db_query']('', '
				SELECT permission, add_deny
				FROM {db_prefix}permissions
				WHERE id_group = {int:copy_from}', array('copy_from' => $copy_id));
            $inserts = array();
            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                if (empty($context['illegal_permissions']) || !in_array($row['permission'], $context['illegal_permissions'])) {
                    $inserts[] = array($id_group, $row['permission'], $row['add_deny']);
                }
            }
            $smcFunc['db_free_result']($request);
            if (!empty($inserts)) {
                $smcFunc['db_insert']('insert', '{db_prefix}permissions', array('id_group' => 'int', 'permission' => 'string', 'add_deny' => 'int'), $inserts, array('id_group', 'permission'));
            }
            $request = $smcFunc['db_query']('', '
				SELECT id_profile, permission, add_deny
				FROM {db_prefix}board_permissions
				WHERE id_group = {int:copy_from}', array('copy_from' => $copy_id));
            $inserts = array();
            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                $inserts[] = array($id_group, $row['id_profile'], $row['permission'], $row['add_deny']);
            }
            $smcFunc['db_free_result']($request);
            if (!empty($inserts)) {
                $smcFunc['db_insert']('insert', '{db_prefix}board_permissions', array('id_group' => 'int', 'id_profile' => 'int', 'permission' => 'string', 'add_deny' => 'int'), $inserts, array('id_group', 'id_profile', 'permission'));
            }
            // Also get some membergroup information if we're copying and not copying from guests...
            if ($copy_id > 0 && $_POST['perm_type'] == 'copy') {
                $request = $smcFunc['db_query']('', '
					SELECT online_color, max_messages, icons
					FROM {db_prefix}membergroups
					WHERE id_group = {int:copy_from}
					LIMIT 1', array('copy_from' => $copy_id));
                $group_info = $smcFunc['db_fetch_assoc']($request);
                $smcFunc['db_free_result']($request);
                // ...and update the new membergroup with it.
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}membergroups
					SET
						online_color = {string:online_color},
						max_messages = {int:max_messages},
						icons = {string:icons}
					WHERE id_group = {int:current_group}', array('max_messages' => $group_info['max_messages'], 'current_group' => $id_group, 'online_color' => $group_info['online_color'], 'icons' => $group_info['icons']));
            } elseif ($_POST['perm_type'] == 'inherit') {
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}membergroups
					SET id_parent = {int:copy_from}
					WHERE id_group = {int:current_group}', array('copy_from' => $copy_id, 'current_group' => $id_group));
            }
        }
        // Make sure all boards selected are stored in a proper array.
        $accesses = empty($_POST['boardaccess']) || !is_array($_POST['boardaccess']) ? array() : $_POST['boardaccess'];
        $changed_boards['allow'] = array();
        $changed_boards['deny'] = array();
        $changed_boards['ignore'] = array();
        foreach ($accesses as $group_id => $action) {
            $changed_boards[$action][] = (int) $group_id;
        }
        foreach (array('allow', 'deny') as $board_action) {
            // Only do this if they have special access requirements.
            if (!empty($changed_boards[$board_action])) {
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}boards
					SET {raw:column} = CASE WHEN {raw:column} = {string:blank_string} THEN {string:group_id_string} ELSE CONCAT({raw:column}, {string:comma_group}) END
					WHERE id_board IN ({array_int:board_list})', array('board_list' => $changed_boards[$board_action], 'blank_string' => '', 'group_id_string' => (string) $id_group, 'comma_group' => ',' . $id_group, 'column' => $board_action == 'allow' ? 'member_groups' : 'deny_member_groups'));
            }
        }
        // If this is joinable then set it to show group membership in people's profiles.
        if (empty($modSettings['show_group_membership']) && $_POST['group_type'] > 1) {
            updateSettings(array('show_group_membership' => 1));
        }
        // Rebuild the group cache.
        updateSettings(array('settings_updated' => time()));
        // We did it.
        logAction('add_group', array('group' => $_POST['group_name']), 'admin');
        // Go change some more settings.
        redirectexit('action=admin;area=membergroups;sa=edit;group=' . $id_group);
    }
    // Just show the 'add membergroup' screen.
    $context['page_title'] = $txt['membergroups_new_group'];
    $context['sub_template'] = 'new_group';
    $context['post_group'] = isset($_REQUEST['postgroup']);
    $context['undefined_group'] = !isset($_REQUEST['postgroup']) && !isset($_REQUEST['generalgroup']);
    $context['allow_protected'] = allowedTo('admin_forum');
    if (!empty($modSettings['deny_boards_access'])) {
        loadLanguage('ManagePermissions');
    }
    $result = $smcFunc['db_query']('', '
		SELECT id_group, group_name
		FROM {db_prefix}membergroups
		WHERE (id_group > {int:moderator_group} OR id_group = {int:global_mod_group})' . (empty($modSettings['permission_enable_postgroups']) ? '
			AND min_posts = {int:min_posts}' : '') . (allowedTo('admin_forum') ? '' : '
			AND group_type != {int:is_protected}') . '
		ORDER BY min_posts, id_group != {int:global_mod_group}, group_name', array('moderator_group' => 3, 'global_mod_group' => 2, 'min_posts' => -1, 'is_protected' => 1));
    $context['groups'] = array();
    while ($row = $smcFunc['db_fetch_assoc']($result)) {
        $context['groups'][] = array('id' => $row['id_group'], 'name' => $row['group_name']);
    }
    $smcFunc['db_free_result']($result);
    $request = $smcFunc['db_query']('', '
		SELECT b.id_cat, c.name AS cat_name, b.id_board, b.name, b.child_level
		FROM {db_prefix}boards AS b
			LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
		ORDER BY board_order', array());
    $context['num_boards'] = $smcFunc['db_num_rows']($request);
    $context['categories'] = array();
    while ($row = $smcFunc['db_fetch_assoc']($request)) {
        // This category hasn't been set up yet..
        if (!isset($context['categories'][$row['id_cat']])) {
            $context['categories'][$row['id_cat']] = array('id' => $row['id_cat'], 'name' => $row['cat_name'], 'boards' => array());
        }
        // Set this board up, and let the template know when it's a child.  (indent them..)
        $context['categories'][$row['id_cat']]['boards'][$row['id_board']] = array('id' => $row['id_board'], 'name' => $row['name'], 'child_level' => $row['child_level'], 'allow' => false, 'deny' => false);
    }
    $smcFunc['db_free_result']($request);
    // Now, let's sort the list of categories into the boards for templates that like that.
    $temp_boards = array();
    foreach ($context['categories'] as $category) {
        $temp_boards[] = array('name' => $category['name'], 'child_ids' => array_keys($category['boards']));
        $temp_boards = array_merge($temp_boards, array_values($category['boards']));
        // Include a list of boards per category for easy toggling.
        $context['categories'][$category['id']]['child_ids'] = array_keys($category['boards']);
    }
    createToken('admin-mmg');
}
Example #2
0
    /**
     * Save the permissions of a form containing inline permissions.
     *
     * @param string[] $permissions
     */
    public static function save_inline_permissions($permissions)
    {
        global $context;
        $db = database();
        // No permissions? Not a great deal to do here.
        if (!allowedTo('manage_permissions')) {
            return;
        }
        // Almighty session check, verify our ways.
        checkSession();
        validateToken('admin-mp');
        // Make sure they can't do certain things,
        // unless they have the right permissions.
        loadIllegalPermissions();
        $insertRows = array();
        foreach ($permissions as $permission) {
            if (!isset($_POST[$permission])) {
                continue;
            }
            foreach ($_POST[$permission] as $id_group => $value) {
                if (in_array($value, array('on', 'deny')) && (empty($context['illegal_permissions']) || !in_array($permission, $context['illegal_permissions']))) {
                    $insertRows[] = array((int) $id_group, $permission, $value == 'on' ? 1 : 0);
                }
            }
        }
        // Remove the old permissions...
        $db->query('', '
			DELETE FROM {db_prefix}permissions
			WHERE permission IN ({array_string:permissions})
			' . (empty($context['illegal_permissions']) ? '' : ' AND permission NOT IN ({array_string:illegal_permissions})'), array('illegal_permissions' => !empty($context['illegal_permissions']) ? $context['illegal_permissions'] : array(), 'permissions' => $permissions));
        // ...and replace them with new ones.
        if (!empty($insertRows)) {
            $db->insert('insert', '{db_prefix}permissions', array('id_group' => 'int', 'permission' => 'string', 'add_deny' => 'int'), $insertRows, array('id_group', 'permission'));
        }
        // Do a full child update.
        updateChildPermissions(array(), -1);
        // Just in case we cached this.
        updateSettings(array('settings_updated' => time()));
    }
Example #3
0
function save_inline_permissions($permissions)
{
    global $context, $db_prefix;
    // No permissions? Not a great deal to do here.
    if (!allowedTo('manage_permissions')) {
        return;
    }
    // Check they can't do certain things.
    loadIllegalPermissions();
    $insertRows = '';
    foreach ($permissions as $permission) {
        if (!isset($_POST[$permission])) {
            continue;
        }
        foreach ($_POST[$permission] as $ID_GROUP => $value) {
            if (in_array($value, array('on', 'deny')) && (empty($context['illegal_permissions']) || !in_array($permission, $context['illegal_permissions']))) {
                $insertRows .= ', (' . (int) $ID_GROUP . ", '{$permission}', " . ($value == 'on' ? '1' : '0') . ')';
            }
        }
    }
    // Remove the old permissions...
    db_query("\n\t\tDELETE FROM {$db_prefix}permissions\n\t\tWHERE permission IN ('" . implode("', '", $permissions) . "')" . (empty($context['illegal_permissions']) ? '' : "\n\t\t\tAND permission NOT IN ('" . implode("', '", $context['illegal_permissions']) . "')"), __FILE__, __LINE__);
    // ...and replace them with new ones.
    if ($insertRows != '') {
        db_query("\n\t\t\tINSERT INTO {$db_prefix}permissions\n\t\t\t\t(ID_GROUP, permission, addDeny)\n\t\t\tVALUES " . substr($insertRows, 2), __FILE__, __LINE__);
    }
}
Example #4
0
function AddMembergroup()
{
    global $context, $txt, $sourcedir, $modSettings, $backend_subdir;
    // A form was submitted, we can start adding.
    if (!empty($_POST['group_name'])) {
        checkSession();
        $postCountBasedGroup = isset($_POST['min_posts']) && (!isset($_POST['postgroup_based']) || !empty($_POST['postgroup_based']));
        $_POST['group_type'] = !isset($_POST['group_type']) || $_POST['group_type'] < 0 || $_POST['group_type'] > 3 || $_POST['group_type'] == 1 && !allowedTo('admin_forum') ? 0 : (int) $_POST['group_type'];
        // !!! Check for members with same name too?
        $request = smf_db_query('
			SELECT MAX(id_group)
			FROM {db_prefix}membergroups', array());
        list($id_group) = mysql_fetch_row($request);
        mysql_free_result($request);
        $id_group++;
        smf_db_insert('', '{db_prefix}membergroups', array('id_group' => 'int', 'description' => 'string', 'group_name' => 'string-80', 'min_posts' => 'int', 'stars' => 'string', 'online_color' => 'string', 'group_type' => 'int'), array($id_group, '', $_POST['group_name'], $postCountBasedGroup ? (int) $_POST['min_posts'] : '-1', '1#star.gif', '', $_POST['group_type']), array('id_group'));
        // Update the post groups now, if this is a post group!
        if (isset($_POST['min_posts'])) {
            updateStats('postgroups');
        }
        // You cannot set permissions for post groups if they are disabled.
        if ($postCountBasedGroup && empty($modSettings['permission_enable_postgroups'])) {
            $_POST['perm_type'] = '';
        }
        if ($_POST['perm_type'] == 'predefined') {
            // Set default permission level.
            require_once $sourcedir . '/' . $backend_subdir . '/ManagePermissions.php';
            setPermissionLevel($_POST['level'], $id_group, 'null');
        } elseif ($_POST['perm_type'] == 'copy' || $_POST['perm_type'] == 'inherit') {
            $copy_id = $_POST['perm_type'] == 'copy' ? (int) $_POST['copyperm'] : (int) $_POST['inheritperm'];
            // Are you a powerful admin?
            if (!allowedTo('admin_forum')) {
                $request = smf_db_query('
					SELECT group_type
					FROM {db_prefix}membergroups
					WHERE id_group = {int:copy_from}
					LIMIT {int:limit}', array('copy_from' => $copy_id, 'limit' => 1));
                list($copy_type) = mysql_fetch_row($request);
                mysql_free_result($request);
                // Protected groups are... well, protected!
                if ($copy_type == 1) {
                    fatal_lang_error('membergroup_does_not_exist');
                }
            }
            // Don't allow copying of a real priviledged person!
            require_once $sourcedir . '/' . $backend_subdir . '/ManagePermissions.php';
            loadIllegalPermissions();
            $request = smf_db_query('
				SELECT permission, add_deny
				FROM {db_prefix}permissions
				WHERE id_group = {int:copy_from}', array('copy_from' => $copy_id));
            $inserts = array();
            while ($row = mysql_fetch_assoc($request)) {
                if (empty($context['illegal_permissions']) || !in_array($row['permission'], $context['illegal_permissions'])) {
                    $inserts[] = array($id_group, $row['permission'], $row['add_deny']);
                }
            }
            mysql_free_result($request);
            if (!empty($inserts)) {
                smf_db_insert('insert', '{db_prefix}permissions', array('id_group' => 'int', 'permission' => 'string', 'add_deny' => 'int'), $inserts, array('id_group', 'permission'));
            }
            $request = smf_db_query('
				SELECT id_profile, permission, add_deny
				FROM {db_prefix}board_permissions
				WHERE id_group = {int:copy_from}', array('copy_from' => $copy_id));
            $inserts = array();
            while ($row = mysql_fetch_assoc($request)) {
                $inserts[] = array($id_group, $row['id_profile'], $row['permission'], $row['add_deny']);
            }
            mysql_free_result($request);
            if (!empty($inserts)) {
                smf_db_insert('insert', '{db_prefix}board_permissions', array('id_group' => 'int', 'id_profile' => 'int', 'permission' => 'string', 'add_deny' => 'int'), $inserts, array('id_group', 'id_profile', 'permission'));
            }
            // Also get some membergroup information if we're copying and not copying from guests...
            if ($copy_id > 0 && $_POST['perm_type'] == 'copy') {
                $request = smf_db_query('
					SELECT online_color, max_messages, stars
					FROM {db_prefix}membergroups
					WHERE id_group = {int:copy_from}
					LIMIT 1', array('copy_from' => $copy_id));
                $group_info = mysql_fetch_assoc($request);
                mysql_free_result($request);
                // ...and update the new membergroup with it.
                smf_db_query('
					UPDATE {db_prefix}membergroups
					SET
						online_color = {string:online_color},
						max_messages = {int:max_messages},
						stars = {string:stars}
					WHERE id_group = {int:current_group}', array('max_messages' => $group_info['max_messages'], 'current_group' => $id_group, 'online_color' => $group_info['online_color'], 'stars' => $group_info['stars']));
            } elseif ($_POST['perm_type'] == 'inherit') {
                smf_db_query('
					UPDATE {db_prefix}membergroups
					SET id_parent = {int:copy_from}
					WHERE id_group = {int:current_group}', array('copy_from' => $copy_id, 'current_group' => $id_group));
            }
        }
        // Make sure all boards selected are stored in a proper array.
        $_POST['boardaccess'] = empty($_POST['boardaccess']) || !is_array($_POST['boardaccess']) ? array() : $_POST['boardaccess'];
        foreach ($_POST['boardaccess'] as $key => $value) {
            $_POST['boardaccess'][$key] = (int) $value;
        }
        // Only do this if they have special access requirements.
        if (!empty($_POST['boardaccess'])) {
            smf_db_query('
				UPDATE {db_prefix}boards
				SET member_groups = CASE WHEN member_groups = {string:blank_string} THEN {string:group_id_string} ELSE CONCAT(member_groups, {string:comma_group}) END
				WHERE id_board IN ({array_int:board_list})', array('board_list' => $_POST['boardaccess'], 'blank_string' => '', 'group_id_string' => (string) $id_group, 'comma_group' => ',' . $id_group));
        }
        // If this is joinable then set it to show group membership in people's profiles.
        if (empty($modSettings['show_group_membership']) && $_POST['group_type'] > 1) {
            updateSettings(array('show_group_membership' => 1));
        }
        // Rebuild the group cache.
        updateSettings(array('settings_updated' => time()));
        // We did it.
        logAction('add_group', array('group' => $_POST['group_name']), 'admin');
        regenerateColorStyle();
        // Go change some more settings.
        redirectexit('action=admin;area=membergroups;sa=edit;group=' . $id_group);
    }
    // Just show the 'add membergroup' screen.
    $context['page_title'] = $txt['membergroups_new_group'];
    $context['sub_template'] = 'new_group';
    $context['post_group'] = isset($_REQUEST['postgroup']);
    $context['undefined_group'] = !isset($_REQUEST['postgroup']) && !isset($_REQUEST['generalgroup']);
    $context['allow_protected'] = allowedTo('admin_forum');
    $result = smf_db_query('
		SELECT id_group, group_name
		FROM {db_prefix}membergroups
		WHERE (id_group > {int:moderator_group} OR id_group = {int:global_mod_group})' . (empty($modSettings['permission_enable_postgroups']) ? '
			AND min_posts = {int:min_posts}' : '') . (allowedTo('admin_forum') ? '' : '
			AND group_type != {int:is_protected}') . '
		ORDER BY min_posts, id_group != {int:global_mod_group}, group_name', array('moderator_group' => 3, 'global_mod_group' => 2, 'min_posts' => -1, 'is_protected' => 1));
    $context['groups'] = array();
    while ($row = mysql_fetch_assoc($result)) {
        $context['groups'][] = array('id' => $row['id_group'], 'name' => $row['group_name']);
    }
    mysql_free_result($result);
    $result = smf_db_query('
		SELECT id_board, name, child_level
		FROM {db_prefix}boards
		ORDER BY board_order', array());
    $context['boards'] = array();
    while ($row = mysql_fetch_assoc($result)) {
        $context['boards'][] = array('id' => $row['id_board'], 'name' => $row['name'], 'child_level' => $row['child_level'], 'selected' => false);
    }
    mysql_free_result($result);
}
Example #5
0
function AddMembergroup()
{
    global $db_prefix, $context, $txt, $sourcedir, $modSettings;
    // A form was submitted, we can start adding.
    if (!empty($_POST['group_name'])) {
        checkSession();
        $postCountBasedGroup = isset($_POST['min_posts']) && (!isset($_POST['postgroup_based']) || !empty($_POST['postgroup_based']));
        // !!! Check for members with same name too?
        $request = db_query("\n\t\t\tSELECT MAX(ID_GROUP)\n\t\t\tFROM {$db_prefix}membergroups", __FILE__, __LINE__);
        list($ID_GROUP) = mysql_fetch_row($request);
        mysql_free_result($request);
        $ID_GROUP++;
        db_query("\n\t\t\tINSERT INTO {$db_prefix}membergroups\n\t\t\t\t(ID_GROUP, groupName, minPosts, stars, onlineColor)\n\t\t\tVALUES ({$ID_GROUP}, SUBSTRING('{$_POST['group_name']}', 1, 80), " . ($postCountBasedGroup ? (int) $_POST['min_posts'] : '-1') . ", '1#star.gif', '')", __FILE__, __LINE__);
        // Update the post groups now, if this is a post group!
        if (isset($_POST['min_posts'])) {
            updateStats('postgroups');
        }
        // You cannot set permissions for post groups if they are disabled.
        if ($postCountBasedGroup && empty($modSettings['permission_enable_postgroups'])) {
            $_POST['perm_type'] = '';
        }
        if ($_POST['perm_type'] == 'predefined') {
            // Set default permission level.
            require_once $sourcedir . '/ManagePermissions.php';
            setPermissionLevel($_POST['level'], $ID_GROUP, 'null');
        } elseif ($_POST['perm_type'] == 'copy') {
            $_POST['copyperm'] = (int) $_POST['copyperm'];
            // Don't allow copying of a real priviledged person!
            require_once $sourcedir . '/ManagePermissions.php';
            loadIllegalPermissions();
            $request = db_query("\n\t\t\t\tSELECT permission, addDeny\n\t\t\t\tFROM {$db_prefix}permissions\n\t\t\t\tWHERE ID_GROUP = {$_POST['copyperm']}", __FILE__, __LINE__);
            $setString = '';
            while ($row = mysql_fetch_assoc($request)) {
                if (empty($context['illegal_permissions']) || !in_array($row['permission'], $context['illegal_permissions'])) {
                    $setString .= "\n\t\t\t\t\t\t({$ID_GROUP}, '{$row['permission']}', {$row['addDeny']}),";
                }
            }
            mysql_free_result($request);
            if (!empty($setString)) {
                db_query("\n\t\t\t\t\tINSERT INTO {$db_prefix}permissions\n\t\t\t\t\t\t(ID_GROUP, permission, addDeny)\n\t\t\t\t\tVALUES" . substr($setString, 0, -1), __FILE__, __LINE__);
            }
            $request = db_query("\n\t\t\t\tSELECT ID_BOARD, permission, addDeny\n\t\t\t\tFROM {$db_prefix}board_permissions\n\t\t\t\tWHERE ID_GROUP = {$_POST['copyperm']}" . (empty($modSettings['permission_enable_by_board']) ? "\n\t\t\t\t\tAND ID_BOARD = 0" : ''), __FILE__, __LINE__);
            $setString = '';
            while ($row = mysql_fetch_assoc($request)) {
                $setString .= "\n\t\t\t\t\t({$ID_GROUP}, {$row['ID_BOARD']}, '{$row['permission']}', {$row['addDeny']}),";
            }
            mysql_free_result($request);
            if (!empty($setString)) {
                db_query("\n\t\t\t\t\tINSERT INTO {$db_prefix}board_permissions\n\t\t\t\t\t\t(ID_GROUP, ID_BOARD, permission, addDeny)\n\t\t\t\t\tVALUES" . substr($setString, 0, -1), __FILE__, __LINE__);
            }
            // Also get some membergroup information if we're not copying from guests...
            if ($_POST['copyperm'] > 0) {
                $request = db_query("\n\t\t\t\t\tSELECT onlineColor, maxMessages, stars\n\t\t\t\t\tFROM {$db_prefix}membergroups\n\t\t\t\t\tWHERE ID_GROUP = {$_POST['copyperm']}\n\t\t\t\t\tLIMIT 1", __FILE__, __LINE__);
                $group_info = mysql_fetch_assoc($request);
                mysql_free_result($request);
                // ...and update the new membergroup with it.
                db_query("\n\t\t\t\t\tUPDATE {$db_prefix}membergroups\n\t\t\t\t\tSET\n\t\t\t\t\t\tonlineColor = '{$group_info['onlineColor']}',\n\t\t\t\t\t\tmaxMessages = {$group_info['maxMessages']},\n\t\t\t\t\t\tstars = '{$group_info['stars']}'\n\t\t\t\t\tWHERE ID_GROUP = {$ID_GROUP}\n\t\t\t\t\tLIMIT 1", __FILE__, __LINE__);
            }
        }
        // Make sure all boards selected are stored in a proper array.
        $_POST['boardaccess'] = empty($_POST['boardaccess']) || !is_array($_POST['boardaccess']) ? array() : $_POST['boardaccess'];
        foreach ($_POST['boardaccess'] as $key => $value) {
            $_POST['boardaccess'][$key] = (int) $value;
        }
        // Only do this if they have special access requirements.
        if (!empty($_POST['boardaccess'])) {
            db_query("\n\t\t\t\tUPDATE {$db_prefix}boards\n\t\t\t\tSET memberGroups = IF(memberGroups = '', '{$ID_GROUP}', CONCAT(memberGroups, ',{$ID_GROUP}'))\n\t\t\t\tWHERE ID_BOARD IN (" . implode(', ', $_POST['boardaccess']) . ")\n\t\t\t\tLIMIT " . count($_POST['boardaccess']), __FILE__, __LINE__);
        }
        // Go change some more settings.
        redirectexit('action=membergroups;sa=edit;group=' . $ID_GROUP);
    }
    // Just show the 'add membergroup' screen.
    $context['page_title'] = $txt['membergroups_new_group'];
    $context['sub_template'] = 'new_group';
    $context['post_group'] = !empty($_REQUEST['postgroup']);
    $context['undefined_group'] = empty($_REQUEST['postgroup']) && empty($_REQUEST['generalgroup']);
    $result = db_query("\n\t\tSELECT ID_GROUP, groupName\n\t\tFROM {$db_prefix}membergroups\n\t\tWHERE (ID_GROUP > 3 OR ID_GROUP = 2)" . (empty($modSettings['permission_enable_postgroups']) ? "\n\t\t\tAND minPosts = -1" : '') . "\n\t\tORDER BY minPosts, ID_GROUP != 2, groupName", __FILE__, __LINE__);
    $context['groups'] = array();
    while ($row = mysql_fetch_assoc($result)) {
        $context['groups'][] = array('id' => $row['ID_GROUP'], 'name' => $row['groupName']);
    }
    mysql_free_result($result);
    $result = db_query("\n\t\tSELECT ID_BOARD, name, childLevel\n\t\tFROM {$db_prefix}boards", __FILE__, __LINE__);
    $context['boards'] = array();
    while ($row = mysql_fetch_assoc($result)) {
        $context['boards'][] = array('id' => $row['ID_BOARD'], 'name' => $row['name'], 'child_level' => $row['childLevel'], 'selected' => false);
    }
    mysql_free_result($result);
}
 /**
  * This function actually saves modifications to a membergroup's board permissions.
  */
 public function action_modify2()
 {
     global $context;
     checkSession();
     validateToken('admin-mp');
     // We'll need to init illegal permissions, update child permissions, etc.
     require_once SUBSDIR . '/Permission.subs.php';
     require_once SUBSDIR . '/ManagePermissions.subs.php';
     loadIllegalPermissions();
     $current_group_id = (int) $_GET['group'];
     $_GET['pid'] = (int) $_GET['pid'];
     // Cannot modify predefined profiles.
     if ($_GET['pid'] > 1 && $_GET['pid'] < 5) {
         fatal_lang_error('no_access', false);
     }
     // Verify this isn't inherited.
     if ($current_group_id == -1 || $current_group_id == 0) {
         $parent = -2;
     } else {
         require_once SUBSDIR . '/Membergroups.subs.php';
         $group = membergroupById($current_group_id, true);
         $parent = $group['id_parent'];
     }
     if ($parent != -2) {
         fatal_lang_error('cannot_edit_permissions_inherited');
     }
     $givePerms = array('membergroup' => array(), 'board' => array());
     // Guest group, we need illegal, guest permissions.
     if ($current_group_id == -1) {
         loadIllegalGuestPermissions();
         $context['illegal_permissions'] = array_merge($context['illegal_permissions'], $context['non_guest_permissions']);
     }
     // Prepare all permissions that were set or denied for addition to the DB.
     if (isset($_POST['perm']) && is_array($_POST['perm'])) {
         foreach ($_POST['perm'] as $perm_type => $perm_array) {
             if (is_array($perm_array)) {
                 foreach ($perm_array as $permission => $value) {
                     if ($value == 'on' || $value == 'deny') {
                         // Don't allow people to escalate themselves!
                         if (!empty($context['illegal_permissions']) && in_array($permission, $context['illegal_permissions'])) {
                             continue;
                         }
                         $givePerms[$perm_type][] = array($permission, $current_group_id, $value == 'deny' ? 0 : 1);
                     }
                 }
             }
         }
     }
     // Insert the general permissions.
     if ($current_group_id != 3 && empty($_GET['pid'])) {
         deleteInvalidPermissions($current_group_id, $context['illegal_permissions']);
         if (!empty($givePerms['membergroup'])) {
             replacePermission($givePerms['membergroup']);
         }
     }
     // Insert the boardpermissions.
     $profileid = max(1, $_GET['pid']);
     deleteAllBoardPermissions($current_group_id, $profileid);
     if (!empty($givePerms['board'])) {
         foreach ($givePerms['board'] as $k => $v) {
             $givePerms['board'][$k][] = $profileid;
         }
         replaceBoardPermission($givePerms['board']);
     }
     // Update any inherited permissions as required.
     updateChildPermissions($current_group_id, $_GET['pid']);
     // Clear cached privs.
     updateSettings(array('settings_updated' => time()));
     redirectexit('action=admin;area=permissions;pid=' . $_GET['pid']);
 }
 /**
  * This function handles adding a membergroup and setting some initial properties.
  *
  * What it does:
  * -Called by ?action=admin;area=membergroups;sa=add.
  * -It requires the manage_membergroups permission.
  * -Allows to use a predefined permission profile or copy one from another group.
  * -Redirects to action=admin;area=membergroups;sa=edit;group=x.
  *
  * @uses the new_group sub template of ManageMembergroups.
  */
 public function action_add()
 {
     global $context, $txt, $modSettings;
     require_once SUBSDIR . '/Membergroups.subs.php';
     // A form was submitted, we can start adding.
     if (isset($_POST['group_name']) && trim($_POST['group_name']) != '') {
         checkSession();
         validateToken('admin-mmg');
         $postCountBasedGroup = isset($_POST['min_posts']) && (!isset($_POST['postgroup_based']) || !empty($_POST['postgroup_based']));
         $_POST['group_type'] = !isset($_POST['group_type']) || $_POST['group_type'] < 0 || $_POST['group_type'] > 3 || $_POST['group_type'] == 1 && !allowedTo('admin_forum') ? 0 : (int) $_POST['group_type'];
         // @todo Check for members with same name too?
         // Don't allow copying of a real priviledged person!
         require_once SUBSDIR . '/Permission.subs.php';
         loadIllegalPermissions();
         $id_group = getMaxGroupID() + 1;
         $minposts = !empty($_POST['min_posts']) ? (int) $_POST['min_posts'] : '-1';
         addMembergroup($id_group, $_POST['group_name'], $minposts, $_POST['group_type']);
         call_integration_hook('integrate_add_membergroup', array($id_group, $postCountBasedGroup));
         // Update the post groups now, if this is a post group!
         if (isset($_POST['min_posts'])) {
             updateStats('postgroups');
         }
         // You cannot set permissions for post groups if they are disabled.
         if ($postCountBasedGroup && empty($modSettings['permission_enable_postgroups'])) {
             $_POST['perm_type'] = '';
         }
         if ($_POST['perm_type'] == 'predefined') {
             // Set default permission level.
             require_once SUBSDIR . '/ManagePermissions.subs.php';
             setPermissionLevel($_POST['level'], $id_group, null);
         } elseif ($_POST['perm_type'] == 'copy' || $_POST['perm_type'] == 'inherit') {
             $copy_id = $_POST['perm_type'] == 'copy' ? (int) $_POST['copyperm'] : (int) $_POST['inheritperm'];
             // Are you a powerful admin?
             if (!allowedTo('admin_forum')) {
                 $copy_type = membergroupById($copy_id);
                 // Protected groups are... well, protected!
                 if ($copy_type['group_type'] == 1) {
                     fatal_lang_error('membergroup_does_not_exist');
                 }
             }
             // Don't allow copying of a real priviledged person!
             require_once SUBSDIR . '/Permission.subs.php';
             loadIllegalPermissions();
             copyPermissions($id_group, $copy_id, $context['illegal_permissions']);
             copyBoardPermissions($id_group, $copy_id);
             // Also get some membergroup information if we're copying and not copying from guests...
             if ($copy_id > 0 && $_POST['perm_type'] == 'copy') {
                 updateCopiedGroup($id_group, $copy_id);
             } elseif ($_POST['perm_type'] == 'inherit') {
                 updateInheritedGroup($id_group, $copy_id);
             }
         }
         // Make sure all boards selected are stored in a proper array.
         $changed_boards = array();
         $accesses = empty($_POST['boardaccess']) || !is_array($_POST['boardaccess']) ? array() : $_POST['boardaccess'];
         $changed_boards['allow'] = array();
         $changed_boards['deny'] = array();
         $changed_boards['ignore'] = array();
         foreach ($accesses as $group_id => $action) {
             $changed_boards[$action][] = (int) $group_id;
         }
         foreach (array('allow', 'deny') as $board_action) {
             // Only do this if they have special access requirements.
             if (!empty($changed_boards[$board_action])) {
                 assignGroupToBoards($id_group, $changed_boards, $board_action);
             }
         }
         // If this is joinable then set it to show group membership in people's profiles.
         if (empty($modSettings['show_group_membership']) && $_POST['group_type'] > 1) {
             updateSettings(array('show_group_membership' => 1));
         }
         // Rebuild the group cache.
         updateSettings(array('settings_updated' => time()));
         // We did it.
         logAction('add_group', array('group' => $_POST['group_name']), 'admin');
         // Go change some more settings.
         redirectexit('action=admin;area=membergroups;sa=edit;group=' . $id_group);
     }
     // Just show the 'add membergroup' screen.
     $context['page_title'] = $txt['membergroups_new_group'];
     $context['sub_template'] = 'new_group';
     $context['post_group'] = isset($_REQUEST['postgroup']);
     $context['undefined_group'] = !isset($_REQUEST['postgroup']) && !isset($_REQUEST['generalgroup']);
     $context['allow_protected'] = allowedTo('admin_forum');
     if (!empty($modSettings['deny_boards_access'])) {
         loadLanguage('ManagePermissions');
     }
     $context['groups'] = getBasicMembergroupData(array('globalmod'), array(), 'min_posts, id_group != {int:global_mod_group}, group_name');
     require_once SUBSDIR . '/Boards.subs.php';
     $context += getBoardList();
     // Include a list of boards per category for easy toggling.
     foreach ($context['categories'] as $category) {
         $context['categories'][$category['id']]['child_ids'] = array_keys($category['boards']);
     }
     createToken('admin-mmg');
 }
/**
 * Set the permission level for a specific profile, group, or group for a profile.
 *
 * @package Permissions
 * @internal
 * @param string $level
 * @param integer|null $group
 * @param integer|null $profile = null, int expected
 */
function setPermissionLevel($level, $group = null, $profile = null)
{
    global $context;
    $db = database();
    // we'll need to init illegal permissions.
    require_once SUBSDIR . '/Permission.subs.php';
    loadIllegalPermissions();
    loadIllegalGuestPermissions();
    // Levels by group... restrict, standard, moderator, maintenance.
    $groupLevels = array('board' => array('inherit' => array()), 'group' => array('inherit' => array()));
    // Levels by board... standard, publish, free.
    $boardLevels = array('inherit' => array());
    // Restrictive - ie. guests.
    $groupLevels['global']['restrict'] = array('search_posts', 'calendar_view', 'view_stats', 'who_view', 'profile_view_own', 'profile_identity_own');
    $groupLevels['board']['restrict'] = array('poll_view', 'post_new', 'post_reply_own', 'post_reply_any', 'delete_own', 'modify_own', 'mark_any_notify', 'mark_notify', 'report_any', 'send_topic');
    // Standard - ie. members.  They can do anything Restrictive can.
    $groupLevels['global']['standard'] = array_merge($groupLevels['global']['restrict'], array('view_mlist', 'karma_edit', 'like_posts', 'pm_read', 'pm_send', 'send_email_to_members', 'profile_view_any', 'profile_extra_own', 'profile_server_avatar', 'profile_upload_avatar', 'profile_remote_avatar', 'profile_remove_own'));
    $groupLevels['board']['standard'] = array_merge($groupLevels['board']['restrict'], array('poll_vote', 'poll_edit_own', 'poll_post', 'poll_add_own', 'post_attachment', 'lock_own', 'remove_own', 'view_attachments'));
    // Moderator - ie. moderators :P.  They can do what standard can, and more.
    $groupLevels['global']['moderator'] = array_merge($groupLevels['global']['standard'], array('calendar_post', 'calendar_edit_own', 'access_mod_center', 'issue_warning'));
    $groupLevels['board']['moderator'] = array_merge($groupLevels['board']['standard'], array('make_sticky', 'poll_edit_any', 'delete_any', 'modify_any', 'lock_any', 'remove_any', 'move_any', 'merge_any', 'split_any', 'poll_lock_any', 'poll_remove_any', 'poll_add_any', 'approve_posts', 'like_posts'));
    // Maintenance - wannabe admins.  They can do almost everything.
    $groupLevels['global']['maintenance'] = array_merge($groupLevels['global']['moderator'], array('manage_attachments', 'manage_smileys', 'manage_boards', 'moderate_forum', 'manage_membergroups', 'manage_bans', 'admin_forum', 'manage_permissions', 'edit_news', 'calendar_edit_any', 'profile_identity_any', 'profile_extra_any', 'profile_title_any'));
    $groupLevels['board']['maintenance'] = array_merge($groupLevels['board']['moderator'], array());
    // Standard - nothing above the group permissions. (this SHOULD be empty.)
    $boardLevels['standard'] = array();
    // Locked - just that, you can't post here.
    $boardLevels['locked'] = array('poll_view', 'mark_notify', 'report_any', 'send_topic', 'view_attachments');
    // Publisher - just a little more...
    $boardLevels['publish'] = array_merge($boardLevels['locked'], array('post_new', 'post_reply_own', 'post_reply_any', 'delete_own', 'modify_own', 'mark_any_notify', 'delete_replies', 'modify_replies', 'poll_vote', 'poll_edit_own', 'poll_post', 'poll_add_own', 'poll_remove_own', 'post_attachment', 'lock_own', 'remove_own'));
    // Free for All - Scary.  Just scary.
    $boardLevels['free'] = array_merge($boardLevels['publish'], array('poll_lock_any', 'poll_edit_any', 'poll_add_any', 'poll_remove_any', 'make_sticky', 'lock_any', 'remove_any', 'delete_any', 'split_any', 'merge_any', 'modify_any', 'approve_posts'));
    // Make sure we're not granting someone too many permissions!
    foreach ($groupLevels['global'][$level] as $k => $permission) {
        if (!empty($context['illegal_permissions']) && in_array($permission, $context['illegal_permissions'])) {
            unset($groupLevels['global'][$level][$k]);
        }
        if ($group == -1 && in_array($permission, $context['non_guest_permissions'])) {
            unset($groupLevels['global'][$level][$k]);
        }
    }
    if ($group == -1) {
        foreach ($groupLevels['board'][$level] as $k => $permission) {
            if (in_array($permission, $context['non_guest_permissions'])) {
                unset($groupLevels['board'][$level][$k]);
            }
        }
    }
    // Reset all cached permissions.
    updateSettings(array('settings_updated' => time()));
    // Setting group permissions.
    if ($profile === null && $group !== null) {
        $group = (int) $group;
        if (empty($groupLevels['global'][$level])) {
            return;
        }
        $db->query('', '
			DELETE FROM {db_prefix}permissions
			WHERE id_group = {int:current_group}
			' . (empty($context['illegal_permissions']) ? '' : ' AND permission NOT IN ({array_string:illegal_permissions})'), array('current_group' => $group, 'illegal_permissions' => !empty($context['illegal_permissions']) ? $context['illegal_permissions'] : array()));
        $db->query('', '
			DELETE FROM {db_prefix}board_permissions
			WHERE id_group = {int:current_group}
				AND id_profile = {int:default_profile}', array('current_group' => $group, 'default_profile' => 1));
        $groupInserts = array();
        foreach ($groupLevels['global'][$level] as $permission) {
            $groupInserts[] = array($group, $permission);
        }
        $db->insert('insert', '{db_prefix}permissions', array('id_group' => 'int', 'permission' => 'string'), $groupInserts, array('id_group'));
        $boardInserts = array();
        foreach ($groupLevels['board'][$level] as $permission) {
            $boardInserts[] = array(1, $group, $permission);
        }
        $db->insert('insert', '{db_prefix}board_permissions', array('id_profile' => 'int', 'id_group' => 'int', 'permission' => 'string'), $boardInserts, array('id_profile', 'id_group'));
    } elseif ($profile !== null && $group !== null && ($profile == 1 || $profile > 4)) {
        $group = (int) $group;
        $profile = (int) $profile;
        if (!empty($groupLevels['global'][$level])) {
            $db->query('', '
				DELETE FROM {db_prefix}board_permissions
				WHERE id_group = {int:current_group}
					AND id_profile = {int:current_profile}', array('current_group' => $group, 'current_profile' => $profile));
        }
        if (!empty($groupLevels['board'][$level])) {
            $boardInserts = array();
            foreach ($groupLevels['board'][$level] as $permission) {
                $boardInserts[] = array($profile, $group, $permission);
            }
            $db->insert('insert', '{db_prefix}board_permissions', array('id_profile' => 'int', 'id_group' => 'int', 'permission' => 'string'), $boardInserts, array('id_profile', 'id_group'));
        }
    } elseif ($profile !== null && $group === null && ($profile == 1 || $profile > 4)) {
        $profile = (int) $profile;
        $db->query('', '
			DELETE FROM {db_prefix}board_permissions
			WHERE id_profile = {int:current_profile}', array('current_profile' => $profile));
        if (empty($boardLevels[$level])) {
            return;
        }
        // Get all the groups...
        $query = $db->query('', '
			SELECT id_group
			FROM {db_prefix}membergroups
			WHERE id_group > {int:moderator_group}
			ORDER BY min_posts, CASE WHEN id_group < {int:newbie_group} THEN id_group ELSE 4 END, group_name', array('moderator_group' => 3, 'newbie_group' => 4));
        while ($row = $db->fetch_row($query)) {
            $group = $row[0];
            $boardInserts = array();
            foreach ($boardLevels[$level] as $permission) {
                $boardInserts[] = array($profile, $group, $permission);
            }
            $db->insert('insert', '{db_prefix}board_permissions', array('id_profile' => 'int', 'id_group' => 'int', 'permission' => 'string'), $boardInserts, array('id_profile', 'id_group'));
        }
        $db->free_result($query);
        // Add permissions for ungrouped members.
        $boardInserts = array();
        foreach ($boardLevels[$level] as $permission) {
            $boardInserts[] = array($profile, 0, $permission);
        }
        $db->insert('insert', '{db_prefix}board_permissions', array('id_profile' => 'int', 'id_group' => 'int', 'permission' => 'string'), $boardInserts, array('id_profile', 'id_group'));
    } else {
        fatal_lang_error('no_access', false);
    }
}