<?php
if (isset($_GET['backend_module'])) $backend_module = addslashes(trim(strip_tags(stripslashes(rawurldecode($_GET['backend_module'])))));
if (isset($_GET['module'])) $module = addslashes(trim(strip_tags(stripslashes(rawurldecode($_GET['module'])))));;
if (isset($_GET['file'])) $file = addslashes(trim(strip_tags(stripslashes(rawurldecode($_GET['file'])))));
if (isset($_GET['multi_module'])) $multi_module = addslashes(trim(strip_tags(stripslashes(rawurldecode($_GET['multi_module'])))));

if (isset($_GET['id'])) $id = addslashes(trim(strip_tags(stripslashes(rawurldecode($_GET['id'])))));
if (isset($_GET['ids'])) $ids = $_GET['ids'];

if (isset($_POST['url'])) $url = addslashes(trim(strip_tags(stripslashes(rawurldecode($_POST['url'])))));
if (isset($_GET['login_error'])) $login_error = addslashes(trim(strip_tags(stripslashes($_GET['login_error']))));

if (isset($_POST['update'])) $update = addslashes(trim(strip_tags(stripslashes(rawurldecode($_POST['update'])))));
else $update = false;
if (isset($_POST['multi_update'])) $multi_update = addslashes(trim(strip_tags(stripslashes(rawurldecode($_POST['multi_update'])))));
else $multi_update = false;

if(isset($_POST['order'])) $order = addslashes(trim(strip_tags(stripslashes($_POST['order']))));
else $order = 'datetime';

if(isset($_POST['lastorder'])) $lastorder = addslashes(trim(strip_tags(stripslashes($_POST['lastorder']))));
else $lastorder = NULL;

if(isset($_POST['orderdir'])) $orderdir = addslashes(trim(strip_tags(stripslashes($_POST['orderdir']))));
else $orderdir = 'ASC';

if(isset($_POST['c_grid'])) $c_grid = addslashes(trim(strip_tags(stripslashes($_POST['c_grid']))));
else if (isset($_SESSION['backend']['c_grid'])) $c_grid = $_SESSION['backend']['c_grid'];
else $c_grid = 1;

if (isset($_GET['tab'])) $tab = addslashes(trim(strip_tags(stripslashes(rawurldecode($_GET['tab'])))));
else $tab = 'data';

if (isset($_GET['sub_page'])) $sub_page = addslashes(trim(strip_tags(stripslashes($_GET['sub_page']))));
else $sub_page = 1;

if (isset($multi_module) && $multi_module) {
	$old_module = $module;
	$module = $multi_module;
}

if (isset($_GET['logout'])){
	unset($_SESSION['backend']);
	header("Location: index.php");
}

if (isset($backend_module) && $backend_module && empty($module)){
	$module = $backend_module;
}
if (empty($module)) $module = 'login';

if (!isset($backend_module) OR !$backend_module) $backend_module = $module;

if (!isset($_SESSION['backend']['language']) OR !$_SESSION['backend']['language']) $_SESSION['backend']['language'] = 'de';
$_SESSION['backend']['c_grid'] = $c_grid;

if (check_table($backend_module.'_labels')){
	$sql = "SELECT label, text FROM ".$backend_module."_labels WHERE c_active = '1' AND language = :language ";
	$result = $conn->prepare($sql);
	$result->bindValue(':language', $_SESSION['backend']['language'], PDO::PARAM_STR);
	$result->execute();
	while($arr = $result->fetch()){
		$arr['text'] = str_replace('[YEAR]', date('Y'), $arr['text']);
	  if (!defined($arr['label'])) define($arr['label'], $arr['text']);
	}
	
	$sql = "SELECT label, text FROM ".$backend_module."_labels WHERE c_active = '1' ";
	$result = $conn->prepare($sql);
	$result->execute();
	while($arr = $result->fetch()){
		$arr['text'] = str_replace('[YEAR]', date('Y'), $arr['text']);
	  if (!defined($arr['label'])) define($arr['label'], $arr['text']);
	}
}

$sql = "SELECT label, text FROM settings_labels WHERE c_active = '1' AND language = :language ";
$result = $conn->prepare($sql);
$result->bindValue(':language', $_SESSION['backend']['language'], PDO::PARAM_STR);
$result->execute();
while($arr = $result->fetch()){
	$arr['text'] = str_replace('[YEAR]', date('Y'), $arr['text']);
  if (!defined($arr['label'])) define($arr['label'], $arr['text']);
}

$sql = "SELECT label, text FROM settings_labels WHERE c_active = '1' ";
$result = $conn->prepare($sql);
$result->execute();
while($arr = $result->fetch()){
	$arr['text'] = str_replace('[YEAR]', date('Y'), $arr['text']);
  if (!defined($arr['label'])) define($arr['label'], $arr['text']);
}

$sql = "SELECT title, value FROM settings_options";
$result = $conn->prepare($sql);
$result->execute();
while ($arr = $result->fetch()){
	$title_settings = str_replace('_'.$module, '', $arr['title']);
	$admin_settings['module'][$title_settings] = $arr['value'];
	if ($arr['value']) $$title_settings = str_replace('[DOMAIN]', str_replace('www.', '', $_SERVER['SERVER_NAME']), $arr['value']);
	else $$title_settings = $arr['value'];
}


if (check_table($backend_module.'_options')){
	$sql = "SELECT title, value FROM ".$backend_module."_options";
	$result = $conn->prepare($sql);
	$result->execute();
	while ($arr = $result->fetch()){
		$title_settings = str_replace('_'.$module, '', $arr['title']);
		$admin_settings['module'][$title_settings] = $arr['value'];
		if ($arr['value']) $$title_settings = str_replace('[DOMAIN]', str_replace('www.', '', $_SERVER['SERVER_NAME']), $arr['value']);
		else $$title_settings = $arr['value'];
	}
}


if (!isset($title_page) OR !$title_page) {
	$title_page = str_replace('[DOMAIN]', str_replace('www.', '', $_SERVER['SERVER_NAME']), 'Comator | [DOMAIN]');
	$sql_check = "SELECT id FROM settings_options WHERE title = 'title_page' ";
	$result_check = $conn->prepare($sql_check);
	$result_check->execute();
	if (!$result_check->rowCount()){
		$sql = "INSERT INTO settings_options SET title = 'title_page', value = 'Comator | [DOMAIN]', c_public = '1'";
		$result = $conn->prepare($sql);
		$result->execute();
		$sql_tmp = "UPDATE settings_options SET id = '1' WHERE title = 'title_page'";
		$result_tmp = $conn->prepare($sql_tmp);
		$result_tmp->execute();
	}
}

$c_languages = false;
$sql = "SELECT id FROM languages ";
$result = $conn->prepare($sql);
$result->execute();
$count_languages = $result->rowCount();
if ($count_languages > 1) $c_languages = true;

if (!isset($language) OR !$language) $language = $_SESSION['backend']['language'];

if (check_table($backend_module.'_modules') && isset($module)){
	$sql = "SELECT * FROM ".$backend_module."_modules WHERE title = :title";
	$result = $conn->prepare($sql);
	$result->bindValue(':title', $module, PDO::PARAM_STR);
	$result->execute();
	if ($result->rowCount()){
		while ($arr = $result->fetch()){
			if ($arr['text']) $module_title = $arr['text'];
			else $module_title = ucwords(str_replace('_', ' ', $module));
		  $c_admin = $arr['c_admin'];
		  $c_editor = $arr['c_editor'];
		  $c_viewer = $arr['c_viewer'];
		  if ($arr['level_module']) $level_module = $arr['level_module'];
		  else {
				$sql_sub = "SELECT level_module FROM backend_modules WHERE title = :title ";
				$result_sub = $conn->prepare($sql_sub);
				$result_sub->bindValue(':title', $backend_module, PDO::PARAM_STR);
				$result_sub->execute();
				while ($arr_sub = $result_sub->fetch()){
				  if ($arr_sub['level_module']) $level_module = $arr_sub['level_module'];
				  else $level_module = $backend_module;
				}
		  }
		}
	} else {
		$sql = "SELECT * FROM backend_modules WHERE title = :title";
		$result = $conn->prepare($sql);
		$result->bindValue(':title', $backend_module, PDO::PARAM_STR);
		$result->execute();
		while ($arr = $result->fetch()){
			if ($arr['text']) $module_title = $arr['text'];
			else $module_title = ucwords(str_replace('_', ' ', $backend_module));
		  $c_admin = $arr['c_admin'];
		  $c_editor = $arr['c_editor'];
		  $c_viewer = $arr['c_viewer'];
		  if ($arr['level_module']) $level_module = $arr['level_module'];
		  else $level_module = $backend_module;
		}
	}
} else if (isset($module) && ($module == 'backend_modules' OR $module == 'modules_manager')) {
	$sql = "SELECT * FROM backend_modules WHERE title = 'settings'";
	$result = $conn->prepare($sql);
	$result->execute();
	while ($arr = $result->fetch()){
		if ($arr['text']) $module_title = $arr['text'];
		else $module_title = ucwords(str_replace('_', ' ', $module));
	  $c_admin = $arr['c_admin'];
	  $c_editor = $arr['c_editor'];
	  $c_viewer = $arr['c_viewer'];
	  if ($arr['level_module']) $level_module = $arr['level_module'];
	  else $level_module = $module;
	}
}

$library_modules = array();
$sql = "SELECT id FROM backend_modules WHERE title = 'library' AND c_active = '1' AND language = :language LIMIT 1";
$result = $conn->prepare($sql);
$result->bindValue(':language', $language, PDO::PARAM_STR);
$result->execute();
if ($result->rowCount()){
	$sql_tmp = "SELECT title, text, icon FROM library_modules WHERE c_active = '1' AND language = :language";
	$result_tmp = $conn->prepare($sql_tmp);
	$result_tmp->bindValue(':language', $language, PDO::PARAM_STR);
	$result_tmp->execute();
	if ($result_tmp->rowCount()){
		while($arr_tmp = $result_tmp->fetch()){
			$library_modules[$arr_tmp['title']]['active'] = true;
			$library_modules[$arr_tmp['title']]['text'] = $arr_tmp['text'];
			$library_modules[$arr_tmp['title']]['icon'] = $arr_tmp['icon'];
		}
	}
}

preg_match("/(.*)_levels/i", $module, $level_module_key);

if (($update OR $multi_update) && (check_table($module) OR isset($level_module_key[1]))) {
	if (isset($level_module_key[1])) $sql = "SELECT * FROM ".$level_module_key[1]."_levels LIMIT 0";
	else $sql = "SELECT * FROM ".$module." LIMIT 0";
	$result = $conn->prepare($sql);
	if ($result->execute()){
		$count_fields = $result->columnCount();
		$ii = 0;
		for($zz = 0; $zz < $count_fields; $zz++){
			$type = $result->getColumnMeta($zz);
			if ($type['name'] != 'id') {
				$ii++;
				$field[$ii] = $type['name'];
				$key = $type['name'];
				switch ($type['native_type']){
					case 'BLOB': 
						if (isset($_POST[$key])) {
							if (isset($_POST['submit']) && $_POST['submit'] == 'reload') $$key = str_replace("'", "&#39;", $_POST[$key]);
					  	else $$key = trim(stripslashes(nl2br($_POST[$key])));
					  }
				  	break;
					case 'LONGLONG':
					case 'LONG':
					case 'SHORT':
				  	settype($_POST[$key], 'integer');
				 		$$key = $_POST[$key]; 
				    break;
				  case 'NEWDECIMAL':
						if ($key != 'latitude' && $key != 'longitude') {
							if (!isset($_POST[$key])) $_POST[$key] = 0;
							$$key = str_replace(",",".",$_POST[$key]);
						}
				  	break;
				  case 'FLOAT':
					case 'DOUBLE':
						if ($key != 'latitude' && $key != 'longitude') {
							if (isset($_POST[$key])) $$key = str_replace(",",".",$_POST[$key]);
						}
				  	break;
				  default:
				  	if (isset($_POST[$key]) && !is_array($_POST[$key])) $$key = trim(strip_tags(stripslashes(str_replace("'", "&#39;", $_POST[$key]))));
				  	else if (substr($key, 0, 2) === 'c_') $$key = 0;
				  	break;
				}
			}
		}
		$count_fields = $ii--;
	}
}


if (isset($_POST['cmd_login'])){
	$login = addslashes(trim(strip_tags(stripslashes($_POST['login']))));
	$password = addslashes(trim(strip_tags(stripslashes($_POST['password']))));
	
	
	if (check_column('settings_users', 'email_hash')) {
    $settings_ini = get_encryption_ini('settings');
    if ($settings_ini && !empty($settings_ini['pepper'])) {
    	$login_hash = hash_value($login, $settings_ini['pepper']);
    	
			$sql = "SELECT id, password, c_admin, c_editor, c_viewer, c_context FROM settings_users 
							WHERE (username = :login OR email_hash = :login_hash) AND c_active = '1' AND (c_admin = '1' OR c_editor = '1' OR c_viewer = '1') LIMIT 1";
			$result = $conn->prepare($sql);
			$result->bindValue(':login', $login, PDO::PARAM_STR);
			$result->bindValue(':login_hash', $login_hash, PDO::PARAM_STR);
			$result->execute();
    } else {
			$sql = "SELECT id, password, c_admin, c_editor, c_viewer, c_context FROM settings_users 
							WHERE (username = :login OR email = :login) AND c_active = '1' AND (c_admin = '1' OR c_editor = '1' OR c_viewer = '1') LIMIT 1";
			$result = $conn->prepare($sql);
			$result->bindValue(':login', $login, PDO::PARAM_STR);
			$result->execute();
    }
	} else {
		$sql = "SELECT id, password, c_admin, c_editor, c_viewer, c_context FROM settings_users 
						WHERE (username = :login OR email = :login) AND c_active = '1' AND (c_admin = '1' OR c_editor = '1' OR c_viewer = '1') LIMIT 1";
		$result = $conn->prepare($sql);
		$result->bindValue(':login', $login, PDO::PARAM_STR);
		$result->execute();
	}
	
	if ($result->rowCount()){
		while ($arr = $result->fetch()){
			$login_success = false;
	    if ($arr['password'] == md5($password)){
	    	$new_hash = password_hash($password, PASSWORD_DEFAULT);
        
        $sql_upd = "UPDATE settings_users SET password = :password WHERE id = :id";
        $result_upd = $conn->prepare($sql_upd);
        $result_upd->bindValue(':password', $new_hash, PDO::PARAM_STR);
        $result_upd->bindValue(':id', $arr['id'], PDO::PARAM_INT);
        $result_upd->execute();
        
	    	$login_success = true;
	    } else if (password_verify($password, $arr['password'])) {
	    	$login_success = true;
	    }
	    
	    if ($login_success === true){
	      $_SESSION['backend']['id_session'] = $arr['id'];
	      $_SESSION['backend'][$session_name] = true;
	      
	      $_SESSION['backend']['permissions']['admin'] = $arr['c_admin'];
	      $_SESSION['backend']['permissions']['editor'] = $arr['c_editor'];
	      $_SESSION['backend']['permissions']['viewer'] = $arr['c_viewer'];
	      $_SESSION['backend']['settings']['context'] = $arr['c_context'];
	      
	      if ($module == 'login' && !str_contains($url, 'module=') && !str_contains($url, 'backend_module=')){
	      	$sql_tmp = "SELECT title FROM backend_modules 
	      							WHERE c_cms = '1' AND c_active = '1' AND (1 = '1' ";
					if ($_SESSION['backend']['permissions']['admin'] == 1) $sql_tmp .= "OR c_admin = '1' ";
					if ($_SESSION['backend']['permissions']['editor'] == 1) $sql_tmp .= "OR c_editor = '1' ";
					if ($_SESSION['backend']['permissions']['viewer'] == 1) $sql_tmp .= "OR c_viewer = '1'";
					$sql_tmp.=") ORDER BY sortorder ASC LIMIT 1";
	      	$result_tmp = $conn->prepare($sql_tmp);
	      	$result_tmp->execute();
	      	if ($result_tmp->rowCount()){
	      		$arr_tmp = $result_tmp->fetch();
	      		if (check_table($arr_tmp['title'].'_modules')){
			      	$sql_sub = "SELECT title FROM ".$arr_tmp['title']."_modules 
			      							WHERE c_cms = '1' AND (1 = '1' ";
							if ($_SESSION['backend']['permissions']['admin'] == 1) $sql_sub .= "OR c_admin = '1' ";
							if ($_SESSION['backend']['permissions']['editor'] == 1) $sql_sub .= "OR c_editor = '1' ";
							if ($_SESSION['backend']['permissions']['viewer'] == 1) $sql_sub .= "OR c_viewer = '1'";
							$sql_sub.=") ORDER BY sortorder ASC LIMIT 1";
			      	$result_sub = $conn->prepare($sql_sub);
			      	$result_sub->execute();
			      	if ($result_sub->rowCount()){
			      		$arr_sub = $result_sub->fetch();
	      				$url = "index.php?module=".$arr_sub['title']."&backend_module=".$arr_tmp['title'];
			      	}
	      		} else {
	      			$url = "index.php?module=".$arr_tmp['title']."&backend_module=".$arr_tmp['title'];
	      		}
	      	}
	      }
	      
	      header("Location: ".$url);
	      exit();
			} else {
	  		header("Location: ".str_replace('&login_error=1', '', $url)."&login_error=1");
			}
		}
	} else {
	  header("Location: ".str_replace('&login_error=1', '', $url)."&login_error=1");
	}
}


if (isset($multi_module) && $multi_module) $module = $old_module;

if (!isset($admin_settings['module'][$module.'_filter'])){
	$admin_settings['module'][$module.'_filter'] = 100;
}


if (isset($_SESSION['backend']) && $_SESSION['backend']){
	if (isset($_SESSION['backend']['toggle']) && $_SESSION['backend']['toggle']){
		if (isset($_SESSION['backend']['toggle'][$backend_module.'_'.$module]) && $_SESSION['backend']['toggle'][$backend_module.'_'.$module]){
			$_SESSION['backend']['toggle_filter'] = $_SESSION['backend']['toggle'][$backend_module.'_'.$module];
		} else {
			$_SESSION['backend']['toggle_filter'] = NULL;
		}
	} else {
		$_SESSION['backend']['toggle_filter'] = NULL;
	}
} else {
	$_SESSION['backend']['toggle_filter'] = NULL;
}

if (isset($_SESSION['backend']['permissions']['monitor']) && !isset($_SESSION['backend']['permissions']['viewer'])) {
	$_SESSION['backend']['permissions']['viewer'] = $_SESSION['backend']['permissions']['monitor'];
}