<?php
# $Id$
# http://www.mapbender.org/index.php/class_administration
# Copyright (C) 2002 CCGIS
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

require_once(dirname(__FILE__)."/../../conf/mapbender.conf");
require_once(dirname(__FILE__)."/class_mb_exception.php");
$con = db_connect(DBSERVER,OWNER,PW);
db_select_db(DB,$con);

require("phpmailer-1.72/class.phpmailer.php");

/**
 * class to wrap administration methods
 *
 * @uses phpmailer
 */
class administration{
    /**
     * checks whether the passed email-address is valid / following a pattern
     * @todo is this an exact representation of the RFC 2822?
     * @todo this should be checked: what about umlaut-domains and tld like '.museum'?
     * @see http://tools.ietf.org/html/rfc2822
     *
     * @param <string> a all lowercase email adress to test
     * @return <boolean> answer to "is the passed over email valid?""
     */
	function isValidEmail($email) {
        if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
            return true;
		}
		return false;
	}

    /**
     * sends an email via php mailer
     *
     * @param <string> an email address for the "From"-field
     * @param <string> the displayed name for the "From"-field
     * @param <string> an email address for the "To"-field
     * @param <string> the displayed name for the "From"-field
     * @param <string> the text to be set as "Subject"
     * @param <string> the text of the emails body
     * @param <string> a reference to an error string
     */
	function sendEmail($fromAddr, $fromName, $toAddr, $toName, $subject, $body, &$error_msg ){

		global $mailHost, $mailUsername, $mailPassword;
		if($fromAddr == ''){
			$fromAddr = MAILADMIN;
		}

		if($fromName == ''){
			$fromName = MAILADMINNAME;
		}

		if ($this->isValidEmail($fromAddr) && $this->isValidEmail($toAddr)) {
			$mail = new PHPMailer();

			if ($fromName != "" ) {
				$mail->FromName = $fromName;
			}

			$mail->IsSMTP();                  // set mailer to use SMTP
			$mail->Host = $mailHost;          // specify main and backup server
			$mail->SMTPAuth = true;           // turn on SMTP authentication
			$mail->Username = $mailUsername;  // SMTP username
			$mail->Password = $mailPassword;  // SMTP password

			$mail->From = $fromAddr;
			$mail->AddAddress($toAddr, $toName);
			#$mail->AddReplyTo("info@ccgis.de", "Information");

			$mail->WordWrap = 50;                                 // set word wrap to 50 characters
			#$mail->AddAttachment("/var/tmp/file.tar.gz");         // add attachments
			#$mail->AddAttachment("/tmp/image.jpg", "new.jpg");    // optional name
			$mail->IsHTML(false);                                  // set email format to HTML

			$mail->Subject = "[".$fromName."] ".$subject;
			$mail->Body    = $body;
			#$mail->AltBody = "This is the body in plain text for non-HTML mail clients";

			$error_msg='';

			if(!$mail->Send())
			{
			   $error_msg .= "Mailer Error: " . $mail->ErrorInfo;
			   return false;
			}

			return true;
		}
		else {
			return false;
		}
	}

    /**
     * returns a random password with numbers and chars both lowercase and uppercase (0-9a-zA-Z)
     *
     * @return <string> the new password
     */
 	function getRandomPassword() {

		// password length
		$max = 16;

		//new password
		$newpass = "";

		for ($i=0;$i <= $max;$i++) {
			//die ASCII-Zeichen 48 - 57 sind die zahlen 0-9
			//die ASCII-Zeichen 65 - 90 sind die buchstaben A-Z (Gro�)
			//die ASCII-Zeichen 97 - 122 sind die buchstaben a-z (Klein)
			$ascii = 0;
			do {
				$ascii=rand(48,122);
			} while ( ($ascii > 57 && $ascii < 65) || ($ascii > 90 && $ascii < 97));
			$newpass .= chr($ascii);
		}
		return $newpass;
 	}

    /**
     * returns the name of a mapbender user which owns the GUI identified by the passed over gui_id.
     *
     * @param <string> the gui_id
     * @return <string> the name of the owner
     */
 	function getOwnerByGui($gui_id){
		$sql = "(SELECT mb_user.mb_user_name";
		$sql .= "FROM mb_user ";
		$sql .= "JOIN gui_mb_user ON mb_user.mb_user_id = gui_mb_user.fkey_mb_user_id ";
		$sql .= "WHERE gui_mb_user.mb_user_type = 'owner' ";
		$sql .= "AND gui_mb_user.fkey_gui_id = $1 ";
		$sql .= "GROUP BY mb_user.mb_user_name ";
		$sql .= ") ";
		$sql .= "UNION ( ";
		$sql .= "SELECT mb_user.mb_user_name ";
		$sql .= "FROM gui_mb_group ";
		$sql .= "JOIN mb_user_mb_group ON mb_user_mb_group.fkey_mb_group_id = gui_mb_group.fkey_mb_group_id ";
		$sql .= "JOIN mb_user ON mb_user.mb_user_id = mb_user_mb_group.fkey_mb_user_id ";
		$sql .= "JOIN gui_mb_user ON mb_user.mb_user_id = gui_mb_user.fkey_mb_user_id ";
		$sql .= "WHERE gui_mb_group.mb_group_type = 'owner' ";
		$sql .= "AND gui_mb_group.fkey_gui_id = $2 ";
		$sql .= "GROUP BY mb_user.mb_user_name)";
		$owner = array();
		$v = array($gui_id,$gui_id);
		$t = array('s','s');
		$res = db_prep_query($sql,$v,$t);
		$cnt = 0;
		while($row = db_fetch_array($res)){
			$owner[$cnt] = $row["mb_user_name"];
			$cnt++;
		}
		return $owner;
 	}

    /**
     * returns the content of the field mb_user_email for the given userid.
     *
     * @param <integer> the userid
     * @return <mixed> the email if one row is found or false if none is foundd
     */
	function getEmailByUserId($userid){
		$sql = "SELECT mb_user_email FROM mb_user ";
		$sql .= "WHERE mb_user_id = $1 GROUP by mb_user_email";
        // TODO why do we group, when userid is a primary key?
		$v = array($userid);
		$t = array('i');
		$res = db_prep_query($sql,$v,$t);
		// TODO shall the next two lines be removed?
        $count_g = 0;
		$array = array();
		$row = db_fetch_array($res);
		if ($row) {
			return $row["mb_user_email"];
		}
		else {
			return false;
		}
	}

    /**
     * returns the name of the user for the given userid.
     *
     * @param <integer> the userid
     * @return  the name if one row is found or false if none is foundd
     */
	function getUserNameByUserId($userid){
		$sql = "SELECT mb_user_name FROM mb_user ";
		$sql .= "WHERE mb_user_id = $1 GROUP BY mb_user_name";
        // TODO why do we group, when userid is a primary key?
		$v = array($userid);
		$t = array("i");
		$res = db_prep_query($sql,$v,$t);
        // TODO shall the next two lines be removed?
		$count_g = 0;
		$array = array();
		$row = db_fetch_array($res);
		if ($row) {
			return $row["mb_user_name"];
		}
		else {
			return false;
		}
	}

    /**
     * returns one or more userids from the given email or false,
     * if there is no record in the database matching the given email
     *
     * @param <string> the email
     * @return <mixed> returns an array of userids or false when no records matches
     */
 	function getUserIdByEmail($email){
		$sql = "SELECT  mb_user_id FROM mb_user ";
		$sql .= "WHERE mb_user_email = $1 GROUP BY mb_user_id";
		$v = array($email);
		$t = array('s');
		$res = db_prep_query($sql,$v,$t);
  		$count_g = 0;
  		$array = array();
		while($row = db_fetch_array($res)){
			$array[$count_g] = $row["mb_user_id"];
			$count_g++;
		}
		if ($count_g >0)	{
			return $array;
		}
		else {
			return false;
		}
 	}

    /**
     * returns one or more owners for the given wm_id. First all guis deploying
     * this wms are selected. Afterwards for each of the guis the owners are
     * selected and stored within an array.
     *
     * @param <integer> the wms_id
     * @return <mixed> an array of usernames which use thw wms in their guis (both for persona or group ownership)
     */
	function getOwnerByWms($wms_id){
		// first get guis which deploy this wms.
        $sql = "SELECT fkey_gui_id FROM gui_wms WHERE fkey_wms_id = $1 GROUP BY fkey_gui_id";
		$v = array($wms_id);
		$t = array('i');
		$count=0;
		$res = db_prep_query($sql,$v,$t);
		while($row = db_fetch_array($res)){
			$gui[$count] = $row["fkey_gui_id"];
			$count++;
		}

		if ($count > 0) {
			// this is not needed! count($gui) is always equal to $count
            if(count($gui)>0) {
				$v = array();
				$t = array();
				$c = 1;
				$sql = "(SELECT mb_user.mb_user_name FROM mb_user JOIN gui_mb_user ";
				$sql .= "ON mb_user.mb_user_id = gui_mb_user.fkey_mb_user_id ";
				$sql .= " WHERE gui_mb_user.mb_user_type = 'owner'";
				$sql .= " AND gui_mb_user.fkey_gui_id IN (";
				for($i=0; $i<count($gui); $i++){
					if($i>0){ $sql .= ",";}
					$sql .= "$".$c;
					$c++;
					array_push($v, $gui[$i]);
					array_push($t, 's');
				}
				$sql .= ") GROUP BY mb_user.mb_user_name";
				$sql .= ") UNION (";
				$sql .= "SELECT mb_user.mb_user_name FROM gui_mb_group JOIN mb_user_mb_group ON  mb_user_mb_group.fkey_mb_group_id = gui_mb_group.fkey_mb_group_id  JOIN mb_user ";
				$sql .= "ON mb_user.mb_user_id = mb_user_mb_group.fkey_mb_user_id ";
				$sql .= " WHERE gui_mb_group.mb_group_type = 'owner'";
				$sql .= " AND gui_mb_group.fkey_gui_id IN (";

				for($j=0; $j<count($gui); $j++){
					if($j>0){ $sql .= ",";}
					$sql .= "$".$c;
					$c++;
					array_push($v, $gui[$i]);
					array_push($t, 's');
				}
				$sql .= ") GROUP BY mb_user.mb_user_name)";

				$user = array();
				$res = db_prep_query($sql,$v,$t);
			}
			$cnt = 0;

			while($row = db_fetch_array($res)){
				$user[$cnt] = $row["mb_user_name"];
				$cnt++;
			}
			if ($cnt>0)	{
                return $user;
            } else {
                return false;
            }
		} else {
          return false;
        }
	}
    /**
     * tests whether a gui with the passed gui_id exits and returns true or false.
     *
     * @param <string> the gui_id to test
     * @return <boolean> Does a Gui with the passed over gui_id exist?
     */
	function guiExists($id){
		$sql = "SELECT * FROM gui WHERE gui_id = $1 ";
		$v = array($id);
		$t = array('s');
		$res = db_prep_query($sql,$v,$t);
		$row = db_fetch_array($res);
		if ($row) {
			return true;
		}
		else {
			return false;
		}
	}

    /**
     * deletes a WMC entry specified by wmc_id and user_id
     *
     * @param <integer> the user_id
     * @param <string> the wmc_id
     * @return <boolean> Did the query run succesfull? This does not necessarily mean that an entry was deleted.
     */
 	function deleteWmc($wmc_id, $user_id){
		$sql = "DELETE FROM mb_user_wmc ";
		$sql .= "WHERE fkey_user_id = $1 AND wmc_id = $2";
		$v = array($user_id,$wmc_id);
		$t = array('i','s');
		$res = db_prep_query($sql,$v,$t);
		if ($res) {
			return true;
		}
		else {
			return false;
		}
 	}

    /**
     * inserts a gui with the specified gui_id, after checking the uniqueness of teh gui id.
     *
     * @uses guiExists
     * @param <string> the name and id of the gui to insert.
     * @return <boolean> could the gui be inserted?
     */
	function insertGui($guiId) {
		if (!$this->guiExists($guiId)) {
			$sql = "INSERT INTO gui VALUES ($1, $2, '', '1')";
			$v = array($guiId,$guiId);
			$t = array('s','s');
			$res = db_prep_query($sql,$v,$t);
			if ($res) {
				return true;
			}
		}
		return false;
	}

    /**
     * deletes links between user and guis in gui_mb_user for a certain gui.
     *
     * @param <string> the gui name
     * @return <boolean> could the sql be executed without errors. This does not necessarily mean, that entries were deleted
     */
	function delAllUsersOfGui($guiId) {
		$sql = "DELETE FROM gui_mb_user WHERE fkey_gui_id = $1 ";
		$v = array($guiId);
		$t = array('s');
		$res = db_prep_query($sql,$v,$t);
		if (!$res) {
			return false;
		}
		else {
			return true;
		}
	}

    /**
     * returns an array of WMS for a given user id
     * @uses getGuisByOwner
     * @param <integer> the user id
     * @return <array> wms ids for the user
     */
	function getWmsByOwner($user_id){
		$gui_list = $this->getGuisByOwner($user_id,true);
		return $this->getWmsByOwnGuis($gui_list);
	}

    /**
     * returns an array of WMS where the owner is the user with the passed user_id
     * @param <integer> the user id
     * @return <array> wms ids for the user
     */
	function getWmsByWmsOwner($user_id){
		$sql = "SELECT wms_id FROM wms WHERE wms_owner = $1";
		$v = array($user_id);
		$t = array('i');
		$res = db_prep_query($sql,$v,$t);
		$r = array();
		while($row = db_fetch_array($res)){
			array_push($r,$row["wms_id"]);
		}
		return $r;
	}

    /**
     * returns an array of user which are associated with a wms
     *
     * @param <integer> the wms id
     * @return <array> user_ids for the wms
     */
	function getUserByWms($wms_id){
		$sql = "SELECT fkey_gui_id FROM gui_wms WHERE fkey_wms_id = $1 GROUP BY fkey_gui_id";
		$v = array($wms_id);
		$t = array('i');
		$count=0;
		$res = db_prep_query($sql,$v,$t);
		while($row = db_fetch_array($res)){
			$gui[$count] = $row["fkey_gui_id"];
			$count++;
		}
		$c = 1;
		$v = array();
		$t = array();
		if(count($gui)>0){
			$sql = "(SELECT mb_user.mb_user_name FROM mb_user JOIN gui_mb_user ";
			$sql .= "ON mb_user.mb_user_id = gui_mb_user.fkey_mb_user_id ";
			$sql .= " WHERE gui_mb_user.fkey_gui_id IN (";
			for($i=0; $i<count($gui); $i++){
				if($i>0){ $sql .= ",";}
				$sql .= "$".$c;
				array_push($v,$gui[$i]);
				array_push($t, 's');
				$c++;
			}
			$sql .= ") GROUP BY mb_user.mb_user_name) UNION";
			$sql .= "(SELECT mb_user.mb_user_name FROM gui_mb_group JOIN mb_user_mb_group ON   mb_user_mb_group.fkey_mb_group_id = gui_mb_group.fkey_mb_group_id     JOIN mb_user ";
			$sql .= "ON mb_user.mb_user_id = mb_user_mb_group.fkey_mb_user_id ";
			$sql .= " WHERE gui_mb_group.fkey_gui_id IN (";
			for($i=0; $i<count($gui); $i++){
				if($i>0){ $sql .= ",";}
				$sql .= "$".$c;
				array_push($v,$gui[$i]);
				array_push($t, 's');
				$c++;
			}
			$sql .= ") GROUP BY mb_user.mb_user_name )";
			$user = array();
			$res = db_prep_query($sql,$v,$t);
			$cnt = 0;
			while($row = db_fetch_array($res)){
				$user[$cnt] = $row["mb_user_name"];
				$cnt++;
			}
		}
		return $user;
	}

    /**
     * selects the WMS-title for a given wms id.
     *
     * @param <integer> the wms id
     * @return <string|boolean> either the title of the wms as string or false when none exists
     */
	function getWmsTitleByWmsId($id){
		$sql = "SELECT wms_title FROM wms WHERE wms_id = $1 GROUP BY wms_title";
		$v = array($id);
		$t = array('i');
		$res = db_prep_query($sql,$v,$t);
		$row = db_fetch_array($res);
		if ($row) return $row["wms_title"]; else return false;
	}

    /**
     * selects the Layer-title for a given layer id.
     *
     * @param <integer> the wms id
     * @return <string|boolean> either the title of the wms as string or false when none exists
     */
	function getLayerTitleByLayerId($id){
		$sql = "SELECT layer_title FROM layer WHERE layer_id = $1 GROUP BY layer_title";
		$v = array($id);
		$t = array('i');
		$res = db_prep_query($sql,$v,$t);
		$row = db_fetch_array($res);
		if ($row) return $row["layer_title"]; else return false;
	}

    /**
     * selects the WMC for a given wmc_id.
     *
     * @param <integer> the wms id
     * @return <string|boolean> either the wmc as string or false when none exists
     */
	function getWmcById($id){
		$sql = "SELECT wmc FROM mb_user_wmc WHERE wmc_id = $1 ";
		$v = array($id);
		$t = array('s');
		$res = db_prep_query($sql,$v,$t);
		$row = db_fetch_array($res);
		if ($row) {
			return $row["wmc"];
		}
		else {
			return false;
		}
	}

    /**
     * resets the loin count of a given user to 0
     * @param <integer> the user id
     * @return <boolean> could the login count be reseted?
     */
	function resetLoginCount($userId) {
		// TODO: isn't mb_user_login_count a integer?
        $sql = "UPDATE mb_user SET mb_user_login_count = '0' ";
		$sql .= "WHERE mb_user_id = $1 ";
		$v = array($userId);
		$t = array('i');
		$res = db_prep_query($sql,$v,$t);
		if (!$res) {
			return false;
		}
		else {
			return true;
		}
	}

	function getUserIdByUserName($username){
		$sql = "SELECT mb_user_id FROM mb_user ";
		$sql .= "WHERE mb_user_name = $1 GROUP BY mb_user_id";
		$v = array($username);
		$t = array('s');
		$res = db_prep_query($sql,$v,$t);
		$row = db_fetch_array($res);
		if ($row) return $row["mb_user_id"]; else return false;
	}

	function setUserAsGuiOwner($guiId, $userId) {
		$sql = "UPDATE gui_mb_user SET mb_user_type = 'owner' ";
		$sql .= "WHERE fkey_gui_id = $1 AND fkey_mb_user_id = $2 ";
		$v = array($guiId,$userId);
		$t = array('s','i');
		$res = db_prep_query($sql,$v,$t);

		if (!$res) {
			return false;
		}
		else {
			return true;
		}
 	}

	function getGuiIdByGuiName($guiTitle){
		$sql = "SELECT gui_id FROM gui ";
		$sql .= "WHERE gui_name = $1 GROUP BY gui_id";
		$v = array($guiTitle);
		$t = array('s');
		$res = db_prep_query($sql,$v,$t);
  		$count_g = 0;
  		$array = array();
		while($row = db_fetch_array($res)){
			$array[$count_g] = $row["gui_id"];
			$count_g++;
		}
		if ($count_g >0)	{
			return $array;
		}
		else {
			return false;
		}
 	}

	function getGuisByOwner($user_id,$ignore_public)
	{
		$sql_guis = "SELECT gui.gui_id FROM gui,gui_mb_user ";
		$sql_guis .= "WHERE (gui.gui_id = gui_mb_user.fkey_gui_id AND gui_mb_user.fkey_mb_user_id = $1) ";
		if (!isset($ignore_public) OR $ignore_public == false){
			$sql_guis .= " AND gui.gui_public = 1 ";
		}
		$sql_guis .= " AND gui_mb_user.mb_user_type = 'owner' GROUP BY gui.gui_id";
		$sql_guis .= " ORDER by gui.gui_id";
		$v = array($user_id);
		$t = array('i');
		$res_guis = db_prep_query($sql_guis,$v,$t);
  		$count_g = 0;
  		$arrayGuis = array();
		while($row = db_fetch_array($res_guis)){
			$arrayGuis[$count_g] = $row["gui_id"];
			$count_g++;
		}
		return $arrayGuis;
 	}

 	function getWmcByOwner($user_id){
		$sql_wmc = "SELECT wmc_id FROM mb_user_wmc ";
		$sql_wmc .= "WHERE fkey_user_id = $1 GROUP BY wmc_id";
		$v = array($user_id);
		$t = array('i');
		$res_wmc = db_prep_query($sql_wmc,$v,$t);
  		$count_g = 0;
  		$arrayWmc = array();
		while($row = db_fetch_array($res_wmc)){
			$arrayWmc[$count_g] = $row["wmc_id"];
			$count_g++;
		}
		return $arrayWmc;
 	}

	function getGuisByPermission($mb_user_id,$ignore_public){
		$arrayGuis = array();
		$mb_user_groups = array();
		$sql_groups = "SELECT fkey_mb_group_id FROM mb_user_mb_group WHERE fkey_mb_user_id = $1 ";
		$v = array($mb_user_id);
		$t = array("i");
		$res_groups = db_prep_query($sql_groups,$v,$t);
		$cnt_groups = 0;
		while($row = db_fetch_array($res_groups)){
			$mb_user_groups[$cnt_groups] = $row["fkey_mb_group_id"];
			$cnt_groups++;
		}
		if($cnt_groups > 0){
			$v = array();
			$t = array();
			$sql_g = "SELECT gui.gui_id FROM gui JOIN gui_mb_group ";
			$sql_g .= " ON gui.gui_id = gui_mb_group.fkey_gui_id WHERE gui_mb_group.fkey_mb_group_id IN (";
			for($i=0; $i<count($mb_user_groups);$i++){
				if($i > 0){$sql_g .= ",";}
				$sql_g .= "$".strval($i+1);
				array_push($v,$mb_user_groups[$i]);
				array_push($t,"i");
			}
			$sql_g .= ") GROUP BY gui.gui_id";
			$res_g = db_prep_query($sql_g,$v,$t);
			while($row = db_fetch_array($res_g)){
				array_push($arrayGuis,$row["gui_id"]);
			}
		}
		$sql_guis = "SELECT gui.gui_id FROM gui JOIN gui_mb_user ON gui.gui_id = gui_mb_user.fkey_gui_id";
		$sql_guis .= " WHERE (gui_mb_user.fkey_mb_user_id = $1) ";
		if (!isset($ignore_public) OR $ignore_public== false){
			$sql_guis .= " AND gui.gui_public = 1 ";
		}
		$sql_guis .= " GROUP BY gui.gui_id";
		$v = array($mb_user_id);
		$t = array("i");
		$res_guis = db_prep_query($sql_guis,$v,$t);
		$guis = array();
		while($row = db_fetch_array($res_guis)){
			if(!in_array($row['gui_id'],$arrayGuis)){
				array_push($arrayGuis,$row["gui_id"]);
			}
		}
		return $arrayGuis;
	}

	function getWmsByOwnGuis($array_gui_ids){
		if(count($array_gui_ids)>0){
			$v = array();
			$t = array();
			$sql = "SELECT fkey_wms_id from gui_wms WHERE gui_wms.fkey_gui_id IN(";
			for($i=0; $i<count($array_gui_ids); $i++){
				if($i>0){ $sql .= ",";}
				$sql .= "$".strval($i+1);
				array_push($v, $array_gui_ids[$i]);
				array_push($t, "s");
			}
			$sql .= ") GROUP BY fkey_wms_id ORDER BY fkey_wms_id";
			$res = db_prep_query($sql,$v,$t);
			$ownguis = array();
			$i=0;
			while($row = db_fetch_array($res)){
				$ownguis[$i] = $row['fkey_wms_id'];
				$i++;
			}
		}
		return $ownguis;
	}

	function getLayerByWms($wms_id){
		$sql = "SELECT layer_id from layer WHERE fkey_wms_id = $1 AND layer_pos NOT IN ('0') GROUP BY layer_id, layer_title ORDER BY layer_title";
		$v = array($wms_id);
		$t = array('i');
		$res = db_prep_query($sql,$v,$t);
		$layer_id_array = array();
		while($row = db_fetch_array($res)){
			$layer_id_array[count($layer_id_array)] = $row['layer_id'];
		}
		return $layer_id_array;
	}

	function getWmsOwner($wms_id){
		$sql = "SELECT fkey_gui_id FROM gui_wms WHERE fkey_wms_id = $1 GROUP BY fkey_gui_id";
		$v = array($wms_id);
		$t = array('i');
		$count=0;
		$res = db_prep_query($sql,$v,$t);
		while($row = db_fetch_array($res)){
			$gui[$count] = $row["fkey_gui_id"];
			$count++;
		}
		$v = array();
		$t = array();
		if(count($gui)>0){
			$sql = "SELECT mb_user.mb_user_name FROM mb_user JOIN gui_mb_user ";
			$sql .= "ON mb_user.mb_user_id = gui_mb_user.fkey_mb_user_id WHERE";
			$sql .= " gui_mb_user.fkey_gui_id IN (";
			for($i=0; $i<count($gui); $i++){
				if($i>0){ $sql .= ",";}
				$sql .= "$".($i+1);
				array_push($v,$gui[$i]);
				array_push($t,'s');
			}
			$sql .= ")";
			$sql .= " AND gui_mb_user.mb_user_type = 'owner' GROUP BY mb_user.mb_user_name";
			$res = db_prep_query($sql,$v,$t);
			$i=0;
			$wmsowner = array();
			while($row = db_fetch_array($res)){
				$wmsowner[$i]=$row['mb_user_name'];
				$i++;
			}
		}
		return $wmsowner;
	}

	function insertUserAsGuiOwner($guiId, $userId){
		$sql = "INSERT INTO gui_mb_user VALUES ($1, $2, 'owner')";
		$v = array($guiId,$userId);
		$t = array('s','i');
		$res = db_prep_query($sql,$v,$t);
		if (!$res) {
			return false;
		}
		else {
			return true;
		}
 	}

   	function checkModulePermission($arrayGuis, $modulePath, $column){
   		$check = CHECK;
		
   		if($check == true){
	   		$perm = false;
			if (!preg_match("/[a-z_]+/", $column)) {
				return false;
			}
	   		if(count($arrayGuis)>0){
	   			$v = array();
	   			$t = array();
		   		$sql = "SELECT ".$column." FROM gui_element WHERE fkey_gui_id IN(";
		   		for($i=0; $i<count($arrayGuis); $i++){
		   			if($i > 0){ $sql .= ","; }
		   			$sql .= "$".($i+1);
		   			array_push($v,$arrayGuis[$i]);
		   			array_push($t,'s');
		   		}
		   		$sql .= ")";
				$res = db_prep_query($sql,$v,$t);
				$cnt = 0;
				while($row = db_fetch_array($res)){
					if(strpos(stripslashes($row[$column]),$modulePath) !== false){
						$perm = true;
					}
					$cnt++;
				}
	   		}
			return $perm;
   		}
   		else{
   			return true;
   		}
   	}

	/**
	 * Checks if a user is allowed to access a GUI element
	 * 
	 * @return boolean 
	 * @param $arrayGuis Object
	 * @param $modulePath Object
	 * @param $elementTag Object
	 */
   	function checkModulePermission_new($userId, $modulePath, $elementTag){
   		if (CHECK) {
			$arrayGuis = $this->getGuisByPermission($userId, true);

			switch ($elementTag) {
				case "a" :
					$column = "e_attributes";
					$pattern = "/^.*href\s*=\s*(\'|\")\.\.((\/[a-zA-Z0-9_\/\.]+)+)(\?|\'|\").*$/";
					$replace = "$2";
					break;
				case "iframe" :
					$column = "e_src";
					$pattern = "/^\.\.((\/[a-zA-Z0-9_\/\.]+)+)(\?|\'|\").*$/";
					$replace = "$1";
					break;
			}

	   		if ($column && count($arrayGuis) > 0) {
	   			$v = array();
	   			$t = array();
		   		$sql = "SELECT DISTINCT ".$column." FROM gui_element WHERE fkey_gui_id IN (";
		   		for($i=0; $i<count($arrayGuis); $i++){
		   			if($i > 0){ $sql .= ","; }
		   			$sql .= "$".($i+1);
		   			array_push($v,$arrayGuis[$i]);
		   			array_push($t,'s');
		   		}
		   		$sql .= ") ORDER BY " . $column;
				$res = db_prep_query($sql,$v,$t);
				while($row = db_fetch_array($res)){
					if ($row[$column]) {
						if (preg_match($pattern, stripslashes($row[$column]))) {
							$dbFilename = preg_replace($pattern, $replace, stripslashes($row[$column]));
//							$e = new mb_notice($dbFilename . " - " . $modulePath);

							if(strpos($modulePath, $dbFilename) !== false){
								return true;
							}
						}
					}
				}
	   		}
			return false;
   		}
		return true;
   	}

   	function getWMSOWSstring($wms_id){
   		$sql = "SELECT wms_owsproxy FROM wms WHERE wms_id = $1 ";
   		$v = array($wms_id);
   		$t = array("i");
   		$res = db_prep_query($sql,$v,$t);
   		if($row = db_fetch_array($res)){
   			return $row["wms_owsproxy"];
   		}
   		else{
   			return false;
   		}
   	}

   	function setWMSOWSstring($wms_id, $status){
   		$sql = "UPDATE wms SET wms_owsproxy = $1 WHERE wms_id = $2 ";
   		$t = array("s","i");
   		if($status == 'on'){
   			$time = md5(microtime(1));
			$v = array($time,$wms_id);
   		}
   		else{
   			$v = array("",$wms_id);
   		}
   		$res = db_prep_query($sql,$v,$t);
   	}

   	function checkURL($url){
		$pos_qm = strpos($url,"?");
		if($pos_qm > 0 && $pos_qm < (strlen($url)-1) && substr($url,(strlen($url)-1)) != "&"){
			$url = $url."&";
			return $url;
		}
		else if($pos_qm === false){
			return $url."?";
		}
		else{
			return $url;
		}
	}
	function getModulPermission($userID,$guiID,$elementID){
		$g = $this->getGuisByPermission($userID,true);
		if(in_array($guiID,$g)){
			$sql = "SELECT * FROM gui_element WHERE fkey_gui_id = $1 AND e_id = $2 ";
			$v = array($guiID,$elementID);
			$t = array('s','s');
			$res = db_prep_query($sql,$v,$t);
			if($row = db_fetch_array($res)){
				return true;
			}
			else{
				return false;
			}
		}
		else{
			return false;
		}
	}
	function getLayerPermission($wms_id, $layer_name, $user_id){
		$layer_id = $this->getLayerIdByLayerName($wms_id,$layer_name);
		$array_guis = $this->getGuisByPermission($user_id,true);
		$v = array();
		$t = array();
		$sql = "SELECT * FROM gui_layer WHERE fkey_gui_id IN (";
		$c = 1;
		for($i=0; $i<count($array_guis); $i++){
			if($i>0){ $sql .= ",";}
			$sql .= "$".$c;
			$c++;
			array_push($v, $array_guis[$i]);
			array_push($t, 's');
		}
		$sql .= ") AND fkey_layer_id = $".$c." AND gui_layer_status = 1";
		array_push($v,$layer_id);
		array_push($t,'i');
		$res = db_prep_query($sql,$v,$t);
		if($row = db_fetch_array($res)){
			return true;
		}
		else{
			return false;
		}
	}
	function getWmsPermission($wms_id, $user_id) {
		$array_guis = $this->getGuisByPermission($user_id,true);
		$v = array();
		$t = array();
		$sql = "SELECT * FROM gui_wms WHERE fkey_gui_id IN (";
		$c = 1;
		for($i=0; $i<count($array_guis); $i++){
			if($i>0){ $sql .= ",";}
			$sql .= "$".$c;
			$c++;
			array_push($v, $array_guis[$i]);
			array_push($t, 's');
		}
		$sql .= ") AND fkey_wms_id = $".$c;
		array_push($v,$wms_id);
		array_push($t,'i');
		$res = db_prep_query($sql,$v,$t);
		if($row = db_fetch_array($res)){
			return true;
		}
		else{
			return false;
		}
	}
	function getLayerIdByLayerName($wms_id, $layer_name){
		$sql = "SELECT layer_id FROM layer WHERE ";
		$sql .= "fkey_wms_id = $1 AND layer_name = $2";
		$v = array($wms_id,$layer_name);
		$t = array('i','s');
		$res = db_prep_query($sql,$v,$t);
		if($row = db_fetch_array($res)){
			return $row['layer_id'];
		}
		else{
			return false;
		}
	}
	function getWmsIdByWmsGetmap($getmap) {
		$sql = "SELECT wms_id FROM wms WHERE ";
		$sql .= "wms_getmap LIKE $1 LIMIT 1";
		$v = array($getmap."%");
		$t = array('s');
		$res = db_prep_query($sql,$v,$t);
		if($row = db_fetch_array($res)){
			return $row['wms_id'];
		}
		else{
			return false;
		}
	}

	function is_utf8_string($string) {
		return preg_match('%(?:
		[\xC2-\xDF][\x80-\xBF]        # non-overlong 2-byte
		|\xE0[\xA0-\xBF][\x80-\xBF]               # excluding overlongs
		|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}      # straight 3-byte
		|\xED[\x80-\x9F][\x80-\xBF]               # excluding surrogates
		|\xF0[\x90-\xBF][\x80-\xBF]{2}    # planes 1-3
		|[\xF1-\xF3][\x80-\xBF]{3}                  # planes 4-15
		|\xF4[\x80-\x8F][\x80-\xBF]{2}    # plane 16
		)+%xs', $string);
	}
	
	function is_utf8_xml($xml) {
		return preg_match('/<\?xml[^>]+encoding="utf-8"[^>]*\?>/is', $xml);
	}
	
	function is_utf8 ($data) {
		return ($this->is_utf8_xml($data) || $this->is_utf8_string($data));
	}
	
	function char_encode($data) {
		if (CHARSET == "UTF-8") {
			if (!$this->is_utf8($data)) {
				$e = new mb_notice("Conversion: ISO-8859-1 to UTF-8");
				return utf8_encode($data);
			}
		}
		else {
			if ($this->is_utf8($data)) {
				$e = new mb_notice("Conversion: UTF-8 to ISO-8859-1");
				return utf8_decode($data);
			}
		}
		$e = new mb_notice("No conversion: is " . CHARSET);
		return $data;
	}

	function char_decode($data) {
		if (CHARSET == "UTF-8") {
			if ($this->is_utf8($data)) {
				$e = new mb_notice("Conversion: UTF-8 to ISO-8859-1");
				return utf8_decode($data);
			}
		}
		$e = new mb_notice("no conversion: is " . CHARSET);
		return $data;
	}
}
?>