<?php
///////////////////////////////////////////////////////////////////////////////////////////////////
#  Author:   Anil Kumar
#  Version:	 1.0
#  Date:     10-July-2013
#  Purpose:  
#  Requires: PHP 5.2+, MySQL 4.1.3+
#  Last Modified: Sep 13, 2013
#  Usage
#
#  		require_once("pdo/cppdo.php");
#		require_once("base.php");
#		require_once("auth/basic.auth.php");
#
#  Copyright 2013, Softnik Technologies.
///////////////////////////////////////////////////////////////////////////////////////////////////
	
require_once("lib/php/config.check.php");
require_once("config.php");
require_once("lib/php/base.php");

/////////////////////////////////////////////////////////////////////////////////////////////////////////

$valid_auth_columns = array('id', 'name', 'display_name', 'password', 'email', 'active', 'readwrite', 'full_name', 'last_sign_in_stamp', 'added_on');

/////////////////////////////////////////////////////////////////////////////////////////////////////////

# Only admin users can use this script.
# If user authentication is disabled, everyone is an admin user!

session_start();
check_authentication_login();
if(is_admin_user() == false)
{
	header("Location: " . get_base_path());
	exit;
}
doSessionSwipeIn();

/////////////////////////////////////////////////////////////////////////////////////////////////////////

function get_base_dir()
{
	return realpath(dirname(__FILE__)) . DIRECTORY_SEPARATOR;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////

function get_cid_from_category($category)
{
	$category = trim($category);
	if($category != "")
	{
		global $db_config_category_table;
		$sql = "select CategoryID from " . $db_config_category_table . " where CategoryName = '$category'";
		$idresults = mysql_query($sql) or die ("Error reading from database");  
		$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
		if(count($row) == 1 && isset($row['CategoryID']))
			return $row['CategoryID'];
	}
	return 0;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////

if(isset($_REQUEST['set']))
{
	require_once("lib/php/pdo/cppdo.php");
	require_once("lib/php/auth/basic.auth.php");
	global $db_config_host, $db_config_database, $db_config_username, $db_config_password, $db_table_prefix;
	
	$pdo = new cpUserManager($db_table_prefix);
	$dbh = $pdo->openMySQL($db_config_host, $db_config_database, $db_config_username, $db_config_password);
	if($dbh)
	{
		$pdo->initTables();
		if(isset($_REQUEST['id']))
		{
			$uid = strip_tags(trim($_REQUEST['id']));
			if(isset($_REQUEST['perms']))
			{
				$permissions = array();
				$perms = $_REQUEST['perms'];
				$perms = str_replace(array("\r","\n"), ",", trim($perms));
				$cats = explode(",", $perms);
				foreach($cats as $cat)
				{
					$c = strip_tags(trim($cat));
					if($c !== "")
						$permissions[] = $c;
				}
				$pdo->setCategoriesForUser($uid, $permissions);
			}
			if(isset($_REQUEST['admin']))
			{
				$admin = false;
				$sadmin = simple_sanitize($_REQUEST['admin']);
				if($sadmin == "yes" || $sadmin == "true")
					$admin = true;
				if($admin)
					$pdo->addUserToGroup($uid, "Admin");
				else
					$pdo->removeUserFromGroup($uid, "Admin");
			}
			$userInfo = $pdo->getUserInfo($uid);
			if($userInfo !== false)
			{
				if(is_array($userInfo))
				{
					$perms = $userInfo['permissions'];
					$categories = "";
					if(is_array($perms))
					{
						foreach($perms as $cat)
						{
							$categories .= $cat['name'] . ", ";
						}
					}
					if($categories == "")
						$categories = "-";
					$userInfo['categories'] = $categories;
					echo json_encode($userInfo);
					//logToFile("php.log", json_encode($userInfo));
				}
			}
		}
	}
	//$elog = $pdo->getLog();
	//logToFile("php.log", $elog);
	exit;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////

if(isset($_REQUEST['info']))
{
	require_once("lib/php/pdo/cppdo.php");
	require_once("lib/php/auth/basic.auth.php");
	global $db_config_host, $db_config_database, $db_config_username, $db_config_password, $db_table_prefix;
	
	$pdo = new cpUserManager($db_table_prefix);
	$dbh = $pdo->openMySQL($db_config_host, $db_config_database, $db_config_username, $db_config_password);
	if($dbh)
	{
		$pdo->initTables();
		if(isset($_REQUEST['id']))
		{
			$uid = intval(strip_tags(trim($_REQUEST['id'])));
			$userInfo = $pdo->getUserInfo($uid);
			if($userInfo !== false)
			{
				if(is_array($userInfo))
				{
					$perms = $userInfo['permissions'];
					$categories = "";
					if(is_array($perms))
					{
						foreach($perms as $cat)
						{
							$categories .= $cat['name'] . ", ";
						}
					}
					if($categories == "")
						$categories = "-";
					$userInfo['categories'] = $categories;
					echo json_encode($userInfo);
				}
			}
		}
	}
	//$pdo->showLog();
	exit;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////

if(isset($_REQUEST['edit']))
{
	require_once("lib/php/pdo/cppdo.php");
	require_once("lib/php/auth/basic.auth.php");
	
	global $db_config_host, $db_config_database, $db_config_username, $db_config_password, $db_table_prefix;
	
	$pdo = new cpUserManager($db_table_prefix);
	$dbh = $pdo->openMySQL($db_config_host, $db_config_database, $db_config_username, $db_config_password);
	if($dbh)
	{
		$pdo->initTables();
		
		if(isset($_REQUEST['oper']))
		{
			$opmode = $_REQUEST['oper'];
			if($opmode == "edit")
			{
				if(isset($_REQUEST['id']))
				{
					$uid = strip_tags(trim($_REQUEST['id']));
					if($_REQUEST['name'])
					{
						$name = strip_tags(trim($_REQUEST['name']));
						//$pdo->changeUserIDName($uid, $name);
					}
					if($_REQUEST['password'])
					{
						$password = strip_tags(trim($_REQUEST['password']));
						if($password != "##########")
							$pdo->resetUserIDPassword($uid, $password);
					}
					if($_REQUEST['display_name'])
					{
						$name = strip_tags(trim($_REQUEST['display_name']));
						$pdo->changeUserIDDisplayName($uid, $name);
					}
					$active = 0;
					if(simple_sanitize($_REQUEST['active']) == "yes")
						$active = 1;
					$pdo->changeUserIDStatus($uid, $active);
					$readwrite = 0;
					$access = simple_sanitize($_REQUEST['readwrite']);
					if($access == 0 || $access == 1 || $access == 2 || $access == 3)
						$readwrite = $access;
					$pdo->changeUserIDReadWrite($uid, $readwrite);
				}
			}
			else if($opmode == "add")
			{
				if($_REQUEST['name'] && $_REQUEST['password'])
				{
					$name = strip_tags(trim($_REQUEST['name']));
					$password = strip_tags(trim($_REQUEST['password']));
					
					$display_name = "";
					if(isset($_REQUEST['display_name']))
						$display_name = strip_tags(trim($_REQUEST['display_name']));
					
					$active = 0;
					if(isset($_REQUEST['active']))
					{
						if(simple_sanitize($_REQUEST['active']) == "yes")
							$active = 1;
					}
					
					$readwrite = 0;
					if(isset($_REQUEST['readwrite']))
					{
						$access = simple_sanitize($_REQUEST['readwrite']);
						if($access == 0 || $access == 1 || $access == 2 || $access == 3)
							$readwrite = $access;
					}
					$status = $pdo->createUser($name, $display_name, $password, "New User", $active, $readwrite);
				}
			}
			else if($opmode == "del")
			{
				if(isset($_REQUEST['id']))
				{
					$uid = strip_tags(trim($_REQUEST['id']));
					$status = $pdo->deleteUserID($uid);
				}
			}
		}
	}
	
	exit;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////

if(isset($_REQUEST['grid']))
{
	connect_to_mysql_and_select_db();

	$page = get_numeric_request_variable('page', 1);     // get the requested page
	$limit = get_numeric_request_variable('rows', 20); // get how many rows we want to have into the grid
	$sidx = get_indexed_request_variable('sidx', 'id', $valid_auth_columns); // get index row - i.e. user click to sort	
	$sord = get_indexed_request_variable('sord', 'asc', array('asc', 'desc')); // get the direction

	global $db_config_domain_table, $db_config_catconnection_table, $db_config_user_table;

	$sqlCount = "SELECT COUNT(DISTINCT a.id) AS count FROM  $db_config_user_table a ";
	
	$result = mysql_query($sqlCount) or die("Connection Error: " . mysql_error());
	$row = mysql_fetch_array($result,MYSQL_ASSOC);
	$count = $row['count'];

	if( $count >0 ) {
		$total_pages = ceil($count/$limit);
	} else {
		$total_pages = 0;
	}
	if ($page > $total_pages) $page=$total_pages;
	$start = $limit*$page - $limit; // do not put $limit*($page - 1)
	
	$SQL = "SELECT DISTINCT a.id, a.name, a.display_name, a.password, a.last_sign_in_stamp, a.active, a.readwrite FROM $db_config_user_table a ";
	$SQL .= " ORDER BY a.$sidx $sord";
	if($count > 0)
		$SQL .= " LIMIT $start , $limit";
	
	$result = mysql_query( $SQL ) or die("Couldn't execute query.".mysql_error());

	$responce = new stdClass();
	$responce->page = $page;
	$responce->total = $total_pages;
	$responce->records = $count;
	$i=0;
	while($row = mysql_fetch_array($result,MYSQL_ASSOC)) 
	{
		$row['password'] = "##########";
		$responce->rows[$i]['id']=$row['id'];
		$responce->rows[$i]['cell']=array($row['name'],$row['password'],$row['display_name'],$row['last_sign_in_stamp'],$row['active'],$row['readwrite']);
		$i++;
	}        
	echo json_encode($responce);

	exit;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////

connect_to_mysql_and_select_db();
global $db_config_category_table;

$sql = "SELECT * FROM  " . $db_config_category_table . " WHERE CategoryID != 1";
$result = mysql_query($sql) or die("Connection Error: " . mysql_error());

$allcatnames = "<h4>All Category Names</h4><ul class=\"bullets\">";
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) 
{
	$allcatnames .= "<li>" . $row['CategoryName'] . "</li>";
}
$allcatnames .= "</ul>";

/////////////////////////////////////////////////////////////////////////////////////////////////////////
	
	$jqtheme = get_theme_name("");
	$title = "";
	if($title == "")
		$title = "Domain Portfolio Manager - User Administration";
	$panesjs = "cfgpanes.js";

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
		<title><?php echo $title; ?></title>
		<meta http-equiv="Content-Language" content="en">
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<link rel="shortcut icon" type="image/x-icon" href="lib/css/img/favicon.ico">
		
		<link type="text/css" href="lib/css/jqueryui/<?php echo $jqtheme; ?>/jquery-ui-1.8.7.custom.css" rel="stylesheet">
		<link type="text/css" href="lib/css/jqueryui/<?php echo $jqtheme; ?>/splitter.1.51.css" rel="stylesheet" media="screen">
		<link type="text/css" href="lib/css/jqueryui/splitter.1.51.css" rel="stylesheet" media="screen">
		<link type="text/css" href="lib/css/jqueryui/ui.jqgrid.css" rel="stylesheet" media="screen">

		<script type="text/javascript" src="lib/js/jquery/jquery-1.5.1.min.js"></script>
		<script type="text/javascript" src="lib/js/jquery/jquery.cookie.min.js"></script>
		<script type="text/javascript" src="lib/js/jquery/jquery-ui-1.8.7.noeffects.min.js"></script>
		<script type="text/javascript" src="lib/js/jquery/splitter.1.51.min.js"></script>
		<script type="text/javascript" src="lib/js/jquery/i18n/grid.locale-en.js"></script>
		<script type="text/javascript" src="lib/js/jquery/jquery.jqGrid.3.8.2.min.js"></script>
		
		<link type="text/css" href="lib/css/default.css" rel="stylesheet" media="all">
		<link type="text/css" href="lib/css/<?php echo $jqtheme; ?>.css" rel="stylesheet" media="all">
		<script type="text/javascript" src="lib/js/buttons.js"></script>
		<style>
			body {min-width: 960px;}
			label 
			{
				display: block;
				width: 150px;
				float: left;
				padding-top:2px;
				font-family: Trebuchet MS,Verdana,Arial,sans-serif; 
			}
			#usertoolbox
			{
				height: 250px;
				min-height: 250px;	
			}
			#usergrid
			{
				height: 550px;
			}
			button {height: 30px;}
			ul.bullets
			{
			  list-style: none;
			  margin: 0px;
			  padding: 0px;
			  padding-top: 10px;
			  margin-bottom: 24px;
			}
			.controlbox 
			{
				font-family:Tahoma,Verdana,Arial;
				font-size:90%;
				width:400px;float:left;position: relative; display:inline; margin-right:20px; margin-left:20px;
			}
			.userbox 
			{
				font-family:Tahoma,Verdana,Arial;
				font-size:85%;
				width:250px;float:left;position: relative; display:inline; margin-right:20px;
			}
			.infobox
			{
				font-family:Tahoma,Verdana,Arial;
				width:250px; font-size:85%; margin-left:20px; padding-top:10px; float:left; position: relative; display:inline; margin-right:20px;
			}
			.textalignleft { text-align:left  !important; }
			.textalignleft div { padding-left: 5px; }
			#ui_user_data_submit {font-size: 85%;}
		</style>
		<script type="text/javascript">
		var current_user_name = "";
		function HandleEnterKey(e, submitid)
		{
			var keycode = (e.keyCode ? e.keyCode : (e.which ? e.which : e.charCode));
			if (keycode == 13)
			{
				if(submitid != "")
					$("#" + submitid).click();
				return false;
			}
			return true;
		}
		function reload_grid(dnload, onlynames)
		{
			var durl = "admin.php?grid";
			jQuery("#user_table").setGridParam({url:durl});
			$("#user_table").trigger("reloadGrid"); 
		}
		function string_length_check(value, colname) 
		{
			len = value.length;
			if (len < 6) 
			   return [false, colname + ": Please enter atleast 6 characters."];
			else 
			   return [true,""];
		}
		$(function()
		{
			jQuery("#user_table").jqGrid({
			url:'admin.php?grid',
			editurl: 'admin.php?edit',
			datatype: "json",
			altRows:true,
			altclass: "gridAltRowClass",
			colNames:['User Name','Password','Display Name','Last Login At', 'Active', 'Access'],
			colModel:[
				{name:'name',index:'name', width:90, sortable:true, editable:true,editrules:{custom:true, custom_func:string_length_check}},
				{name:'password',index:'password', width:100,editable:true,edittype:"password",editrules:{custom:true, custom_func:string_length_check}},
				{name:'display_name',index:'display_name', sortable:true,width:150,editable:true},
				{name:'last_sign_in_stamp',index:'last_sign_in_stamp', sortable:true,width:140,sorttype:'date',formatter:'date', formatoptions:{srcformat:"Y-m-d H:i:s",newformat:"d-M-Y H:i:s"}},
				{name:'active',index:'active', width:40, sortable:true,formatter:'checkbox',editable:true,edittype:"checkbox",editoptions:{value:"Yes:No"}},
				{name:'readwrite',index:'readwrite', width:60, sortable:true, editable:true,formatter:"select",edittype:"select",editoptions:{value:{0:'View',1:'View+Edit+Add+Delete',2:'View+Edit',3:'View+Edit+Add'}}}
			],
			rownumbers: true,
			rowNum:10,
			rowList:[10,20,50],
			height: '300',
			width: 950,
			pager: '#user_pager',
			sortname: 'id',
			viewrecords: true,
			sortorder: "desc",
			multiselect: false,
			multiboxonly:false,
			shrinkToFit: true,
			onSelectRow: function(ids) 	{showUserData(ids);},
			scrollOffset: 36,
			caption: "User Table"
			});
			jQuery("#user_table").jqGrid('navGrid','#user_pager',{search:false,edit:true,add:true,del:true
			},
			{ // edit option
				  beforeShowForm: function(form) { $('#tr_name', form).hide(); }
			  },
			  { // add option
				  beforeShowForm: function(form) { $('#tr_name', form).show(); }
			  }
			);
			
			jQuery("#user_table").jqGrid('setLabel', 'name', '', 'textalignleft');
			jQuery("#user_table").jqGrid('setLabel', 'password', '', 'textalignleft');
			jQuery("#user_table").jqGrid('setLabel', 'display_name', '', 'textalignleft');
			jQuery("#user_table").jqGrid('setLabel', 'last_sign_in_stamp', '', 'textalignleft');
			jQuery("#user_table").jqGrid('setLabel', 'active', '', 'textalignleft');
			jQuery("#user_table").jqGrid('setLabel', 'readwrite', '', 'textalignleft');
					
			$("#UserViewPane").splitter({
				splitHorizontal: true,
				outline: true,
				sizeTop: true,
				anchorToWindow: true,
				accessKey: "I"
			});
			
			$(window).bind('resize', function() {fixGridSizes();}).trigger('resize');
			
			$("#UserViewPane").bind('resize', function() {fixGridSizes();}).trigger('resize');
			
			$('#user_group_button').change(function () 
			{
				setPermissions();
			});
			
			$("#ui_user_data_submit").button().click(function() 
			{
				setPermissions();
			});
		});
		
		function setPermissions()
		{
			ids = $('#user_table').jqGrid ('getGridParam', 'selrow');
			if(ids == null || ids == 0)
				;
			else
			{
				var user = jQuery("#user_table").getCell(ids, "name"); 
				if (user.toLowerCase() == current_user_name.toLowerCase() && user != "")
				{
					var checked = $('#user_group_button').is(":checked")
					var datastr = 'admin=' + checked + "&perms=" + $("#cat_names").val();
					datastr += "&id=" + ids;
					var turl = "admin.php?set";
					var request = $.ajax({type: "POST",	url: turl, data: datastr});
					request.done(function(msg) 
					{  
						var x = jQuery.parseJSON(msg);
						if(x.admin)
							$('#user_group_button').attr('checked','checked');
						else
							$('#user_group_button').removeAttr('checked');
						$('#cat_names').html(x.categories);
					});
					request.fail(function(jqXHR, textStatus) {});
				}
			}
		}
		
		function fixGridSizes()
		{
			$("#user_table").setGridWidth($(window).width()-20, true);
			$("#user_table").setGridHeight($("#usergrid").height()-100, true);
		}
		
		function showUserData(ids)
		{
			if(ids == null || ids == 0)
				;
			else
			{
				var user = jQuery("#user_table").getCell(ids, "name"); 
				current_user_name = user;
				jQuery("#userhead").html("<h3>" + user + "</h3>");
				var turl = "admin.php" + "?info&id=" + ids;
				var request = $.ajax({type: "POST",	url: turl});
				request.done(function(msg) 
				{  
					var x = jQuery.parseJSON(msg);
					if(x.admin)
						$('#user_group_button').attr('checked','checked');
					else
						$('#user_group_button').removeAttr('checked');
					//$('#cat_names').html(x.categories);
					$("textarea#cat_names").val(x.categories);
					//alert(x.categories);
				});
				request.fail(function(jqXHR, textStatus) {});
			}
		}
		</script>
<?php
		if(get_main_logo_image() != "")
			echo "\t\t<style> .mainlogo {background-image: url('" . get_main_logo_image() . "');}</style>\n";
?>
</head>
<body>
	<div id="header">
		<div class="mainlogo">&nbsp;</div>
		<div class="navbar">
			<button id="menu"></button>
			&nbsp;&nbsp;
			<button id="pfolio"></button>
			&nbsp;&nbsp;
		<?php
			if(is_admin_user())
			{
		?>
				<button id="subdomains"></button>
				<button id="report"></button>
				<button id="config"></button>
				<button id="appsetup"></button>
		<?php
			}
			show_link_buttons();
			if(is_user_auth_enabled())
			{
		?>
				&nbsp;&nbsp;
				<button id="logout"></button>
		<?php
			}
		?>
		</div>
		<div class="clear">&nbsp;</div>
	</div>
	
	<div id="UserViewPane">
		<div id="usergrid" style="padding:10px;">
			<table id="user_table"></table>
			<div id="user_pager"></div>
		</div>
		<div id="usertoolbox" style="margin:10px;">
			<div class="toolcontainer">
				<div class="userbox" style="text-align:right">
					<p id="userhead">Please select a user from the list above.</p>
					<div class="dotline"></div>
					<p><input type="checkbox" id="user_group_button">&nbsp;Administrator</button></p>
					<p><b>Important:</b>&nbsp;To enable user authentication you have to 
					specify a super-admin username and password in the 'Basic App Setup' (creating users here is not enough).
					For more instructions please see the 'Authentication' tab in 'Basic App Setup'.</p>
				</div>
				<div class="controlbox">
					<p>Please type in the categories (comma separated) the user can view. Checking the <b>Administrator</b>
					box at left will allow the user to view &amp; modify all categories.</p>
					<textarea id="cat_names" rows="6" style="width:400px;"></textarea></p>
					<p><button id="ui_user_data_submit" style="width:80px;">Update</button>
					
				</div>
				<div class="infobox" style="overflow:auto; height:200px;">
					<?php echo $allcatnames; ?>
				</div>
				<div style="clear:both;"></div>
			</div>
		</div>
	</div>
</body>
</html>
<?php
?>
