<?php
/* $Id: groupmanager.php,v 1.54 2003/11/14 05:00:54 emailtotom 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.54 $", __FILE__);

// =================================================
//	              create entry
// =================================================

if (isset($_POST["op"]) && $_POST["op"] == "create"){
	queryRights2("root_modules_admin_groupmanager_creategroups");
    
    $_POST["groupname"] = strtolower(str_replace(array("#","@"," ",",",".","/","\\","'","\""),"",trim($_POST["groupname"])));

    // Groupname mustn't be ""    
    if ($_POST["groupname"] != "" and !ereg('[^a-z0-9]',$_POST["groupname"])) {

      $gname = $conn->QMagic($_POST["groupname"]);

      $sql = "SELECT name FROM mgw_groups WHERE name = ". $gname;
      if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

   	  if($res->RecordCount() == 0) {
      
          // Create Group
    $id = mgw_genID('mgw__seq_groups', 50005);
    $gname = $conn->QMagic($_POST["groupname"]);
    $gdesc = $conn->QMagic($_POST["description"]);

    $sql="INSERT INTO mgw_groups (id, name, description, lu_user, lu_date) VALUES ($id, $gname, $gdesc, ".$_SESSION["MGW"]->userid.", ".$conn->DBTimeStamp(time()).")";

    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
      } else {
          // Groupname already exists, display form again with description
          $smarty->assign("suname","create");
          $smarty->assign("suclass","submit");
          $smarty->assign("mode","new");
          $smarty->assign("td", array("description"=>$_POST["description"]));
          $smarty->assign("exception",Lang::getLanguageString("err_duplicategroup"));
            
          $smarty->display('groupmanager_edit.tpl');
          exit;
      }

    } else {
      // Groupname is "", display form again with description
      $smarty->assign("suname","create");
      $smarty->assign("suclass","submit");
      $smarty->assign("mode","new");
      $smarty->assign("td", array("description"=>$_POST["description"]));
      $smarty->assign("exception",Lang::getLanguageString("err_nogroupname"));
            
      $smarty->display('groupmanager_edit.tpl');
      exit;
    }
}

// =================================================
//	              edit entry
// =================================================

if (isset($_POST["op"]) && $_POST["op"] == "edit"){
	queryRights2("root_modules_admin_groupmanager_modifygroups");

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

    if ($_POST["groupname"] != "" and !ereg('[^a-z0-9]',$_POST["groupname"])) {
    $gname = $conn->QMagic($_POST["groupname"]);
    $gdesc = $conn->QMagic($_POST["description"]);
	 	
    $sql="update mgw_groups set name=$gname, description=$gdesc, 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 group
// =================================================
if(isset($_POST["confirmation_yes"])) {
  queryRights2("root_modules_admin_groupmanager_deletegroups");

  $id = (int) $_POST["itemid"];
	$sql = "DELETE FROM mgw_groups WHERE id=$id";
	if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	// delete also the member mapping for that group
	$sql = "DELETE FROM mgw_groups_members WHERE groupid=$id";
	if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
}
elseif (isset($_GET["view"]) && $_GET["view"] == "delete"){
    queryRights2("root_modules_admin_groupmanager_deletegroups");

    $id = (int) $_GET["id"];
    $sql = "SELECT * FROM mgw_groups WHERE id=$id";
    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $row = $res->FetchRow();
		
    $smarty->assign("menuid", "1");
    $smarty->assign("itemid", $id);
    $smarty->assign("parms", str_replace("delete","list",$_SERVER["QUERY_STRING"]));
    $smarty->assign("reallydeleteitem", Lang::getLanguageString("reallydelgroup"));
    $smarty->assign("deleteheader", Lang::getLanguageString("deletegrouph"));
    $smarty->assign("deletedetail1", $row["name"]);
    $smarty->assign("deletedetail2", $row["description"]);
    $smarty->assign("suclass", "submit");
		
    $smarty->display($appconf["gentemplates"] ."/delete_item.tpl");
    exit();
}


// =================================================
//	              New Item Formular
// =================================================
if (isset($_GET["view"]) && $_GET["view"] == "newform") {
    queryRights2("root_modules_admin_groupmanager_creategroups");

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

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

// ================================================
//			Edit group form
// ================================================
if (isset($_GET["view"]) && $_GET["view"] == "editform") {
    queryRights2("root_modules_admin_groupmanager_modifygroups");

    $id = (int) $_GET["id"];

    $sql = "SELECT * FROM mgw_groups WHERE id = $id";
    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $row = $res->FetchRow();
	
    $smarty->assign("suname","edit");
    $smarty->assign("suclass","submit");
    $smarty->assign("mode","edit");
    $smarty->assign("td", $row);
    $smarty->assign("editgroup", Lang::getParmLang(Lang::getLanguageString("editgroup"), array($row["name"])));
	
    $smarty->display('groupmanager_edit.tpl');
    exit();
}

// =================================================
//	              adding users to group
// =================================================
if (isset($_POST["add"])) {
    queryRights2("root_modules_admin_groupmanager_adduserstogroups");

    for($i=0;$i<count($_POST["usersnotingroup"]);$i++) {
	$sql = "insert into mgw_groups_members (groupid, userid, lu_user, lu_date) values (".(int)$_POST["groupid"].", ".(int)$_POST["usersnotingroup"][$i].", ".$_SESSION["MGW"]->userid.", ".$conn->DBTimeStamp(time()).")";
	if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    }
	
    // go to edit formular
    $_GET["id"] = $_POST["groupid"];
    $_GET["view"] = "editmembersform";
}

// =================================================
//	         removing users from group
// =================================================
if(isset($_POST["remove"])) {
    queryRights2("root_modules_admin_groupmanager_removeusersfromgroups");

    for($i=0;$i<count($_POST["groupmembers"]);$i++) {
	$sql = "delete from mgw_groups_members where groupid=".(int)$_POST["groupid"]." and userid=".(int)$_POST["groupmembers"][$i];
	if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    }
	
    // go to edit formular
    $_GET["id"] = $_POST["groupid"];
    $_GET["view"] = "editmembersform";
}
 
// =================================================
//	              edit members form
// =================================================
if (isset($_GET["view"]) && $_GET["view"] == "editmembersform") {
    queryRights2("root_modules_admin_groupmanager_adduserstogroups");

    include(INCLUDEPATH . "mSelectBox.class.php");
    $id = (int) $_GET["id"];

    $sb5 = new mSelectBox("usersnotingroup");
    $sb5->setContentType("sql");
    $sb5->setSQLvalue("id");
    $sb5->setSQLcontent("username");
    $sb5->setMultiple(true);
    $sb5->addContent("SELECT a.*, b.userid, b.groupid FROM mgw_users a LEFT JOIN mgw_groups_members b ON a.id = b.userid AND b.groupid=$id WHERE b.groupid IS NULL");
    $sb5->setHeight(10);
    $smarty->assign("sballusers", $sb5->draw());

    $sb3 = new mSelectBox("groupmembers");
    $sb3->setContentType("sql");
    $sb3->setSQLvalue("userid");
    $sb3->setSQLcontent("uname");
    $sb3->setMultiple(true);
    $sb3->addContent("SELECT a.*, b.username AS uname FROM mgw_groups_members a, mgw_users b WHERE a.userid = b.id AND groupid=$id");
    $sb3->setHeight(10);
    $smarty->assign("sbgroupusers", $sb3->draw());

	
    $sql = "SELECT * FROM mgw_groups WHERE id=$id";
    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $row = $res->FetchRow();

    $smarty->assign("editmembersgroupx", Lang::getParmLang(Lang::getLanguageString("editmembersgroupx"), array($row["name"])));
    $smarty->assign("groupmembers", Lang::getParmLang(Lang::getLanguageString("groupmembers"), array($row["name"])));
    $smarty->assign("usernotingroup", Lang::getParmLang(Lang::getLanguageString("usernotingroup"), array($row["name"])));
    $smarty->assign("id", $id);
    $smarty->assign("suclass", "submit");

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


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

$icons = getIconStrings();

$sql = "SELECT a.id, a.name, a.description, a.lu_date, b.username AS lu_user from mgw_groups a LEFT JOIN mgw_users b ON a.lu_user = b.id";
if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
while($row = $res->FetchRow()){

    $row['lu_date'] = $conn->UnixDate($row['lu_date']);
    // calculate members of each group
    $sql2 = "SELECT COUNT(*) AS mycounter FROM mgw_groups_members WHERE groupid=".(int)$row["id"];
    if(!$res2 = $conn->Execute($sql2)) exit(showSQLerror($sql2, $conn->ErrorMsg(), __LINE__, __FILE__));
    $row2 = $res2->FetchRow();

    $completecounter = sprintf("%03d",$row2["mycounter"]) . "&nbsp;&nbsp;<a href=\"groupmanager.php?mod=admin&amp;obj=group&amp;view=editmembersform&amp;id=".$row["id"]."&amp;".SID."\" class=\"edit\">". Lang::getLanguageString("editmembers")."</a>";
    $smarty->append("cntmembers",$completecounter);

    // create Action URLs
    $editlink = "<a href=\"groupmanager.php?mod=admin&amp;obj=group&amp;view=editform&amp;id=". $row["id"] ."&amp;".SID."\" class=\"edit\">". $icons["edit"] . "</a>";
    $dellink = "<a href=\"groupmanager.php?mod=admin&amp;obj=group&amp;view=delete&amp;id=". $row["id"] ."&amp;".SID."\" onclick=\"return check_delete()\" class=\"delete\">". $icons["delete"] . "</a>";

    $urls[] = $editlink . $icons["space"] . $dellink;
    $smarty->append("td",$row);
}	
		
$smarty->assign('urls', $urls);
		
$smarty->display("groupmanager_list.tpl");
?>