<?php
/* $Id: usermanager.php,v 1.77 2003/12/03 17:34:05 k-fish Exp $ */

$myEnv["module"] = "admin";
$myEnv['stdsmenu'] = false;
$myEnv["output"] = "html";
		
include("../../config.inc.php");
include(INCLUDEPATH . "container.inc.php");

// adding file revision into global array
revisionInit("\$Revision: 1.77 $", __FILE__);

// =================================================
//	              check data
// =================================================
if(isset($_POST["create"]) or isset($_POST["edit"])) {

    $_POST["firstname"] = trim($_POST["firstname"]);
    $_POST["lastname"] = trim($_POST["lastname"]);

    $_POST["usernameform"] = strtolower(str_replace(array("#","@"," ",",",".","/","\\","'","\""),"",trim($_POST["usernameform"])));
    $errormsg = '';

    if(isset($_POST["create"])) {
	$gname = $conn->QMagic($_POST["usernameform"]);

	$sql = "SELECT username FROM mgw_users WHERE username = ".$gname;
	if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	
	if($res->RecordCount() > 0) { $errormsg .= Lang::getLanguageString("err_duplicateuser").'<br />';}
	if($_POST["usernameform"]=="") { $errormsg .= Lang::getLanguageString("err_nousername").'<br />';}
	if(ereg('[^a-z0-9]',$_POST["usernameform"])) { $errormsg .= Lang::getLanguageString("err_nousername").'<br />';}

	$errorsrc='create';
    }
    else{
	$errorsrc='edit';
    }

    if($_POST["firstname"] == "") $errormsg .= Lang::getLanguageString("err_nofirstname").'<br />';
    if($_POST["lastname"] == "") $errormsg .= Lang::getLanguageString("err_nolastname").'<br />';
    if((strlen($_POST["pw"]) < 6) && (strlen($_POST["pw"]) > 0)) {
	$errormsg .= Lang::getLanguageString("err_pwtooshort").'<br />';
    }
    if($_POST["pw"] <> $_POST["pwagain"]) $errormsg .= Lang::getLanguageString("err_pwsnotequal");

    if($errormsg != '') {
	$smarty->assign("errormsg",$errormsg);
    }
    else $errorsrc=false;
}

// =================================================
//	              create entry
// =================================================
	 
if (isset($_POST["create"]) && !$errorsrc){
	queryRights2("root_modules_admin_usermanager_createusers");

    $id = mgw_genID('mgw__seq_users', 5);

    $usernameform = $conn->QMagic($_POST["usernameform"]);
    $lastname = $conn->QMagic($_POST["lastname"]);
    $firstname = $conn->QMagic($_POST["firstname"]);
    $occupation = $conn->QMagic($_POST["occupation"]);
    $workloc = $conn->QMagic($_POST["workloc"]);
    $sex = $conn->QMagic($_POST["sex"]);
    $telephone = $conn->QMagic($_POST["telephone"]);
    $email = $conn->QMagic($_POST["email"]);
    $mobil = $conn->QMagic($_POST["mobil"]);
    $language = $conn->QMagic($_POST["language"]);

    $bdayts = $_POST["birthdayYear"]."-".$_POST["birthdayMonth"]."-".$_POST["birthdayDay"]." 00:00:00";
    $birthday=$conn->DBTimeStamp($bdayts);

    // md5 the password
    $md5pw = md5($_POST["pw"]);
	
    $sql="INSERT INTO mgw_users (id, username, lastname, firstname, occupation, workloc, birthday, sex, mobil, telephone, email, skintheme, pw, lang, lu_user, lu_date, lastin) VALUES ($id, $usernameform, $lastname, $firstname, $occupation, $workloc, $birthday, $sex, $mobil, $telephone, $email, 'Morelogs_Silver.css', ".$conn->QMagic($md5pw).", $language, '".$_SESSION["MGW"]->userid."', ".$conn->DBTimeStamp(time()).", ".$conn->DBTimeStamp(time()).")";
    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	
    $sql = "INSERT INTO mgw_groups_members (groupid, userid, lu_user, lu_date) VALUES (".(int) $_POST["group"].", $id, ".$_SESSION["MGW"]->userid.", ".$conn->DBTimeStamp(time()).")";
    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
}

// =================================================
//	              create entry (batch)
// =================================================
/* creates users from a batch file. CSV format, fields as follows.
 * delimiter is comma, fields enclosed in double quotes
 *
 * "usernameform","lastname","firstname","occupation","workloc","birthday","sex","mobil","telephone","email","md5pw"
 */	 
if (isset($_POST["batchcreate"])){
	queryRights2("root_modules_admin_usermanager_createusersfromfile");

    if (is_uploaded_file($_FILES['batchfile']['tmp_name'])) {
	$fp = fopen($_FILES['batchfile']['tmp_name'],"r");
	while ($data = fgetcsv ($fp, 500, ",")) {
	    $id = $conn->GenID('mgw__seq_users', 5);
	    $usernameform = $conn->quote($data[0]);
	    $lastname = $conn->quote($data[1]);
	    $firstname = $conn->quote($data[2]);
	    $occupation = $conn->quote($data[3]);
	    $workloc = $conn->quote($data[4]);
	    $birthday = $conn->quote($data[5]);
	    $sex = $conn->quote($data[6]);
	    $mobil = $conn->quote($data[7]);
	    $telephone = $conn->quote($data[8]);
	    $email = $conn->quote($data[9]);
	    $md5pw = md5($data[10]);

	    if(!empty($data[0]) && !empty($data[10])){
		$sql="INSERT INTO mgw_users (id, username, lastname, firstname, occupation, workloc, birthday, sex, mobil, telephone, email, skintheme, pw, lang,lu_user, lu_date, lastin) VALUES ($id, $usernameform, $lastname, $firstname, $occupation, $workloc, $birthday, $sex, $mobil, $telephone, $email, 'Morelogs_Silver.css', '$md5pw', '$language', '".$_SESSION["MGW"]->userid."', ".$conn->DBTimeStamp(time())."', ".$conn->DBTimeStamp(time()).")";
		if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

		$sql = "INSERT INTO mgw_groups_members (groupid, userid, lu_user, lu_date) VALUES (".(int) $_POST["group"].", $id, ".$_SESSION["MGW"]->userid.", ".$conn->DBTimeStamp(time()).")";
		if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	    }
 	}
	fclose ($fp);
    }
}

// =================================================
//	              edit entry
// =================================================
	 
if (isset($_POST["edit"]) && !$errorsrc){
	queryRights2("root_modules_admin_usermanager_modifyusers");

    $id = (int) $_POST["id"];
    $usernameform = $conn->QMagic($_POST["usernameform"]);
    $lastname = $conn->QMagic($_POST["lastname"]);
    $firstname = $conn->QMagic($_POST["firstname"]);
    $occupation = $conn->quote($_POST["occupation"]);
    $workloc = $conn->quote($_POST["workloc"]);
    $sex = $conn->quote($_POST["sex"]);
    $email = $conn->QMagic($_POST["email"]);
    $mobil = $conn->QMagic($_POST["mobil"]);
    $telephone = $conn->quote($_POST["telephone"]);	
    $language = $conn->QMagic($_POST["language"]);

    $bdayts = $_POST["birthdayYear"]."-".$_POST["birthdayMonth"]."-".$_POST["birthdayDay"]." 00:00:00";
    $birthday=$conn->DBTimeStamp($bdayts);

    if(strlen($_POST["pw"]) >= 6 && ($_POST["pw"] == $_POST["pwagain"])) {
	$sql="UPDATE mgw_users SET lastname=$lastname, firstname=$firstname, occupation=$occupation, workloc=$workloc, birthday=$birthday, sex=$sex, mobil=$mobil, telephone=$telephone, email=$email, pw=".$conn->QMagic(md5($_POST["pw"])).", lang=$language, lu_user=". $_SESSION["MGW"]->userid .", lu_date=". $conn->DBTimeStamp(time()). " WHERE id=$id";
    }
    else {
	$sql="UPDATE mgw_users SET lastname=$lastname, firstname=$firstname, occupation=$occupation, workloc=$workloc, birthday=$birthday, sex=$sex, mobil=$mobil, telephone=$telephone, email=$email, lang=$language, lu_user=".$_SESSION["MGW"]->userid .", lu_date=". $conn->DBTimeStamp(time()). " WHERE id=$id";
    }
    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
}
   
// =================================================
//	              delete user
// =================================================

if (isset($_GET["action"]) && $_GET["action"] == "delete"){
	queryRights2("root_modules_admin_usermanager_deleteusers");
	
    // show confirmation screen if it wasnt there so far
    if(!isset($_POST["confirmation_no"]) and !isset($_POST["confirmation_yes"])) {
	$sql = "SELECT * FROM mgw_users WHERE id='".(int) $_GET["id"]."'";
	if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	$row = $res->FetchRow();

	$smarty->assign("menuid", "1");
	$smarty->assign("suclass", "submit");
	$smarty->assign("itemid", (int) $_GET["id"]);
	$smarty->assign("parms", $_SERVER["QUERY_STRING"]);
	$smarty->assign("reallydeleteitem", Lang::getLanguageString("reallydeluser"));
	$smarty->assign("deleteheader", Lang::getLanguageString("deleteuserh"));
	$smarty->assign("deletedetail2", $row["lastname"].", " .$row["firstname"]);
	$smarty->assign("deletedetail1", $row["username"]);

	$smarty->display($appconf["gentemplates"] ."/delete_item.tpl");
	exit();
    }

    // delete only when user said so
    if(isset($_POST["confirmation_yes"])) {
	$sql = "DELETE FROM mgw_users WHERE id='".(int) $_POST["itemid"]."'";
	if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	$sql = "DELETE FROM mgw_groups_members WHERE userid='".(int) $_POST["itemid"]."'";
	if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    }
}

// =================================================
//	              New Item Formular
// =================================================
if ((isset($_GET["action"]) && $_GET["action"] == "newform") || (isset($errorsrc) && $errorsrc == 'create')) {
	queryRights2("root_modules_admin_usermanager_createusers");

    include(INCLUDEPATH . "mSelectBox.class.php");

    if(isset($errorsrc) && $errorsrc == 'create'){
	$row['username'] = $_POST['usernameform'];
	$row['firstname'] = $_POST['firstname'];
	$row['lastname'] = $_POST['lastname'];
	$occupation = $_POST['occupation'];
	$workloc = $_POST['workloc'];
	$row['sex'] = $_POST['sex'];
	$row['mobil'] = $_POST['mobil'];
	$row['telephone'] = $_POST['telephone'];
	$row['email'] = $_POST['email'];
	$smarty->assign('td', $row);

	$lang = $_POST['language'];
	$group = $_POST['group'];
	
	$bdayts = $_POST["birthdayYear"]."-".$_POST["birthdayMonth"]."-".$_POST["birthdayDay"]." 00:00:00";
	$smarty->assign('bdayts', $conn->DBTimeStamp($bdayts));
    }
    else{
	$lang = 'login';
	$group = 50001;
	$occupation = '';
	$workloc = '';
    }

    $sb5 = new mSelectBox("language");
    $sb5->setContentType("sql");
    $sb5->setSQLvalue("langcode");
    $sb5->setSQLcontent("description");
    $sb5->addContent("SELECT * FROM mgw_languages");
    $sb5->addOption("login",Lang::getLanguageString("login_select"));
    $smarty->assign("langbox", $sb5->draw($lang));

    $sb6 = new mSelectBox("group");
    $sb6->setContentType("sql");
    $sb6->setSQLvalue("id");
    $sb6->setSQLcontent("name");
    $sb6->addContent("SELECT * FROM mgw_groups");
    $smarty->assign("groupbox", $sb6->draw($group));
    
    $sb7 = new mSelectBox("occupation");
    $sb7->setContentType("sql");
    $sb7->setSQLvalue("id");
    $sb7->setSQLcontent("name");
    $sb7->addContent("SELECT id,name FROM mgw_occupations");
    $smarty->assign("occupationbox", $sb7->draw($occupation));
    
    $sb8 = new mSelectBox("workloc");
    $sb8->setContentType("sql");
    $sb8->setSQLvalue("id");
    $sb8->setSQLcontent("name");
    $sb8->addContent("SELECT id,name FROM mgw_workplace");
    $smarty->assign("worklocbox", $sb8->draw($workloc));

    $smarty->assign("mode","new");
    $smarty->assign("suname","create");
    $smarty->assign("suclass","submit");

    $smarty->display('usermanager_edit.tpl');
    exit();
}
 
// =================================================
//	              New Item Formular (Batch)
// =================================================
if (isset($_GET["action"]) && $_GET["action"] == "newformmultiple") {
	queryRights2("root_modules_admin_usermanager_createusersfromfile");

    include(INCLUDEPATH . "mSelectBox.class.php");
    $smarty->assign("suname","create");
    $smarty->assign("suclass","submit");

    $sb5 = new mSelectBox("language");
    $sb5->setContentType("sql");
    $sb5->setSQLvalue("langcode");
    $sb5->setSQLcontent("description");
    $sb5->addContent("SELECT * FROM mgw_languages");
    $sb5->addOption("login",Lang::getLanguageString("login_select"),"pre");
    $smarty->assign("langbox", $sb5->draw("login"));

    $sb6 = new mSelectBox("group");
    $sb6->setContentType("sql");
    $sb6->setSQLvalue("id");
    $sb6->setSQLcontent("name");
    $sb6->addContent("SELECT * FROM mgw_groups");
    $smarty->assign("groupbox", $sb6->draw(50001));

    $smarty->assign("mode","new");

    $smarty->display('usermanager_batch.tpl');
    exit();
}
 
// =================================================
//	              Detail Ansicht
// =================================================
if (isset($_GET["action"]) && $_GET["action"] == "details") {
    $smarty->display("usermanager_details.tpl");
    exit();
}


// =================================================
//	              Edit Item Formular
// =================================================
if ((isset($_GET["action"]) && $_GET["action"] == "editform") || (isset($errorsrc) && $errorsrc == 'edit')) {
	queryRights2("root_modules_admin_usermanager_modifyusers");

    include(INCLUDEPATH . "mSelectBox.class.php");

    if(isset($_GET["action"]) && $_GET["action"] == "editform"){
	$id = (int)$_GET["id"];

	$sql = "SELECT * FROM mgw_users WHERE id=".$id;
	if(($row = $conn->GetRow($sql))===false) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	$smarty->assign('bdayts', $conn->UnixDate($row['birthday']));
    }
    else{
	$id = (int)$_POST["id"];

	$row['id'] = $id;
	$row['username'] = $_POST['usernameform'];
	$row['firstname'] = $_POST['firstname'];
	$row['lastname'] = $_POST['lastname'];
	$row['occupation'] = $_POST['occupation'];
	$row['workplace'] = $_POST['workloc'];
	$row['sex'] = $_POST['sex'];
	$row['mobil'] = $_POST['mobil'];
	$row['telephone'] = $_POST['telephone'];
	$row['email'] = $_POST['email'];
	$row['lang'] = $_POST['language'];
	$row['group'] = $_POST['group'];

	$bdayts = $_POST["birthdayYear"]."-".$_POST["birthdayMonth"]."-".$_POST["birthdayDay"]." 00:00:00";
	$smarty->assign('bdayts', $conn->UnixDate($bdayts));
    }

    $sb5 = new mSelectBox("language");
    $sb5->setContentType("sql");
    $sb5->setSQLvalue("langcode");
    $sb5->setSQLcontent("description");
    $sb5->addOption("login",Lang::getLanguageString("login_select"));
    $sb5->addContent("SELECT langcode,description FROM mgw_languages ORDER BY description");
    $smarty->assign("langbox", $sb5->draw($row["lang"]));
    
    $sb6 = new mSelectBox("occupation");
    $sb6->setContentType("sql");
    $sb6->setSQLvalue("id");
    $sb6->setSQLcontent("name");
    $sb6->addContent("SELECT id,name FROM mgw_occupations");
    $smarty->assign("occupationbox", $sb6->draw($row['occupation']));

    $sb7 = new mSelectBox("workloc");
    $sb7->setContentType("sql");
    $sb7->setSQLvalue("id");
    $sb7->setSQLcontent("name");
    $sb7->addContent("SELECT id,name FROM mgw_workplace");
    $smarty->assign("worklocbox", $sb7->draw($row['workloc']));

    $row["pw"]="";
    $smarty->assign("id", $id);
    $smarty->assign("td", $row);
    $smarty->assign("suname","edit");
    $smarty->assign("suclass","submit");

    $smarty->assign("mode","edit");

    $smarty->display('usermanager_edit.tpl');
    exit();
}


// =================================================
//	              List View
// =================================================
queryRights2("root_modules_admin_usermanager_listusers");

$icons = getIconStrings();

$sql = "SELECT * from mgw_users ORDER BY username";

// ========== PAGING STUFF =================
if (isset($_GET['npage'])){
    $curr_page = $_GET['npage'];
}
else {
    $curr_page = 1; // at first page
}
// =========================================
	
if(!$res = $conn->PageExecute($sql, 25, $curr_page)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
		
// ========== PAGING STUFF #2 ================
// if NOT on first page
if(!$res->AtFirstPage()) {
    $smarty->assign("_prev", true); 
    $smarty->assign("npage", $res->AbsolutePage() - 1);
}
	
// if NOT on last page
if(!$res->AtLastPage()) {
    $smarty->assign("_next", true); 
    $smarty->assign("npage", $res->AbsolutePage() + 1);
}
// ============================================

$counter = 0;
while($row = $res->FetchRow()){
    $counter++;
    $row['lu_date'] = $conn->UnixTimestamp($row['lu_date']);
    $row['email'] = linkEmail($row["email"]);

    // create Action URLs
    $editlink = "<a href=\"usermanager.php?action=editform&id=". $row["id"]. "&".SID."\" class=\"edit\">".$icons["edit"]."</a>";
    $dellink = "<a href=\"usermanager.php?action=delete&id=". $row["id"]. "&".SID."\" class=\"delete\">".$icons["delete"]."</a>";
    $urls[] = $editlink . $icons["space"] . $dellink;

    $smarty->append("td",$row);
}
	
// ========== PAGING STUFF #3 ==================
// display next link when more records available
if($counter<>25) $smarty->assign("next", false); else $smarty->assign("next", true);

$smarty->assign('urls', $urls);
$smarty->assign('action', (isset($_GET["action"])) ? $_GET["action"] : '');

$smarty->display("usermanager_list.tpl");
?>
