<?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

/*
 *	this file creates fields for the interface in groups.lte
*/

// get twig instance
$admin = LEPTON_admin::getInstance();
$oTWIG = lib_twig_box::getInstance();

// prevent users to access url without permission
if ($admin->userHasAdminRights() == false)
{

    if (!in_array('groups', $_SESSION['SYSTEM_PERMISSIONS']))
    {
	header("Location: ".ADMIN_URL."");
	exit(0);
    }
}

// enable custom files, start with index file (not in LEPsem BE-THEME)
if (LEPTON_handle::require_alternative('groups/groups.php')) return 0;


$LEPTON_basics = LEPTON_basics::getInstance();

$iCurrentGroupID = LEPTON_core::getValue("group_id", "integer", "post");


//	Get all groups for the groups-tree left, except the group 1 (Administrators)!
$all_groups = [];
$database->execute_query(
	"SELECT `group_id`,`name` from `". TABLE_PREFIX."groups` WHERE `group_id` <> 1",
	true,
	$all_groups,
	true
);

if (($iCurrentGroupID === 0) || ($iCurrentGroupID == 1) )
{
	$group = [
		'group_id'	=> -1,
		'name'	=> "",
		'backend_access'	=> 0,
		'system_permissions' => "",
		'module_permissions' => ""
	];
}
else
{
	// Get group values
	$group = [];
	$database->execute_query(
		"SELECT * FROM `".TABLE_PREFIX."groups` WHERE `group_id` = ".$iCurrentGroupID,
		true,
		$group,
		false
	);
}

//	Get backend access value
$backend_access = $group['backend_access'];

//	Get the system permissions/languages
$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 = explode(',', $group['system_permissions']);

$system_permissions = [];

foreach ($system_lookups as $sys_key => $subkeys)
{
	$sub_keys = [];
	foreach($subkeys as $item)
	{
		$sub_keys[] = [
			'name' => $sys_key."_".$item,
			'label'	=> $LEPTON_basics->get_backend_translation( strtoupper($item) ),
			'checked' => in_array( $sys_key."_".$item, $group_system_permissions ) ? 1 : 0
		];
	}

	$system_permissions[] = [
		'name'	=> $sys_key,
		'label'	=> $MENU[ (strtoupper($sys_key)) ],
		'checked' => in_array( $sys_key, $group_system_permissions ) ? 1 : 0,
		'sub_keys'	=> $sub_keys
	];
}


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

$group_module_permissions = explode(',', $group['module_permissions']);

$module_permissions = [];
foreach($all_modules as &$module)
{
	$module_permissions[] = [
		'name'	=> $module['name'],
		'directory' => $module['directory'],
		'permission' => in_array($module['directory'], $group_module_permissions) ? 1 : 0
	];
}

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

$admintools_permissions = [];
foreach($all_tools as &$tool)
{
	$admintools_permissions[] = [
		'name'	=> $tool['name'],
		'directory' => $tool['directory'],
		'permission' => in_array($tool['directory'], $group_module_permissions) ? 1 : 0
	];
}

//	Get/Build secure-hash for the js-calls
LEPTON_handle::register('random_string');
$hash = [
	'h_name' => random_string(16),
	'h_value' => random_string(24)
];
$_SESSION['backend_group_h'] = $hash['h_name'];
$_SESSION['backend_group_v'] = $hash['h_value'];

$page_values = [
	'THEME' => $THEME,
	'all_groups' => $all_groups,
	'group' => $group,
	'ACTION_URL' => ADMIN_URL.'/groups/save.php',
	'backend_access' => $backend_access,
	'system_permissions' => $system_permissions,
	'module_permissions' => $module_permissions,
	'admintools_permissions' => $admintools_permissions,
	'hash'	=> $hash,
	'FORM_NAME' => "groups_".random_string(12),
    'p_groups_add' => $admin->getGroupsPermissions("add"),
    'p_groups_modify' => $admin->getGroupsPermissions("modify"),
    'p_groups_delete' => $admin->getGroupsPermissions("delete")
];

if (isset($_SESSION['last_saved_group_id']))
{
	$page_values['last_saved_group_id'] = $_SESSION['last_saved_group_id'];
	unset( $_SESSION['last_saved_group_id'] );
}
else
{
	if (isset($all_groups[0]))
	{
		$page_values['last_saved_group_id'] = $all_groups[0]['group_id']; //0;
	}
}

echo $oTWIG->render(
	"@theme/groups.lte",
	$page_values
);

$admin->print_footer();
