<?php
/**
 * This file is part of LEPTON Core, released under the GNU GPL
 * Please see LICENSE and COPYING files in your package for details, specially for terms and warranties.
 *
 * NOTICE:LEPTON CMS Package has several different licenses.
 * Please see the individual license in the header of each single file or info.php of modules and templates.
 *
 * @author          LEPTON Project
 * @copyright       2010-2026 LEPTON Project
 * @link            https://lepton-cms.org
 * @license         https://gnu.org/licenses/gpl.html
 * @license_terms   please see LICENSE and COPYING files in your package
 *
 */

// include secure.php to protect this file and the whole CMS!
if(!defined("SEC_FILE")){define("SEC_FILE",'/framework/secure.php' );}
if (defined('LEPTON_PATH')) {
	include LEPTON_PATH.SEC_FILE;
} else {
	$oneback = "../";
	$root = $oneback;
	$level = 1;
	while (($level < 10) && (!file_exists($root.SEC_FILE))) {
		$root .= $oneback;
		$level += 1;
	}
	if (file_exists($root.SEC_FILE)) {
		include $root.SEC_FILE;
	} else {
		trigger_error(sprintf("[ <b>%s</b> ] Can't include secure.php!", $_SERVER['SCRIPT_NAME']), E_USER_ERROR);
	}
}
// end include secure file


$admin = LEPTON_admin::getInstance('Access', 'groups_modify');

// Create a javascript back link
$js_back = "javascript: history.go(-1);";

// Check if group group_id is a valid number and is not 1
if(!isset($_POST['group_id']) || !is_numeric($_POST['group_id']) || $_POST['group_id'] == 1)
{
	header("Location: index.php");
	exit(0);
}
else
{
	$group_id = intval($_POST['group_id']);
}

// Gather details entered
$group_name = $database->get_one("SELECT `name` FROM `".TABLE_PREFIX."groups` WHERE `group_id` = ".$group_id);

// Check values
if ($group_id != -1 && is_null($group_name))
{
	$admin->print_error($MESSAGE['GROUPS_GROUP_NAME_BLANK']." [1]");
}
elseif ($group_id == -1)
{
    $group_name = isset($_POST['group_name']) ? $_POST['group_name'] : "";
}
else
{
	$group_name = isset($_POST['group_name']) ? $_POST['group_name'] : "";
}

$sPostedGroupName = trim( (isset($_POST['group_name']) ? $_POST['group_name'] : "" ) );

if( ($sPostedGroupName != "") && ( $sPostedGroupName != $group_name ) )
{
	$group_name = $sPostedGroupName;
}

if (isset($_POST['job']))
{
	if ($_POST['job'] == "delete" && !isset($_POST['copy']))
	{
		$database->simple_query("DELETE FROM `".TABLE_PREFIX."groups` WHERE `group_id` = ".$group_id);

		// Delete users in the group
        /*
            Example given
            - Group to delete is nr. 5
            - Some users are only member of this group - [5]
                --> this user can be deleted
            - Some users are members of more than one group - e.g. [3,4,7]
            - Some users are members of other groups AND of this one - e.g. [1,3,5,7,11]
                --> this user cannot be deleted, but the group_id must out of the list
        */

        $aAllUsers = [];
        $database->execute_query(
            "SELECT `user_id`, `groups_id` FROM `".TABLE_PREFIX."users` WHERE `user_id` > 1",
            true,
            $aAllUsers,
            true
        );

        foreach ($aAllUsers as $tempUser)
        {
            $tempList = explode(",", $tempUser['groups_id']);
            if ((count($tempList) === 1) && (in_array($group_id, $tempList)))
            {
                // user is only in this group - so we can delete him.
                $database->simple_query("DELETE FROM `".TABLE_PREFIX."users` WHERE `user_id` = ".$tempUser['user_id']);

            }
            else
            {
                // is the group in the user-list?
                if (in_array($group_id, $tempList))
                {
                    // Yes - we've to extract this entry.
                    $aNewList = [];
                    foreach ($tempList as $tempID)
                    {
                        if ($tempID != $group_id)
                        {
                            $aNewList[] = $tempID;
                        }

                    }
                    // Zurück schreiben
                    $database->build_and_execute(
                        'UPDATE',
                        TABLE_PREFIX."users",
                        [
                            'groups_id' => implode(",", $aNewList)
                        ],
                        "`user_id` = ".$tempUser['user_id']
                    );
                }
            }
        }

        // Delete the group_id also in all pages -> admin_groups
        $allPages = [];
        $database->execute_query(
            "SELECT `page_id`, `admin_groups` FROM `".TABLE_PREFIX."pages`",
            true,
            $allPages,
            true
        );

        foreach ($allPages as $page)
        {
            $pageAdminGroups = explode(",", $page['admin_groups']);
            if (in_array($group_id, $pageAdminGroups))
            {
                // update
                $newArray = [];
                foreach ($pageAdminGroups as $item)
                {
                    if ($group_id != $item)
                    {
                        $newArray[] = $item;
                    }
                }

                $database->build_and_execute(
                    "update",
                    TABLE_PREFIX."pages",
                    [
                        'admin_groups' => implode(",", $newArray)
                    ],
                    "page_id =".$page['page_id']
                );
            }
        }

		$admin->print_success($MESSAGE['GROUPS_DELETED']." [2]", ADMIN_URL.'/groups/groups.php');

		return true;
	}
	elseif ($_POST['job'] == "copy" || isset($_POST['copy'])) 	// copy group
	{
		$to_copy = [];
		$database->execute_query(
			"SELECT * FROM `".TABLE_PREFIX."groups` WHERE `group_id` = ".$group_id." LIMIT 1",
			true,
			$to_copy,
			false
		);

		if (!empty($to_copy))
		{
			unset($to_copy['group_id']);
			$to_copy['name'] .= '- Copy';

			$database->build_and_execute(
				"INSERT",
				TABLE_PREFIX."groups",
				$to_copy
			);
		}

		$admin->print_success($MESSAGE['GROUPS_SAVED'], ADMIN_URL.'/groups/groups.php');

		return true;
	}
}


//	Get the system permissions
$system_lookups = [
	'pages'		=> ['view', 'add', 'add_level_0', 'settings', 'modify', 'delete'],
	'media'		=> ['view', 'upload', 'rename', 'delete', 'create'],
	'preferences'   => ['access'],
	'settings'	=> ['access'],
	'users'		=> ['view', 'add', 'modify', 'delete'],
	'groups'	=> ['view', 'add', 'modify', 'delete'],
];

$group_system_permissions = [];
foreach ($system_lookups as $key=>$subkeys)
{
	$one_is_set = false;
	foreach ($subkeys as &$sub)
	{
		$temp_name = $key."_".$sub;

		if (isset($_POST[ $temp_name]))
		{
			if (intval($_POST[ $temp_name]) == 1)
			{
				$group_system_permissions[] = $temp_name;
				$one_is_set = true;
			}
		}
	}
	if (true === $one_is_set)
	{
	    $group_system_permissions[] = $key;
	}
}

$system_permissions = implode(",", $group_system_permissions);


//	Get the module permissions
$all_modules = [];
$database->execute_query(
	'SELECT `name`,`directory` FROM `'.TABLE_PREFIX.'addons` WHERE `type` = "module" AND (`function` = "page" OR `function`="tool") ORDER BY `name`',
	true,
	$all_modules,
	true
);

$group_module_permissions = [];
foreach ($all_modules as &$module)
{
	if (isset($_POST[ $module['directory'] ]))
	{
		if (intval($_POST[ $module['directory'] ]) == 1)
		{
			$group_module_permissions[] = $module['directory'];
		}
	}
}
$module_permissions = implode(",", $group_module_permissions);

// backend access == 0 did not clear all other fields, it can easily be used to switch backend access off without loosing other permissions, @erpe 2020418
$fields = array(
	'name' => $group_name,
	'backend_access'    => $_POST['backend_access'],
	'system_permissions' => $system_permissions,
	'module_permissions' => $module_permissions
);

if ($group_id == -1)
{
	// Insert a new group
	$database->build_and_execute(
		'INSERT',
		TABLE_PREFIX."groups",
		$fields
	);

	// get the last insert id from groups
	$group_id = $database->get_one("SELECT LAST_INSERT_ID()");
}
else
{

	// Update an existing group
	$database->build_and_execute(
		'UPDATE',
		TABLE_PREFIX."groups",
		$fields,
		"`group_id` = ".$group_id
	);
}

//  Remember last saved group-id
$_SESSION['last_saved_group_id'] = $group_id;

$admin->print_success($MESSAGE['GROUPS_SAVED'], ADMIN_URL.'/groups/groups.php');
