[Mapbender-commits] r6957 - in branches: . mapbender mapbender/conf mapbender/core mapbender/http mapbender/http/classes mapbender/http/frames mapbender/http/javascripts mapbender/http/php mapbender/http/plugins mapbender/http/print mapbender/http/tmp mapbender/lib mapbender/resources mapbender/resources/locale/bg_BG mapbender/resources/locale/es_ES mapbender/resources/locale/fr_FR mapbender/resources/locale/hu_HU mapbender/resources/locale/it_IT mapbender/resources/locale/pt_PT mapbender/test/http/classes mapbender/tools mapbender/tools/wms_extent

svn_mapbender at osgeo.org svn_mapbender at osgeo.org
Wed Sep 29 07:31:11 EDT 2010


Author: christoph
Date: 2010-09-29 11:31:10 +0000 (Wed, 29 Sep 2010)
New Revision: 6957

Added:
   branches/mapbender/
   branches/mapbender/conf/
   branches/mapbender/core/system.php
   branches/mapbender/http/classes/class_bbox.php
   branches/mapbender/http/classes/class_elementVar.php
   branches/mapbender/http/classes/class_layer_monitor.php
   branches/mapbender/http/classes/class_map.php
   branches/mapbender/http/classes/class_metadata_new.php
   branches/mapbender/http/classes/class_wmc.php
   branches/mapbender/http/classes/class_wms.php
   branches/mapbender/http/classes/class_wms_1_1_1_factory.php
   branches/mapbender/http/classes/class_wms_factory.php
   branches/mapbender/http/img/
   branches/mapbender/http/javascripts/
   branches/mapbender/http/javascripts/initWmcObj.php
   branches/mapbender/http/javascripts/mod_savewmc.js
   branches/mapbender/http/javascripts/mod_searchCSW_ajax_button.php
   branches/mapbender/http/javascripts/wms.js
   branches/mapbender/http/php/mod_showMetadata.php
   branches/mapbender/http/php/wms.php
   branches/mapbender/http/plugins/mb_extendedSearch.js
   branches/mapbender/http/plugins/mb_extendedSearch_server.php
   branches/mapbender/http/plugins/mb_metadata_server.php
   branches/mapbender/http/plugins/mb_print.js
   branches/mapbender/http/print/printFactory.php
   branches/mapbender/resources/db/
   branches/mapbender/resources/locale/bg_BG/LC_MESSAGES/
   branches/mapbender/resources/locale/es_ES/LC_MESSAGES/
   branches/mapbender/resources/locale/fr_FR/LC_MESSAGES/
   branches/mapbender/resources/locale/hu_HU/LC_MESSAGES/
   branches/mapbender/resources/locale/it_IT/LC_MESSAGES/
   branches/mapbender/resources/locale/pt_PT/LC_MESSAGES/
   branches/mapbender/test/http/classes/GetApiTest.php
   branches/mapbender/tools/mapFiler.php
   branches/mapbender/tools/wms_extent/extent_service.conf
   branches/mapbender/tools/wms_extent/extents.map
   branches/mapbender/tools/wms_extent/readme.txt
   branches/mapbender/tools/wms_extent/symbolset_mapbender.sym
   branches/mapbender/tools/wms_extent/target_small.png
Removed:
   branches/mapbender/conf/
   branches/mapbender/core/system.php
   branches/mapbender/http/classes/class_bbox.php
   branches/mapbender/http/classes/class_elementVar.php
   branches/mapbender/http/classes/class_layer_monitor.php
   branches/mapbender/http/classes/class_map.php
   branches/mapbender/http/classes/class_metadata_new.php
   branches/mapbender/http/classes/class_wmc.php
   branches/mapbender/http/classes/class_wms.php
   branches/mapbender/http/classes/class_wms_1_1_1_factory.php
   branches/mapbender/http/classes/class_wms_factory.php
   branches/mapbender/http/img/
   branches/mapbender/http/javascripts/
   branches/mapbender/http/javascripts/initWmcObj.php
   branches/mapbender/http/javascripts/mod_savewmc.js
   branches/mapbender/http/javascripts/mod_searchCSW_ajax_button.php
   branches/mapbender/http/javascripts/wms.js
   branches/mapbender/http/php/mod_showMetadata.php
   branches/mapbender/http/php/wms.php
   branches/mapbender/http/plugins/mb_extendedSearch.js
   branches/mapbender/http/plugins/mb_extendedSearch_server.php
   branches/mapbender/http/plugins/mb_metadata_server.php
   branches/mapbender/http/plugins/mb_print.js
   branches/mapbender/http/print/printFactory.php
   branches/mapbender/http/tmp/ReadMe.txt
   branches/mapbender/lib/class_Singleton.php
   branches/mapbender/lib/database-mysql.php
   branches/mapbender/lib/database-mysqli.php
   branches/mapbender/resources/db/
   branches/mapbender/resources/locale/bg_BG/LC_MESSAGES/
   branches/mapbender/resources/locale/es_ES/LC_MESSAGES/
   branches/mapbender/resources/locale/fr_FR/LC_MESSAGES/
   branches/mapbender/resources/locale/hu_HU/LC_MESSAGES/
   branches/mapbender/resources/locale/it_IT/LC_MESSAGES/
   branches/mapbender/resources/locale/pt_PT/LC_MESSAGES/
   branches/mapbender/test/http/classes/GetApiTest.php
   branches/mapbender/test/http/classes/GroupTest.php
   branches/mapbender/test/http/classes/MbNoticeTest.php
   branches/mapbender/test/http/classes/MbWarningTest.php
   branches/mapbender/test/http/classes/UserTest.php
   branches/mapbender/tools/mapFiler.php
Modified:
   branches/mapbender/core/globalSettings.php
   branches/mapbender/http/classes/class_administration.php
   branches/mapbender/http/frames/index.php
   branches/mapbender/http/print/mapbender_template.json
   branches/mapbender/lib/class_GetApi.php
   branches/mapbender/lib/class_Mapbender.php
   branches/mapbender/lib/class_Mapbender_session.php
   branches/mapbender/lib/database-pgsql.php
Log:
-


Property changes on: branches/mapbender
___________________________________________________________________
Added: svn:ignore
   + .project

Added: svn:mergeinfo
   + /branches/kmq_dev:4021-4487


Property changes on: branches/mapbender/conf
___________________________________________________________________
Added: svn:ignore
   + mapbender.conf


Modified: branches/mapbender/core/globalSettings.php
===================================================================
--- trunk/mapbender/core/globalSettings.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/core/globalSettings.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -92,12 +92,7 @@
 //
 // database wrapper
 //
-if(SYS_DBTYPE=="mysql") {
-	require_once(dirname(__FILE__) . "/../lib/database-mysql.php"); 
-}
-else {
-	require_once(dirname(__FILE__) . "/../lib/database-pgsql.php"); 
-}
+require_once(dirname(__FILE__) . "/../lib/database-pgsql.php"); 
 
 //
 // class for error handling

Deleted: branches/mapbender/core/system.php
===================================================================
--- trunk/mapbender/core/system.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/core/system.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,71 +0,0 @@
-<?php
-# $Id$
-# 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.
-
-
-//define("SESSION_NAME", "TRUNK_SESSID");
-#
-# mapbender version
-#
-define("MB_VERSION_NUMBER", "2.7");
-define("MB_VERSION_APPENDIX", "alpha");
-define("MB_RELEASE_DATE", mktime(0,0,0,9,4,2010));//h, min,sec,month,day,year
-
-#
-# constants from map.js
-#
-define("MB_RESOLUTION", "28.35");
-define("MB_FEATURE_COUNT", "100");
-define("MB_SECURITY_PROXY", "http://wms.wheregroup.com/mapbender/tools/security_proxy.php?mb_ows_security_proxy=");
-#
-# available log levels
-#
-define("LOG_LEVEL_LIST", "off,error,warning,notice,all");
-
-#
-# OpenLayers path
-#
-define("OPENLAYERS_PATH", "../extensions/OpenLayers-2.9.1/");
-
-#
-# Module search paths
-#
-$pathArray = array(
-	"../javascripts/",
-	OPENLAYERS_PATH,
-	OPENLAYERS_PATH . "lib/OpenLayers/"
-);
-define("MODULE_SEARCH_PATHS", implode(",", $pathArray));
-unset($pathArray);
-
-# FirePHP error log re-routing
-define("LOG_PHP_WITH_FIREPHP", "off"); // "on" or "off"
-
-define("MODULES_NOT_RELYING_ON_GLOBALS",
-	"mapframe1,featureInfo1,gazetteerWFS,back,forward,zoomCoords,zoomFull,zoomIn1," .
-	"zoomOut1,selArea1,pan1,copyright,dependentDiv,dragMapSize," .
-	"dynamicOverview,FeatureInfoRedirect,highlightPOI,navFrame,sandclock," .
-	"scaleBar,scaleSelect,setBBOX,setPOI2Scale,reload,overview,addWMS," .
-	"repaint,changeEPSG,User,AdminTabs,GroupEditor,GuiEditor,UserEditor,".
-	"scalebar,addWMSfromTree,mousewheelZoom,mapframe1_mousewheelZoom,doubleclickZoom," .
-	"overviewToggle,resizeMapsize,coordsLookup,selArea1,loadwmc,savewmc," . 
-	"resultList,mb_featureList_digitize,md_editor_container,md_editor_data," . 
-	"md_editor_navigation,md_editor_search_data,md_editor_result_data,metadata_create_data,".
-	"metadata_create_service,metadata_create_application,mb_md_selectAction,mb_md_editMetadataByData,mb_md_path," . 
-	"mb_md_editMetadataByService,mb_md_editMetadataByApplication,md_editor_xml_import," . 
-	"muenster_setExtRequest,muenster_toolbar,csvUpload"
-);

Copied: branches/mapbender/core/system.php (from rev 6936, trunk/mapbender/core/system.php)
===================================================================
--- branches/mapbender/core/system.php	                        (rev 0)
+++ branches/mapbender/core/system.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -0,0 +1,71 @@
+<?php
+# $Id$
+# 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.
+
+
+//define("SESSION_NAME", "TRUNK_SESSID");
+#
+# mapbender version
+#
+define("MB_VERSION_NUMBER", "2.7");
+define("MB_VERSION_APPENDIX", "alpha");
+define("MB_RELEASE_DATE", mktime(0,0,0,9,4,2010));//h, min,sec,month,day,year
+
+#
+# constants from map.js
+#
+define("MB_RESOLUTION", "28.35");
+define("MB_FEATURE_COUNT", "100");
+define("MB_SECURITY_PROXY", "http://wms.wheregroup.com/mapbender/tools/security_proxy.php?mb_ows_security_proxy=");
+#
+# available log levels
+#
+define("LOG_LEVEL_LIST", "off,error,warning,notice,all");
+
+#
+# OpenLayers path
+#
+define("OPENLAYERS_PATH", "../extensions/OpenLayers-2.9.1/");
+
+#
+# Module search paths
+#
+$pathArray = array(
+	"../javascripts/",
+	OPENLAYERS_PATH,
+	OPENLAYERS_PATH . "lib/OpenLayers/"
+);
+define("MODULE_SEARCH_PATHS", implode(",", $pathArray));
+unset($pathArray);
+
+# FirePHP error log re-routing
+define("LOG_PHP_WITH_FIREPHP", "on"); // "on" or "off"
+
+define("MODULES_NOT_RELYING_ON_GLOBALS",
+	"mapframe1,featureInfo1,gazetteerWFS,back,forward,zoomCoords,zoomFull,zoomIn1," .
+	"zoomOut1,selArea1,pan1,copyright,dependentDiv,dragMapSize," .
+	"dynamicOverview,FeatureInfoRedirect,highlightPOI,navFrame,sandclock," .
+	"scaleBar,scaleSelect,setBBOX,setPOI2Scale,reload,overview,addWMS," .
+	"repaint,changeEPSG,User,AdminTabs,GroupEditor,GuiEditor,UserEditor,".
+	"scalebar,addWMSfromTree,mousewheelZoom,mapframe1_mousewheelZoom,doubleclickZoom," .
+	"overviewToggle,resizeMapsize,coordsLookup,selArea1,loadwmc,savewmc," . 
+	"resultList,mb_featureList_digitize,md_editor_container,md_editor_data," . 
+	"md_editor_navigation,md_editor_search_data,md_editor_result_data,metadata_create_data,".
+	"metadata_create_service,metadata_create_application,mb_md_selectAction,mb_md_editMetadataByData,mb_md_path," . 
+	"mb_md_editMetadataByService,mb_md_editMetadataByApplication,md_editor_xml_import," . 
+	"muenster_setExtRequest,muenster_toolbar,csvUpload"
+);

Modified: branches/mapbender/http/classes/class_administration.php
===================================================================
--- trunk/mapbender/http/classes/class_administration.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/http/classes/class_administration.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -560,13 +560,14 @@
      * @return string|boolean	either the wmc as string or false when none exists
      * @deprecated
      */
+/*
 	function getWmcById($id){
 		$e = new mb_notice("administration->getWmcById is deprecated, use wmc->getDocument instead!"); 
 
 		$wmc = new wmc();
 		return $wmc->getDocument($id);
 	}
-
+*/
     /**
      * resets the login count of a given user to 0
      * @param integer	the user id
@@ -586,7 +587,7 @@
 			return true;
 		}
 	}
-
+/*
 	function getAllFilteredUsers($owner) {
 		$allUsers = array();
 		$sql = "SELECT mb_user_id,mb_user_name,mb_user_email FROM mb_user ";
@@ -603,7 +604,9 @@
 		header("Content-type:text/plain; charset=utf-8");
 		return $output;
 	}
-
+ *
+ */
+/*
 	function getAllUserColumns($userId) {
 		$userArray = array();
 		$sql = "SELECT * FROM mb_user WHERE mb_user_id = $1";
@@ -623,11 +626,12 @@
 		header("Content-type:text/plain; charset=utf-8");
 		return $output;
 	}
-
+*/
 	/**
 	 * Returns an array of column names and fieldtype for a table.
 	 * 
 	 */
+/*
 	function getTableColumns($table) {
 		$sql = "SELECT * FROM $table LIMIT 1";
 		$columnArray = array();
@@ -650,7 +654,8 @@
 
 		return $columnArray;
 	}
-
+*/
+/*
 	function deleteTableRecord($table,$keyField,$keyFieldValue) {
 		$sql = "DELETE FROM $table WHERE $keyField = $1";
 		$v = array($keyFieldValue); 
@@ -663,7 +668,7 @@
 			return true;
 		}
 	}
-
+*/
 	function getUserIdByUserName($username){
 		$sql = "SELECT mb_user_id FROM mb_user ";
 		$sql .= "WHERE mb_user_name = $1 GROUP BY mb_user_id";

Deleted: branches/mapbender/http/classes/class_bbox.php
===================================================================
--- trunk/mapbender/http/classes/class_bbox.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/http/classes/class_bbox.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,175 +0,0 @@
-<?php
-# $Id$
-# http://www.mapbender.org/index.php/
-# 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__)."/../../core/globalSettings.php");
-require_once(dirname(__FILE__)."/class_point.php");
-
-/**
- * A bounding box consisting of an lower left and an upper right point, and an EPSG.
- */
-class Mapbender_bbox {
-	var $min;
-	var $max;
-	var $epsg;
-	
-	/**
-	 * @constructor
-	 */
-	function __construct() {
-		if (func_num_args() == 5) {
-			$param0 = func_get_arg(0);
-			$param1 = func_get_arg(1);
-			$param2 = func_get_arg(2);
-			$param3 = func_get_arg(3);
-			$param4 = func_get_arg(4);
-		}
-		else if (func_num_args() == 3) {
-			$param0 = func_get_arg(0);
-			$param1 = func_get_arg(1);
-			$param2 = func_get_arg(2);
-		}
-		else {
-			return;
-		}
-		
-		// params are point, point, epsg
-		if (is_a($param0, "Mapbender_point") && is_a($param1, "Mapbender_point") && !$param3 && !$param4) {
-			$e = new mb_notice("Mapbender_bbox: constructor: point1, point2, epsg");
-			$min = $param0; // is a Mapbender_point
-			$max = $param1; // is a Mapbender_point
-			$epsg = $param2; // is an EPSG code like "EPSG:4326"
-			
-			if (($min->isWestOf($max) && $min->isSouthOf($max)) || $min->equals($max)) {
-				if ($min->epsg == $max->epsg && $min->epsg == $epsg) {
-					$this->min = $min;
-					$this->max = $max;
-					$this->epsg = $epsg;
-				}
-				else {
-					$e = new mb_exception("Mapbender_bbox: constructor: EPSG mismatch!");
-				}
-			}
-			else {
-				$e = new mb_exception("Mapbender_bbox: constructor: min (".$this->min.") is not southwest of max (".$this->max.")!");
-			}
-		}
-		// params are x1, y1, x2, xy, epsg
-		else {
-			$e = new mb_notice("Mapbender_bbox: constructor: x1, y1, x2, y2, epsg");
-			$min = new Mapbender_point($param0, $param1, $param4);
-			$max = new Mapbender_point($param2, $param3, $param4);
-			$epsg = $param4; // is an EPSG code like "EPSG:4326"
-			
-			if ($min->isWestOf($max) && $min->isSouthOf($max)) {
-				if ($min->epsg == $max->epsg && $min->epsg == $epsg) {
-					$this->min = $min;
-					$this->max = $max;
-					$this->epsg = $epsg;
-				}
-				else {
-					$e = new mb_exception("Mapbender_bbox: constructor: EPSG mismatch!");
-				}
-			}
-			else {
-				$e = new mb_exception("Mapbender_bbox: constructor: min (".$this->min.") is not southwest of max (".$this->max.")!");
-			}
-			
-		}
-	}
-	
-	/**
-	 * Computes a new bounding box, bbox1 UNION bbox2
-	 */
-	static function union ($bboxArray) {
-		if (count($bboxArray) == 1) {
-			return array_pop($bboxArray);
-		}
-		elseif (count($bboxArray) >= 2) {
-			
-			$bbox1 = array_pop($bboxArray);
-			$bbox2 = Mapbender_bbox::union($bboxArray);
-
-			if (!($bbox1 != null && $bbox1->isValid()) && !($bbox2 != null && $bbox2->isValid())) {
-				$e = new mb_exception("Mapbender_bbox: union: both parameters invalid!");
-				return null;
-			}
-			elseif (!($bbox1 != null && $bbox1->isValid()) && ($bbox2 != null && $bbox2->isValid())) {
-				$e = new mb_exception("Mapbender_bbox: union: first parameter invalid!");
-				return $bbox2;
-			}
-			elseif (($bbox1 != null && $bbox1->isValid()) && !($bbox2 != null && $bbox2->isValid())) {
-				$e = new mb_exception("Mapbender_bbox: union: second parameter invalid!");
-				return $bbox1;
-			}
-			else {
-				if ($bbox1->epsg == $bbox2->epsg) {
-					$e = new mb_notice("Mapbender_bbox: union: bbox1 is: " . $bbox1);
-					$e = new mb_notice("Mapbender_bbox: union: bbox2 is: " . $bbox2);
-					$e = new mb_notice("Mapbender_bbox: union: merging bbox1 and bbox2...");
-					return new Mapbender_bbox(Mapbender_point::min($bbox1->min, $bbox2->min), Mapbender_point::max($bbox1->max, $bbox2->max), $bbox1->epsg);
-				}
-				else {
-					$e = new mb_exception("Mapbender_bbox: cannot process union with different EPSG codes");
-				}
-			}
-		}
-		else {
-			$e = new mb_exception("Mapbender_bbox: Invalid parameter (Not an array)!");
-		}
-		return null;
-	}
-	
-	/**
-	 * transforms this bbox in another EPSG
-	 * @param toEpsg transform the bbox to this EPSG code, example: "EPSG:4326" 
-	 */
-	function transform($toEpsg) {
-		if ($this->isValid()) {
-			$this->epsg = $toEpsg;
-			$this->min->transform($toEpsg);
-			$this->max->transform($toEpsg);
-			return true;
-		}
-		return false;
-	}
-
-	/**
-	 * checks if lower left and upper right coordinate are set, as well as EPSG
-	 */
-	function isValid() {
-		if ($this->min != null && $this->max != null && $this->epsg != null) {
-			return true;
-		}
-		$e = new mb_exception("Mapbender_bbox: this is not a valid bbox!");
-		return false;
-	}
-	
-	function toHtml () {
-		return (string) $this->min->toHtml() . " | " . $this->max->toHtml(); 
-	}
-	
-	function __toString() {
-		return (string) "[" . $this->min . $this->max . " " . $this->epsg . "]"; 
-	}
-	
-	function toJson() {
-		return (string) "[" . $this->min->x . ",". $this->min->y . "," . $this->max->x . "," . $this->max->y . "]";
-	}
-}
-?>

Copied: branches/mapbender/http/classes/class_bbox.php (from rev 6955, trunk/mapbender/http/classes/class_bbox.php)
===================================================================
--- branches/mapbender/http/classes/class_bbox.php	                        (rev 0)
+++ branches/mapbender/http/classes/class_bbox.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -0,0 +1,181 @@
+<?php
+# $Id$
+# http://www.mapbender.org/index.php/
+# 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__)."/../../core/globalSettings.php");
+require_once(dirname(__FILE__)."/class_point.php");
+
+/**
+ * A bounding box consisting of an lower left and an upper right point, and an EPSG.
+ */
+class Mapbender_bbox {
+	var $min;
+	var $max;
+	var $epsg;
+	
+	/**
+	 * @constructor
+	 */
+	function __construct() {
+		if (func_num_args() == 5) {
+			$param0 = func_get_arg(0);
+			$param1 = func_get_arg(1);
+			$param2 = func_get_arg(2);
+			$param3 = func_get_arg(3);
+			$param4 = func_get_arg(4);
+		}
+		else if (func_num_args() == 3) {
+			$param0 = func_get_arg(0);
+			$param1 = func_get_arg(1);
+			$param2 = func_get_arg(2);
+		}
+		else {
+			return;
+		}
+		
+		// params are point, point, epsg
+		if (is_a($param0, "Mapbender_point") && is_a($param1, "Mapbender_point") && !$param3 && !$param4) {
+			$e = new mb_notice("Mapbender_bbox: constructor: point1, point2, epsg");
+			$min = $param0; // is a Mapbender_point
+			$max = $param1; // is a Mapbender_point
+			$epsg = $param2; // is an EPSG code like "EPSG:4326"
+			
+			if (($min->isWestOf($max) && $min->isSouthOf($max)) || $min->equals($max)) {
+				if ($min->epsg == $max->epsg && $min->epsg == $epsg) {
+					$this->min = $min;
+					$this->max = $max;
+					$this->epsg = $epsg;
+				}
+				else {
+					$e = new mb_exception("Mapbender_bbox: constructor: EPSG mismatch!");
+				}
+			}
+			else {
+				$e = new mb_exception("Mapbender_bbox: constructor: min (".$this->min.") is not southwest of max (".$this->max.")!");
+			}
+		}
+		// params are x1, y1, x2, xy, epsg
+		else {
+			$e = new mb_notice("Mapbender_bbox: constructor: x1, y1, x2, y2, epsg");
+			$min = new Mapbender_point($param0, $param1, $param4);
+			$max = new Mapbender_point($param2, $param3, $param4);
+			$epsg = $param4; // is an EPSG code like "EPSG:4326"
+			
+			if ($min->isWestOf($max) && $min->isSouthOf($max)) {
+				if ($min->epsg == $max->epsg && $min->epsg == $epsg) {
+					$this->min = $min;
+					$this->max = $max;
+					$this->epsg = $epsg;
+				}
+				else {
+					$e = new mb_exception("Mapbender_bbox: constructor: EPSG mismatch!");
+				}
+			}
+			else {
+				$e = new mb_exception("Mapbender_bbox: constructor: min (".$this->min.") is not southwest of max (".$this->max.")!");
+			}
+			
+		}
+	}
+
+	public static function createFromLayerEpsg ($c) {
+		return new Mapbender_bbox(
+			$c["minx"], $c["miny"], $c["maxx"], $c["maxy"], $c["epsg"]
+		);
+	}
+
+	/**
+	 * Computes a new bounding box, bbox1 UNION bbox2
+	 */
+	static function union ($bboxArray) {
+		if (count($bboxArray) == 1) {
+			return array_pop($bboxArray);
+		}
+		elseif (count($bboxArray) >= 2) {
+			
+			$bbox1 = array_pop($bboxArray);
+			$bbox2 = Mapbender_bbox::union($bboxArray);
+
+			if (!($bbox1 != null && $bbox1->isValid()) && !($bbox2 != null && $bbox2->isValid())) {
+				$e = new mb_exception("Mapbender_bbox: union: both parameters invalid!");
+				return null;
+			}
+			elseif (!($bbox1 != null && $bbox1->isValid()) && ($bbox2 != null && $bbox2->isValid())) {
+				$e = new mb_exception("Mapbender_bbox: union: first parameter invalid!");
+				return $bbox2;
+			}
+			elseif (($bbox1 != null && $bbox1->isValid()) && !($bbox2 != null && $bbox2->isValid())) {
+				$e = new mb_exception("Mapbender_bbox: union: second parameter invalid!");
+				return $bbox1;
+			}
+			else {
+				if ($bbox1->epsg == $bbox2->epsg) {
+					$e = new mb_notice("Mapbender_bbox: union: bbox1 is: " . $bbox1);
+					$e = new mb_notice("Mapbender_bbox: union: bbox2 is: " . $bbox2);
+					$e = new mb_notice("Mapbender_bbox: union: merging bbox1 and bbox2...");
+					return new Mapbender_bbox(Mapbender_point::min($bbox1->min, $bbox2->min), Mapbender_point::max($bbox1->max, $bbox2->max), $bbox1->epsg);
+				}
+				else {
+					$e = new mb_exception("Mapbender_bbox: cannot process union with different EPSG codes");
+				}
+			}
+		}
+		else {
+			$e = new mb_exception("Mapbender_bbox: Invalid parameter (Not an array)!");
+		}
+		return null;
+	}
+	
+	/**
+	 * transforms this bbox in another EPSG
+	 * @param toEpsg transform the bbox to this EPSG code, example: "EPSG:4326" 
+	 */
+	function transform($toEpsg) {
+		if ($this->isValid()) {
+			$this->epsg = $toEpsg;
+			$this->min->transform($toEpsg);
+			$this->max->transform($toEpsg);
+			return true;
+		}
+		return false;
+	}
+
+	/**
+	 * checks if lower left and upper right coordinate are set, as well as EPSG
+	 */
+	function isValid() {
+		if ($this->min != null && $this->max != null && $this->epsg != null) {
+			return true;
+		}
+		$e = new mb_exception("Mapbender_bbox: this is not a valid bbox!");
+		return false;
+	}
+	
+	function toHtml () {
+		return (string) $this->min->toHtml() . " | " . $this->max->toHtml(); 
+	}
+	
+	function __toString() {
+		return (string) "[" . $this->min . $this->max . " " . $this->epsg . "]"; 
+	}
+	
+	function toJson() {
+		return (string) "[" . $this->min->x . ",". $this->min->y . "," . $this->max->x . "," . $this->max->y . "]";
+	}
+}
+?>

Deleted: branches/mapbender/http/classes/class_elementVar.php
===================================================================
--- trunk/mapbender/http/classes/class_elementVar.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/http/classes/class_elementVar.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,119 +0,0 @@
-<?php
-# License:
-# Copyright (c) 2009, Open Source Geospatial Foundation
-# This program is dual licensed under the GNU General Public License 
-# and Simplified BSD license.  
-# http://svn.osgeo.org/mapbender/trunk/mapbender/license/license.txt
-
-require_once(dirname(__FILE__)."/../../core/globalSettings.php");
-require_once(dirname(__FILE__)."/../classes/class_RPCEndpoint.php");
-
-/**
- * A Mapbender user as described in the table mb_user.
- */
-class ElementVar implements RPCObject{
-	/**
-	 * @var Integer The User ID
-	 */
-	var $applicationId;
-	var $elementId;
-	var $name;  
-	var $value;
-	var $context;
-	var $type;
-	
-	/**
-	 * Constructor
-	 * @param $application String 	name of the application
-	 * @param $element String 	name of the element
-	 */
-	public function __construct () {
-		if (func_num_args() === 3) {
-			try {
-				$this->applicationId = func_get_arg(0);
-				$this->elementId = func_get_arg(1);
-				$this->name = func_get_arg(2);
-				$this->load();
-			}
-			catch (Exception $e) {
-				throw new Exception ("Could not initialize element var.");
-			}
-		}
-	}	
-
-	
-	/**
-	 * @return String the name of this element var
-	 */
-	public function __toString () {
-		return (string) $this->name;	
-	}
-
-
-    /*
-    * @return Assoc Array containing the fields to send to the user
-    */
-    public function getFields() {
-        $result = array(
-        );
-		return $result;
-	}
-
-	public function create() {
-	}
-
-
-	/*
-	*	@param	$changes JSON  keys and their values of what to change in the object
-	*/
-	public function change($changes) {
-	}
-
-	public function commit() {
-	}
-
-	public function remove() {
-	}
-	
-	public function toSql () {
-		$insert .= "INSERT INTO gui_element_vars(fkey_gui_id, fkey_e_id, var_name, var_value, context, var_type";
-		$insert .= ") VALUES (";
-		$insert .= "'" . $this->applicationId . "',";
-		$insert .= "'" . $this->elementId . "',";
-		$insert .= "'" . $this->name . "',";
-		$insert .= "'" . db_escape_string($this->value) . "',";
-		$insert .= "'" . db_escape_string($this->context) . "',";
-		$insert .= "'" . $this->type . "'";
-		$insert.=");\n";
-		return $insert;
-	}
-
-	public function load() {
-		$sql = "SELECT * from gui_element_vars WHERE fkey_gui_id = $1 AND fkey_e_id = $2 AND var_name = $3; ";
-		$v = array($this->applicationId, $this->elementId, $this->name);
-		$t = array("s", "s", "s");
-		$res = db_prep_query($sql, $v, $t);
-
-		if ($row = db_fetch_array($res)) {
-			$this->value = $row["var_value"];
-			$this->context = $row["context"];
-			$this->type = $row["var_type"];
-		}
-		else {
-			 throw new Exception("no such element var");
-		}
-	}
-
-	public static function getList($filter) {
-      return array();
-    }
-
-    public static function byName($name) {
-      return null;
-    }
-	
-	public function isValid () {
-		return true;
-	}
-}
-?>

Copied: branches/mapbender/http/classes/class_elementVar.php (from rev 6929, trunk/mapbender/http/classes/class_elementVar.php)
===================================================================
--- branches/mapbender/http/classes/class_elementVar.php	                        (rev 0)
+++ branches/mapbender/http/classes/class_elementVar.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -0,0 +1,120 @@
+<?php
+# License:
+# Copyright (c) 2009, Open Source Geospatial Foundation
+# This program is dual licensed under the GNU General Public License 
+# and Simplified BSD license.  
+# http://svn.osgeo.org/mapbender/trunk/mapbender/license/license.txt
+
+require_once(dirname(__FILE__)."/../../core/globalSettings.php");
+require_once(dirname(__FILE__)."/../classes/class_RPCEndpoint.php");
+
+/**
+ * A Mapbender user as described in the table mb_user.
+ */
+class ElementVar implements RPCObject{
+	/**
+	 * @var Integer The User ID
+	 */
+	var $applicationId;
+	var $elementId;
+	var $name;  
+	var $value;
+	var $context;
+	var $type;
+	
+	/**
+	 * Constructor
+	 * @param $application String 	name of the application
+	 * @param $element String		name of the element
+	 * @param $name String			name of the element var
+	 */
+	public function __construct () {
+		if (func_num_args() === 3) {
+			try {
+				$this->applicationId = func_get_arg(0);
+				$this->elementId = func_get_arg(1);
+				$this->name = func_get_arg(2);
+				$this->load();
+			}
+			catch (Exception $e) {
+				throw new Exception ("Could not initialize element var.");
+			}
+		}
+	}	
+
+	
+	/**
+	 * @return String the name of this element var
+	 */
+	public function __toString () {
+		return (string) $this->name;	
+	}
+
+
+    /*
+    * @return Assoc Array containing the fields to send to the user
+    */
+    public function getFields() {
+        $result = array(
+        );
+		return $result;
+	}
+
+	public function create() {
+	}
+
+
+	/*
+	*	@param	$changes JSON  keys and their values of what to change in the object
+	*/
+	public function change($changes) {
+	}
+
+	public function commit() {
+	}
+
+	public function remove() {
+	}
+	
+	public function toSql () {
+		$insert .= "INSERT INTO gui_element_vars(fkey_gui_id, fkey_e_id, var_name, var_value, context, var_type";
+		$insert .= ") VALUES (";
+		$insert .= "'" . $this->applicationId . "',";
+		$insert .= "'" . $this->elementId . "',";
+		$insert .= "'" . $this->name . "',";
+		$insert .= "'" . db_escape_string($this->value) . "',";
+		$insert .= "'" . db_escape_string($this->context) . "',";
+		$insert .= "'" . $this->type . "'";
+		$insert.=");\n";
+		return $insert;
+	}
+
+	public function load() {
+		$sql = "SELECT * from gui_element_vars WHERE fkey_gui_id = $1 AND fkey_e_id = $2 AND var_name = $3; ";
+		$v = array($this->applicationId, $this->elementId, $this->name);
+		$t = array("s", "s", "s");
+		$res = db_prep_query($sql, $v, $t);
+
+		if ($row = db_fetch_array($res)) {
+			$this->value = $row["var_value"];
+			$this->context = $row["context"];
+			$this->type = $row["var_type"];
+		}
+		else {
+			 throw new Exception("no such element var");
+		}
+	}
+
+	public static function getList($filter) {
+      return array();
+    }
+
+    public static function byName($name) {
+      return null;
+    }
+	
+	public function isValid () {
+		return true;
+	}
+}
+?>

Deleted: branches/mapbender/http/classes/class_layer_monitor.php
===================================================================
--- trunk/mapbender/http/classes/class_layer_monitor.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/http/classes/class_layer_monitor.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,57 +0,0 @@
-<?php
-# $Id$
-# http://www.mapbender.org/index.php/
-# 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__)."/../../core/globalSettings.php");
-
-class Layer_load_count {
-
-	function __construct () {
-	}
-	
-	/**
-	 * increments the load count in table "layer_load_count" for
-	 * each layer in the WMC document by one. 
-	 */
-	function increment($layer_id) {
-
-		//check if an entry exists for the current layer id
-		$sql = "SELECT load_count FROM layer_load_count WHERE fkey_layer_id = $1";
-		$v = array($layer_id);
-		$t = array('i');
-		$res = db_prep_query($sql, $v, $t);
-		$row = db_fetch_array($res);
-
-		//if yes, increment the load counter
-		if ($row) {
-			$currentCount = $row["load_count"];
-			$sql = "UPDATE layer_load_count SET load_count = $1 WHERE fkey_layer_id = $2";
-			$v = array(intval($currentCount + 1), $layer_id);
-			$t = array('i', 'i');
-			$res = db_prep_query($sql, $v, $t);
-		}
-		//if no, insert a new row with current layer id and load_count = 1
-		else {
-			$sql = "INSERT INTO layer_load_count (fkey_layer_id, load_count) VALUES ($1, 1)";
-			$v = array($layer_id);
-			$t = array('i');
-			$res = db_prep_query($sql, $v, $t);
-		}
-	}
-}
-?>

Copied: branches/mapbender/http/classes/class_layer_monitor.php (from rev 6931, trunk/mapbender/http/classes/class_layer_monitor.php)
===================================================================
--- branches/mapbender/http/classes/class_layer_monitor.php	                        (rev 0)
+++ branches/mapbender/http/classes/class_layer_monitor.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -0,0 +1,60 @@
+<?php
+# $Id$
+# http://www.mapbender.org/index.php/
+# 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__)."/../../core/globalSettings.php");
+
+class Layer_load_count {
+
+	function __construct () {
+	}
+	
+	/**
+	 * increments the load count in table "layer_load_count" for
+	 * each layer in the WMC document by one. 
+	 */
+	function increment($layer_id) {
+		if (!is_numeric($layer_id)) {
+			return false;
+		}
+
+		//check if an entry exists for the current layer id
+		$sql = "SELECT load_count FROM layer_load_count WHERE fkey_layer_id = $1";
+		$v = array($layer_id);
+		$t = array('i');
+		$res = db_prep_query($sql, $v, $t);
+		$row = db_fetch_array($res);
+
+		//if yes, increment the load counter
+		if ($row) {
+			$currentCount = $row["load_count"];
+			$sql = "UPDATE layer_load_count SET load_count = $1 WHERE fkey_layer_id = $2";
+			$v = array(intval($currentCount + 1), $layer_id);
+			$t = array('i', 'i');
+			$res = db_prep_query($sql, $v, $t);
+		}
+		//if no, insert a new row with current layer id and load_count = 1
+		else {
+			$sql = "INSERT INTO layer_load_count (fkey_layer_id, load_count) VALUES ($1, 1)";
+			$v = array($layer_id);
+			$t = array('i');
+			$res = db_prep_query($sql, $v, $t);
+		}
+	}
+}
+?>

Deleted: branches/mapbender/http/classes/class_map.php
===================================================================
--- trunk/mapbender/http/classes/class_map.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/http/classes/class_map.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,706 +0,0 @@
-<?php
-require_once(dirname(__FILE__)."/../classes/class_bbox.php");
-/**
- * Representing a map object, identical to the JS object in javascripts/map.js
- * @class
- */
-class Map {
-
-	private $width;
-	private $height;
-	private $frameName;
-	private $elementName;
-	private $extent;
-	private $zoomFullExtentArray = array();
-	private $isOverview = false;
-	private $wmsArray = array();
-	
-	/**
-	 * @destructor
-	 * @param
-	 */
-	function __destruct() {
-	}
-
-	/**
-	 * @constructor
-	 * @param
-	 */
-	function __construct() {
-	}
-	
-	//-------------------------------------------------------------------------
-	// getter and setter
-	//-------------------------------------------------------------------------
-	/**
-	 * @param $value Integer
-	 */
-	public function setWidth ($value) {
-		$this->width = $value;
-	}
-
-	/**
-	 * 
-	 * @return 
-	 */
-	public function getWidth () {
-		return $this->width;
-	}
-
-	/**
-	 * @param $value Integer
-	 */
-	public function setHeight ($value) {
-		$this->height = $value;
-	}
-
-	/**
-	 * 
-	 * @return 
-	 */
-	public function getHeight () {
-		return $this->height;
-	}
-
-	/**
-	 * @param $value String
-	 */
-	public function setFrameName ($value) {
-		$this->frameName = strval($value);
-	}
-
-	/**
-	 * @param $value String
-	 */
-	public function setElementName ($value) {
-		$this->elementName = strval($value);
-	}
-
-	/**
-	 * 
-	 * @return String
-	 */
-	public function getFrameName () {
-		return $this->frameName;	
-	}
-	
-	public function addZoomFullExtent ($aMapbenderBbox) {
-		array_push($this->zoomFullExtentArray, $aMapbenderBbox);
-	}
-	
-	public function getZoomFullExtentArray () {
-		return $this->zoomFullExtentArray;
-	}
-	/**
-	 * @param $value String
-	 */
-	public function setExtent ($aMapbenderBbox) {
-		$this->extent = $aMapbenderBbox;
-	}
-
-	/**
-	 * 
-	 * @return Mapbender_bbox 
-	 */
-	public function getExtent () {
-		return $this->extent;	
-	}
-
-	/**
-	 * 
-	 * @return Mapbender_bbox extent information
-	 */
-	public function getExtentInfo () {
-		return array($this->extent->min->x, $this->extent->min->y, $this->extent->max->x, $this->extent->max->y);	
-	}	
-	
-	/**
-	 * converts the extent of the map so that the maximum	extent will be displayed
-	 *
-	 */
-	public function calculateExtent($aMapbenderBbox) {
-		$relation_px_x = $this->getWidth() / $this->getHeight();
-		$relation_px_y = $this->getHeight() / $this->getWidth();
-		$extentx = ($aMapbenderBbox->max->x - $aMapbenderBbox->min->x);
-		$extenty = ($aMapbenderBbox->max->y - $aMapbenderBbox->min->y);
-		$centerx = $aMapbenderBbox->min->x + $extentx/2;
-		$centery = $aMapbenderBbox->min->y + $extenty/2;
-		$relation_bbox_x = $extentx / $extenty;     
-		if($relation_bbox_x <= $relation_px_x){                
-			$aMapbenderBbox->min->x = $centerx - $relation_px_x * $extenty / 2;
-			$aMapbenderBbox->max->x = $centerx + $relation_px_x * $extenty / 2;
-		}
-		if($relation_bbox_x > $relation_px_x){                
-			$aMapbenderBbox->min->y = $centery - $relation_px_y * $extentx / 2;
-			$aMapbenderBbox->max->y = $centery + $relation_px_y * $extentx / 2;
-		}
-		$this->setExtent($aMapbenderBbox);
-	}
-	/**
-	 * 
-	 * @return Int scale of map
-	 */
-	public function getScale($mapResolutionDpi = MB_RESOLUTION){
-		$scale;
-		$xtenty;
-		$bbox = $this->getExtentInfo();
-		
-		if ($this->getEpsg() == "EPSG:4326") {
-			$pxLenx = ($bbox[2] - $bbox[0]) / $this->getWidth();
-			$pxLeny = ($bbox[3] - $bbox[1]) / $this->getHeight();
-			$lat_from = ((($bbox[3] - $bbox[1]) / 2) * M_PI) / 180;
-			$lat_to = ((($bbox[3] - $bbox[1]) / 2 + $pxLeny) * M_PI) / 180;
-			$lon_from = ((($bbox[2] - $bbox[0]) / 2) * M_PI) / 180;
-			$lon_to = ((($bbox[2] - $bbox[0]) / 2 + $pxLeny) * M_PI) / 180;
-			$dist = 6371229 * acos(sin($lat_from) * sin($lat_to) + cos($lat_from) * cos($lat_to) * cos($lon_from - $lon_to));
-			$scale = ($dist / sqrt(2)) * ($mapResolutionDpi * 100);
-		}
-		else {
-			$xtenty = $bbox[3] - $bbox[1];
-			$scale = ($xtenty / $this->getHeight()) * ($mapResolutionDpi * 100);
-		}
-		return round($scale);
-	}	
-	
-	
-	/**
-	 * 
-	 * @return String EPSG code of the map.
-	 */
-	public function getEpsg () {
-		return $this->extent->epsg;	
-	}
-	
-	public function getWms ($index) {
-		if (is_numeric($index)) {
-			$i = intval($index, 10); 
-			if ($i < count($this->wmsArray) && count($this->wmsArray) > 0 && $i >= 0) {
-				return $this->wmsArray[$i];
-			}
-		}
-		return null;
-	}
-	
-	/**
-	 * 
-	 * @return 
-	 */
-	public function getWmsArray () {
-		return $this->wmsArray;	
-	}
-	
-	/**
-	 * 
-	 * @return 
-	 * @param $wmsArray Object
-	 */
-	public function setWmsArray ($wmsArray) {
-		$this->wmsArray = $wmsArray;
-	}
-	
-	/**
-	 * 
-	 * @return 
-	 */
-	public function isOverview () {
-		return $this->isOverview;
-	}
-	
-	public function setIsOverview ($bool) {
-		$this->isOverview = $bool;
-	}
-	
-	/**
-	 * @param $value Object
-	 */
-	public function addWms ($value) {
-		array_push($this->wms, $value);
-	}	
-
-
-	// ------------------------------------------------------------------------
-	// map manipulation
-	// ------------------------------------------------------------------------
-
-	/**
-	 * Appends the WMS of another map to this map.
-	 * 
-	 * @param $anotherMap Map
-	 */
-	public function append ($anotherMap) {
-		$this->wmsArray = array_merge($anotherMap->getWmsArray(), $this->wmsArray);
-	}
-		
-	/**
-	 * Merges this map with another map: Copies the map settings from the 
-	 * other map and merges the WMS (keeping the settings of the other
-	 * map if there are duplicates)
-	 * 
-	 * @param $anotherMap Map
-	 */
-	public function merge ($anotherMap) {
-		$this->width = $anotherMap->width;
-		$this->height = $anotherMap->height;
-		$this->frameName = $anotherMap->frameName;
-		$this->elementName = $anotherMap->elementName;
-		$this->extent = $anotherMap->extent;
-		$this->isOverview = $anotherMap->isOverview;
-		$this->wmsArray = wms::merge(array_merge($anotherMap->getWmsArray(), $this->wmsArray));
-	}
-
-	/**
-	 * Adds WMS to this map
-	 * 
-	 * @return 
-	 */
-	public function appendWmsArray ($wmsArray) {
-		$this->wmsArray = array_merge($this->wmsArray, $wmsArray);
-	}
-	
-	/**
-	 * Merge WMS into this map
-	 * 
-	 * @return 
-	 */
-	public function mergeWmsArray ($wmsArray) {
-		if (func_num_args() > 1 
-			&& is_array($wmsArray) 
-			&& count($wmsArray) > 0) {
-			$options = func_get_arg(1);
-
-			if ($options["zoom"]) {
-				$ext = $this->getExtent();
-				$srs = $ext->epsg;
-				$currentWms = $wmsArray[0];
-
-				$bboxExists = false;
-				$wgs84Index = null;
-				// check if SRS of root layer matches WMC SRS
-				for ($i = 0; $i < count($currentWms->objLayer[0]->layer_epsg); $i++) {
-					$currentLayerEpsg = $currentWms->objLayer[0]->layer_epsg[$i];
-					if ($currentLayerEpsg["epsg"] !== $srs) {
-						if ($currentLayerEpsg["epsg"] === "EPSG:4326") {
-							$wgs84Index = $i;
-						}
-						continue;
-					}
-
-					// calculate WMC bbox from root layer bbox
-					$bboxExists = true;
-					$this->calculateExtent(new Mapbender_bbox(
-						$currentLayerEpsg["minx"], 
-						$currentLayerEpsg["miny"], 
-						$currentLayerEpsg["maxx"], 
-						$currentLayerEpsg["maxy"], 
-						$srs
-					));
-				}
-				
-				if (!$bboxExists && !is_null($wgs84Index)) {
-					$currentLayerEpsg = $currentWms->objLayer[0]->layer_epsg[$wgs84Index];
-					$extArray = array(
-						$currentLayerEpsg["minx"],
-						$currentLayerEpsg["miny"],
-						$currentLayerEpsg["maxx"],
-						$currentLayerEpsg["maxy"],
-					);
-					$oldEPSG = "4326";
-					$newEPSG = preg_replace("/EPSG:/","", $srs);
-
-					// calculate bbox via PostGIS
-					if(SYS_DBTYPE=='pgsql') {
-						$con = db_connect($DBSERVER,$OWNER,$PW);
-						$sqlMinx = "SELECT X(transform(GeometryFromText('POINT(".$extArray[0]." ".$extArray[1].")',".$oldEPSG."),".$newEPSG.")) as minx";
-						$resMinx = db_query($sqlMinx);
-						$minx = floatval(db_result($resMinx,0,"minx"));
-						
-						$sqlMiny = "SELECT Y(transform(GeometryFromText('POINT(".$extArray[0]." ".$extArray[1].")',".$oldEPSG."),".$newEPSG.")) as miny";
-						$resMiny = db_query($sqlMiny);
-						$miny = floatval(db_result($resMiny,0,"miny"));
-						
-						$sqlMaxx = "SELECT X(transform(GeometryFromText('POINT(".$extArray[2]." ".$extArray[3].")',".$oldEPSG."),".$newEPSG.")) as maxx";
-						$resMaxx = db_query($sqlMaxx);
-						$maxx = floatval(db_result($resMaxx,0,"maxx"));
-						
-						$sqlMaxy = "SELECT Y(transform(GeometryFromText('POINT(".$extArray[2]." ".$extArray[3].")',".$oldEPSG."),".$newEPSG.")) as maxy";
-						$resMaxy = db_query($sqlMaxy);
-						$maxy = floatval(db_result($resMaxy,0,"maxy"));
-					}
-					else {
-						$con_string = "host=$GEOS_DBSERVER port=$GEOS_PORT dbname=$GEOS_DB user=$GEOS_OWNER password=$GEOS_PW";
-						$con = pg_connect($con_string) or die ("Error while connecting database");
-						
-						$sqlMinx = "SELECT X(transform(GeometryFromText('POINT(".$extArray[0]." ".$extArray[1].")',".$oldEPSG."),".$newEPSG.")) as minx";
-						$resMinx = pg_query($con,$sqlMinx);
-						$minx = floatval(pg_fetch_result($resMinx,0,"minx"));
-						
-						$sqlMiny = "SELECT Y(transform(GeometryFromText('POINT(".$extArray[0]." ".$extArray[1].")',".$oldEPSG."),".$newEPSG.")) as miny";
-						$resMiny = pg_query($con,$sqlMiny);
-						$miny = floatval(pg_fetch_result($resMiny,0,"miny"));
-						
-						$sqlMaxx = "SELECT X(transform(GeometryFromText('POINT(".$extArray[2]." ".$extArray[3].")',".$oldEPSG."),".$newEPSG.")) as maxx";
-						$resMaxx = pg_query($con,$sqlMaxx);
-						$maxx = floatval(pg_fetch_result($resMaxx,0,"maxx"));
-						
-						$sqlMaxy = "SELECT Y(transform(GeometryFromText('POINT(".$extArray[2]." ".$extArray[3].")',".$oldEPSG."),".$newEPSG.")) as maxy";
-						$resMaxy = pg_query($con,$sqlMaxy);
-						$maxy = floatval(pg_fetch_result($resMaxy,0,"maxy"));
-					}
-					$bboxExists = true;
-					$this->calculateExtent(new Mapbender_bbox(
-						$minx, 
-						$miny, 
-						$maxx, 
-						$maxy, 
-						$srs
-					));
-				}
-				
-				if (!$bboxExists) {
-					$e = new mb_exception(__FILE__ . ": mergeWmsArray: Could not determine bounding box of WMS in SRS " . $srs);
-				}
-			}
-			
-			// visibility of WMS
-			if (isset($options["visible"])) {
-				if ($options["visible"]) {
-					// set all layers of WMS to visible
-					for ($i = 0; $i < count($wmsArray); $i++) {
-						$numLayers = count($wmsArray[$i]->objLayer);
-	
-						// using option show is dependent to option visible = true
-						if ($options["show"] && is_numeric($options["show"])) {
-							// do not display if layer count is too big
-							if ($numLayers > intval($options["show"])) {
-								continue;
-							}
-						}
-						
-						for ($j = 0; $j < $numLayers; $j++) {
-							$wmsArray[$i]->objLayer[$j]->gui_layer_visible = 1;
-						}
-					}
-				}
-				else {
-					// set all layers of WMS to visible
-					for ($i = 0; $i < count($wmsArray); $i++) {
-						$numLayers = count($wmsArray[$i]->objLayer);
-	
-						for ($j = 0; $j < $numLayers; $j++) {
-							$wmsArray[$i]->objLayer[$j]->gui_layer_visible = 0;
-						}
-					}
-				}
-			}
-			
-			
-			if ($options["show"] && is_numeric($options["show"]) && !isset($options["visible"])) {
-				$e = new mb_exception("show");
-				// set all layers of WMS to visible
-				for ($i = 0; $i < count($wmsArray); $i++) {
-					$numLayers = count($wmsArray[$i]->objLayer);
-					
-					// do not display if layer count is too big
-					if ($numLayers > intval($options["show"])) {
-						continue;
-					}
-					
-					for ($j = 0; $j < $numLayers; $j++) {
-						$wmsArray[$i]->objLayer[$j]->gui_layer_visible = 1;
-					}
-				}
-			}
-		}
-		
-		$this->wmsArray = wms::merge(array_merge($this->wmsArray, $wmsArray));
-	}
-
-
-	// ------------------------------------------------------------------------
-	// Instantiation
-	// ------------------------------------------------------------------------
-	/**
-	 * 
-	 * @return 
-	 * @param $jsMapObject Object
-	 */
-	public function createFromJs ($jsMapObject) {
-		$b = $jsMapObject->extent;
-
-		$srs = $jsMapObject->epsg;
-		$bbox = new Mapbender_bbox(
-			$b->min->x, 
-			$b->min->y, 
-			$b->max->x, 
-			$b->max->y, 
-			$srs
-		);
-
-		$this->width = $jsMapObject->width;
-		$this->height = $jsMapObject->height;
-		// there are no more map frames in Mapbender 2.6
-		$this->frameName = $jsMapObject->elementName;
-		$this->extent = $bbox;
-		
-		if (isset($jsMapObject->isOverview) && $jsMapObject->isOverview == "1") {
-			$this->isOverview = true;
-		}
-
-		for ($i=0; $i < count($jsMapObject->wms); $i++){
-	
-			$currentWms = $jsMapObject->wms[$i];
-			$wms = new wms();
-
-			//
-			// set WMS data
-			//
-			$wms->wms_id = $currentWms->wms_id;
-			$wms->wms_version = $currentWms->wms_version;
-			$wms->wms_title = $currentWms->wms_title;
-			$wms->wms_abstract = $currentWms->wms_abstract;
-			$wms->wms_getmap = $currentWms->wms_getmap;
-			$wms->wms_getfeatureinfo = $currentWms->wms_getfeatureinfo;
-			$wms->wms_getlegendurl = $currentWms->wms_getlegendurl;
-			$wms->wms_filter = $currentWms->wms_filter;
-			$wms->wms_srs = $currentWms->wms_srs;
-			$wms->gui_epsg = $currentWms->gui_epsg;
-			$wms->gui_minx = $currentWms->gui_minx;
-			$wms->gui_miny = $currentWms->gui_miny;
-			$wms->gui_maxx = $currentWms->gui_maxx;
-			$wms->gui_maxy = $currentWms->gui_maxy;
-			$wms->gui_wms_mapformat = $currentWms->gui_wms_mapformat;
-			$wms->gui_wms_featureinfoformat = $currentWms->gui_wms_featureinfoformat;
-			$wms->gui_wms_exceptionformat = $currentWms->gui_wms_exceptionformat;
-			$wms->gui_wms_opacity = $currentWms->wms_opacity;
-			$wms->gui_wms_sldurl = $currentWms->gui_wms_sldurl;
-			$wms->gui_wms_visible = $currentWms->gui_wms_visible;
-			$wms->gui_wms_epsg = $currentWms->gui_wms_epsg;
-			$wms->data_type = $currentWms->data_type;
-			$wms->data_format = $currentWms->data_format;
-
-			for ($k = 0; $k < count($currentWms->objLayer); $k++){
-				// the current layer of the JSON map object
-				$currentLayer = $currentWms->objLayer[$k];
-
-				// add new layer to WMS
-				$pos = $currentLayer->layer_pos;
-				$parent = $currentLayer->layer_parent;
-				$wms->addLayer($pos, $parent); 
-
-				$newLayerIndex = count($wms->objLayer) - 1;
-				// $newLayer is a short cut to the layer we just added
-				$newLayer = $wms->objLayer[$newLayerIndex];
-				
-				// set layer data
-				$newLayer->layer_uid = $currentLayer->layer_uid;
-				$newLayer->layer_name = $currentLayer->layer_name;
-				$newLayer->layer_title = $currentLayer->layer_title;
-				$newLayer->layer_dataurl_href = $currentLayer->layer_dataurl_href;
-				$newLayer->layer_pos = $currentLayer->layer_pos;
-				$newLayer->layer_queryable = $currentLayer->layer_queryable;
-				$newLayer->layer_minscale = $currentLayer->layer_minscale;
-				$newLayer->layer_maxscale = $currentLayer->layer_maxscale;
-				$newLayer->layer_metadataurl = $currentLayer->metadataurl;
-				$newLayer->gui_layer_wms_id = $currentLayer->gui_layer_wms_id;
-//				$newLayer->gui_layer_wms_id = $wms->objLayer[0]->layer_uid;
-				$newLayer->gui_layer_status = $currentLayer->gui_layer_status;
-				$newLayer->gui_layer_style = $currentLayer->gui_layer_style;
-				$newLayer->gui_layer_selectable = $currentLayer->gui_layer_selectable;
-
-				if ($this->isOverview) {
-					preg_match_all("/LAYERS\=([^&]*)/", $jsMapObject->mapURL[0], $resultMatrix);
-					$layerList = $resultMatrix[1][0];
-					$layerListArray = explode(",", $layerList);
-					$newLayer->gui_layer_visible = (in_array($currentLayer->layer_name, $layerListArray)) ? 1 : 0;
-				}
-				else {
-					$newLayer->gui_layer_visible = $currentLayer->gui_layer_visible;
-				}
-				$newLayer->gui_layer_queryable = $currentLayer->gui_layer_queryable;
-				$newLayer->gui_layer_querylayer = $currentLayer->gui_layer_querylayer;
-				$newLayer->gui_layer_minscale = $currentLayer->gui_layer_minscale;
-				$newLayer->gui_layer_maxscale = $currentLayer->gui_layer_maxscale;
-				$newLayer->gui_layer_wfs_featuretype = $currentLayer->gui_layer_wfs_featuretype;
-				$newLayer->gui_layer_title = $currentLayer->gui_layer_title;
-
-				// BEWARE THIS IS SUPER UGLY CODE
-				$newLayer->layer_epsg = array();
-				for ($z = 0; $z < count($currentLayer->layer_epsg); $z++) {
-					$newLayer->layer_epsg[$z] = array();
-					$newLayer->layer_epsg[$z]["epsg"] = $currentLayer->layer_epsg[$z]->epsg;
-					$newLayer->layer_epsg[$z]["minx"] = $currentLayer->layer_epsg[$z]->minx;
-					$newLayer->layer_epsg[$z]["miny"] = $currentLayer->layer_epsg[$z]->miny;
-					$newLayer->layer_epsg[$z]["maxx"] = $currentLayer->layer_epsg[$z]->maxx;
-					$newLayer->layer_epsg[$z]["maxy"] = $currentLayer->layer_epsg[$z]->maxy;
-				}
-				
-				// BEWARE THIS IS SUPER UGLY CODE
-				$newLayer->layer_style = array();
-				for ($z = 0; $z < count($currentLayer->layer_style); $z++) {
-					$newLayer->layer_style[$z] = array();
-					$newLayer->layer_style[$z]["name"] = $currentLayer->layer_style[$z]->name ? $currentLayer->layer_style[$z]->name : "default";
-					$newLayer->layer_style[$z]["title"] = $currentLayer->layer_style[$z]->title ? $currentLayer->layer_style[$z]->title : "default";
-					$newLayer->layer_style[$z]["legendurl"] = $currentLayer->layer_style[$z]->legendurl;
-					$newLayer->layer_style[$z]["legendurlformat"] = $currentLayer->layer_style[$z]->legendurlformat;
-				}
-
-			}
-			array_push($this->wmsArray, $wms);
-		}
-		return true;
-	}
-	
-	
-	// ------------------------------------------------------------------------
-	// database functions
-	// ------------------------------------------------------------------------
-	public static function selectMainMapByApplication ($appId) {
-		return map::selectByApplication($appId, "mapframe1");
-	}
-	
-	public static function selectOverviewMapByApplication ($appId) {
-		$currentMap = map::selectByApplication($appId, "overview");
-		if ($currentMap !== null) {
-			$currentMap->setIsOverview(true);
-		}
-		return $currentMap;
-	}
-
-
-	// ------------------------------------------------------------------------
-	// Output
-	// ------------------------------------------------------------------------
-	/**
-	 * Returns an array of string, which are JS statements.
-	 * @return String[]
-	 */
-	public function toJavaScript ($wmsJson) {
-		$jsCodeArray = array();
-
-		// syntax has changed in 2.6! Map is no longer a frame
-		$registerMapString = "var currentWmcMap = Mapbender.modules['" . 
-			$this->frameName . "'];" .
-			"currentWmcMap.elementName = '" . $this->frameName . "';" . 
-			"currentWmcMap.setWidth(" . $this->width . ");" . 
-			"currentWmcMap.setHeight(" . $this->height . ");"; 
-		array_push($jsCodeArray, $registerMapString);
-
-		// if map is overview...
-		if ($this->isOverview) {
-			// ...set overview flag
-			$setOverviewFlagString = "currentWmcMap.isOverview = true;";
-			array_push($jsCodeArray, $setOverviewFlagString);
-		}
-
-		// calculate extent
-		$calcExtentString = "currentWmcMap.setSrs({" . 
-			"srs: '" . $this->extent->epsg . "'," . 
-			"extent: new Mapbender.Extent(" . 
-			$this->extent->min->x . ", " . 
-			$this->extent->min->y . ", " . 
-			$this->extent->max->x . ", " . 
-			$this->extent->max->y . ")});"; 
-		array_push($jsCodeArray, $calcExtentString);
-		
-		$setWmsString = "currentWmcMap.setWms(" . $wmsJson . ");";
-		array_push($jsCodeArray, $setWmsString);
-		
-		$initWmsString = "currentWmcMap.initializeWms();";
-		array_push($jsCodeArray, $initWmsString);
-
-
-		return $jsCodeArray;
-	}
-
-
-	// ------------------------------------------------------------------------
-	// PRIVATE FUNCTIONS
-	// ------------------------------------------------------------------------
-	
-	private static function selectByApplication ($appId, $frameName) {
-		// find the mapframe in the application elements...
-		$sql = "SELECT * FROM gui_element WHERE fkey_gui_id = $1 AND " . 
-				"e_id = $2 AND e_public = 1 LIMIT 1";
-		$v = array($appId, $frameName);
-		$t = array('s', 's');
-		$res = db_prep_query($sql,$v,$t);
-		$row = db_fetch_array($res);
-		
-		// if found...
-		if ($row) {
-			$currentMap = new Map();
-
-			// use settings from database
-			$currentMap->setWidth($row["e_width"]);
-			$currentMap->setHeight($row["e_height"]);
-			$currentMap->setFrameName($row["e_id"]);
-			
-			// get the WMS 
-			$wmsArray = wms::selectMyWmsByApplication($appId);
-			
-//			$e = new mb_notice("WMS in this map: " . implode(",", $wmsArray));
-			
-			// if this is the overview, find the WMS index and 
-			// reset the WMS array
-			// BEWARE, SUPER UGLY CODE AHEAD!!
-			// (BUT THERE IS NO OTHER WAY TO DO IT)
-			if (strpos($row["e_js_file"], "mb_overview.js") !== false) {
-//				$e = new mb_exception("guess this is the OV");
-
-				$ov_sql = "SELECT var_value FROM gui_element_vars WHERE " . 
-					"var_name = 'overview_wms' AND fkey_e_id = $1 AND " . 
-					"fkey_gui_id = $2";
-				$ov_v = array($frameName, $appId);
-				$ov_t = array('s', 's');
-				$ov_res = db_prep_query($ov_sql, $ov_v, $ov_t);
-				$ov_row = db_fetch_array($ov_res);
-				if ($ov_row) {
-					$ov_index = intval($ov_row["var_value"]);
-				}
-				
-//				$e = new mb_exception("OV index: " . $ovIndex);
-				if (!isset($ovIndex)) {
-					$ovIndex = 0;
-				}
-				$wmsArray = array($wmsArray[$ovIndex]);	
-//				$e = new mb_notice("WMS in this map (corrected): " . implode(",", $wmsArray));
-			}
-			else {
-//				$e = new mb_exception("guess this is NOT the OV");
-			}
-
-			$currentMap->wmsArray = $wmsArray;
-			
-			// EXTENT
-			$sql = "SELECT gui_wms_epsg FROM gui_wms WHERE gui_wms_position = 0 AND fkey_gui_id = $1";
-			$v = array($appId);
-			$t = array('s');
-			$res = db_prep_query($sql, $v, $t);
-			$row = db_fetch_array($res);
-			$epsg = $row["gui_wms_epsg"];
-			$layer_epsg = $wmsArray[0]->objLayer[0]->layer_epsg;
-			$j = 0;
-			for ($i = 0; $i < count($layer_epsg); $i++) {
-				if ($layer_epsg[$i]["epsg"] === $epsg) {
-					$j = $i;
-					break;
-				}
-			}
-			$minx = $wmsArray[0]->objLayer[0]->layer_epsg[$j]["minx"];
-			$miny = $wmsArray[0]->objLayer[0]->layer_epsg[$j]["miny"];
-			$maxx = $wmsArray[0]->objLayer[0]->layer_epsg[$j]["maxx"];
-			$maxy = $wmsArray[0]->objLayer[0]->layer_epsg[$j]["maxy"];
-			$epsg = $wmsArray[0]->objLayer[0]->layer_epsg[$j]["epsg"];
-			$mapExtent = new Mapbender_bbox($minx, $miny, $maxx, $maxy, $epsg);
-			
-			$currentMap->setExtent($mapExtent);
-			return $currentMap;			
-		}
-		else {
-			return null;
-		}
-	}
-	
-
-}
-?>

Copied: branches/mapbender/http/classes/class_map.php (from rev 6955, trunk/mapbender/http/classes/class_map.php)
===================================================================
--- branches/mapbender/http/classes/class_map.php	                        (rev 0)
+++ branches/mapbender/http/classes/class_map.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -0,0 +1,737 @@
+<?php
+require_once(dirname(__FILE__)."/../classes/class_bbox.php");
+/**
+ * Representing a map object, identical to the JS object in javascripts/map.js
+ * @class
+ */
+class Map {
+
+	private $width;
+	private $height;
+	private $frameName;
+	private $elementName;
+	private $extent;
+	private $zoomFullExtentArray = array();
+	private $isOverview = false;
+	private $wmsArray = array();
+	
+	/**
+	 * @destructor
+	 * @param
+	 */
+	function __destruct() {
+	}
+
+	/**
+	 * @constructor
+	 * @param
+	 */
+	function __construct() {
+	}
+	
+	//-------------------------------------------------------------------------
+	// getter and setter
+	//-------------------------------------------------------------------------
+	/**
+	 * @param $value Integer
+	 */
+	public function setWidth ($value) {
+		$this->width = $value;
+	}
+
+	/**
+	 * 
+	 * @return 
+	 */
+	public function getWidth () {
+		return $this->width;
+	}
+
+	/**
+	 * @param $value Integer
+	 */
+	public function setHeight ($value) {
+		$this->height = $value;
+	}
+
+	/**
+	 * 
+	 * @return 
+	 */
+	public function getHeight () {
+		return $this->height;
+	}
+
+	/**
+	 * @param $value String
+	 */
+	public function setFrameName ($value) {
+		$this->frameName = strval($value);
+	}
+
+	/**
+	 * @param $value String
+	 */
+	public function setElementName ($value) {
+		$this->elementName = strval($value);
+	}
+
+	/**
+	 * 
+	 * @return String
+	 */
+	public function getFrameName () {
+		return $this->frameName;	
+	}
+	
+	public function addZoomFullExtent ($aMapbenderBbox) {
+		array_push($this->zoomFullExtentArray, $aMapbenderBbox);
+	}
+	
+	public function getZoomFullExtentArray () {
+		return $this->zoomFullExtentArray;
+	}
+	/**
+	 * @param $value String
+	 */
+	public function setExtent ($aMapbenderBbox) {
+		$this->extent = $aMapbenderBbox;
+	}
+
+	/**
+	 * 
+	 * @return Mapbender_bbox 
+	 */
+	public function getExtent () {
+		return $this->extent;	
+	}
+
+	/**
+	 * 
+	 * @return Mapbender_bbox extent information
+	 */
+	public function getExtentInfo () {
+		return array($this->extent->min->x, $this->extent->min->y, $this->extent->max->x, $this->extent->max->y);	
+	}	
+	
+	/**
+	 * converts the extent of the map so that the maximum	extent will be displayed
+	 *
+	 */
+	public function calculateExtent($aMapbenderBbox) {
+		$relation_px_x = $this->getWidth() / $this->getHeight();
+		$relation_px_y = $this->getHeight() / $this->getWidth();
+		$extentx = ($aMapbenderBbox->max->x - $aMapbenderBbox->min->x);
+		$extenty = ($aMapbenderBbox->max->y - $aMapbenderBbox->min->y);
+		$centerx = $aMapbenderBbox->min->x + $extentx/2;
+		$centery = $aMapbenderBbox->min->y + $extenty/2;
+		$relation_bbox_x = $extentx / $extenty;     
+		if($relation_bbox_x <= $relation_px_x){                
+			$aMapbenderBbox->min->x = $centerx - $relation_px_x * $extenty / 2;
+			$aMapbenderBbox->max->x = $centerx + $relation_px_x * $extenty / 2;
+		}
+		if($relation_bbox_x > $relation_px_x){                
+			$aMapbenderBbox->min->y = $centery - $relation_px_y * $extentx / 2;
+			$aMapbenderBbox->max->y = $centery + $relation_px_y * $extentx / 2;
+		}
+		$this->setExtent($aMapbenderBbox);
+	}
+	/**
+	 * 
+	 * @return Int scale of map
+	 */
+	public function getScale($mapResolutionDpi = MB_RESOLUTION){
+		$scale;
+		$xtenty;
+		$bbox = $this->getExtentInfo();
+		
+		if ($this->getEpsg() == "EPSG:4326") {
+			$pxLenx = ($bbox[2] - $bbox[0]) / $this->getWidth();
+			$pxLeny = ($bbox[3] - $bbox[1]) / $this->getHeight();
+			$lat_from = ((($bbox[3] - $bbox[1]) / 2) * M_PI) / 180;
+			$lat_to = ((($bbox[3] - $bbox[1]) / 2 + $pxLeny) * M_PI) / 180;
+			$lon_from = ((($bbox[2] - $bbox[0]) / 2) * M_PI) / 180;
+			$lon_to = ((($bbox[2] - $bbox[0]) / 2 + $pxLeny) * M_PI) / 180;
+			$dist = 6371229 * acos(sin($lat_from) * sin($lat_to) + cos($lat_from) * cos($lat_to) * cos($lon_from - $lon_to));
+			$scale = ($dist / sqrt(2)) * ($mapResolutionDpi * 100);
+		}
+		else {
+			$xtenty = $bbox[3] - $bbox[1];
+			$scale = ($xtenty / $this->getHeight()) * ($mapResolutionDpi * 100);
+		}
+		return round($scale);
+	}	
+	
+	
+	/**
+	 * 
+	 * @return String EPSG code of the map.
+	 */
+	public function getEpsg () {
+		return $this->extent->epsg;	
+	}
+	
+	public function getWms ($index) {
+		if (is_numeric($index)) {
+			$i = intval($index, 10); 
+			if ($i < count($this->wmsArray) && count($this->wmsArray) > 0 && $i >= 0) {
+				return $this->wmsArray[$i];
+			}
+		}
+		return null;
+	}
+	
+	/**
+	 * 
+	 * @return 
+	 */
+	public function getWmsArray () {
+		return $this->wmsArray;	
+	}
+	
+	/**
+	 * 
+	 * @return 
+	 * @param $wmsArray Object
+	 */
+	public function setWmsArray ($wmsArray) {
+		$this->wmsArray = $wmsArray;
+	}
+	
+	/**
+	 * 
+	 * @return 
+	 */
+	public function isOverview () {
+		return $this->isOverview;
+	}
+	
+	public function setIsOverview ($bool) {
+		$this->isOverview = $bool;
+	}
+	
+	/**
+	 * @param $value Object
+	 */
+	public function addWms ($value) {
+		array_push($this->wms, $value);
+	}	
+
+
+	// ------------------------------------------------------------------------
+	// map manipulation
+	// ------------------------------------------------------------------------
+
+	/**
+	 * Appends the WMS of another map to this map.
+	 * 
+	 * @param $anotherMap Map
+	 */
+	public function append ($anotherMap) {
+		$this->wmsArray = array_merge($anotherMap->getWmsArray(), $this->wmsArray);
+	}
+		
+	/**
+	 * Merges this map with another map: Copies the map settings from the 
+	 * other map and merges the WMS (keeping the settings of the other
+	 * map if there are duplicates)
+	 * 
+	 * @param $anotherMap Map
+	 */
+	public function merge ($anotherMap) {
+		$this->width = $anotherMap->width;
+		$this->height = $anotherMap->height;
+		$this->frameName = $anotherMap->frameName;
+		$this->elementName = $anotherMap->elementName;
+		$this->extent = $anotherMap->extent;
+		$this->isOverview = $anotherMap->isOverview;
+		$this->wmsArray = wms::merge(array_merge($anotherMap->getWmsArray(), $this->wmsArray));
+	}
+
+	/**
+	 * Adds WMS to this map
+	 * 
+	 * @return 
+	 */
+	public function appendWmsArray ($wmsArray) {
+		$this->wmsArray = array_merge($this->wmsArray, $wmsArray);
+	}
+
+	private function reprojectExtent ($bbox) {
+		if (!is_a($bbox, "Mapbender_bbox")) {
+			throw new Exception("Input must be a Mapbender bounding box.");
+		}
+		if (preg_replace("/EPSG:/","", $bbox->epsg) !== "4326") {
+			throw new Exception("Input must be a WGS84 bounding box.");
+		}
+		$ext = $this->getExtent();
+		$srs = $ext->epsg;
+
+		$extArray = array(
+			$bbox->min->x,
+			$bbox->min->y,
+			$bbox->max->x,
+			$bbox->max->y
+		);
+		$oldEPSG = "4326";
+		$newEPSG = preg_replace("/EPSG:/","", $srs);
+
+		// calculate bbox via PostGIS
+		if(SYS_DBTYPE=='pgsql') {
+			$con = db_connect($DBSERVER,$OWNER,$PW);
+			$sqlMinx = "SELECT X(transform(GeometryFromText('POINT(".$extArray[0]." ".$extArray[1].")',".$oldEPSG."),".$newEPSG.")) as minx";
+			$resMinx = db_query($sqlMinx);
+			$minx = floatval(db_result($resMinx,0,"minx"));
+
+			$sqlMiny = "SELECT Y(transform(GeometryFromText('POINT(".$extArray[0]." ".$extArray[1].")',".$oldEPSG."),".$newEPSG.")) as miny";
+			$resMiny = db_query($sqlMiny);
+			$miny = floatval(db_result($resMiny,0,"miny"));
+
+			$sqlMaxx = "SELECT X(transform(GeometryFromText('POINT(".$extArray[2]." ".$extArray[3].")',".$oldEPSG."),".$newEPSG.")) as maxx";
+			$resMaxx = db_query($sqlMaxx);
+			$maxx = floatval(db_result($resMaxx,0,"maxx"));
+
+			$sqlMaxy = "SELECT Y(transform(GeometryFromText('POINT(".$extArray[2]." ".$extArray[3].")',".$oldEPSG."),".$newEPSG.")) as maxy";
+			$resMaxy = db_query($sqlMaxy);
+			$maxy = floatval(db_result($resMaxy,0,"maxy"));
+		}
+
+		if ($minx && $miny && $maxx && $maxy) {
+			return new Mapbender_bbox(
+				$minx,
+				$miny,
+				$maxx,
+				$maxy,
+				$srs
+			);
+		}
+		throw new Exception("Bounding box reprojection failed.");
+	}
+
+	public function mergeExtent ($input) {
+		$ext = $this->getExtent();
+		$srs = $ext->epsg;
+
+		$bboxArray = $input;
+
+		if (is_a($input, "Mapbender_bbox")) {
+			$bboxArray = array($input);
+		}
+
+		// assume bbox array
+		if (is_array($input)) {
+
+			$wgs84Index = null;
+
+			// check if SRS matches WMC SRS
+			for ($i = 0; $i < count($bboxArray); $i++) {
+				$c = $bboxArray[$i];
+				if ($c->epsg !== $srs) {
+					if ($c->epsg === "EPSG:4326") {
+						$wgs84Index = $i;
+					}
+					continue;
+				}
+
+				// recalculate WMC bbox
+				$this->calculateExtent($c);
+				return;
+			}
+
+			if (!is_null($wgs84Index)) {
+				try {
+					$c = $bboxArray[$wgs84Index];
+					$reprojectedBbox = $this->reprojectExtent($c);
+					$this->calculateExtent($reprojectedBbox);
+				}
+				catch (Exception $e) {
+					new mb_exception("Could not merge extent.");
+				}
+				return;
+			}
+		}
+		$e = new mb_exception(__FILE__ . ": mergeWmsArray: Could not determine bounding box of WMS in SRS " . $srs);
+	}
+
+	/**
+	 * Merge WMS into this map
+	 * 
+	 * @return 
+	 */
+	public function mergeWmsArray ($wmsArray) {
+		if (func_num_args() > 1 
+			&& is_array($wmsArray) 
+			&& count($wmsArray) > 0) {
+			$options = func_get_arg(1);
+
+			if ($options["zoom"]) {
+				$currentWms = $wmsArray[0];
+				$bboxArray = array();
+				for ($i = 0; $i < count($currentWms->objLayer[0]->layer_epsg); $i++) {
+					$bboxArray[]= Mapbender_bbox::createFromLayerEpsg(
+						$currentWms->objLayer[0]->layer_epsg[$i]
+					);
+				}
+				$this->mergeExtent($bboxArray);
+			}
+			
+			// visibility of WMS
+			if (isset($options["visible"])) {
+				if ($options["visible"]) {
+					// set all layers of WMS to visible
+					for ($i = 0; $i < count($wmsArray); $i++) {
+						$numLayers = count($wmsArray[$i]->objLayer);
+
+						// using option show is dependent to option visible = true
+						if ($options["show"] && is_numeric($options["show"])) {
+							// do not display if layer count is too big
+							if ($numLayers > intval($options["show"])) {
+								continue;
+							}
+						}
+
+						for ($j = 0; $j < $numLayers; $j++) {
+							$wmsArray[$i]->objLayer[$j]->gui_layer_visible = 1;
+						}
+					}
+				}
+				else {
+					// set all layers of WMS to visible
+					for ($i = 0; $i < count($wmsArray); $i++) {
+						$numLayers = count($wmsArray[$i]->objLayer);
+
+						for ($j = 0; $j < $numLayers; $j++) {
+							$wmsArray[$i]->objLayer[$j]->gui_layer_visible = 0;
+						}
+					}
+				}
+			}
+
+			// querylayer
+			if (isset($options["querylayer"])) {
+				$val = $options["querylayer"] ? 1 : 0;
+				
+				// set all queryable layers of WMS to querylayer
+				for ($i = 0; $i < count($wmsArray); $i++) {
+					$numLayers = count($wmsArray[$i]->objLayer);
+
+					for ($j = 0; $j < $numLayers; $j++) {
+						$currentLayer = $wmsArray[$i]->objLayer[$j];
+						if ($currentLayer->gui_layer_queryable) {
+							$currentLayer->gui_layer_querylayer = $val;
+						}
+					}
+				}
+			}
+
+			
+			if ($options["show"] && is_numeric($options["show"]) && !isset($options["visible"])) {
+				$e = new mb_exception("show");
+				// set all layers of WMS to visible
+				for ($i = 0; $i < count($wmsArray); $i++) {
+					$numLayers = count($wmsArray[$i]->objLayer);
+					
+					// do not display if layer count is too big
+					if ($numLayers > intval($options["show"])) {
+						continue;
+					}
+					
+					for ($j = 0; $j < $numLayers; $j++) {
+						$wmsArray[$i]->objLayer[$j]->gui_layer_visible = 1;
+					}
+				}
+			}
+		}
+		
+		$this->wmsArray = wms::merge(array_merge($this->wmsArray, $wmsArray));
+	}
+
+
+	// ------------------------------------------------------------------------
+	// Instantiation
+	// ------------------------------------------------------------------------
+	/**
+	 * 
+	 * @return 
+	 * @param $jsMapObject Object
+	 */
+	public function createFromJs ($jsMapObject) {
+		$b = $jsMapObject->extent;
+
+		$srs = $jsMapObject->epsg;
+		$bbox = new Mapbender_bbox(
+			$b->min->x, 
+			$b->min->y, 
+			$b->max->x, 
+			$b->max->y, 
+			$srs
+		);
+
+		$this->width = $jsMapObject->width;
+		$this->height = $jsMapObject->height;
+		// there are no more map frames in Mapbender 2.6
+		$this->frameName = $jsMapObject->elementName;
+		$this->extent = $bbox;
+		
+		if (isset($jsMapObject->isOverview) && $jsMapObject->isOverview == "1") {
+			$this->isOverview = true;
+		}
+
+		for ($i=0; $i < count($jsMapObject->wms); $i++){
+	
+			$currentWms = $jsMapObject->wms[$i];
+			$wms = new wms();
+
+			//
+			// set WMS data
+			//
+			$wms->wms_id = $currentWms->wms_id;
+			$wms->wms_version = $currentWms->wms_version;
+			$wms->wms_title = $currentWms->wms_title;
+			$wms->wms_abstract = $currentWms->wms_abstract;
+			$wms->wms_getmap = $currentWms->wms_getmap;
+			$wms->wms_getfeatureinfo = $currentWms->wms_getfeatureinfo;
+			$wms->wms_getlegendurl = $currentWms->wms_getlegendurl;
+			$wms->wms_filter = $currentWms->wms_filter;
+			$wms->wms_srs = $currentWms->wms_srs;
+			$wms->gui_epsg = $currentWms->gui_epsg;
+			$wms->gui_minx = $currentWms->gui_minx;
+			$wms->gui_miny = $currentWms->gui_miny;
+			$wms->gui_maxx = $currentWms->gui_maxx;
+			$wms->gui_maxy = $currentWms->gui_maxy;
+			$wms->gui_wms_mapformat = $currentWms->gui_wms_mapformat;
+			$wms->gui_wms_featureinfoformat = $currentWms->gui_wms_featureinfoformat;
+			$wms->gui_wms_exceptionformat = $currentWms->gui_wms_exceptionformat;
+			$wms->gui_wms_opacity = $currentWms->wms_opacity;
+			$wms->gui_wms_sldurl = $currentWms->gui_wms_sldurl;
+			$wms->gui_wms_visible = $currentWms->gui_wms_visible;
+			$wms->gui_wms_epsg = $currentWms->gui_wms_epsg;
+			$wms->data_type = $currentWms->data_type;
+			$wms->data_format = $currentWms->data_format;
+
+			for ($k = 0; $k < count($currentWms->objLayer); $k++){
+				// the current layer of the JSON map object
+				$currentLayer = $currentWms->objLayer[$k];
+
+				// add new layer to WMS
+				$pos = $currentLayer->layer_pos;
+				$parent = $currentLayer->layer_parent;
+				$wms->addLayer($pos, $parent); 
+
+				$newLayerIndex = count($wms->objLayer) - 1;
+				// $newLayer is a short cut to the layer we just added
+				$newLayer = $wms->objLayer[$newLayerIndex];
+				
+				// set layer data
+				$newLayer->layer_uid = $currentLayer->layer_uid;
+				$newLayer->layer_name = $currentLayer->layer_name;
+				$newLayer->layer_title = $currentLayer->layer_title;
+				$newLayer->layer_dataurl_href = $currentLayer->layer_dataurl_href;
+				$newLayer->layer_pos = $currentLayer->layer_pos;
+				$newLayer->layer_queryable = $currentLayer->layer_queryable;
+				$newLayer->layer_minscale = $currentLayer->layer_minscale;
+				$newLayer->layer_maxscale = $currentLayer->layer_maxscale;
+				$newLayer->layer_metadataurl = $currentLayer->metadataurl;
+				$newLayer->gui_layer_wms_id = $currentLayer->gui_layer_wms_id;
+//				$newLayer->gui_layer_wms_id = $wms->objLayer[0]->layer_uid;
+				$newLayer->gui_layer_status = $currentLayer->gui_layer_status;
+				$newLayer->gui_layer_style = $currentLayer->gui_layer_style;
+				$newLayer->gui_layer_selectable = $currentLayer->gui_layer_selectable;
+
+				if ($this->isOverview) {
+					preg_match_all("/LAYERS\=([^&]*)/", $jsMapObject->mapURL[0], $resultMatrix);
+					$layerList = $resultMatrix[1][0];
+					$layerListArray = explode(",", $layerList);
+					$newLayer->gui_layer_visible = (in_array($currentLayer->layer_name, $layerListArray)) ? 1 : 0;
+				}
+				else {
+					$newLayer->gui_layer_visible = $currentLayer->gui_layer_visible;
+				}
+				$newLayer->gui_layer_queryable = $currentLayer->gui_layer_queryable;
+				$newLayer->gui_layer_querylayer = $currentLayer->gui_layer_querylayer;
+				$newLayer->gui_layer_minscale = $currentLayer->gui_layer_minscale;
+				$newLayer->gui_layer_maxscale = $currentLayer->gui_layer_maxscale;
+				$newLayer->gui_layer_wfs_featuretype = $currentLayer->gui_layer_wfs_featuretype;
+				$newLayer->gui_layer_title = $currentLayer->gui_layer_title;
+
+				// BEWARE THIS IS SUPER UGLY CODE
+				$newLayer->layer_epsg = array();
+				for ($z = 0; $z < count($currentLayer->layer_epsg); $z++) {
+					$newLayer->layer_epsg[$z] = array();
+					$newLayer->layer_epsg[$z]["epsg"] = $currentLayer->layer_epsg[$z]->epsg;
+					$newLayer->layer_epsg[$z]["minx"] = $currentLayer->layer_epsg[$z]->minx;
+					$newLayer->layer_epsg[$z]["miny"] = $currentLayer->layer_epsg[$z]->miny;
+					$newLayer->layer_epsg[$z]["maxx"] = $currentLayer->layer_epsg[$z]->maxx;
+					$newLayer->layer_epsg[$z]["maxy"] = $currentLayer->layer_epsg[$z]->maxy;
+				}
+				
+				// BEWARE THIS IS SUPER UGLY CODE
+				$newLayer->layer_style = array();
+				for ($z = 0; $z < count($currentLayer->layer_style); $z++) {
+					$newLayer->layer_style[$z] = array();
+					$newLayer->layer_style[$z]["name"] = $currentLayer->layer_style[$z]->name ? $currentLayer->layer_style[$z]->name : "default";
+					$newLayer->layer_style[$z]["title"] = $currentLayer->layer_style[$z]->title ? $currentLayer->layer_style[$z]->title : "default";
+					$newLayer->layer_style[$z]["legendurl"] = $currentLayer->layer_style[$z]->legendurl;
+					$newLayer->layer_style[$z]["legendurlformat"] = $currentLayer->layer_style[$z]->legendurlformat;
+				}
+
+			}
+			array_push($this->wmsArray, $wms);
+		}
+		return true;
+	}
+	
+	
+	// ------------------------------------------------------------------------
+	// database functions
+	// ------------------------------------------------------------------------
+	public static function selectMainMapByApplication ($appId) {
+		return map::selectByApplication($appId, "mapframe1");
+	}
+	
+	public static function selectOverviewMapByApplication ($appId) {
+		$currentMap = map::selectByApplication($appId, "overview");
+		if ($currentMap !== null) {
+			$currentMap->setIsOverview(true);
+		}
+		return $currentMap;
+	}
+
+
+	// ------------------------------------------------------------------------
+	// Output
+	// ------------------------------------------------------------------------
+	/**
+	 * Returns an array of string, which are JS statements.
+	 * @return String[]
+	 */
+	public function toJavaScript ($wmsJson) {
+		$jsCodeArray = array();
+
+		// syntax has changed in 2.6! Map is no longer a frame
+		$registerMapString = "var currentWmcMap = Mapbender.modules['" . 
+			$this->frameName . "'];" .
+			"currentWmcMap.elementName = '" . $this->frameName . "';" . 
+			"currentWmcMap.setWidth(" . $this->width . ");" . 
+			"currentWmcMap.setHeight(" . $this->height . ");"; 
+		array_push($jsCodeArray, $registerMapString);
+
+		// if map is overview...
+		if ($this->isOverview) {
+			// ...set overview flag
+			$setOverviewFlagString = "currentWmcMap.isOverview = true;";
+			array_push($jsCodeArray, $setOverviewFlagString);
+		}
+
+		// calculate extent
+		$calcExtentString = "currentWmcMap.setSrs({" . 
+			"srs: '" . $this->extent->epsg . "'," . 
+			"extent: new Mapbender.Extent(" . 
+			$this->extent->min->x . ", " . 
+			$this->extent->min->y . ", " . 
+			$this->extent->max->x . ", " . 
+			$this->extent->max->y . ")});"; 
+		array_push($jsCodeArray, $calcExtentString);
+		
+		$setWmsString = "currentWmcMap.setWms(" . $wmsJson . ");";
+		array_push($jsCodeArray, $setWmsString);
+		
+		$initWmsString = "currentWmcMap.initializeWms();";
+		array_push($jsCodeArray, $initWmsString);
+
+
+		return $jsCodeArray;
+	}
+
+
+	// ------------------------------------------------------------------------
+	// PRIVATE FUNCTIONS
+	// ------------------------------------------------------------------------
+	
+	private static function selectByApplication ($appId, $frameName) {
+		// find the mapframe in the application elements...
+		$sql = "SELECT * FROM gui_element WHERE fkey_gui_id = $1 AND " . 
+				"e_id = $2 AND e_public = 1 LIMIT 1";
+		$v = array($appId, $frameName);
+		$t = array('s', 's');
+		$res = db_prep_query($sql,$v,$t);
+		$row = db_fetch_array($res);
+		
+		// if found...
+		if ($row) {
+			$currentMap = new Map();
+
+			// use settings from database
+			$currentMap->setWidth($row["e_width"]);
+			$currentMap->setHeight($row["e_height"]);
+			$currentMap->setFrameName($row["e_id"]);
+			
+			// get the WMS 
+			$wmsArray = wms::selectMyWmsByApplication($appId);
+			
+//			$e = new mb_notice("WMS in this map: " . implode(",", $wmsArray));
+			
+			// if this is the overview, find the WMS index and 
+			// reset the WMS array
+			// BEWARE, SUPER UGLY CODE AHEAD!!
+			// (BUT THERE IS NO OTHER WAY TO DO IT)
+			if (strpos($row["e_js_file"], "mb_overview.js") !== false) {
+//				$e = new mb_exception("guess this is the OV");
+
+				$ov_sql = "SELECT var_value FROM gui_element_vars WHERE " . 
+					"var_name = 'overview_wms' AND fkey_e_id = $1 AND " . 
+					"fkey_gui_id = $2";
+				$ov_v = array($frameName, $appId);
+				$ov_t = array('s', 's');
+				$ov_res = db_prep_query($ov_sql, $ov_v, $ov_t);
+				$ov_row = db_fetch_array($ov_res);
+				if ($ov_row) {
+					$ov_index = intval($ov_row["var_value"]);
+				}
+				
+//				$e = new mb_exception("OV index: " . $ovIndex);
+				if (!isset($ovIndex)) {
+					$ovIndex = 0;
+				}
+				$wmsArray = array($wmsArray[$ovIndex]);	
+//				$e = new mb_notice("WMS in this map (corrected): " . implode(",", $wmsArray));
+			}
+			else {
+//				$e = new mb_exception("guess this is NOT the OV");
+			}
+
+			$currentMap->wmsArray = $wmsArray;
+			
+			// EXTENT
+			$sql = "SELECT gui_wms_epsg FROM gui_wms WHERE gui_wms_position = 0 AND fkey_gui_id = $1";
+			$v = array($appId);
+			$t = array('s');
+			$res = db_prep_query($sql, $v, $t);
+			$row = db_fetch_array($res);
+			$epsg = $row["gui_wms_epsg"];
+			$layer_epsg = $wmsArray[0]->objLayer[0]->layer_epsg;
+			$j = 0;
+			for ($i = 0; $i < count($layer_epsg); $i++) {
+				if ($layer_epsg[$i]["epsg"] === $epsg) {
+					$j = $i;
+					break;
+				}
+			}
+			$minx = $wmsArray[0]->objLayer[0]->layer_epsg[$j]["minx"];
+			$miny = $wmsArray[0]->objLayer[0]->layer_epsg[$j]["miny"];
+			$maxx = $wmsArray[0]->objLayer[0]->layer_epsg[$j]["maxx"];
+			$maxy = $wmsArray[0]->objLayer[0]->layer_epsg[$j]["maxy"];
+			$epsg = $wmsArray[0]->objLayer[0]->layer_epsg[$j]["epsg"];
+			$mapExtent = new Mapbender_bbox($minx, $miny, $maxx, $maxy, $epsg);
+			
+			$currentMap->setExtent($mapExtent);
+			return $currentMap;			
+		}
+		else {
+			return null;
+		}
+	}
+	
+
+}
+?>

Deleted: branches/mapbender/http/classes/class_metadata_new.php
===================================================================
--- trunk/mapbender/http/classes/class_metadata_new.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/http/classes/class_metadata_new.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,1743 +0,0 @@
-<?php
-#Script to call this class: http://www.geoportal.rlp.de/mapbender/php/mod_callMetadata.php
-#Class for getting results out of the mapbender service registry 
-#Resulttypes: WMS, WMS-Layer, (WFS), WFS-Featurtyps, WFS-Conf, WMC, GeoRSS-Feeds, ...
-#Possible filters: registrating organizations, time, bbox (fully inside, intersects, fully outside), ISO Topic Categories, INSPIRE themes, INSPIRE: keywords, classification of data/service ... - maybe relevant for the german broker not for one instance, quality and actuality (maybe spatial and temporal), bbox, deegree of conformity with ir, access and use constraints, responsible parties - maybe one is enough? We must have a look at the INSPIRE Metadata IR
-#Metadata we need to fullfil the demands of INSPIRE:
-#1. INSPIRE conformity classification for WMS/WFS/WCS
-#2. Temporal Extents at WMS/WMS-Layer/WFS/WFS-Featuretype levels - for datasets if demanded - til now there is no demand defined in the guidance-paper for metadata ir
-#3. Classified access and use contraints - which classes? - Check IR Data Sharing and IR Metadata
-#4. 
-#Every ressource which should be send to INSPIRE can be filtered - but is not neccessary for a standardized approach
-#Another problem is the ranking of the different ressources. The ranking should be homogeneus. 
-#Till now we rank the using of WMS Layers when Caps are requested and when s.o. load one layer into the geoportal.
-#The same things have to be done for the wfs-conf, wmc and georssfeeds
-#The searching for metadata should be parallel done. We need different classes for doing the search. They should be requested by one central class (class_metadata.php).
-#Classes for filtering after the results have been send to the portal:
-#1. ISO Topic Categories
-#2. INSPIRE Themes
-#3. Access and use classification
-#4. departments which provides the ressources - we need the new concept for the administration of this departments - store the addresses in the group table and give the relation - originating group in table mb_user_mb_group 
-#Cause we have a authorization layer, we need the id of the requesting user which is defined in the session. If no session is set, it should be the anonymous user of the portal.
-#We need a parameter for internationalization - it should be send with the search request! Some of the Classes can be provided with different languages.
-#WMC and GeoRSS-Feeds have no or a to complex authorization info - maybe we need to test if wmc consists of info which is fully or only partually available to the anonymous user. 
-
-require_once(dirname(__FILE__)."/../../core/globalSettings.php");
-require_once(dirname(__FILE__)."/class_administration.php");
-require_once(dirname(__FILE__)."/class_mb_exception.php");
-require_once(dirname(__FILE__)."/class_json.php");
-
-//definition for the things which are common to all kind of metadata ressources
-
-class searchMetadata {
-	var $userId;
-	var $searchId;
-	var $searchText;
-	var $registratingDepartments;
-	var $isoCategories;
-	var $inspireThemes;
-	var $customCategories;
-	var $timeBegin;
-	var $timeEnd;
-	var $regTimeBegin;
-	var $regTimeEnd;
-	var $maxResults;
-	var $searchBbox;
-	var $searchTypeBbox;
-	var $accessRestrictions;
-	var $languageCode;
-	var $searchStartTime;
-	var $searchView;
-	var $searchURL;
-	var $searchEPSG;
-	var $searchResources;
-	var $searchPages;
-	var $outputFormat;
-	var $resultTarget;
-	var $tempFolder;
-	var $orderBy;
-	var $hostName;
-
-	function __construct($userId, $searchId, $searchText, $registratingDepartments, $isoCategories, $inspireThemes, $timeBegin, $timeEnd, $regTimeBegin, $regTimeEnd, $maxResults, $searchBbox, $searchTypeBbox, $accessRestrictions, $languageCode, $searchEPSG, $searchResources, $searchPages, $outputFormat, $resultTarget, $searchURL, $customCategories, $hostName, $orderBy){
-		$this->userId = (integer)$userId;
-		$this->searchId = $searchId;
-		$this->searchText = $searchText;
-		$this->registratingDepartments = $registratingDepartments; //array with ids of the registrating groups in the mb database
-		$this->registratingDepartmentsArray = explode(",",$this->registratingDepartments);
-		$this->isoCategories = $isoCategories;
-		$this->inspireThemes = $inspireThemes;
-		$this->customCategories = $customCategories;
-		$this->timeBegin = $timeBegin;
-		$this->timeEnd = $timeEnd;
-		$this->regTimeBegin = $regTimeBegin;
-		$this->regTimeEnd = $regTimeEnd;
-		$this->maxResults = (integer)$maxResults;
-		$this->searchBbox = $searchBbox;
-		$this->searchTypeBbox = $searchTypeBbox;
-		$this->accessRestrictions = $accessRestrictions;
-		$this->languageCode = $languageCode;
-		$this->searchEPSG = $searchEPSG;
-		$this->searchResources = $searchResources;
-		$this->searchPages = $searchPages;
-		$this->outputFormat = $outputFormat;
-		$this->resultTarget = $resultTarget;
-		$this->searchURL = $searchURL;
-		$this->hostName = $hostName;
-		$this->orderBy = $orderBy;
-		//definitions for tags
-		$this->maxObjects = 15;
-		$this->maxFontSize = 30;
-		$this->maxWeight = 0;
-		$this->scale = 'linear';
-
-
-
-
-
-		$this->tempFolder = TMPDIR; //TODO define another path - maybe the one which is given in mapbender.conf
-		if ($this->outputFormat == 'json'){
-			$this->json = new Mapbender_JSON;
-		}
-		$this->accessableLayers = NULL;
-		//set a time to find time consumers
-		$this->searchStartTime = $this->microtime_float();
-		//Defining of the different database categories		
-		$this->resourceClassifications = array();
-		$this->resourceClassifications[0]['title'] = "ISO 19115"; //TODO: define the translations somewhere? - This is done in call_metadata.php before. Maybe we can get them from there? - It will be shown in the rightside categories table
-		$this->resourceClassifications[0]['tablename'] = 'md_topic_category';
-		$this->resourceClassifications[0]['requestName'] = 'isoCategories';
-		$this->resourceClassifications[0]['id_wms'] = 'layer_id';
-		$this->resourceClassifications[0]['id_wfs'] = 'featuretype_id';
-		$this->resourceClassifications[0]['relation_wms'] = 'layer_md_topic_category';
-		$this->resourceClassifications[0]['relation_wfs'] = 'featuretype_md_topic_category';//TODO: define this in mapbender
-
-		$this->resourceClassifications[1]['title'] = "INSPIRE"; //TODO: define the translations somewhere? - This is done in call_metadata.php before. Maybe we can get them from there? - It will be shown in the rightside categories table
-		$this->resourceClassifications[1]['tablename'] = 'inspire_category';
-		$this->resourceClassifications[1]['requestName'] = 'inspireThemes';
-		$this->resourceClassifications[1]['id_wms'] = 'layer_id';
-		$this->resourceClassifications[1]['id_wfs'] = 'featuretype_id';
-		$this->resourceClassifications[1]['relation_wms'] = 'layer_inspire_category';
-		$this->resourceClassifications[1]['relation_wfs'] = 'featuretype_inspire_category';//TODO: define this in mapbender
-
-		$this->resourceClassifications[2]['title'] = "Custom"; //TODO: define the translations somewhere? - This is done in call_metadata.php before. Maybe we can get them from there? - It will be shown in the rightside categories table
-		$this->resourceClassifications[2]['tablename'] = 'custom_category';
-		$this->resourceClassifications[2]['requestName'] = 'customCategories';
-		$this->resourceClassifications[2]['id_wms'] = 'layer_id';
-		$this->resourceClassifications[2]['id_wfs'] = 'featuretype_id';
-		$this->resourceClassifications[2]['relation_wms'] = 'layer_custom_category';
-		$this->resourceClassifications[2]['relation_wfs'] = 'featuretype_custom_category';//TODO: define this in mapbender
-
-
-
-
-
-
-
-		//Defining of the different result categories		
-		$this->resourceCategories = array();
-		$this->resourceCategories[0]['name'] = 'WMS';
-		$this->resourceCategories[1]['name'] = 'WFS';
-		$this->resourceCategories[2]['name'] = 'WMC';
-		$this->resourceCategories[3]['name'] = 'DAD';
-		switch($this->languageCode){
-        		case 'de':
-                	$this->resourceCategories[0]['name2show'] = 'Darstellungsdienste';
-			$this->resourceCategories[1]['name2show'] = 'Such- und Download- und Erfassungsmodule';
-			$this->resourceCategories[2]['name2show'] = 'Kartenzusammenstellungen';
-			$this->resourceCategories[3]['name2show'] = 'KML/Newsfeeds';
-			$this->keywordTitle = 'Schlagwortliste';
-       			break;
-        		case 'en':
-               		$this->resourceCategories[0]['name2show'] = 'Viewingservices';
-			$this->resourceCategories[1]['name2show'] = 'Search- and Downloadservices';
-			$this->resourceCategories[2]['name2show'] = 'Combined Maps';
-			$this->resourceCategories[3]['name2show'] = 'KML/Newsfeeds';
-			$this->keywordTitle = 'Keywordlist';
-        		break;
-        		case 'fr':
-          	     	$this->resourceCategories[0]['name2show'] = 'Viewingservices';
-			$this->resourceCategories[1]['name2show'] = 'Search- and Downloadservices';
-			$this->resourceCategories[2]['name2show'] = 'Combined Maps';
-			$this->resourceCategories[3]['name2show'] = 'KML/Newsfeeds';
-			$this->keywordTitle = 'Keywordlist';
-       			break;
-     			default:
-                	$this->resourceCategories[0]['name2show'] = 'Darstellungsdienste';
-			$this->resourceCategories[1]['name2show'] = 'Such- und Download- und Erfassungsmodule';
-			$this->resourceCategories[2]['name2show'] = 'Kartenzusammenstellungen';
-			$this->resourceCategories[3]['name2show'] = 'KML/Newsfeeds';
-			$this->keywordTitle = 'Schlagwortliste';
-		}	
-		//not needed til now - maybe usefull for georss output
-		if ($this->outputFormat == "xml") {
-			//Initialize XML documents
-			if (isset($this->searchResources) & strtolower($this->searchResources) === "wms") {
-				$this->wmsDoc = new DOMDocument('1.0');
-			}
-			if (isset($this->searchResources) & strtolower($this->searchResources) === "wfs") {
-				$this->wfsDoc = new DOMDocument('1.0');
-				$this->generateWFSMetadata($this->wfsDoc);
-			}
-			if (isset($this->searchResources) & strtolower($this->searchResources) === "wmc") {
-				$this->wmcDoc = new DOMDocument('1.0');
-				$this->generateWMCMetadata($this->wmcDoc);
-			}
-			if (isset($this->searchResources) & strtolower($this->searchResources) === "georss") {
-				$this->georssDoc = new DOMDocument('1.0');
-			}
-		}
-		
-		if ($this->outputFormat === "json") {
-			$this->e = new mb_exception("orderBy old: ".$this->orderBy);
-			if (isset($this->searchResources) & strtolower($this->searchResources) === "wfs") {
-				$this->databaseIdColumnName = 'featuretype_id';
-				$this->databaseTableName = 'wfs_featuretype';
-				//$this->keywordRelation = 'wfs_featuretype_keyword';
-				$this->searchView = 'search_wfs_view';
-				switch ($this->orderBy) {
-					case "rank":
-						$this->orderBy = " ORDER BY wfs_id,featuretype_id,wfs_conf_id ";
-						break;
-					case "id":
-						$this->orderBy = " ORDER BY wfs_id,featuretype_id,wfs_conf_id ";
-						break;
-					case "title":
-						$this->orderBy = " ORDER BY featuretype_title ";
-						break;
-					case "date":
-						$this->orderBy = " ORDER BY wfs_timestamp DESC ";
-						break;
-					default:
-						$this->orderBy = " ORDER BY wfs_id,featuretype_id,wfs_conf_id ";
-				}
-				
-				$this->resourceClasses = NULL;
-				$this->generateWFSMetadata($this->wfsDoc);
-			}
-			if (isset($this->searchResources) & strtolower($this->searchResources) === "wms") {
-				$this->databaseIdColumnName = 'layer_id';
-				$this->databaseTableName = 'layer';
-				//$this->keywordRelation = 'layer_keyword';
-				$this->searchView = 'wms_search_table';
-				switch ($this->orderBy) {
-					case "rank":
-						$this->orderBy = " ORDER BY load_count DESC";
-						break;
-					case "id":
-						$this->orderBy = " ORDER BY wms_id,layer_pos DESC";
-						break;
-					case "title":
-						$this->orderBy = " ORDER BY layer_title ";
-						break;
-					case "date":
-						$this->orderBy = " ORDER BY wms_timestamp DESC ";
-						break;
-					default:
-						$this->orderBy = " ORDER BY load_count DESC";
-				}
-				
-				$this->resourceClasses = array(0,1,2);
-				$this->generateWMSMetadata($this->wmsDoc);
-			}
-			if (isset($this->searchResources) & strtolower($this->searchResources) === "wmc") {
-				$this->searchView = 'search_wmc_view';
-				$this->databaseIdColumnName = 'wmc_id';
-				$this->databaseTableName = 'wmc';
-
-				switch ($this->orderBy) {
-					case "rank":
-						$this->orderBy = " ORDER BY wmc_id ";
-						break;
-					case "id":
-						$this->orderBy = " ORDER BY wmc_id ";
-						break;
-					case "title":
-						$this->orderBy = " ORDER BY wmc_title ";
-						break;
-					case "date":
-						$this->orderBy = " ORDER BY wmc_timestamp DESC ";
-						break;
-					default:
-						$this->orderBy = " ORDER BY wmc_title ";
-				}
-				
-				$this->resourceClasses = NULL; #TODO adopt to count classifications
-				$this->generateWMCMetadata($this->wmcDoc);
-			}
-		}
-	$this->e = new mb_exception("orderBy new: ".$this->orderBy);
-	}
-
-	private function microtime_float() {
-    		list($usec, $sec) = explode(" ", microtime());
-    		return ((float)$usec + (float)$sec);
-	}
-	private function generateXMLHead($xmlDoc) {
-		$xmlDoc->encoding = CHARSET;
-		$result = $xmlDoc->createElement("result");
-		$xmlDoc->appendChild($result);
-		//Result Count
-		$overLimit = $xmlDoc->createElement("overLimit");
-		$result->appendChild($overLimit);
-		//$tr_text = $xmlDoc->createTextNode($this->isOverLimit);
-		$tr_text = $xmlDoc->createTextNode("really?");
-		$overLimit->appendChild($tr_text);
-		$rd = $xmlDoc->createElement("redirect");
-		$result->appendChild($rd);
-		$trd = $xmlDoc->createTextNode("not yet ready...");
-		$rd->appendChild($trd);
-	}
-	private function generateXMLFoot($xmlDoc){
-		$results = $xmlDoc->getElementsByTagName("result");			
-		foreach ($results as $result) {
-			$result->appendChild($ready);
-		}
-	}
-	private function flipDiagonally($arr) {
-    		$out = array();
-    		foreach ($arr as $key => $subarr) {
-      			foreach ($subarr as $subkey => $subvalue) {
-        			$out[$subkey][$key] = $subvalue;
-       			 }
-    		}
-   		return $out;
-	}
-
-	private function generateWFSMetadataJSON($res, $n) {
-		//initialize object
-		$this->wfsJSON = new stdClass;
-		$this->wfsJSON->wfs = (object) array(
-				'md' => (object) array(
-					'nresults' => $n, 
-					'p' => $this->searchPages,
-					'rpp' => $this->maxResults
-					),
-				'srv' => array()
-				);
-			
-		//read out records
-		$serverCount = 0;
-		$wfsMatrix = db_fetch_all($res);
-		//sort result for accessing the right services
-		$wfsMatrix = $this->flipDiagonally($wfsMatrix);
-		//TODO check if order by db or order by php is faster! 
-		#array_multisort($wfsMatrix['wfs_id'], SORT_ASC,$wfsMatrix['featuretype_id'], SORT_ASC,$wfsMatrix['wfs_conf_id'], SORT_ASC); //have some problems - the database version is more stable
-		#print_r($wfsMatrix);
-		$wfsMatrix = $this->flipDiagonally($wfsMatrix);
-		//read out first server entry - maybe this a little bit timeconsuming TODO
-		$j = 0; //count identical wfs_id => double featuretype
-		$l = 0; //index featuretype and or modul per wfs
-		$m = 0; //index modul per featuretype
-		for($i=0; $i<count($wfsMatrix);$i++){
-				$this->wfsJSON->wfs->srv[$i-$j]->id = $wfsMatrix[$i]['wfs_id'];
-				$this->wfsJSON->wfs->srv[$i-$j]->title = $wfsMatrix[$i]['wfs_title'];
-				$this->wfsJSON->wfs->srv[$i-$j]->abstract = $wfsMatrix[$i]['wfs_abstract'];
-				$this->wfsJSON->wfs->srv[$i-$j]->date = date("d.m.Y",$wfsMatrix[$i]['wfs_timestamp']);
-				$this->wfsJSON->wfs->srv[$i-$j]->respOrg = $wfsMatrix[$i]['mb_group_name'];
-				$this->wfsJSON->wfs->srv[$i-$j]->logoUrl = $wfsMatrix[$i]['mb_group_logo_path'];
-				$this->wfsJSON->wfs->srv[$i-$j]->mdLink = "http://".$this->hostName."/mapbender/x_geoportal/showWFSMetadata.php?id=".$wfsMatrix[$i]['wfs_id'];
-				$spatialSource = "";
-				$stateOrProvince = $wfsMatrix[$i]['administrativearea']; 
-				if ($stateOrProvince == "NULL" || $stateOrProvince == "") {
-					$spatialSource = $wfsMatrix[$i]['country'];
-				} else {
-					$spatialSource = $wfsMatrix[$i]['administrativearea'];
-				}
-				$this->wfsJSON->wfs->srv[$i-$j]->iso3166 = $spatialSource;
-				//check if a disclaimer has to be shown and give the relevant symbol
-				//$this->wfsJSON->wfs->srv[$i-$j]->tou = $wfsMatrix[$i]['termsofuse'];
-				list($hasConstraints, $symbolLink) = $this->hasConstraints("wfs", $wfsMatrix[$i]['wfs_id']);
-				$this->wfsJSON->wfs->srv[$i-$j]->hasConstraints = $hasConstraints;
-				$this->wfsJSON->wfs->srv[$i-$j]->symbolLink = $symbolLink;
-				//TODO check the field accessconstraints - which should be presented?
-				$this->wfsJSON->wfs->srv[$i-$j]->status = NULL; //$wfsMatrix[$i][''];
-				$this->wfsJSON->wfs->srv[$i-$j]->avail = NULL; //$wfsMatrix[$i][''];
-				$this->wfsJSON->wfs->srv[$i-$j]->logged = NULL; //$wfsMatrix[$i][''];
-				$this->wfsJSON->wfs->srv[$i-$j]->price = NULL; //$wfsMatrix[$i][''];
-				$this->wfsJSON->wfs->srv[$i-$j]->nwaccess = NULL; //$wfsMatrix[$i][''];
-				$this->wfsJSON->wfs->srv[$i-$j]->bbox = array(-180.0,-90.0,180.0,90.0); //$wfsMatrix[$i][''];
-				//if featuretype hasn't been created - do it
-				if (!isset($this->wfsJSON->wfs->srv[$i-$j]->ftype)) {
-					$this->wfsJSON->wfs->srv[$i-$j]->ftype = array();
-				}
-				//fill in featuretype infos
-				$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->id = (integer)$wfsMatrix[$i]['featuretype_id'];
-				$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->title = $wfsMatrix[$i]['featuretype_title'];
-				$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->abstract = $wfsMatrix[$i]['featuretype_abstract'];
-				$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->mdLink = "http://".$this->hostName."/mapbender/x_geoportal/showWFeatureTypeMetadata.php?id=".$wfsMatrix[$i]['featuretype_id'];
-				$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->geomtype = $wfsMatrix[$i]['element_type'];
-				$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->bbox = array(-180.0,-90.0,180.0,90.0);//TODO: $wfsMatrix[$i]['bbox'];
-
-
-				//give info for inspire categories - not relevant for other services or instances of mapbender TODO: comment it if the mapbender installation is not used to generate inspire output
-				if (isset($wfsMatrix[$i]['md_inspire_cats']) & ($wfsMatrix[$i]['md_inspire_cats'] != '')){
-					$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->inspire = 1;
-				}
-				else {
-					$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->inspire = 0;
-				}
-				//fill in categories
-				#if (!isset($this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->cat)) {
-				#	$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->cat = array();
-				#}
-				#if (isset($wfsMatrix[$i]['iso_categories'])) {
-				#}
-				//if (isset($wfsMatrix[$i]['inspire_category'])) {
-					//TODO write the categories as JSON into Database!
-					#$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->cat[0]->type = 'INSPIRE Kategorie';
- 					#$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->cat[0]->value = 'Umwelt';
-					#$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->cat[0]->symbol = 'umwelt.png';
-				//}
-				#if (isset($wfsMatrix[$i]['custom_categories'])) {
-				#}
-				//if modul hasn't been created - do it
-				if (!isset($this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->modul)) {	
-					$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->modul = array();
-				}
-				//fill in modul infos
-				$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->modul[$m]->id = $wfsMatrix[$i]['wfs_conf_id'];	
-				$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->modul[$m]->title = $wfsMatrix[$i]['wfs_conf_description'];	
-				$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->modul[$m]->abstract = $wfsMatrix[$i]['wfs_conf_abstract'];
-				$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->modul[$m]->type = $wfsMatrix[$i]['modultype'];
-				$equalEPSG = $wfsMatrix[$i]['featuretype_srs'];
-                       		$isEqual = true;
-				//control if EPSG is supported by Client
-		        	if ($equalEPSG == $this->searchEPSG){
-					$isEqual = false;		
-		        	}	
-				$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->modul[$m]->srsProblem = $isEqual;
-				//generate Link to show metadata
-				$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->modul[$m]->mdLink = "http://".$this->hostName."/mapbender/x_geoportal/showWFSConfMetadata.php?id=".$wfsMatrix[$i]['wfs_conf_id'];
-				$perText = $this->getPermissionValueForWFS($wfsMatrix[$i]['wfs_id'], $wfsMatrix[$i]['wfs_conf_id']);
-				$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->modul[$m]->permission = $perText;
-				if ($wfsMatrix[$i]['wfs_id'] == $wfsMatrix[$i+1]['wfs_id']){
-					$j++; //next record is the same service
-					$l++;	
-				}
-				else
-				{
-					$l = 0;
-				}
-
-				if ($wfsMatrix[$i]['featuretype_id'] == $wfsMatrix[$i+1]['featuretype_id']){
-					$m++;
-				}
-				else
-				{
-					$m = 0;
-				}		
-			}
-			
-	}
-	private function generateWMCMetadataJSON($res, $n) {
-		//initialize object
-		$this->wmcJSON = new stdClass;
-		$this->wmcJSON->wmc = (object) array(
-				'md' => (object) array(
-					'nresults' => $n, 
-					'p' => $this->searchPages,
-					'rpp' => $this->maxResults
-					),
-				'srv' => array()
-				);
-			
-		//read out records
-		$serverCount = 0;
-		$wmcMatrix = db_fetch_all($res);
-		//sort result for accessing the right services
-		$wmcMatrix = $this->flipDiagonally($wmcMatrix);
-		//TODO check if order by db or order by php is faster! 
-		#array_multisort($wfsMatrix['wfs_id'], SORT_ASC,$wfsMatrix['featuretype_id'], SORT_ASC,$wfsMatrix['wfs_conf_id'], SORT_ASC); //have some problems - the database version is more stable
-		#print_r($wfsMatrix);
-		$wmcMatrix = $this->flipDiagonally($wmcMatrix);
-		//read out first server entry - maybe this a little bit timeconsuming TODO
-		for($i=0; $i<count($wmcMatrix);$i++){
-			$this->wmcJSON->wmc->srv[$i]->id = $wmcMatrix[$i]['wmc_id'];
-			$this->wmcJSON->wmc->srv[$i]->title = $wmcMatrix[$i]['wmc_title'];
-			$this->wmcJSON->wmc->srv[$i]->abstract = $wmcMatrix[$i]['abstract'];
-			$this->wmcJSON->wmc->srv[$i]->date = date("d.m.Y",$wmcMatrix[$i]['wmc_timestamp']);
-			$this->wmcJSON->wmc->srv[$i]->respOrg = $wmcMatrix[$i]['mb_group_name'];
-			$this->wmcJSON->wmc->srv[$i]->mdLink = "http://".$this->hostName."/mapbender/x_geoportal/showWMCMetadata.php?id=".$wmcMatrix[$i]['wmc_id'];
-			$this->wmcJSON->wmc->srv[$i]->previewURL = "http://".$this->hostName."/mapbender/x_geoportal/mod_wmcPreview.php?id=".$wmcMatrix[$i]['wmc_id'];
-			$spatialSource = "";
-			$stateOrProvince = $wmcMatrix[$i]['mb_group_stateorprovince']; 
-			if ($stateOrProvince == "NULL" || $stateOrProvince == "") {
-				$spatialSource = $wmcMatrix[$i]['mb_group_country'];
-			} else {
-				$spatialSource = $wmcMatrix[$i]['mb_group_stateorprovince'];
-			}
-			$this->wmcJSON->wmc->srv[$i-$j]->iso3166 = $spatialSource;
-				
-			$this->wmcJSON->wmc->srv[$i-$j]->bbox = array($wmcMatrix[$i]['bbox']); //TODO: read out bbox from wmc $wmcMatrix[$i][''];
-
-			#$equalEPSG = $wmcMatrix[$i]['srs'];
-                       	#$isEqual = true;
-			//control if EPSG is supported by Client
-		        #if ($equalEPSG == $this->searchEPSG){
-			#	$isEqual = false;		
-		        #}	
-				
-		}
-			
-	}
-
-
-
-
-
-	private function generateWMSMetadataJSON($res, $n) {
-		//initialize object
-		$this->wmsJSON = new stdClass;
-		$this->wmsJSON->wms = (object) array(
-				'md' => (object) array(
-					'nresults' => $n, 
-					'p' => $this->searchPages,
-					'rpp' => $this->maxResults
-					),
-				'srv' => array()
-				);
-		//read out records
-		$serverCount = 0;
-		$wmsMatrix = db_fetch_all($res);
-		$layerIdArray = array();
-		//read out array with unique wms_ids in wmsMatrix
-		$wmsIdArray = array();
-		//initialize root layer id;
-		$rootLayerId = -1;
-		$j = 0;
-		//get array with all available layer_id for this user:
- 		$admin = new administration();
-		$this->accessableLayers = $admin->getLayersByPermission($this->userId);
-		#echo "<br>user_id: ".$this->userId."<br><br>";
-		#var_dump($this->accessableLayers);
-		#echo "<br>";
-		#$countWmsMatrix = count($wmsMatrix);
-		#echo $countWmsMatrix;
-		if ($n != 0) {
-		for($i=0; $i<count($wmsMatrix);$i++){				
-			$layerID = $wmsMatrix[$i]['layer_id'];
-			#echo "<br>LayerID: ".$layerID."<br>";	
-			#$wmsID = $wmsMatrix[$i]['wms_id']; //get first wms id - in the next loop - dont get second, but some else!
-			if (!in_array($layerID, $layerIdArray) or !in_array($rootLayerId, $layerIdArray)) {
-				$wmsID = $wmsMatrix[$i]['wms_id']; //get first wms id - in the next loop - dont get second, but some else!
-				//Select all layers of with this wms_id into new array per WMS - the grouping should be done by wms!
-				$subLayers = $this->filter_by_value($wmsMatrix, 'wms_id', $wmsID);
-				#echo "<br>wms_id: ".$wmsID."<br>";
-				#echo "<br>Number of sublayers: <br>";
-				#print(count($subLayers));
-				//Sort array by load_count - problem: maybe there are some groups between where count is to low (they have no load count because you cannot load them by name)? - Therefor we need some ideas - or pull them out of the database and show them greyed out. Another way will be to define a new group (or wms with the same id) for those layers which are more than one integer away from their parents
-				$subLayersFlip = $this->flipDiagonally($subLayers);
-				#var_dump($subLayers['layer_pos']);
-				#$subLayers = $this->flipDiagonally($subLayers);
-				//go backwards through the layerTree to get the layer with the highest position without gaps in between
-				#var_dump($subLayers['layer_id']);
-				#echo "<br>";
-				$index = array_search($layerID, $subLayersFlip['layer_id']);
-				#echo "<br>found layer_id= ".$layerID." at index: ".$index." in sublayerstable layer_pos=".$subLayers[$index]['layer_pos']." <br>";
-				
-				#echo "<br>sublayers: ";
-				#var_dump($subLayersFlip);
-				#echo "<br>";
-				$rootIndex = $this->getLayerParent($subLayersFlip, $index);
-				$rootLayerPos = $subLayers[$rootIndex]['layer_pos'];
-				$rootLayerId = $subLayers[$rootIndex]['layer_id'];
-				#echo "<br>root layer for this layer: <br>";
-				#echo "<br>id= "..""
-				#echo "<br>";
-				#echo "<br>LayerId:<br>";
-				#echo "<br>".$layerID."<br>";
-				#echo "<br>rootLayerPos:<br>";
-				#echo "<br>".$rootLayerPos."<br>";
-				#echo "<br>rootLayerId:<br>";
-				#echo "<br>".$rootLayerId."<br>";
-				//push root layer id in array
-				array_push($layerIdArray, $rootLayerId);
-				#echo "<br>root Layer ID: ".$rootLayerId."<br>";
-				#array_multisort($subLayers['layer_pos'], SORT_ASC);
-				#print_r($subLayers);
-				#$subLayers = $this->flipDiagonally($subLayers);
-				#print_r("<br>rootIndex: ".$rootIndex."<br>");
-				//Create object for wms service level
-				$this->wmsJSON->wms->srv[$j]->id = (integer)$subLayers[$rootIndex]['wms_id'];
-				$this->wmsJSON->wms->srv[$j]->title = $subLayers[$rootIndex]['wms_title'];
-				$this->wmsJSON->wms->srv[$j]->abstract = $subLayers[$rootIndex]['wms_abstract'];
-				$this->wmsJSON->wms->srv[$j]->date = date("d.m.Y",$subLayers[$rootIndex]['wms_timestamp']);
-				#$this->wmsJSON->wms->srv[$j]->respOrg = "test";
-				$this->wmsJSON->wms->srv[$j]->loadCount = (integer)$subLayers[$rootIndex]['load_count'];
-				#$this->wmsJSON->wms->srv[$j]->mdLink = "http://".$_SERVER['HTTP_HOST']."/mapbender/x_geoportal/mod_layerMetadata.php?id=".(integer)$subLayers[$rootIndex]['layer_id'];
-				$spatialSource = "";
-				$stateOrProvince = $subLayers[$rootIndex]['stateorprovince']; 
-				#echo $stateOrProvince."<br>";
-				if ($stateOrProvince == "NULL" || $stateOrProvince == "") {
-					$spatialSource = $subLayers[$rootIndex]['country'];
-				} else {
-					$spatialSource = $subLayers[$rootIndex]['stateorprovince'];
-				}
-				$this->wmsJSON->wms->srv[$j]->iso3166 = $spatialSource;
-				$this->wmsJSON->wms->srv[$j]->respOrg = $subLayers[$rootIndex]['mb_group_name'];
-				$this->wmsJSON->wms->srv[$j]->logoUrl = $subLayers[$rootIndex]['mb_group_logo_path'];
-				#$this->wmsJSON->wms->srv[$j]->tou = $subLayers[$rootIndex]['termsofuse'];
-				//check if a disclaimer has to be shown and give the relevant symbol
-				list($hasConstraints, $symbolLink) = $this->hasConstraints("wms", $subLayers[$rootIndex]['wms_id']);
-				$this->wmsJSON->wms->srv[$j]->hasConstraints = $hasConstraints;
-				$this->wmsJSON->wms->srv[$j]->symbolLink = $symbolLink;
-				//TODO check the field accessconstraints - which should be presented?
-				$this->wmsJSON->wms->srv[$j]->status = $subLayers[$rootIndex]['status']; //$wmsMatrix[$i][''];
-				$this->wmsJSON->wms->srv[$j]->avail = $subLayers[$rootIndex]['availability']; //$wmsMatrix[$i][''];
-				//get info about defined price
-				if ($subLayers[$rootIndex]['wms_pricevolume'] == '' OR $subLayers[$rootIndex]['wms_pricevolume'] == 0){
-					$this->wmsJSON->wms->srv[$j]->price = NULL;
-				}
-				else {
-					$this->wmsJSON->wms->srv[$j]->price = $subLayers[$rootIndex]['wms_pricevolume'];
-				}
-				//get info about logging of resource
-				if ($subLayers[$rootIndex]['wms_proxylog'] == NULL OR $subLayers[$rootIndex]['wms_proxylog'] == 0){
-					 $this->wmsJSON->wms->srv[$j]->logged = false;
-				}
-				else {
-					 $this->wmsJSON->wms->srv[$j]->logged = true;
-				}
-				//get info about network_accessability
-				if ($subLayers[$rootIndex]['wms_network_access'] == NULL OR $subLayers[$rootIndex]['wms_network_access'] == 0){
-					 $this->wmsJSON->wms->srv[$j]->nwaccess = false;
-				}
-				else {
-					 $this->wmsJSON->wms->srv[$j]->nwaccess = true;
-				}
-				#$this->wmsJSON->wms->srv[$j]->logged = NULL; //$wmsMatrix[$i][''];
-				#$this->wmsJSON->wms->srv[$j]->price = NULL; //$wmsMatrix[$i][''];
-				#$this->wmsJSON->wms->srv[$j]->nwaccess = NULL; //$wmsMatrix[$i][''];
-				$this->wmsJSON->wms->srv[$j]->bbox = $subLayers[$rootIndex]['bbox']; //$wmsMatrix[$i][''];
-				//Call recursively the child elements, give and pull $layerIdArray to push the done elements in the array to avoid double results
-				#print_r($subLayers);
-				//generate the layer-entry for the so called root layer - maybe this is only a group layer if there is a gap in the layer hierachy
-				$this->wmsJSON->wms->srv[$j]->layer = array();
-				$this->wmsJSON->wms->srv[$j]->layer[0]->id = (integer)$subLayers[$rootIndex]['layer_id'];
-				$this->wmsJSON->wms->srv[$j]->layer[0]->title = $subLayers[$rootIndex]['layer_title'];
-				$this->wmsJSON->wms->srv[$j]->layer[0]->abstract = $subLayers[$rootIndex]['layer_abstract'];
-				$this->wmsJSON->wms->srv[$j]->layer[0]->mdLink = "http://".$this->hostName."/mapbender/php/mod_showMetadata.php?resource=layer&id=".(integer)$subLayers[$rootIndex]['layer_id'];
-				$this->wmsJSON->wms->srv[$j]->layer[0]->previewURL = "http://".$this->hostName."/mapbender/x_geoportal/mod_layerPreview.php?id=".(integer)$subLayers[$rootIndex]['layer_id'];
-				if ($subLayers[$rootIndex]['layer_name'] == ''){
-					$this->wmsJSON->wms->srv[$j]->layer[0]->loadable = 0;
-				}
-				else {
-					$this->wmsJSON->wms->srv[$j]->layer[0]->loadable = 1;
-				}
-				if ($subLayers[$rootIndex]['layer_pos'] == '0'){
-					$this->wmsJSON->wms->srv[$j]->layer[0]->isRoot = true;
-				}
-				else {
-					$this->wmsJSON->wms->srv[$j]->layer[0]->isRoot = false;
-				}
-				//give info for inspire categories - not relevant for other services or instances of mapbender TODO: comment it if the mapbender installation is not used to generate inspire output
-				if ($subLayers[$rootIndex]['md_inspire_cats'] == ''){
-					$this->wmsJSON->wms->srv[$j]->layer[0]->inspire = 0;
-				}
-				else {
-					$this->wmsJSON->wms->srv[$j]->layer[0]->inspire = 1;
-				}
-				//get info about queryable or not
-				if ($subLayers[$rootIndex]['layer_queryable'] == 1){
-					$this->wmsJSON->wms->srv[$j]->layer[0]->queryable = 1;
-				}
-				else {
-					$this->wmsJSON->wms->srv[$j]->layer[0]->queryable = 0;
-				}
-				
-				#if ($subLayers[$rootIndex]['layer_name'] == ''){
-				#	$this->wmsJSON->wms->srv[$i-$j]->layer[0]->loadable = 0;
-				#}
-				#else {
-				#	$this->wmsJSON->wms->srv[$i-$j]->layer[0]->loadable = 1;
-				#}
-				$this->wmsJSON->wms->srv[$j]->layer[0]->loadCount = $subLayers[$rootIndex]['load_count'];
-				#$servObject->layer[$countsublayer]->mdLink = $_SERVER['HOST']."/mapbender/x_geoportal/showWFeatureTypeMetadata.php?id=".$wfsMatrix[$i]['featuretype_id'];
-				#$servObject->layer[$countsublayer]->geomtype = $wfsMatrix[$i]['element_type'];
-				$this->wmsJSON->wms->srv[$j]->layer[0]->bbox = $subLayers[$rootIndex]['bbox'];
-				$this->wmsJSON->wms->srv[$j]->layer[0]->permission = $this->getPermissionValueForLayer($subLayers[$rootIndex]['layer_id'], $subLayers[$rootIndex]['wms_id']); //TODO: Make this much more faster
-				//when the entry for the first server has been written, the server entry is fixed and the next one will be a new server or a part of the old one.
-				 //increment server (highest object id)
-				
-				$layerIdArray = $this->writeWMSChilds($layerIdArray, $rootLayerPos, $subLayers, $this->wmsJSON->wms->srv[$j]->layer[0]);
-				$j++;
-				//generate php object - if root layer was found - > layer_parent='' give hint to visualize folder symbol. 		
-				}
-			}
-		}			
-	}
-
-	private function generateWMSMetadata($xmlDoc) {
-		$starttime = $this->microtime_float();
-		list($sql, $v, $t, $n) = $this->generateSearchSQL();
-		//call database search in limits
-		$res = db_prep_query($sql, $v, $t);
-		if ($this->outputFormat == 'json'){
-			//generate json
-			$this->generateWMSMetadataJSON($res,$n);
-			$usedTime = $this->microtime_float() - $starttime;
-			//put in the time to generate the data
-			$this->wmsJSON->wms->md->genTime = $usedTime;
-			$this->wmsJSON = $this->json->encode($this->wmsJSON);
-			if ($this->resultTarget == 'file') {
-				if($wmsFileHandle = fopen($this->tempFolder."/".$this->searchId."_".$this->searchResources."_".$this->searchPages.".json","w")){
-					fwrite($wmsFileHandle,$this->wmsJSON);
-					fclose($wmsFileHandle);
-				}
-			}
-			if ($this->resultTarget == 'web' or $this->resultTarget == 'debug') {
-				echo $this->wmsJSON;
-			}
-		}
-		$usedTime2 = $this->microtime_float() - $starttime;
-		//echo "<br>used time: ".$usedTime."<br>";
-		$e = new mb_exception("Time to generate WMS-Metadata: ".$usedTime2);
-		$e = new mb_exception("Wrote the MD_WMS-File");
-	}
-
-
-
-	private function generateWFSMetadata($xmlDoc) {
-		$starttime = $this->microtime_float();
-		list($sql, $v, $t, $n) = $this->generateSearchSQL();
-		//call database search
-		$res = db_prep_query($sql, $v, $t);
-		if ($this->outputFormat == 'json'){
-			//generate json
-			$this->generateWFSMetadataJSON($res, $n);
-			$usedTime = $this->microtime_float() - $starttime;
-			//put in the time to generate the data
-			$this->wfsJSON->wfs->md->genTime = $usedTime;
-			$this->wfsJSON = $this->json->encode($this->wfsJSON);
-			if ($this->resultTarget == 'file') {
-				if($wfsFileHandle = fopen($this->tempFolder."/".$this->searchId."_".$this->searchResources."_".$this->searchPages.".json","w")){
-					fwrite($wfsFileHandle,$this->wfsJSON);
-					fclose($wfsFileHandle);
-				}
-			}
-			if ($this->resultTarget == 'web'or $this->resultTarget == 'debug') {
-				echo $this->wfsJSON;
-			}
-		}
-		if ($this->outputFormat == 'xml'){
-			//generate xml
-			$this->generateXMLHead($xmlDoc);
-			$this->generateXMLFoot($xmlDoc);
-			$this->generateWFSResultXML($xmlDoc,$res);
-			if ($this->resultTarget == 'file') {
-				if($wfsFileHandleXML = fopen($this->tempFolder."/".$this->searchId."_".$this->searchResources."_".$this->searchPages.".xml","w")){
-					fwrite($wfsFileHandleXML,$xmlDoc->saveXML());
-					fclose($wfsFileHandleXML);
-				}
-			}
-			if ($this->resultTarget == 'web') {
-				header("Content-type: application/xhtml+xml; charset=UTF-8");
-				echo $xmlDoc->saveXML();
-			}
-		}
-		
-		$e = new mb_exception("Time to generate WFS-Metadata: ".$usedTime);
-		$e = new mb_exception("Wrote the MD_WFS-File");
-	}
-	private function generateWMCMetadata($xmlDoc) {
-		$starttime = $this->microtime_float();
-		list($sql, $v, $t, $n) = $this->generateSearchSQL();
-		//call database search in limits
-		$res = db_prep_query($sql, $v, $t);
-		if ($this->outputFormat == 'json'){
-			//generate json
-			$this->generateWMCMetadataJSON($res,$n);
-			$usedTime = $this->microtime_float() - $starttime;
-			//put in the time to generate the data
-			$this->wmcJSON->wmc->md->genTime = $usedTime;
-			$this->wmcJSON = $this->json->encode($this->wmcJSON);
-			if ($this->resultTarget == 'file') {
-				if($wmcFileHandle = fopen($this->tempFolder."/".$this->searchId."_".$this->searchResources."_".$this->searchPages.".json","w")){
-					fwrite($wmcFileHandle,$this->wmcJSON);
-					fclose($wmcFileHandle);
-				}
-			}
-			if ($this->resultTarget == 'web' or $this->resultTarget == 'debug') {
-				echo $this->wmcJSON;
-			}
-		}
-		$usedTime2 = $this->microtime_float() - $starttime;
-		//echo "<br>used time: ".$usedTime."<br>";
-		$e = new mb_exception("Time to generate WMC-Metadata: ".$usedTime2);
-		$e = new mb_exception("Wrote the MD_WMC-File");
-	}
-
-
-
-
-
-	private function replaceChars_all($text){
-		$search = array( "ä",  "ö",  "ü",  "Ä",  "Ö",  "Ü",  "ß");
-		$repWith = array("ae", "oe", "ue", "AE", "OE", "UE", "ss");
-		$replaced = str_replace($search, $repWith, $text);
-		return $replaced;
-	}
-	private function generateSearchSQL() {
-		//elements needed to exist in mb wfs,wms,wmc view or table:
-		//1. textfield - all texts - searchText
-		//2. responsible organisations - given id 
-		//3. bbox - is not explicit given in the wfs metadata? Since WFS 1.1.0 a latlonbbox is present
-		//4. isoTopicCategory - is not been saved til now
-		//5. ...
-		//parse searchText into different array elements to allow an AND search
-		$searchStringArray = $this->generateSearchStringArray();
-		$v = array();
-		$t = array();
-		$sql = "SELECT * from ".$this->searchView." where ";
-		#$sqlN = "SELECT count(".$this->searchResources."_id) from ".$this->searchView." where ";
-		$whereStr = "";
-		$whereCondArray = array();
-		$isTextSearch = "false";
-		$e = new mb_exception("Number of used searchstrings: ".count($searchStringArray));
-		//textsearch
-		if ($this->searchText != NULL) {
-			for($i=0; $i < count($searchStringArray); $i++){
-				$isTextSearch = "true";
-				if($i>0) {
-					$whereStr .= " AND ";
-				}
-				$whereStr .= "searchtext LIKE $".($i+1);
-				//output for debugging
-				$e = new mb_notice("Part of string".$i.": ".$searchStringArray[$i]);
-				$e = new mb_notice("converted: ".$this->replaceChars_all($searchStringArray[$i]));			
-				$va = "%".trim(strtoupper($this->replaceChars_all($searchStringArray[$i])))."%";
-				$e = new mb_notice($this->searchResources." Searchtext in SQL: ".$va);
-				array_push($v,$va);
-				array_push($t,"s");	
-			}
-		}
-
-
-		// This is only for the later postgis versions. The within and disjoint is to slow, cause there is no usage of the geometrical index in the old versions!
-		//check for postgis version
-		//sql for get version string
-		//get version number
-		if ((strtolower($this->searchResources) === "wms" or strtolower($this->searchResources) === "wmc") & $this->searchBbox != NULL) {
-			//decide which type of search should be done
-			//check for postgis version cause postgis versions < 1.4 have problems when doing disjoint and inside
-			//
-			$sqlPostgisVersion = "SELECT postgis_version();";
-			$vPostgisVersion = array();
-			$tPostgisVersion = array();
-			$resPostgisVersion = db_prep_query($sqlPostgisVersion, $vPostgisVersion, $tPostgisVersion);
-			// get version string
-			while($row = db_fetch_array($resPostgisVersion)){
-				$postgisVersion = $row['postgis_version'];
-				$postgisVersionArray = explode(" ",$postgisVersion);
-				$postgisVersionSmall = explode(".",$postgisVersionArray[0]);
-				$postgisSubNumber = $postgisVersionSmall[1];
-				$e = new mb_exception("class_metadata.php: postgis sub number = ".$postgisSubNumber);
-			}
-			//
-			//
-			if ((integer)$postgisSubNumber >= 4){
-				#$spatialFilter = "(the_geom ";	
-				$e = new mb_exception("class_metadata.php: spatial operator: ".$this->searchTypeBbox);
-				if ($this->searchTypeBbox == 'outside') {
-					$spatialFilter = ' disjoint(';
-				} elseif ($this->searchTypeBbox == 'inside') { 
-					$spatialFilter = ' within(';
-				} else {
-					$spatialFilter = ' intersects(';
-				}
-				//define spatial filter
-				if(count(explode(',',$this->searchBbox)) == 4){   //if searchBbox has 4 entries
-					$spatialFilterCoords = explode(',',$this->searchBbox);//read out searchBbox
-					//definition of the spatial filter
-					$spatialFilter .= 'GeomFromText(\'POLYGON(('.$spatialFilterCoords[0];//minx
-					$spatialFilter .= ' '.$spatialFilterCoords[1].',';//miny
-					$spatialFilter .= $spatialFilterCoords[0];//minx
-					$spatialFilter .= ' '.$spatialFilterCoords[3].',';//maxy
-					$spatialFilter .= $spatialFilterCoords[2];//maxx
-					$spatialFilter .= ' '.$spatialFilterCoords[3].',';//maxy
-					$spatialFilter .= $spatialFilterCoords[2];//maxx
-					$spatialFilter .= ' '.$spatialFilterCoords[1].',';//miny
-					$spatialFilter .= $spatialFilterCoords[0];//minx
-					$spatialFilter .= ' '.$spatialFilterCoords[1].'))\',4326)';//miny
-					$spatialFilter .= ",the_geom)";
-					array_push($whereCondArray, $spatialFilter);
-				}
-			} else {
-		
-				$spatialFilter = ' the_geom && ';
-				//define spatial filter
-				if(count(explode(',',$this->searchBbox)) == 4){   //if searchBbox has 4 entries
-					$spatialFilterCoords = explode(',',$this->searchBbox);//read out searchBbox
-					//definition of the spatial filter
-					$spatialFilter .= 'GeomFromText(\'POLYGON(('.$spatialFilterCoords[0];//minx
-					$spatialFilter .= ' '.$spatialFilterCoords[1].',';//miny
-					$spatialFilter .= $spatialFilterCoords[0];//minx
-					$spatialFilter .= ' '.$spatialFilterCoords[3].',';//maxy
-					$spatialFilter .= $spatialFilterCoords[2];//maxx
-					$spatialFilter .= ' '.$spatialFilterCoords[3].',';//maxy
-					$spatialFilter .= $spatialFilterCoords[2];//maxx
-					$spatialFilter .= ' '.$spatialFilterCoords[1].',';//miny
-					$spatialFilter .= $spatialFilterCoords[0];//minx
-					$spatialFilter .= ' '.$spatialFilterCoords[1].'))\',4326)';//miny
-					#$spatialFilter .= ",the_geom)";
-					array_push($whereCondArray, $spatialFilter);
-				}
-			}
-		}	
-		//search filter for md_topic_categories
-		//
-		if ((strtolower($this->searchResources) === "wms" or strtolower($this->searchResources) === "wmc") & $this->isoCategories != NULL) {
-			
-			$isoArray = explode(',',$this->isoCategories);
-			$topicCond = "(";
-			for($i=0; $i < count($isoArray); $i++){
-				if ($i == 0) {
-					$topicCond .= "(md_topic_cats LIKE '%{".$isoArray[$i]."}%') ";			
-				} else {
-					$topicCond .= "AND (md_topic_cats LIKE '%{".$isoArray[$i]."}%') ";
-				}
-			}
-			$topicCond .= ")";
-			array_push($whereCondArray, $topicCond);
-		}
-		//search filter for inspire_categories
-		//
-		if (strtolower($this->searchResources) === "wms" & $this->inspireThemes != NULL) {
-			
-			$inspireArray = explode(',',$this->inspireThemes);
-			$inspireCond = "(";
-			for($i=0; $i < count($inspireArray); $i++){
-				if ($i == 0) {
-					$inspireCond .= "(md_inspire_cats LIKE '%{".$inspireArray[$i]."}%') ";			
-				} else {
-					$inspireCond .= "AND (md_inspire_cats LIKE '%{".$inspireArray[$i]."}%') ";
-				}
-			}
-			$inspireCond .= ")";
-			array_push($whereCondArray, $inspireCond);
-		}
-		//search filter for custom_categories
-		//
-		if (strtolower($this->searchResources) === "wms" & $this->customCategories != NULL) {
-			
-			$customArray = explode(',',$this->customCategories);
-			$customCond = "(";
-			for($i=0; $i < count($customArray); $i++){
-				if ($i == 0) {
-					$customCond .= "(md_custom_cats LIKE '%{".$customArray[$i]."}%') ";			
-				} else {
-					$customCond .= "AND (md_custom_cats LIKE '%{".$customArray[$i]."}%') ";
-				}
-			}
-			$customCond .= ")";
-			array_push($whereCondArray, $customCond);
-		}
-		
-
-
-		//date condition
-		//if begin and end are set
-		//echo "<br> regTimeBegin: ".$this-> regTimeBegin." regTimeEnd: ".$this-> regTimeEnd."<br>";
-		
-		if ($this->regTimeBegin != NULL && $this->regTimeEnd != NULL){
-			$time ="(TO_TIMESTAMP(".$this->searchResources."_timestamp) BETWEEN '".$this->regTimeBegin."' AND '".$this->regTimeEnd."')";
-			array_push($whereCondArray, $time);
-			//only begin is set		
-		}
-		if ($this->regTimeBegin != NULL && $this->regTimeEnd == NULL){
-			$time ="(TO_TIMESTAMP(".$this->searchResources."_timestamp) > '".$this->regTimeBegin."')";
-			array_push($whereCondArray, $time);
-		}
-		if ($this->regTimeBegin == NULL && $this->regTimeEnd != NULL){
-			$time ="(TO_TIMESTAMP(".$this->searchResources."_timestamp) < '".$this->regTimeEnd."')";
-			array_push($whereCondArray, $time);
-		}
-
- 
-		//department condition
-		//TODO: generate filter for new sql check if at least some department is requested
-		//generate array
-		//$this->registratingDepartments = explode(',',$this->registratingDepartments);
-		#if(count($this->registratingDepartments) > 0 & $this->registratingDepartments){
-		if($this->registratingDepartments != NULL){		
-			$dep = " department IN (".$this->registratingDepartments.") ";
-			array_push($whereCondArray, $dep);	
-		}
-		// Creating the WHERE clause, based on a array
-		if(count($whereCondArray) > 0){
-			$txt_whereCond = "";
-			for ($index = 0; $index < sizeof($whereCondArray); $index++) {
-				$array_element = $whereCondArray[$index];
-				if($isTextSearch == "true") {
-					$txt_whereCond .= " AND ".$array_element;
-				} else {
-					if($index>0){
-					$txt_whereCond .= " AND ".$array_element;		
-					} else {
-						$txt_whereCond .= " ".$array_element;	
-					}	
-				}
-			}
-			$whereStr .= $txt_whereCond;
-		}
-		//Add WHERE condition to search
-		$sql .= $whereStr;
-		//TODO ORDER BY in SQL - not necessary for counting things:
-		$sql .= $this->orderBy;
-		//Calculate Paging for OFFSET and LIMIT values:
-		$offset = ((integer)$this->maxResults) * ((integer)$this->searchPages -1);
-		$limit = (integer)$this->maxResults;
-		//defining range for paging
-		$sql .= " LIMIT ".$limit." OFFSET ".$offset."";
-		//Print out search SQL term
-		$e = new mb_exception("class_metadata.php: Search => SQL-Request of ".$this->searchResources." service metadata: ".$sql."");
-		//parameter: searchId -> can be used global, searchResources -> is only one type per instance!!-> global,which categories -> can be defined global! $whereStr
-		$n = $this->writeCategories($whereStr, $v, $t); 
-		//write counts to filesystem to avoid to many database connections
-		//only write them, if searchId is given - problem: searches with same searchId's maybe get wrong information
-		return array($sql, $v, $t, $n);
-	}
-
-
-
-
-
-
-
-
-
-
-/** Function to write a json file which includes the categories of the search result for each searchResource - wms/wfs/wmc/georss, new: it should also count the keyword distribution of the searchResource ans save it as a special json file!
-
-**/
-	private function writeCategories($whereStr, $v, $t) {
-		//generate count sql
-		//generate count of all entries	
-		$sqlN = "SELECT count(".$this->searchResources."_id) from ".$this->searchView." where ";
-		$sqlN .= $whereStr;
-		//Get total number of results 
-		$count = db_prep_query($sqlN, $v, $t);
-		$n = db_fetch_all($count);
-		#echo "<br>N: ".var_dump($n)."<br>";
-		$n = $n[0]['count'];
-		$e = new mb_notice("class_metadata.php: Search => SQL-Request of ".$this->searchResources." service metadata N: ".$sqlN." Number of found objects: ".$n);
-		if ($this->searchId != 'dummysearch') { //searchId is not the default id! - it has been explicitly defined 
-			//check if cat file already exists:
-			//filename to search for:
-			$filename = $this->tempFolder."/".$this->searchId."_".$this->searchResources."_cat.json";
-			$keyFilename = $this->tempFolder."/".$this->searchId."_".$this->searchResources."_keywords.json";
-			if (!file_exists($filename)  or $this->resultTarget == 'debug') { //TODO at the moment the cat file will be overwritten - change this in production system
-				//open category file for results
-				$this->catJSON = new stdClass;
-				$this->catJSON->searchMD = (object) array(
-					'searchId' => $this->searchId,
-					'n' => $n
-					);
-				//new: also generate a json object for the keyword distribution
-				$this->keyJSON = new stdClass;
-				$this->keyJSON->tagCloud = (object) array(
-					'searchId' => $this->searchId,
-					'maxFontSize' => $this->maxFontSize,
-					'maxObjects' => $this->maxObjects,
-					'title' => $this->keywordTitle,
-					'tags' => array()
-					);
-				$this->inc = $this->maxFontSize/$this->maxObjects;//maybe 10 or 5 or ...
-				//generate the list of category counts
-				$sqlCat = array();
-				//generate the sql for the keyword count
-				$sqlKeyword = "select keyword.keyword, COUNT(*) "; 
-				$sqlKeyword .= "FROM (select ";
-				$sqlKeyword .= $this->databaseIdColumnName;
-				$sqlKeyword .= " FROM ".$this->searchView." WHERE ".$whereStr.") as a";
-				$sqlKeyword .= " INNER JOIN ".$this->databaseTableName."_keyword ON (";
-				$sqlKeyword .= $this->databaseTableName."_keyword.fkey_".$this->databaseIdColumnName." = a.";
-				$sqlKeyword .= $this->databaseIdColumnName.") ";
-				$sqlKeyword .= "INNER JOIN keyword ON (keyword.keyword_id=".$this->databaseTableName."_keyword.fkey_keyword_id) WHERE (keyword.keyword NOTNULL AND keyword.keyword <> '')";
-				$sqlKeyword .= "GROUP BY keyword.keyword  ORDER BY COUNT DESC LIMIT  ".$this->maxObjects;
-				//do sql select for keyword cloud
-				$resKeyword = db_prep_query($sqlKeyword, $v, $t);
-				$keywordCounts = db_fetch_all($resKeyword);
-				
-				if (count($keywordCounts) > 0) {
-					$this->maxWeight = $keywordCounts[0]['count'];
-					for ($j = 0; $j < count($keywordCounts); $j++) {
-						if ($this->scale == 'linear'){
-							//order in a linear scale desc
-							 $keywordCounts[$j]['count'] = $this->maxFontSize-($j*$this->inc);
-						} else {
-							//set weight prop to count 
-							 $keywordCounts[$j]['count'] = $keywordCounts[$j]['count']*$this->maxFontSize/$this->maxWeight;
-						}
-					}
-					//$this->maxWeight = $keywordCounts[0]['count'];
-					shuffle($keywordCounts);
-					for ($j = 0; $j < count($keywordCounts); $j++) {
-						$this->keyJSON->tagCloud->tags[$j]->title = $keywordCounts[$j]['keyword'];
-						//generate the weight:
-						//if ($this->scale == 'linear'){
-							//order in a linear scale desc
-							 $this->keyJSON->tagCloud->tags[$j]->weight = $keywordCounts[$j]['count'];
-						//} else {
-							//set weight prop to count 
-							// $this->keyJSON->tagCloud->tags[$j]->weight = $keywordCounts[$j]['count']*$this->maxFontSize/$this->maxWeight;
-						//}
-						//$this->keyJSON->tags[$j]->weight = $keywordCounts[$j]['count'];
-
-						$paramValue = $this->getValueForParam('searchText', $this->searchURL);	
-						//delete resources part from query and set some new one
-						$searchUrlKeywords = $this->delTotalFromQuery('searchResources',$this->searchURL);
-						//append the resource parameter:
-						$searchUrlKeywords .= '&searchResources='.$this->searchResources;
-						$e = new mb_exception("class_metadata_new: value ".$paramValue." for searchText param found");
-						$paramValue = urldecode($paramValue);
-						if ($paramValue == false) {
-							$this->keyJSON->tagCloud->tags[$j]->url = $searchUrlKeywords."&searchText=".$keywordCounts[$j]['keyword'];
-						} else {
-							$this->keyJSON->tagCloud->tags[$j]->url = $this->addToQuery('searchText',$searchUrlKeywords,$keywordCounts[$j]['keyword'],$paramValue);
-						}
-					}
-				}
-				//encode json!
-				$this->keyJSON = $this->json->encode($this->keyJSON);
-				//write clouds to file
-				if($keyFileHandle = fopen($keyFilename, "w")){
-					fwrite($keyFileHandle,$this->keyJSON);
-					fclose($keyFileHandle);
-					$e = new mb_notice("class_metadata: new ".$this->searchResources."_keyword_file created!");
-				} else {
-					$e = new mb_notice("class_metadata: cannot create ".$this->searchResources."_keyword_file!");
-				}
-				if ($this->resultTarget == 'debug') {
-					echo "<br>DEBUG: show keywords: <br>".$this->keyJSON."<br><br>";
-				}
-
-/** "$resourceId." from ".$wms_view." where ".$whereClause.") as a";
-				$sqlKeyword .= "(select keyword, count(*) from keyword INNER JOIN  layer_keyword  ON (layer_keyword.fkey_keyword_id = keyword.keyword_id) GROUP BY keyword.keyword) ";
-				$sqlKeyword .= " GROUP BY keyword.keyword)) as a WHERE a.keyword <> '' GROUP BY a.keyword ORDER BY sum DESC LIMIT $1";
-**/
-
-
-				//check if categories are defined for the resource
-				if ($this->resourceClasses != NULL) {
-					$this->catJSON->searchMD->category = array();
-					for ($i = 0; $i < count($this->resourceClasses); $i++) {
-						//TODO: not to set the classification?
-						$this->catJSON->searchMD->category[$i]->title = $this->resourceClassifications[$i]['title'];
-						$sqlCat[$i] = "SELECT ".$this->resourceClassifications[$i]['tablename'];
-						$sqlCat[$i] .= ".".$this->resourceClassifications[$i]['tablename']."_id, ";
-						$sqlCat[$i] .= " ".$this->resourceClassifications[$i]['tablename'].".";
-						$sqlCat[$i] .= $this->resourceClassifications[$i]['tablename']."_code_";
-						$sqlCat[$i] .= $this->languageCode.", COUNT(*) FROM ".$this->searchView;
-						
-						//first join for connection table
-						$sqlCat[$i] .= " INNER JOIN ".$this->resourceClassifications[$i]['relation_'.$this->searchResources];
-						$sqlCat[$i] .= " ON (";
-						$sqlCat[$i] .= $this->resourceClassifications[$i]['relation_'.$this->searchResources].".fkey_";
-						$sqlCat[$i] .= $this->resourceClassifications[$i]['id_'.$this->searchResources]."=".$this->searchView;
-						$sqlCat[$i] .= ".".$this->resourceClassifications[$i]['id_'.$this->searchResources];
-						$sqlCat[$i] .= ") INNER JOIN ";
-						$sqlCat[$i] .= $this->resourceClassifications[$i]['tablename']." ON (";
-						$sqlCat[$i] .= $this->resourceClassifications[$i]['tablename'].".";
-						$sqlCat[$i] .= $this->resourceClassifications[$i]['tablename']."_id=";
-						$sqlCat[$i] .= $this->resourceClassifications[$i]['relation_'.$this->searchResources].".fkey_";
-						$sqlCat[$i] .= $this->resourceClassifications[$i]['tablename']."_id)";
-						$sqlCat[$i] .= " WHERE ".$whereStr."  GROUP BY ";
-
-						$sqlCat[$i] .= $this->resourceClassifications[$i]['tablename'].".";
-						$sqlCat[$i] .= $this->resourceClassifications[$i]['tablename']."_id,";
-						$sqlCat[$i] .= $this->resourceClassifications[$i]['tablename'].".";
-						$sqlCat[$i] .= $this->resourceClassifications[$i]['tablename']."_code_".$this->languageCode." ORDER BY ";
-						$sqlCat[$i] .= $this->resourceClassifications[$i]['tablename']."_id";
-						$sqlCategory = $sqlCat[$i];
-
-						//call sql for count of category
-						$res = db_prep_query($sqlCategory, $v, $t);
-						$categoryCounts = db_fetch_all($res);
-						//if none found: $categoryCounts=false
-						#echo "<br>count sub categories :".$categoryCounts."<br>";
-						if ($categoryCounts) {
-						//write results in json object
-						if (count($categoryCounts) > 0) {
-							#echo "<br>count main categories".count($categoryCounts)."<br>";
-							#echo "<br>vardump main categories".var_dump($categoryCounts)."<br>";
-							$this->catJSON->searchMD->category[$i]->subcat = array();
-							for ($j = 0; $j < count($categoryCounts); $j++) {
-								$this->catJSON->searchMD->category[$i]->subcat[$j]->id = $categoryCounts[$j][$this->resourceClassifications[$i]['tablename']."_id"];
-								$this->catJSON->searchMD->category[$i]->subcat[$j]->title = $categoryCounts[$j][$this->resourceClassifications[$i]['tablename']."_code_".$this->languageCode];
-								$this->catJSON->searchMD->category[$i]->subcat[$j]->count = $categoryCounts[$j]['count'];
-								//delete requestParam for this category and for id - cause a new search is started from searchURL
-								$filteredSearchString = $this->delTotalFromQuery('searchId',$this->searchURL);
-								//uncomment the following line if a or category search is intended
-								//$filteredSearchString = $this->delTotalFromQuery($this->resourceClassifications[$i]['requestName'],$filteredSearchString);
-								//TODO: maybe adopt this to do a and search and not a or like it is done now
-								//check if category search was requested and rewrite the search url
-								//get the value of the param as string or false if not set!
-								$paramValue = $this->getValueForParam($this->resourceClassifications[$i]['requestName'], $filteredSearchString);
-								$paramValue = urldecode($paramValue);
-								if ($paramValue == false) {
-									//add new category to search
-
-								//set filter for this categoryid
-								$filteredSearchString .= "&".$this->resourceClassifications[$i]['requestName']."=".$categoryCounts[$j][$this->resourceClassifications[$i]['tablename']."_id"];
-								
-								
-								} else {
-									//rewrite the searchUrl
-									$filteredSearchString = $this->addToQuery($this->resourceClassifications[$i]['requestName'],$filteredSearchString,$categoryCounts[$j][$this->resourceClassifications[$i]['tablename']."_id"],$paramValue);
-								}
-
-								$this->catJSON->searchMD->category[$i]->subcat[$j]->filterLink = $filteredSearchString;
-							}
-						}
-						} else {
-							#$this->catJSON->searchMD->category[$i]->subcat = array();
-						}
-						$e = new mb_notice("class_metadata: countsql: ".$sqlCat[$i]);
-					}
-				}
-
-				$this->catJSON = $this->json->encode($this->catJSON);
-				//write categories files only when file is requested and the searchid was not used before!
-				if ($this->resultTarget == 'file') {
-					if($catFileHandle = fopen($filename, "w")){
-						fwrite($catFileHandle,$this->catJSON);
-						fclose($catFileHandle);
-						$e = new mb_notice("class_metadata: new ".$this->searchResources."_class_file created!");
-					} else {
-						$e = new mb_notice("class_metadata: cannot create ".$this->searchResources."_cat_file!");
-					}
-					
-				} 
-				if ($this->resultTarget == 'debug') {
-					echo "<br>DEBUG: show categories: <br>".$this->catJSON."<br><br>";
-				}
-			} else {
-				$e = new mb_exception("class_metadata: ".$this->searchResources."_class_file: ".$filename." already exists - no new one is generated!");				
-			}	
-		} else {
-			if ($this->resultTarget == 'debug') {
-				echo "<br>DEBUG: Standard ID dummysearch was invoked - classifications won't be counted!<br>";
-			}
-			$e = new mb_exception("class_metadata: standard dummysearch was invoked - classifications won't be counted!");	
-		}			
-		return $n;
-	}
-
-
-
-
-	private function generateWFSResultXML($wfsDoc, $res) {
-		$c = $this->wfsDoc->createElement("category");
-		$results = $this->wfsDoc->getElementsByTagName("result");
-		foreach ($results as $result) {
-			$result->appendChild($c);
-			$c->setAttribute('name', "WFS");
-			$c->setAttribute('count', "0");
-		}
-		$i = 0;
-		while($row = db_fetch_array($res)){
-			$m = $this->wfsDoc->createElement('member');
-			$m->setAttribute('wfs_id', $row['wfs_id']);
-			$m->setAttribute('layer_pos', "");
-			$c->appendChild($m);	 // member categorie 1 (first member)
-			// epsg - TODO adopt
-			$epsg = $this->wfsDoc->createElement('epsg');
-			$m->appendChild($epsg);	
-			$equalEPSG = $row['featuretype_srs'];
-                       	$isequal = "false";
-		        if ($equalEPSG == $this->search_epsg){
-				$isequal = "true";		
-		        }	
-		       	//Insert end
-			$epsg_text = $this->wfsDoc->createTextNode($isequal);
-			$epsg->appendChild($epsg_text);
-			// country codes
-			$state = $this->wfsDoc->createElement('federalstate');
-			$m->appendChild($state);
-			$spatialSource = "";
-			$stateorprovince = $row['administrativearea']; 
-			if ($stateorprovince == "NULL" || $stateorprovince == "") {
-				$spatialSource = $row['country'];
-			} else {
-				$spatialSource = $row['administrativearea'];
-			}
-			$countr_code_text = $this->wfsDoc->createTextNode($spatialSource);
-			$state->appendChild($countr_code_text);
-			//type
-			$type = $this->wfsDoc->createElement('type');
-			$m->appendChild($type);
-			$ttype = $this->wfsDoc->createTextNode("wfs");
-			$type->appendChild($ttype);
-                        //wfs_id
-			$wfsid = $this->wfsDoc->createElement('wfs_id');
-			$m->appendChild($wfsid);
-			$twfsid = $this->wfsDoc->createTextNode($row['wfs_id']);
-			$wfsid->appendChild($twfsid);
-			//id
-			$id = $this->wfsDoc->createElement('featuretype_id');
-			$m->appendChild($id);
-			$tid = $this->wfsDoc->createTextNode($row['featuretype_id']);
-			$id->appendChild($tid);
-			//title
-			$title = $this->wfsDoc->createElement('featuretype_title');
-			$m->appendChild($title);
-			$ttitle = $this->wfsDoc->createTextNode($row['featuretype_title']);
-			$title->appendChild($ttitle);
-			//abstract
-			$abst = $this->wfsDoc->createElement('featuretype_abstract');
-			$m->appendChild($abst);  
-			$tabst = $this->wfsDoc->createTextNode($row['featuretype_abstract']);
-			$abst->appendChild($tabst);
-			// accesscontraints				
-			$ac = $this->wfsDoc->createElement('accessconstraints');
-			$m->appendChild($ac);	
-//			$myac = $this->getAccessConstraints($this->cat[$i]['member'][$ii]['wms_id'], $this->cat[$i]['member'][$ii]['accessconstraints'], $this->cat[$i]['member'][$ii]['layer_id']);				
-			$myac = $this->wfsDoc->createTextNode($row['accessconstraints']);							
-			$ac->appendChild($myac);
-			// termsofuse				
-			$ter = $this->wfsDoc->createElement('termsofuse');
-			$m->appendChild($ter);
-			$myter =  $this->wfsDoc->createTextNode($row['termsofuse']);				
-			$ter->appendChild($myter);
-			//date
-			$date = $this->wfsDoc->createElement('date');
-			$m->appendChild($date);
-			$tdate = $this->wfsDoc->createTextNode(date("d.m.Y",$row['wfs_timestamp']));
-			$date->appendChild($tdate);	
-			// Geomtype
-			$geo = $this->wfsDoc->createElement('geomtype');
-			$m->appendChild($geo);
-			//$geo_text = $this->getGeoType($row['wfs_id'], $row['featuretype_id']);
-			$geo_text = $this->wfsDoc->createTextNode($row['element_type']);
-			//$ge =  $this->wfsDoc->createTextNode($geo_text);
-			$geo->appendChild($geo_text);
-			//department
-			$dm = $this->wfsDoc->createElement('department');
-			$m->appendChild($dm);
-			$tdm = $this->wfsDoc->createTextNode($row['mb_group_name']);
-			$dm->appendChild($tdm);
-			//permission  		 Leseberechtigung des Benutzers(true), sonst Email zur Beantragung(email)
-			$per = $this->wfsDoc->createElement('permission');
-			$m->appendChild($per);
-			$per_text = $this->getPermissionValueForWFS($row['wfs_id'], $row['wfs_conf_id']);
-			$pe =  $this->wfsDoc->createTextNode($per_text);
-			$per->appendChild($pe);
-			//wfs_conf_id
-			$conf_id = $this->wfsDoc->createElement('wfs_conf_id');
-			$m->appendChild($conf_id);
-			$c_id = $this->wfsDoc->createTextNode($row['wfs_conf_id']);
-			$conf_id->appendChild($c_id);
-			//wfs_conf_title
-			$conf_title = $this->wfsDoc->createElement('wfs_conf_title');
-			$m->appendChild($conf_title);
-			$conf_title_text = $this->wfsDoc->createTextNode($row['wfs_conf_abstract']);
-			$conf_title->appendChild($conf_title_text);
-			//wfs_conf_abstract
-			$conf_abstract = $this->wfsDoc->createElement('wfs_conf_abstract');
-			$m->appendChild($conf_abstract);
-			$c_abstract = $this->wfsDoc->createTextNode($row['wfs_conf_description']);
-			$conf_abstract->appendChild($c_abstract);
-			//wfs_conf_modul
-			$conf_modul = $this->wfsDoc->createElement('wfs_conf_modul');
-			$m->appendChild($conf_modul);
-			$c_modul = $this->wfsDoc->createTextNode($row['modultype']);
-			$conf_modul->appendChild($c_modul);
-			$i++;
-		}
-		$c->setAttribute('count', $i);
-	}
-
-	private function getPermissionValueForWFS($wfs_id, $wfs_conf_id){
-		//TODO: Set Email of owner into view for ressource - so it don't have to be searched?
-		$return_permission = "";
-		//get permission
-		$admin = new administration();
-		$myWFSconfs = $admin->getWfsConfByPermission($this->userId);
-		$this->myWFSConfs = $myWFSconfs;
-		for ($index = 0; $index < sizeof($this->myWFSConfs); $index++) {
-			$array_element = $this->myWFSConfs[$index];
-		}
-		if (in_array($wfs_conf_id, $this->myWFSConfs)){
-			$return_permission = "true";
-		} else {
-			$sql = "SELECT wfs.wfs_id, mb_user.mb_user_email as email FROM wfs, mb_user where wfs.wfs_owner=mb_user.mb_user_id "."and wfs.wfs_id=$1";
-			$v = array($wfs_id);
-			$t = array('i');
-			$res = db_prep_query($sql, $v, $t);
-			// get email
-			$mail = "";
-			while($row = db_fetch_array($res)){
-				$mail = $row['email'];
-				$return_permission = $mail; 
-			}
-		}
-		return $return_permission;
-	}
-
-	private function getPermissionValueForLayer($layerId,$wmsId){
-		//TODO: Set Email of owner into view for ressource - so it don't have to be searched?
-		$return_permission="";
-		#$admin = new administration();
-		#$permission = $admin->getLayerPermission($wms_id, $layer_name, $this->userId);
-		#echo "<br>wms_id: ".$wms_id."<br>";
-		#echo "<br>layer_name: ".$layer_name."<br>";
-		#echo "<br>user_id: ".$this->userId."<br>";
-		#echo "<br>Permission: ".$permission."<br>";
-               # var_dump($this->accessableLayers);
-		if (in_array($layerId, $this->accessableLayers)){
-			$return_permission = "true";
-			return $return_permission;
-		} else {
-			$sql = "SELECT mb_user.mb_user_email as email FROM wms, mb_user WHERE wms.wms_owner=mb_user.mb_user_id";
-			$sql .= " AND wms.wms_id=$1";
-			$v = array($wmsId);
-			$t = array('i');
-			$res = db_prep_query($sql, $v, $t);
-			// get email
-			$mail="";
-			while($row = db_fetch_array($res)){
-				$mail = $row['email'];
-				$return_permission = $mail; 
-			}
-		return $return_permission;
-		}
-	}	
-
-	
-
-	private function generateSearchStringArray() {
-		//'wfs test array' -> ('wfs' 'test' 'array')
-		$asstr = array();
-		if ($this->searchText != "false"){
-			$asstr = split(",",$this->searchText);
-			//delete left and right whitespaces
-			for ($i=0; $i<count($asstr);$i++) {
-				$asstr[$i]=ltrim($asstr[$i]);
-				$asstr[$i]=rtrim($asstr[$i]);
-			}	
-		}
-		return $asstr;
-	}			
-		
-	//out of php doc - test if it is faster than normal array_search	
-	private function fast_in_array($elem, $array) {
-   		$top = sizeof($array) -1;
-   		$bot = 0;
-		while($top >= $bot) {
-			$p = floor(($top + $bot) / 2);
-			if ($array[$p] < $elem) $bot = $p + 1;
-			elseif ($array[$p] > $elem) $top = $p - 1;
-			else return TRUE;
-		}
-    	return FALSE;
-	}
-	/*
-	* filtering an array
-	*/
-	private function filter_by_value ($array, $index, $value){
-        	if(is_array($array) && count($array)>0) {
-            		foreach(array_keys($array) as $key){
-                		$temp[$key] = $array[$key][$index];
-                		if ($temp[$key] == $value){
-                    			$newarray[$key] = $array[$key];
-                		}
-           		}
-          	}
-      	return $newarray;
-    	} 
-
-	//function to get the parent of the given layer by crawling the layertree upwards
-	private function getLayerParent ($layerArray, $index){
-		//only layers of one service should be in $layerArray
-		#$parentExists = false;
-		#var_dump($layerArray);
-		$layerIDKey = $layerArray['layer_id'][$index];	
-		#echo ("layerIDKey= ".$layerIDKey."<br>");
-		$layerParentPos = $layerArray['layer_parent'][$index];//get first parent object position
-		#echo ("layerParentPos= ".$layerParentPos."<br>");
-		#echo("<br>number of sublayers ".count(flipDiagonally($layerArray))."<br>");
-		#echo("<br>size of layerArray['layer_pos']: ".count($layerArray['layer_pos'])."<br>");
-		#var_dump($layerArray['layer_pos']);
-		#echo "<br>flipped layerArray: <br> ";
-		#var_dump(flipDiagonally($layerArray));
-		#echo "<br>";		
-
-		if ($layerParentPos == '') {
-			//root layer directly found
-			return $index;
-		}
-		#echo ("layerParentPos= ".$layerParentPos."<br>");
-		//Initialize index of layer parent - first it references the layer itself
-		$layerParentIndex = $index;
-		//loop to search higher parent objects - maybe this can be faster if the loop is not used over all sublayer elements! Do a while loop instead!
-		$highestParentLayerNotFound = true;
-		while ($highestParentLayerNotFound) {
-			#echo("<br>i= ".$i."<br>");
-			#echo("<br>layerParentPosNew= ".$layerParentPos."<br>");
-			$layerParentIndexNew = array_search((string)$layerParentPos, $layerArray['layer_pos']);
-			#echo("<br>layerParentIndexNew= ".$layerParentIndexNew."<br>");
-			if ($layerParentIndexNew != false) {
-				//some parent has been found
-				$layerParentIndex = $layerParentIndexNew;
-				$layerParentPos = $layerArray['layer_parent'][$layerParentIndex];
-				if ($layerParentPos == '') {
-					$highestParentLayerNotFound = false;
-					return $layerParentIndex; //a real root layer was found!
-				}
-				
-				#$layerParentIndex = array_search($layerParentPos, $layerArray['layer_pos']);
-			} else {
-				$highestParentLayerNotFound = false; //no higher layer could be found
-				return $layerParentIndex;
-			}
-		}
-		return $layerParentIndex;  
-    	} 
-
-
-	//function to write the child elements to the resulting wms object -> object is given by reference
-	private function writeWMSChilds($layerIdArray, $rootLayerPos, $subLayers, &$servObject) {
-		#echo "test";
-		#echo "<br>subLayers:<br>";
-		#var_dump($subLayers);
-		#echo "<br>";
-		$childLayers = $this->filter_by_value($subLayers, 'layer_parent', $rootLayerPos); //the root layer position in the sublayer array was located before. In this step, all layers will be pulled out of sublayer, where root layer position is parent object
-		#echo "<br<childLayers:<br>";
-		#var_dump($childLayers);
-		#echo "<br>";
-		#echo "test";
-		#print_r($childLayers);
-		#print_r($childLayers);
-		$countsublayer = 0;
-		//if child exists create a new layer array for these 
-		if (count($childLayers) != 0) {
-			$servObject->layer = array();
-		}
-		foreach ($childLayers as $child){	
-			#echo "<br>countsublayer: ".$countsublayer."<br>";
-			#echo "<br>Child id: ".$child['layer_id']."<br>";
-			#echo "<br>Child pos: ".$child['layer_pos']."<br>";
-			$servObject->layer[$countsublayer]->id = $child['layer_id'];
-			$servObject->layer[$countsublayer]->title = $child['layer_title'];
-			$servObject->layer[$countsublayer]->abstract = $child['layer_abstract'];
-			$servObject->layer[$countsublayer]->previewURL = "http://".$this->hostName."/mapbender/x_geoportal/mod_layerPreview.php?id=".$child['layer_id'];
-			$servObject->layer[$countsublayer]->mdLink = "http://".$this->hostName."/mapbender/x_geoportal/mod_showMetadata.php?resource=layer&id=".$child['layer_id'];
-			if ($child['layer_name'] == ''){
-				$servObject->layer[$countsublayer]->loadable = 0;
-			} else {
-				$servObject->layer[$countsublayer]->loadable = 1;
-			}
-			//give info for inspire categories - not relevant for other services or instances of mapbender TODO: comment it if the mapbender installation is not used to generate inspire output
-			if ($child['md_inspire_cats'] == ''){
-				$servObject->layer[$countsublayer]->inspire = 0;
-			}
-			else {
-				$servObject->layer[$countsublayer]->inspire = 1;
-			}
-			//get info about queryable or not
-			if ($child['layer_queryable'] == 1){
-				$servObject->layer[$countsublayer]->queryable = 1;
-			}
-			else {
-				$servObject->layer[$countsublayer]->queryable = 0;
-			}
-				
-			$servObject->layer[$countsublayer]->loadCount = $child['load_count'];
-			$servObject->layer[$countsublayer]->bbox = $child['bbox'];
-			$servObject->layer[$countsublayer]->permission = $this->getPermissionValueForLayer($child['layer_id'],$child['wms_id']); //TODO: make this much faster!!!! - is done by collecting all accessable resources once. Maybe this has to be adopted if the count of the resources become higher
-			//call this function itself - search sublayers in the layer object.
-			$layerIdArray = $this->writeWMSChilds($layerIdArray, $child['layer_pos'], $subLayers, $servObject->layer[$countsublayer]);//TODO create a timeout condition !
-			array_push($layerIdArray, $child['layer_id']); //child have been identified and recursively written 
-			#var_dump($layerIdArray);#
-			#echo "<br>";
-			$countsublayer ++;
-		}
-		return $layerIdArray;
-	}
-
-
-
-	
-	private function hasConstraints($type,$id) {
-		if ($type == "wms") {
-			$sql = "SELECT wms.accessconstraints, wms.fees, wms.wms_network_access , wms.wms_pricevolume, wms.wms_proxylog, termsofuse.name,";
-			$sql .= " termsofuse.termsofuse_id, termsofuse.symbollink, termsofuse.description,termsofuse.descriptionlink from wms LEFT OUTER JOIN";
-			$sql .= "  wms_termsofuse ON  (wms.wms_id = wms_termsofuse.fkey_wms_id) LEFT OUTER JOIN termsofuse ON";
-			$sql .= " (wms_termsofuse.fkey_termsofuse_id=termsofuse.termsofuse_id) where wms.wms_id = $1";
-}
-		if ($type == "wfs") {
-			$sql = "SELECT accessconstraints, fees, wfs_network_access , termsofuse.name,";
-			$sql .= " termsofuse.termsofuse_id ,termsofuse.symbollink, termsofuse.description,termsofuse.descriptionlink from wfs LEFT OUTER JOIN";
-			$sql .= "  wfs_termsofuse ON  (wfs.wfs_id = wfs_termsofuse.fkey_wfs_id) LEFT OUTER JOIN termsofuse ON";
-			$sql .= " (wfs_termsofuse.fkey_termsofuse_id=termsofuse.termsofuse_id) where wfs.wfs_id = $1";	
-}
-		$v = array();
-		$t = array();
-
-
-		array_push($t, "i");
-		array_push($v, $id);
-
-		$res = db_prep_query($sql,$v,$t);
-
-		$row = db_fetch_array($res);
-
-
-
-		if ((isset($row[$type.'_proxylog']) & $row[$type.'_proxylog'] != 0) or strtoupper($row['accessconstraints']) != "NONE" or strtoupper($row['fees']) != "NONE" or isset($row['termsofuse_id']) ) {
-		//service has some constraints defined!
-		//give symbol and true
-		//termsofuse symbol or exclamation mark
-			if (isset($row['termsofuse_id']) & $row['symbollink'] != "") {
- 				$symbolLink = $row['symbollink'];
-			} else {
-				$symbolLink = "http://".$this->hostName."/portal/fileadmin/design/icn_warn.png";
-			}
-			$hasConstraints = true;
-			#$disclaimerLink = $_SERVER['HTTP_HOST']."/mapbender/php/mod_getServiceDisclaimer.php?type=".$type."&id=".$id;
-			#$symbolMouseOver = "Nutzungsbedingungen"; //TODO internationalize it
-
-		} else {
-		//give symbol and false
-		//green symbol
-			$symbolLink = "http://".$this->hostName."/portal/fileadmin/design/icn_ok.png";
-       			#$disclaimerLink = "";
-			$hasConstraints = false;
-			#$symbolMouseOver = "Frei zugänglich"; //TODO internationalize it
-		}
-
-		//generate json output:
-		#$json = new Mapbender_JSON;
-		#$returnJSON = new stdClass;
-		#$returnJSON->serviceConstraints = (object) array(
-				#'hasConstraints' => $hasConstraints,
-				#'disclaimerLink' => $disclaimerLink, 
-				#'symbolLink' => $symbolLink,
-				#'symbolMouseOver' => $symbolMouseOver
-		#	);
-		#$returnJSON = $json->encode($returnJSON);
-		#echo $returnJSON;
-		return array($hasConstraints, $symbolLink);
-	}
-	//function to delete one of the comma separated values from one get request
-	//
-	//
-	//
-	//
-	private function delFromQuery($paramName,$queryString,$string,$queryArray,$queryList) {
-		//check if if count searchArray = 1
-		if (count($queryArray) == 1){
-			//remove request parameter from url by regexpr or replace
-			$str2search = $paramName."=".$queryList;
-			$str2exchange = "";
-			$queryStringNew = str_replace($str2search, $str2exchange, $queryString);
-			$queryStringNew = str_replace("&&", "&", $queryStringNew);
-		} else {
-		//there are more than one filter - reduce the filter  
-			$objectList = "";
-			for($i=0; $i < count($queryArray); $i++){
-				if ($queryArray[$i] != $string){
-					$objectList .= $queryArray[$i].",";		
-				} 
-			}
-			//remove last comma
-			$objectList = rtrim($objectList, ",");
-			$str2search = $paramName."=".$queryList;
-			$str2exchange = $paramName."=".$objectList;
-			$queryStringNew = str_replace($str2search, $str2exchange, $queryString);
-		}
-	return $queryStringNew;
-	}
-	
-
-	
-	private function getValueForParam($paramName,$queryString) {
-		#another approach:
-		parse_str($queryString, $allQueries);
-		if (isset($allQueries[$paramName]) & $allQueries[$paramName] != '') {
-			return $allQueries[$paramName];
-		} else {
-			return false;
-		}
-
-
-#		old version
-
-/*		#TODO: check if last and first ampersand was set before
-		$queryString = "&".$queryString."&";
-		#$pattern = '/\b'.$paramName.'=([a-z0-9-]+)\&?/';
-		$pattern = '/\b&'.$paramName.'\=[^&]+&?/';
-		#$pattern = '/^&'.$paramName.'=[a-zA-ZöäüÖÄÜß,]*&$/';
-		$e = new mb_exception("class_metadata_new.php: look for pattern: ".$pattern."  in ".$queryString);
- 		if (!preg_match($pattern, $queryString, $matches)){
-			
-			return false;
-		} else {
-			//some param found
-			//delete $paramName= and the last ampersand!
-			if (count($matches) == 1) {
-				$requestString = $matches[0];
-				$requestString = ltrim($requestString,"&".$paramName."=");
-				$requestString = rtrim($requestString,'&');
-
-				return $requestString;
-			} else {
-				$e = new mb_exception("class_metadata_new.php: There are parameter ambiguities!");
-				#echo "Parameter Ambiguities found!";
-				die();
-			}
-		}*/
-	}	
-
-	private function addToQuery($paramName,$queryString,$string,$queryList) {
-		//test if string was part of query before, if so, don't extent the query
-		//TODO: the strings come from json and so they are urlencoded! maybe we have to decode them to find the commata
-		$queryListComma = urldecode($queryList);
-		$queryListC = ",".$queryListComma.",";
-		$pattern = ','.$string.',';	
- 		if (!preg_match($pattern, $queryListC)){
-			//append the new element
-			$queryListNew = $queryListC.$string;
-			//echo "query string new: ".$queryListNew."<br>";
-			//delete the commatas
-			$queryListNew = ltrim($queryListNew,',');
-			//generate the new query string
-			$queryStringNew = str_replace($paramName.'='.$queryList,$paramName.'='.$queryListNew,$queryString);
-			//echo "query string new: ".$queryListNew."<br>";
-			//dump old and new querystring for debugging
-			//$this->logit("class_metadata_new: queryString_old:".$queryString);
-			//$this->logit("class_metadata_new: queryString_new:".$queryStringNew);
-			return $queryStringNew;
-		} else {
-			//$this->logit("class_metadata_new: queryString unchanged:".$queryString);
-			//return the old one!
-			return $queryString;
-		}
-	}
-	//for debugging purposes
-	private function logit($text){
-	 	if($h = fopen("/tmp/class_metadata_new.log","a")){
-					$content = $text .chr(13).chr(10);
-					if(!fwrite($h,$content)){
-						#exit;
-					}
-					fclose($h);
-				}
-	 	
-	 }
-
-
-
-
-	private function delTotalFromQuery($paramName,$queryString) {
-		$queryString = "&".$queryString;
-		#echo "<br>queryString: ".$queryString."<br>";
-		$queryStringNew = preg_replace('/\b'.$paramName.'\=[^&]+&?/',"",$queryString);
-		$queryStringNew = ltrim($queryStringNew,'&');
-		$queryStringNew = rtrim($queryStringNew,'&');
-		return $queryStringNew;
-	}	
-		
-}
-?>

Copied: branches/mapbender/http/classes/class_metadata_new.php (from rev 6926, trunk/mapbender/http/classes/class_metadata_new.php)
===================================================================
--- branches/mapbender/http/classes/class_metadata_new.php	                        (rev 0)
+++ branches/mapbender/http/classes/class_metadata_new.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -0,0 +1,1743 @@
+<?php
+#Script to call this class: http://www.geoportal.rlp.de/mapbender/php/mod_callMetadata.php
+#Class for getting results out of the mapbender service registry 
+#Resulttypes: WMS, WMS-Layer, (WFS), WFS-Featurtyps, WFS-Conf, WMC, GeoRSS-Feeds, ...
+#Possible filters: registrating organizations, time, bbox (fully inside, intersects, fully outside), ISO Topic Categories, INSPIRE themes, INSPIRE: keywords, classification of data/service ... - maybe relevant for the german broker not for one instance, quality and actuality (maybe spatial and temporal), bbox, deegree of conformity with ir, access and use constraints, responsible parties - maybe one is enough? We must have a look at the INSPIRE Metadata IR
+#Metadata we need to fullfil the demands of INSPIRE:
+#1. INSPIRE conformity classification for WMS/WFS/WCS
+#2. Temporal Extents at WMS/WMS-Layer/WFS/WFS-Featuretype levels - for datasets if demanded - til now there is no demand defined in the guidance-paper for metadata ir
+#3. Classified access and use contraints - which classes? - Check IR Data Sharing and IR Metadata
+#4. 
+#Every ressource which should be send to INSPIRE can be filtered - but is not neccessary for a standardized approach
+#Another problem is the ranking of the different ressources. The ranking should be homogeneus. 
+#Till now we rank the using of WMS Layers when Caps are requested and when s.o. load one layer into the geoportal.
+#The same things have to be done for the wfs-conf, wmc and georssfeeds
+#The searching for metadata should be parallel done. We need different classes for doing the search. They should be requested by one central class (class_metadata.php).
+#Classes for filtering after the results have been send to the portal:
+#1. ISO Topic Categories
+#2. INSPIRE Themes
+#3. Access and use classification
+#4. departments which provides the ressources - we need the new concept for the administration of this departments - store the addresses in the group table and give the relation - originating group in table mb_user_mb_group 
+#Cause we have a authorization layer, we need the id of the requesting user which is defined in the session. If no session is set, it should be the anonymous user of the portal.
+#We need a parameter for internationalization - it should be send with the search request! Some of the Classes can be provided with different languages.
+#WMC and GeoRSS-Feeds have no or a to complex authorization info - maybe we need to test if wmc consists of info which is fully or only partually available to the anonymous user. 
+
+require_once(dirname(__FILE__)."/../../core/globalSettings.php");
+require_once(dirname(__FILE__)."/class_administration.php");
+require_once(dirname(__FILE__)."/class_mb_exception.php");
+require_once(dirname(__FILE__)."/class_json.php");
+
+//definition for the things which are common to all kind of metadata ressources
+
+class searchMetadata {
+	var $userId;
+	var $searchId;
+	var $searchText;
+	var $registratingDepartments;
+	var $isoCategories;
+	var $inspireThemes;
+	var $customCategories;
+	var $timeBegin;
+	var $timeEnd;
+	var $regTimeBegin;
+	var $regTimeEnd;
+	var $maxResults;
+	var $searchBbox;
+	var $searchTypeBbox;
+	var $accessRestrictions;
+	var $languageCode;
+	var $searchStartTime;
+	var $searchView;
+	var $searchURL;
+	var $searchEPSG;
+	var $searchResources;
+	var $searchPages;
+	var $outputFormat;
+	var $resultTarget;
+	var $tempFolder;
+	var $orderBy;
+	var $hostName;
+
+	function __construct($userId, $searchId, $searchText, $registratingDepartments, $isoCategories, $inspireThemes, $timeBegin, $timeEnd, $regTimeBegin, $regTimeEnd, $maxResults, $searchBbox, $searchTypeBbox, $accessRestrictions, $languageCode, $searchEPSG, $searchResources, $searchPages, $outputFormat, $resultTarget, $searchURL, $customCategories, $hostName, $orderBy){
+		$this->userId = (integer)$userId;
+		$this->searchId = $searchId;
+		$this->searchText = $searchText;
+		$this->registratingDepartments = $registratingDepartments; //array with ids of the registrating groups in the mb database
+		$this->registratingDepartmentsArray = explode(",",$this->registratingDepartments);
+		$this->isoCategories = $isoCategories;
+		$this->inspireThemes = $inspireThemes;
+		$this->customCategories = $customCategories;
+		$this->timeBegin = $timeBegin;
+		$this->timeEnd = $timeEnd;
+		$this->regTimeBegin = $regTimeBegin;
+		$this->regTimeEnd = $regTimeEnd;
+		$this->maxResults = (integer)$maxResults;
+		$this->searchBbox = $searchBbox;
+		$this->searchTypeBbox = $searchTypeBbox;
+		$this->accessRestrictions = $accessRestrictions;
+		$this->languageCode = $languageCode;
+		$this->searchEPSG = $searchEPSG;
+		$this->searchResources = $searchResources;
+		$this->searchPages = $searchPages;
+		$this->outputFormat = $outputFormat;
+		$this->resultTarget = $resultTarget;
+		$this->searchURL = $searchURL;
+		$this->hostName = $hostName;
+		$this->orderBy = $orderBy;
+		//definitions for tags
+		$this->maxObjects = 15;
+		$this->maxFontSize = 30;
+		$this->maxWeight = 0;
+		$this->scale = 'linear';
+
+
+
+
+
+		$this->tempFolder = TMPDIR; //TODO define another path - maybe the one which is given in mapbender.conf
+		if ($this->outputFormat == 'json'){
+			$this->json = new Mapbender_JSON;
+		}
+		$this->accessableLayers = NULL;
+		//set a time to find time consumers
+		$this->searchStartTime = $this->microtime_float();
+		//Defining of the different database categories		
+		$this->resourceClassifications = array();
+		$this->resourceClassifications[0]['title'] = "ISO 19115"; //TODO: define the translations somewhere? - This is done in call_metadata.php before. Maybe we can get them from there? - It will be shown in the rightside categories table
+		$this->resourceClassifications[0]['tablename'] = 'md_topic_category';
+		$this->resourceClassifications[0]['requestName'] = 'isoCategories';
+		$this->resourceClassifications[0]['id_wms'] = 'layer_id';
+		$this->resourceClassifications[0]['id_wfs'] = 'featuretype_id';
+		$this->resourceClassifications[0]['relation_wms'] = 'layer_md_topic_category';
+		$this->resourceClassifications[0]['relation_wfs'] = 'featuretype_md_topic_category';//TODO: define this in mapbender
+
+		$this->resourceClassifications[1]['title'] = "INSPIRE"; //TODO: define the translations somewhere? - This is done in call_metadata.php before. Maybe we can get them from there? - It will be shown in the rightside categories table
+		$this->resourceClassifications[1]['tablename'] = 'inspire_category';
+		$this->resourceClassifications[1]['requestName'] = 'inspireThemes';
+		$this->resourceClassifications[1]['id_wms'] = 'layer_id';
+		$this->resourceClassifications[1]['id_wfs'] = 'featuretype_id';
+		$this->resourceClassifications[1]['relation_wms'] = 'layer_inspire_category';
+		$this->resourceClassifications[1]['relation_wfs'] = 'featuretype_inspire_category';//TODO: define this in mapbender
+
+		$this->resourceClassifications[2]['title'] = "Custom"; //TODO: define the translations somewhere? - This is done in call_metadata.php before. Maybe we can get them from there? - It will be shown in the rightside categories table
+		$this->resourceClassifications[2]['tablename'] = 'custom_category';
+		$this->resourceClassifications[2]['requestName'] = 'customCategories';
+		$this->resourceClassifications[2]['id_wms'] = 'layer_id';
+		$this->resourceClassifications[2]['id_wfs'] = 'featuretype_id';
+		$this->resourceClassifications[2]['relation_wms'] = 'layer_custom_category';
+		$this->resourceClassifications[2]['relation_wfs'] = 'featuretype_custom_category';//TODO: define this in mapbender
+
+
+
+
+
+
+
+		//Defining of the different result categories		
+		$this->resourceCategories = array();
+		$this->resourceCategories[0]['name'] = 'WMS';
+		$this->resourceCategories[1]['name'] = 'WFS';
+		$this->resourceCategories[2]['name'] = 'WMC';
+		$this->resourceCategories[3]['name'] = 'DAD';
+		switch($this->languageCode){
+        		case 'de':
+                	$this->resourceCategories[0]['name2show'] = 'Darstellungsdienste';
+			$this->resourceCategories[1]['name2show'] = 'Such- und Download- und Erfassungsmodule';
+			$this->resourceCategories[2]['name2show'] = 'Kartenzusammenstellungen';
+			$this->resourceCategories[3]['name2show'] = 'KML/Newsfeeds';
+			$this->keywordTitle = 'Schlagwortliste';
+       			break;
+        		case 'en':
+               		$this->resourceCategories[0]['name2show'] = 'Viewingservices';
+			$this->resourceCategories[1]['name2show'] = 'Search- and Downloadservices';
+			$this->resourceCategories[2]['name2show'] = 'Combined Maps';
+			$this->resourceCategories[3]['name2show'] = 'KML/Newsfeeds';
+			$this->keywordTitle = 'Keywordlist';
+        		break;
+        		case 'fr':
+          	     	$this->resourceCategories[0]['name2show'] = 'Viewingservices';
+			$this->resourceCategories[1]['name2show'] = 'Search- and Downloadservices';
+			$this->resourceCategories[2]['name2show'] = 'Combined Maps';
+			$this->resourceCategories[3]['name2show'] = 'KML/Newsfeeds';
+			$this->keywordTitle = 'Keywordlist';
+       			break;
+     			default:
+                	$this->resourceCategories[0]['name2show'] = 'Darstellungsdienste';
+			$this->resourceCategories[1]['name2show'] = 'Such- und Download- und Erfassungsmodule';
+			$this->resourceCategories[2]['name2show'] = 'Kartenzusammenstellungen';
+			$this->resourceCategories[3]['name2show'] = 'KML/Newsfeeds';
+			$this->keywordTitle = 'Schlagwortliste';
+		}	
+		//not needed til now - maybe usefull for georss output
+		if ($this->outputFormat == "xml") {
+			//Initialize XML documents
+			if (isset($this->searchResources) & strtolower($this->searchResources) === "wms") {
+				$this->wmsDoc = new DOMDocument('1.0');
+			}
+			if (isset($this->searchResources) & strtolower($this->searchResources) === "wfs") {
+				$this->wfsDoc = new DOMDocument('1.0');
+				$this->generateWFSMetadata($this->wfsDoc);
+			}
+			if (isset($this->searchResources) & strtolower($this->searchResources) === "wmc") {
+				$this->wmcDoc = new DOMDocument('1.0');
+				$this->generateWMCMetadata($this->wmcDoc);
+			}
+			if (isset($this->searchResources) & strtolower($this->searchResources) === "georss") {
+				$this->georssDoc = new DOMDocument('1.0');
+			}
+		}
+		
+		if ($this->outputFormat === "json") {
+			$this->e = new mb_exception("orderBy old: ".$this->orderBy);
+			if (isset($this->searchResources) & strtolower($this->searchResources) === "wfs") {
+				$this->databaseIdColumnName = 'featuretype_id';
+				$this->databaseTableName = 'wfs_featuretype';
+				//$this->keywordRelation = 'wfs_featuretype_keyword';
+				$this->searchView = 'search_wfs_view';
+				switch ($this->orderBy) {
+					case "rank":
+						$this->orderBy = " ORDER BY wfs_id,featuretype_id,wfs_conf_id ";
+						break;
+					case "id":
+						$this->orderBy = " ORDER BY wfs_id,featuretype_id,wfs_conf_id ";
+						break;
+					case "title":
+						$this->orderBy = " ORDER BY featuretype_title ";
+						break;
+					case "date":
+						$this->orderBy = " ORDER BY wfs_timestamp DESC ";
+						break;
+					default:
+						$this->orderBy = " ORDER BY wfs_id,featuretype_id,wfs_conf_id ";
+				}
+				
+				$this->resourceClasses = NULL;
+				$this->generateWFSMetadata($this->wfsDoc);
+			}
+			if (isset($this->searchResources) & strtolower($this->searchResources) === "wms") {
+				$this->databaseIdColumnName = 'layer_id';
+				$this->databaseTableName = 'layer';
+				//$this->keywordRelation = 'layer_keyword';
+				$this->searchView = 'wms_search_table';
+				switch ($this->orderBy) {
+					case "rank":
+						$this->orderBy = " ORDER BY load_count DESC";
+						break;
+					case "id":
+						$this->orderBy = " ORDER BY wms_id,layer_pos DESC";
+						break;
+					case "title":
+						$this->orderBy = " ORDER BY layer_title ";
+						break;
+					case "date":
+						$this->orderBy = " ORDER BY wms_timestamp DESC ";
+						break;
+					default:
+						$this->orderBy = " ORDER BY load_count DESC";
+				}
+				
+				$this->resourceClasses = array(0,1,2);
+				$this->generateWMSMetadata($this->wmsDoc);
+			}
+			if (isset($this->searchResources) & strtolower($this->searchResources) === "wmc") {
+				$this->searchView = 'search_wmc_view';
+				$this->databaseIdColumnName = 'wmc_id';
+				$this->databaseTableName = 'wmc';
+
+				switch ($this->orderBy) {
+					case "rank":
+						$this->orderBy = " ORDER BY wmc_id ";
+						break;
+					case "id":
+						$this->orderBy = " ORDER BY wmc_id ";
+						break;
+					case "title":
+						$this->orderBy = " ORDER BY wmc_title ";
+						break;
+					case "date":
+						$this->orderBy = " ORDER BY wmc_timestamp DESC ";
+						break;
+					default:
+						$this->orderBy = " ORDER BY wmc_title ";
+				}
+				
+				$this->resourceClasses = NULL; #TODO adopt to count classifications
+				$this->generateWMCMetadata($this->wmcDoc);
+			}
+		}
+	$this->e = new mb_exception("orderBy new: ".$this->orderBy);
+	}
+
+	private function microtime_float() {
+    		list($usec, $sec) = explode(" ", microtime());
+    		return ((float)$usec + (float)$sec);
+	}
+	private function generateXMLHead($xmlDoc) {
+		$xmlDoc->encoding = CHARSET;
+		$result = $xmlDoc->createElement("result");
+		$xmlDoc->appendChild($result);
+		//Result Count
+		$overLimit = $xmlDoc->createElement("overLimit");
+		$result->appendChild($overLimit);
+		//$tr_text = $xmlDoc->createTextNode($this->isOverLimit);
+		$tr_text = $xmlDoc->createTextNode("really?");
+		$overLimit->appendChild($tr_text);
+		$rd = $xmlDoc->createElement("redirect");
+		$result->appendChild($rd);
+		$trd = $xmlDoc->createTextNode("not yet ready...");
+		$rd->appendChild($trd);
+	}
+	private function generateXMLFoot($xmlDoc){
+		$results = $xmlDoc->getElementsByTagName("result");			
+		foreach ($results as $result) {
+			$result->appendChild($ready);
+		}
+	}
+	private function flipDiagonally($arr) {
+    		$out = array();
+    		foreach ($arr as $key => $subarr) {
+      			foreach ($subarr as $subkey => $subvalue) {
+        			$out[$subkey][$key] = $subvalue;
+       			 }
+    		}
+   		return $out;
+	}
+
+	private function generateWFSMetadataJSON($res, $n) {
+		//initialize object
+		$this->wfsJSON = new stdClass;
+		$this->wfsJSON->wfs = (object) array(
+				'md' => (object) array(
+					'nresults' => $n, 
+					'p' => $this->searchPages,
+					'rpp' => $this->maxResults
+					),
+				'srv' => array()
+				);
+			
+		//read out records
+		$serverCount = 0;
+		$wfsMatrix = db_fetch_all($res);
+		//sort result for accessing the right services
+		$wfsMatrix = $this->flipDiagonally($wfsMatrix);
+		//TODO check if order by db or order by php is faster! 
+		#array_multisort($wfsMatrix['wfs_id'], SORT_ASC,$wfsMatrix['featuretype_id'], SORT_ASC,$wfsMatrix['wfs_conf_id'], SORT_ASC); //have some problems - the database version is more stable
+		#print_r($wfsMatrix);
+		$wfsMatrix = $this->flipDiagonally($wfsMatrix);
+		//read out first server entry - maybe this a little bit timeconsuming TODO
+		$j = 0; //count identical wfs_id => double featuretype
+		$l = 0; //index featuretype and or modul per wfs
+		$m = 0; //index modul per featuretype
+		for($i=0; $i<count($wfsMatrix);$i++){
+				$this->wfsJSON->wfs->srv[$i-$j]->id = $wfsMatrix[$i]['wfs_id'];
+				$this->wfsJSON->wfs->srv[$i-$j]->title = $wfsMatrix[$i]['wfs_title'];
+				$this->wfsJSON->wfs->srv[$i-$j]->abstract = $wfsMatrix[$i]['wfs_abstract'];
+				$this->wfsJSON->wfs->srv[$i-$j]->date = date("d.m.Y",$wfsMatrix[$i]['wfs_timestamp']);
+				$this->wfsJSON->wfs->srv[$i-$j]->respOrg = $wfsMatrix[$i]['mb_group_name'];
+				$this->wfsJSON->wfs->srv[$i-$j]->logoUrl = $wfsMatrix[$i]['mb_group_logo_path'];
+				$this->wfsJSON->wfs->srv[$i-$j]->mdLink = "http://".$this->hostName."/mapbender/x_geoportal/showWFSMetadata.php?id=".$wfsMatrix[$i]['wfs_id'];
+				$spatialSource = "";
+				$stateOrProvince = $wfsMatrix[$i]['administrativearea']; 
+				if ($stateOrProvince == "NULL" || $stateOrProvince == "") {
+					$spatialSource = $wfsMatrix[$i]['country'];
+				} else {
+					$spatialSource = $wfsMatrix[$i]['administrativearea'];
+				}
+				$this->wfsJSON->wfs->srv[$i-$j]->iso3166 = $spatialSource;
+				//check if a disclaimer has to be shown and give the relevant symbol
+				//$this->wfsJSON->wfs->srv[$i-$j]->tou = $wfsMatrix[$i]['termsofuse'];
+				list($hasConstraints, $symbolLink) = $this->hasConstraints("wfs", $wfsMatrix[$i]['wfs_id']);
+				$this->wfsJSON->wfs->srv[$i-$j]->hasConstraints = $hasConstraints;
+				$this->wfsJSON->wfs->srv[$i-$j]->symbolLink = $symbolLink;
+				//TODO check the field accessconstraints - which should be presented?
+				$this->wfsJSON->wfs->srv[$i-$j]->status = NULL; //$wfsMatrix[$i][''];
+				$this->wfsJSON->wfs->srv[$i-$j]->avail = NULL; //$wfsMatrix[$i][''];
+				$this->wfsJSON->wfs->srv[$i-$j]->logged = NULL; //$wfsMatrix[$i][''];
+				$this->wfsJSON->wfs->srv[$i-$j]->price = NULL; //$wfsMatrix[$i][''];
+				$this->wfsJSON->wfs->srv[$i-$j]->nwaccess = NULL; //$wfsMatrix[$i][''];
+				$this->wfsJSON->wfs->srv[$i-$j]->bbox = array(-180.0,-90.0,180.0,90.0); //$wfsMatrix[$i][''];
+				//if featuretype hasn't been created - do it
+				if (!isset($this->wfsJSON->wfs->srv[$i-$j]->ftype)) {
+					$this->wfsJSON->wfs->srv[$i-$j]->ftype = array();
+				}
+				//fill in featuretype infos
+				$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->id = (integer)$wfsMatrix[$i]['featuretype_id'];
+				$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->title = $wfsMatrix[$i]['featuretype_title'];
+				$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->abstract = $wfsMatrix[$i]['featuretype_abstract'];
+				$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->mdLink = "http://".$this->hostName."/mapbender/x_geoportal/showWFeatureTypeMetadata.php?id=".$wfsMatrix[$i]['featuretype_id'];
+				$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->geomtype = $wfsMatrix[$i]['element_type'];
+				$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->bbox = array(-180.0,-90.0,180.0,90.0);//TODO: $wfsMatrix[$i]['bbox'];
+
+
+				//give info for inspire categories - not relevant for other services or instances of mapbender TODO: comment it if the mapbender installation is not used to generate inspire output
+				if (isset($wfsMatrix[$i]['md_inspire_cats']) & ($wfsMatrix[$i]['md_inspire_cats'] != '')){
+					$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->inspire = 1;
+				}
+				else {
+					$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->inspire = 0;
+				}
+				//fill in categories
+				#if (!isset($this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->cat)) {
+				#	$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->cat = array();
+				#}
+				#if (isset($wfsMatrix[$i]['iso_categories'])) {
+				#}
+				//if (isset($wfsMatrix[$i]['inspire_category'])) {
+					//TODO write the categories as JSON into Database!
+					#$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->cat[0]->type = 'INSPIRE Kategorie';
+ 					#$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->cat[0]->value = 'Umwelt';
+					#$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->cat[0]->symbol = 'umwelt.png';
+				//}
+				#if (isset($wfsMatrix[$i]['custom_categories'])) {
+				#}
+				//if modul hasn't been created - do it
+				if (!isset($this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->modul)) {	
+					$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->modul = array();
+				}
+				//fill in modul infos
+				$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->modul[$m]->id = $wfsMatrix[$i]['wfs_conf_id'];	
+				$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->modul[$m]->title = $wfsMatrix[$i]['wfs_conf_description'];	
+				$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->modul[$m]->abstract = $wfsMatrix[$i]['wfs_conf_abstract'];
+				$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->modul[$m]->type = $wfsMatrix[$i]['modultype'];
+				$equalEPSG = $wfsMatrix[$i]['featuretype_srs'];
+                       		$isEqual = true;
+				//control if EPSG is supported by Client
+		        	if ($equalEPSG == $this->searchEPSG){
+					$isEqual = false;		
+		        	}	
+				$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->modul[$m]->srsProblem = $isEqual;
+				//generate Link to show metadata
+				$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->modul[$m]->mdLink = "http://".$this->hostName."/mapbender/x_geoportal/showWFSConfMetadata.php?id=".$wfsMatrix[$i]['wfs_conf_id'];
+				$perText = $this->getPermissionValueForWFS($wfsMatrix[$i]['wfs_id'], $wfsMatrix[$i]['wfs_conf_id']);
+				$this->wfsJSON->wfs->srv[$i-$j]->ftype[$l-$m]->modul[$m]->permission = $perText;
+				if ($wfsMatrix[$i]['wfs_id'] == $wfsMatrix[$i+1]['wfs_id']){
+					$j++; //next record is the same service
+					$l++;	
+				}
+				else
+				{
+					$l = 0;
+				}
+
+				if ($wfsMatrix[$i]['featuretype_id'] == $wfsMatrix[$i+1]['featuretype_id']){
+					$m++;
+				}
+				else
+				{
+					$m = 0;
+				}		
+			}
+			
+	}
+	private function generateWMCMetadataJSON($res, $n) {
+		//initialize object
+		$this->wmcJSON = new stdClass;
+		$this->wmcJSON->wmc = (object) array(
+				'md' => (object) array(
+					'nresults' => $n, 
+					'p' => $this->searchPages,
+					'rpp' => $this->maxResults
+					),
+				'srv' => array()
+				);
+			
+		//read out records
+		$serverCount = 0;
+		$wmcMatrix = db_fetch_all($res);
+		//sort result for accessing the right services
+		$wmcMatrix = $this->flipDiagonally($wmcMatrix);
+		//TODO check if order by db or order by php is faster! 
+		#array_multisort($wfsMatrix['wfs_id'], SORT_ASC,$wfsMatrix['featuretype_id'], SORT_ASC,$wfsMatrix['wfs_conf_id'], SORT_ASC); //have some problems - the database version is more stable
+		#print_r($wfsMatrix);
+		$wmcMatrix = $this->flipDiagonally($wmcMatrix);
+		//read out first server entry - maybe this a little bit timeconsuming TODO
+		for($i=0; $i<count($wmcMatrix);$i++){
+			$this->wmcJSON->wmc->srv[$i]->id = $wmcMatrix[$i]['wmc_id'];
+			$this->wmcJSON->wmc->srv[$i]->title = $wmcMatrix[$i]['wmc_title'];
+			$this->wmcJSON->wmc->srv[$i]->abstract = $wmcMatrix[$i]['abstract'];
+			$this->wmcJSON->wmc->srv[$i]->date = date("d.m.Y",$wmcMatrix[$i]['wmc_timestamp']);
+			$this->wmcJSON->wmc->srv[$i]->respOrg = $wmcMatrix[$i]['mb_group_name'];
+			$this->wmcJSON->wmc->srv[$i]->mdLink = "http://".$this->hostName."/mapbender/x_geoportal/showWMCMetadata.php?id=".$wmcMatrix[$i]['wmc_id'];
+			$this->wmcJSON->wmc->srv[$i]->previewURL = "http://".$this->hostName."/mapbender/x_geoportal/mod_wmcPreview.php?id=".$wmcMatrix[$i]['wmc_id'];
+			$spatialSource = "";
+			$stateOrProvince = $wmcMatrix[$i]['mb_group_stateorprovince']; 
+			if ($stateOrProvince == "NULL" || $stateOrProvince == "") {
+				$spatialSource = $wmcMatrix[$i]['mb_group_country'];
+			} else {
+				$spatialSource = $wmcMatrix[$i]['mb_group_stateorprovince'];
+			}
+			$this->wmcJSON->wmc->srv[$i-$j]->iso3166 = $spatialSource;
+				
+			$this->wmcJSON->wmc->srv[$i-$j]->bbox = array($wmcMatrix[$i]['bbox']); //TODO: read out bbox from wmc $wmcMatrix[$i][''];
+
+			#$equalEPSG = $wmcMatrix[$i]['srs'];
+                       	#$isEqual = true;
+			//control if EPSG is supported by Client
+		        #if ($equalEPSG == $this->searchEPSG){
+			#	$isEqual = false;		
+		        #}	
+				
+		}
+			
+	}
+
+
+
+
+
+	private function generateWMSMetadataJSON($res, $n) {
+		//initialize object
+		$this->wmsJSON = new stdClass;
+		$this->wmsJSON->wms = (object) array(
+				'md' => (object) array(
+					'nresults' => $n, 
+					'p' => $this->searchPages,
+					'rpp' => $this->maxResults
+					),
+				'srv' => array()
+				);
+		//read out records
+		$serverCount = 0;
+		$wmsMatrix = db_fetch_all($res);
+		$layerIdArray = array();
+		//read out array with unique wms_ids in wmsMatrix
+		$wmsIdArray = array();
+		//initialize root layer id;
+		$rootLayerId = -1;
+		$j = 0;
+		//get array with all available layer_id for this user:
+ 		$admin = new administration();
+		$this->accessableLayers = $admin->getLayersByPermission($this->userId);
+		#echo "<br>user_id: ".$this->userId."<br><br>";
+		#var_dump($this->accessableLayers);
+		#echo "<br>";
+		#$countWmsMatrix = count($wmsMatrix);
+		#echo $countWmsMatrix;
+		if ($n != 0) {
+		for($i=0; $i<count($wmsMatrix);$i++){				
+			$layerID = $wmsMatrix[$i]['layer_id'];
+			#echo "<br>LayerID: ".$layerID."<br>";	
+			#$wmsID = $wmsMatrix[$i]['wms_id']; //get first wms id - in the next loop - dont get second, but some else!
+			if (!in_array($layerID, $layerIdArray) or !in_array($rootLayerId, $layerIdArray)) {
+				$wmsID = $wmsMatrix[$i]['wms_id']; //get first wms id - in the next loop - dont get second, but some else!
+				//Select all layers of with this wms_id into new array per WMS - the grouping should be done by wms!
+				$subLayers = $this->filter_by_value($wmsMatrix, 'wms_id', $wmsID);
+				#echo "<br>wms_id: ".$wmsID."<br>";
+				#echo "<br>Number of sublayers: <br>";
+				#print(count($subLayers));
+				//Sort array by load_count - problem: maybe there are some groups between where count is to low (they have no load count because you cannot load them by name)? - Therefor we need some ideas - or pull them out of the database and show them greyed out. Another way will be to define a new group (or wms with the same id) for those layers which are more than one integer away from their parents
+				$subLayersFlip = $this->flipDiagonally($subLayers);
+				#var_dump($subLayers['layer_pos']);
+				#$subLayers = $this->flipDiagonally($subLayers);
+				//go backwards through the layerTree to get the layer with the highest position without gaps in between
+				#var_dump($subLayers['layer_id']);
+				#echo "<br>";
+				$index = array_search($layerID, $subLayersFlip['layer_id']);
+				#echo "<br>found layer_id= ".$layerID." at index: ".$index." in sublayerstable layer_pos=".$subLayers[$index]['layer_pos']." <br>";
+				
+				#echo "<br>sublayers: ";
+				#var_dump($subLayersFlip);
+				#echo "<br>";
+				$rootIndex = $this->getLayerParent($subLayersFlip, $index);
+				$rootLayerPos = $subLayers[$rootIndex]['layer_pos'];
+				$rootLayerId = $subLayers[$rootIndex]['layer_id'];
+				#echo "<br>root layer for this layer: <br>";
+				#echo "<br>id= "..""
+				#echo "<br>";
+				#echo "<br>LayerId:<br>";
+				#echo "<br>".$layerID."<br>";
+				#echo "<br>rootLayerPos:<br>";
+				#echo "<br>".$rootLayerPos."<br>";
+				#echo "<br>rootLayerId:<br>";
+				#echo "<br>".$rootLayerId."<br>";
+				//push root layer id in array
+				array_push($layerIdArray, $rootLayerId);
+				#echo "<br>root Layer ID: ".$rootLayerId."<br>";
+				#array_multisort($subLayers['layer_pos'], SORT_ASC);
+				#print_r($subLayers);
+				#$subLayers = $this->flipDiagonally($subLayers);
+				#print_r("<br>rootIndex: ".$rootIndex."<br>");
+				//Create object for wms service level
+				$this->wmsJSON->wms->srv[$j]->id = (integer)$subLayers[$rootIndex]['wms_id'];
+				$this->wmsJSON->wms->srv[$j]->title = $subLayers[$rootIndex]['wms_title'];
+				$this->wmsJSON->wms->srv[$j]->abstract = $subLayers[$rootIndex]['wms_abstract'];
+				$this->wmsJSON->wms->srv[$j]->date = date("d.m.Y",$subLayers[$rootIndex]['wms_timestamp']);
+				#$this->wmsJSON->wms->srv[$j]->respOrg = "test";
+				$this->wmsJSON->wms->srv[$j]->loadCount = (integer)$subLayers[$rootIndex]['load_count'];
+				#$this->wmsJSON->wms->srv[$j]->mdLink = "http://".$_SERVER['HTTP_HOST']."/mapbender/x_geoportal/mod_layerMetadata.php?id=".(integer)$subLayers[$rootIndex]['layer_id'];
+				$spatialSource = "";
+				$stateOrProvince = $subLayers[$rootIndex]['stateorprovince']; 
+				#echo $stateOrProvince."<br>";
+				if ($stateOrProvince == "NULL" || $stateOrProvince == "") {
+					$spatialSource = $subLayers[$rootIndex]['country'];
+				} else {
+					$spatialSource = $subLayers[$rootIndex]['stateorprovince'];
+				}
+				$this->wmsJSON->wms->srv[$j]->iso3166 = $spatialSource;
+				$this->wmsJSON->wms->srv[$j]->respOrg = $subLayers[$rootIndex]['mb_group_name'];
+				$this->wmsJSON->wms->srv[$j]->logoUrl = $subLayers[$rootIndex]['mb_group_logo_path'];
+				#$this->wmsJSON->wms->srv[$j]->tou = $subLayers[$rootIndex]['termsofuse'];
+				//check if a disclaimer has to be shown and give the relevant symbol
+				list($hasConstraints, $symbolLink) = $this->hasConstraints("wms", $subLayers[$rootIndex]['wms_id']);
+				$this->wmsJSON->wms->srv[$j]->hasConstraints = $hasConstraints;
+				$this->wmsJSON->wms->srv[$j]->symbolLink = $symbolLink;
+				//TODO check the field accessconstraints - which should be presented?
+				$this->wmsJSON->wms->srv[$j]->status = $subLayers[$rootIndex]['status']; //$wmsMatrix[$i][''];
+				$this->wmsJSON->wms->srv[$j]->avail = $subLayers[$rootIndex]['availability']; //$wmsMatrix[$i][''];
+				//get info about defined price
+				if ($subLayers[$rootIndex]['wms_pricevolume'] == '' OR $subLayers[$rootIndex]['wms_pricevolume'] == 0){
+					$this->wmsJSON->wms->srv[$j]->price = NULL;
+				}
+				else {
+					$this->wmsJSON->wms->srv[$j]->price = $subLayers[$rootIndex]['wms_pricevolume'];
+				}
+				//get info about logging of resource
+				if ($subLayers[$rootIndex]['wms_proxylog'] == NULL OR $subLayers[$rootIndex]['wms_proxylog'] == 0){
+					 $this->wmsJSON->wms->srv[$j]->logged = false;
+				}
+				else {
+					 $this->wmsJSON->wms->srv[$j]->logged = true;
+				}
+				//get info about network_accessability
+				if ($subLayers[$rootIndex]['wms_network_access'] == NULL OR $subLayers[$rootIndex]['wms_network_access'] == 0){
+					 $this->wmsJSON->wms->srv[$j]->nwaccess = false;
+				}
+				else {
+					 $this->wmsJSON->wms->srv[$j]->nwaccess = true;
+				}
+				#$this->wmsJSON->wms->srv[$j]->logged = NULL; //$wmsMatrix[$i][''];
+				#$this->wmsJSON->wms->srv[$j]->price = NULL; //$wmsMatrix[$i][''];
+				#$this->wmsJSON->wms->srv[$j]->nwaccess = NULL; //$wmsMatrix[$i][''];
+				$this->wmsJSON->wms->srv[$j]->bbox = $subLayers[$rootIndex]['bbox']; //$wmsMatrix[$i][''];
+				//Call recursively the child elements, give and pull $layerIdArray to push the done elements in the array to avoid double results
+				#print_r($subLayers);
+				//generate the layer-entry for the so called root layer - maybe this is only a group layer if there is a gap in the layer hierachy
+				$this->wmsJSON->wms->srv[$j]->layer = array();
+				$this->wmsJSON->wms->srv[$j]->layer[0]->id = (integer)$subLayers[$rootIndex]['layer_id'];
+				$this->wmsJSON->wms->srv[$j]->layer[0]->title = $subLayers[$rootIndex]['layer_title'];
+				$this->wmsJSON->wms->srv[$j]->layer[0]->abstract = $subLayers[$rootIndex]['layer_abstract'];
+				$this->wmsJSON->wms->srv[$j]->layer[0]->mdLink = "http://".$this->hostName."/mapbender/php/mod_showMetadata.php?resource=layer&layout=tabs&id=".(integer)$subLayers[$rootIndex]['layer_id'];
+				$this->wmsJSON->wms->srv[$j]->layer[0]->previewURL = "http://".$this->hostName."/mapbender/x_geoportal/mod_layerPreview.php?id=".(integer)$subLayers[$rootIndex]['layer_id'];
+				if ($subLayers[$rootIndex]['layer_name'] == ''){
+					$this->wmsJSON->wms->srv[$j]->layer[0]->loadable = 0;
+				}
+				else {
+					$this->wmsJSON->wms->srv[$j]->layer[0]->loadable = 1;
+				}
+				if ($subLayers[$rootIndex]['layer_pos'] == '0'){
+					$this->wmsJSON->wms->srv[$j]->layer[0]->isRoot = true;
+				}
+				else {
+					$this->wmsJSON->wms->srv[$j]->layer[0]->isRoot = false;
+				}
+				//give info for inspire categories - not relevant for other services or instances of mapbender TODO: comment it if the mapbender installation is not used to generate inspire output
+				if ($subLayers[$rootIndex]['md_inspire_cats'] == ''){
+					$this->wmsJSON->wms->srv[$j]->layer[0]->inspire = 0;
+				}
+				else {
+					$this->wmsJSON->wms->srv[$j]->layer[0]->inspire = 1;
+				}
+				//get info about queryable or not
+				if ($subLayers[$rootIndex]['layer_queryable'] == 1){
+					$this->wmsJSON->wms->srv[$j]->layer[0]->queryable = 1;
+				}
+				else {
+					$this->wmsJSON->wms->srv[$j]->layer[0]->queryable = 0;
+				}
+				
+				#if ($subLayers[$rootIndex]['layer_name'] == ''){
+				#	$this->wmsJSON->wms->srv[$i-$j]->layer[0]->loadable = 0;
+				#}
+				#else {
+				#	$this->wmsJSON->wms->srv[$i-$j]->layer[0]->loadable = 1;
+				#}
+				$this->wmsJSON->wms->srv[$j]->layer[0]->loadCount = $subLayers[$rootIndex]['load_count'];
+				#$servObject->layer[$countsublayer]->mdLink = $_SERVER['HOST']."/mapbender/x_geoportal/showWFeatureTypeMetadata.php?id=".$wfsMatrix[$i]['featuretype_id'];
+				#$servObject->layer[$countsublayer]->geomtype = $wfsMatrix[$i]['element_type'];
+				$this->wmsJSON->wms->srv[$j]->layer[0]->bbox = $subLayers[$rootIndex]['bbox'];
+				$this->wmsJSON->wms->srv[$j]->layer[0]->permission = $this->getPermissionValueForLayer($subLayers[$rootIndex]['layer_id'], $subLayers[$rootIndex]['wms_id']); //TODO: Make this much more faster
+				//when the entry for the first server has been written, the server entry is fixed and the next one will be a new server or a part of the old one.
+				 //increment server (highest object id)
+				
+				$layerIdArray = $this->writeWMSChilds($layerIdArray, $rootLayerPos, $subLayers, $this->wmsJSON->wms->srv[$j]->layer[0]);
+				$j++;
+				//generate php object - if root layer was found - > layer_parent='' give hint to visualize folder symbol. 		
+				}
+			}
+		}			
+	}
+
+	private function generateWMSMetadata($xmlDoc) {
+		$starttime = $this->microtime_float();
+		list($sql, $v, $t, $n) = $this->generateSearchSQL();
+		//call database search in limits
+		$res = db_prep_query($sql, $v, $t);
+		if ($this->outputFormat == 'json'){
+			//generate json
+			$this->generateWMSMetadataJSON($res,$n);
+			$usedTime = $this->microtime_float() - $starttime;
+			//put in the time to generate the data
+			$this->wmsJSON->wms->md->genTime = $usedTime;
+			$this->wmsJSON = $this->json->encode($this->wmsJSON);
+			if ($this->resultTarget == 'file') {
+				if($wmsFileHandle = fopen($this->tempFolder."/".$this->searchId."_".$this->searchResources."_".$this->searchPages.".json","w")){
+					fwrite($wmsFileHandle,$this->wmsJSON);
+					fclose($wmsFileHandle);
+				}
+			}
+			if ($this->resultTarget == 'web' or $this->resultTarget == 'debug') {
+				echo $this->wmsJSON;
+			}
+		}
+		$usedTime2 = $this->microtime_float() - $starttime;
+		//echo "<br>used time: ".$usedTime."<br>";
+		$e = new mb_exception("Time to generate WMS-Metadata: ".$usedTime2);
+		$e = new mb_exception("Wrote the MD_WMS-File");
+	}
+
+
+
+	private function generateWFSMetadata($xmlDoc) {
+		$starttime = $this->microtime_float();
+		list($sql, $v, $t, $n) = $this->generateSearchSQL();
+		//call database search
+		$res = db_prep_query($sql, $v, $t);
+		if ($this->outputFormat == 'json'){
+			//generate json
+			$this->generateWFSMetadataJSON($res, $n);
+			$usedTime = $this->microtime_float() - $starttime;
+			//put in the time to generate the data
+			$this->wfsJSON->wfs->md->genTime = $usedTime;
+			$this->wfsJSON = $this->json->encode($this->wfsJSON);
+			if ($this->resultTarget == 'file') {
+				if($wfsFileHandle = fopen($this->tempFolder."/".$this->searchId."_".$this->searchResources."_".$this->searchPages.".json","w")){
+					fwrite($wfsFileHandle,$this->wfsJSON);
+					fclose($wfsFileHandle);
+				}
+			}
+			if ($this->resultTarget == 'web'or $this->resultTarget == 'debug') {
+				echo $this->wfsJSON;
+			}
+		}
+		if ($this->outputFormat == 'xml'){
+			//generate xml
+			$this->generateXMLHead($xmlDoc);
+			$this->generateXMLFoot($xmlDoc);
+			$this->generateWFSResultXML($xmlDoc,$res);
+			if ($this->resultTarget == 'file') {
+				if($wfsFileHandleXML = fopen($this->tempFolder."/".$this->searchId."_".$this->searchResources."_".$this->searchPages.".xml","w")){
+					fwrite($wfsFileHandleXML,$xmlDoc->saveXML());
+					fclose($wfsFileHandleXML);
+				}
+			}
+			if ($this->resultTarget == 'web') {
+				header("Content-type: application/xhtml+xml; charset=UTF-8");
+				echo $xmlDoc->saveXML();
+			}
+		}
+		
+		$e = new mb_exception("Time to generate WFS-Metadata: ".$usedTime);
+		$e = new mb_exception("Wrote the MD_WFS-File");
+	}
+	private function generateWMCMetadata($xmlDoc) {
+		$starttime = $this->microtime_float();
+		list($sql, $v, $t, $n) = $this->generateSearchSQL();
+		//call database search in limits
+		$res = db_prep_query($sql, $v, $t);
+		if ($this->outputFormat == 'json'){
+			//generate json
+			$this->generateWMCMetadataJSON($res,$n);
+			$usedTime = $this->microtime_float() - $starttime;
+			//put in the time to generate the data
+			$this->wmcJSON->wmc->md->genTime = $usedTime;
+			$this->wmcJSON = $this->json->encode($this->wmcJSON);
+			if ($this->resultTarget == 'file') {
+				if($wmcFileHandle = fopen($this->tempFolder."/".$this->searchId."_".$this->searchResources."_".$this->searchPages.".json","w")){
+					fwrite($wmcFileHandle,$this->wmcJSON);
+					fclose($wmcFileHandle);
+				}
+			}
+			if ($this->resultTarget == 'web' or $this->resultTarget == 'debug') {
+				echo $this->wmcJSON;
+			}
+		}
+		$usedTime2 = $this->microtime_float() - $starttime;
+		//echo "<br>used time: ".$usedTime."<br>";
+		$e = new mb_exception("Time to generate WMC-Metadata: ".$usedTime2);
+		$e = new mb_exception("Wrote the MD_WMC-File");
+	}
+
+
+
+
+
+	private function replaceChars_all($text){
+		$search = array( "ä",  "ö",  "ü",  "Ä",  "Ö",  "Ü",  "ß");
+		$repWith = array("ae", "oe", "ue", "AE", "OE", "UE", "ss");
+		$replaced = str_replace($search, $repWith, $text);
+		return $replaced;
+	}
+	private function generateSearchSQL() {
+		//elements needed to exist in mb wfs,wms,wmc view or table:
+		//1. textfield - all texts - searchText
+		//2. responsible organisations - given id 
+		//3. bbox - is not explicit given in the wfs metadata? Since WFS 1.1.0 a latlonbbox is present
+		//4. isoTopicCategory - is not been saved til now
+		//5. ...
+		//parse searchText into different array elements to allow an AND search
+		$searchStringArray = $this->generateSearchStringArray();
+		$v = array();
+		$t = array();
+		$sql = "SELECT * from ".$this->searchView." where ";
+		#$sqlN = "SELECT count(".$this->searchResources."_id) from ".$this->searchView." where ";
+		$whereStr = "";
+		$whereCondArray = array();
+		$isTextSearch = "false";
+		$e = new mb_exception("Number of used searchstrings: ".count($searchStringArray));
+		//textsearch
+		if ($this->searchText != NULL) {
+			for($i=0; $i < count($searchStringArray); $i++){
+				$isTextSearch = "true";
+				if($i>0) {
+					$whereStr .= " AND ";
+				}
+				$whereStr .= "searchtext LIKE $".($i+1);
+				//output for debugging
+				$e = new mb_notice("Part of string".$i.": ".$searchStringArray[$i]);
+				$e = new mb_notice("converted: ".$this->replaceChars_all($searchStringArray[$i]));			
+				$va = "%".trim(strtoupper($this->replaceChars_all($searchStringArray[$i])))."%";
+				$e = new mb_notice($this->searchResources." Searchtext in SQL: ".$va);
+				array_push($v,$va);
+				array_push($t,"s");	
+			}
+		}
+
+
+		// This is only for the later postgis versions. The within and disjoint is to slow, cause there is no usage of the geometrical index in the old versions!
+		//check for postgis version
+		//sql for get version string
+		//get version number
+		if ((strtolower($this->searchResources) === "wms" or strtolower($this->searchResources) === "wmc") & $this->searchBbox != NULL) {
+			//decide which type of search should be done
+			//check for postgis version cause postgis versions < 1.4 have problems when doing disjoint and inside
+			//
+			$sqlPostgisVersion = "SELECT postgis_version();";
+			$vPostgisVersion = array();
+			$tPostgisVersion = array();
+			$resPostgisVersion = db_prep_query($sqlPostgisVersion, $vPostgisVersion, $tPostgisVersion);
+			// get version string
+			while($row = db_fetch_array($resPostgisVersion)){
+				$postgisVersion = $row['postgis_version'];
+				$postgisVersionArray = explode(" ",$postgisVersion);
+				$postgisVersionSmall = explode(".",$postgisVersionArray[0]);
+				$postgisSubNumber = $postgisVersionSmall[1];
+				$e = new mb_exception("class_metadata.php: postgis sub number = ".$postgisSubNumber);
+			}
+			//
+			//
+			if ((integer)$postgisSubNumber >= 4){
+				#$spatialFilter = "(the_geom ";	
+				$e = new mb_exception("class_metadata.php: spatial operator: ".$this->searchTypeBbox);
+				if ($this->searchTypeBbox == 'outside') {
+					$spatialFilter = ' disjoint(';
+				} elseif ($this->searchTypeBbox == 'inside') { 
+					$spatialFilter = ' within(';
+				} else {
+					$spatialFilter = ' intersects(';
+				}
+				//define spatial filter
+				if(count(explode(',',$this->searchBbox)) == 4){   //if searchBbox has 4 entries
+					$spatialFilterCoords = explode(',',$this->searchBbox);//read out searchBbox
+					//definition of the spatial filter
+					$spatialFilter .= 'GeomFromText(\'POLYGON(('.$spatialFilterCoords[0];//minx
+					$spatialFilter .= ' '.$spatialFilterCoords[1].',';//miny
+					$spatialFilter .= $spatialFilterCoords[0];//minx
+					$spatialFilter .= ' '.$spatialFilterCoords[3].',';//maxy
+					$spatialFilter .= $spatialFilterCoords[2];//maxx
+					$spatialFilter .= ' '.$spatialFilterCoords[3].',';//maxy
+					$spatialFilter .= $spatialFilterCoords[2];//maxx
+					$spatialFilter .= ' '.$spatialFilterCoords[1].',';//miny
+					$spatialFilter .= $spatialFilterCoords[0];//minx
+					$spatialFilter .= ' '.$spatialFilterCoords[1].'))\',4326)';//miny
+					$spatialFilter .= ",the_geom)";
+					array_push($whereCondArray, $spatialFilter);
+				}
+			} else {
+		
+				$spatialFilter = ' the_geom && ';
+				//define spatial filter
+				if(count(explode(',',$this->searchBbox)) == 4){   //if searchBbox has 4 entries
+					$spatialFilterCoords = explode(',',$this->searchBbox);//read out searchBbox
+					//definition of the spatial filter
+					$spatialFilter .= 'GeomFromText(\'POLYGON(('.$spatialFilterCoords[0];//minx
+					$spatialFilter .= ' '.$spatialFilterCoords[1].',';//miny
+					$spatialFilter .= $spatialFilterCoords[0];//minx
+					$spatialFilter .= ' '.$spatialFilterCoords[3].',';//maxy
+					$spatialFilter .= $spatialFilterCoords[2];//maxx
+					$spatialFilter .= ' '.$spatialFilterCoords[3].',';//maxy
+					$spatialFilter .= $spatialFilterCoords[2];//maxx
+					$spatialFilter .= ' '.$spatialFilterCoords[1].',';//miny
+					$spatialFilter .= $spatialFilterCoords[0];//minx
+					$spatialFilter .= ' '.$spatialFilterCoords[1].'))\',4326)';//miny
+					#$spatialFilter .= ",the_geom)";
+					array_push($whereCondArray, $spatialFilter);
+				}
+			}
+		}	
+		//search filter for md_topic_categories
+		//
+		if ((strtolower($this->searchResources) === "wms" or strtolower($this->searchResources) === "wmc") & $this->isoCategories != NULL) {
+			
+			$isoArray = explode(',',$this->isoCategories);
+			$topicCond = "(";
+			for($i=0; $i < count($isoArray); $i++){
+				if ($i == 0) {
+					$topicCond .= "(md_topic_cats LIKE '%{".$isoArray[$i]."}%') ";			
+				} else {
+					$topicCond .= "AND (md_topic_cats LIKE '%{".$isoArray[$i]."}%') ";
+				}
+			}
+			$topicCond .= ")";
+			array_push($whereCondArray, $topicCond);
+		}
+		//search filter for inspire_categories
+		//
+		if (strtolower($this->searchResources) === "wms" & $this->inspireThemes != NULL) {
+			
+			$inspireArray = explode(',',$this->inspireThemes);
+			$inspireCond = "(";
+			for($i=0; $i < count($inspireArray); $i++){
+				if ($i == 0) {
+					$inspireCond .= "(md_inspire_cats LIKE '%{".$inspireArray[$i]."}%') ";			
+				} else {
+					$inspireCond .= "AND (md_inspire_cats LIKE '%{".$inspireArray[$i]."}%') ";
+				}
+			}
+			$inspireCond .= ")";
+			array_push($whereCondArray, $inspireCond);
+		}
+		//search filter for custom_categories
+		//
+		if (strtolower($this->searchResources) === "wms" & $this->customCategories != NULL) {
+			
+			$customArray = explode(',',$this->customCategories);
+			$customCond = "(";
+			for($i=0; $i < count($customArray); $i++){
+				if ($i == 0) {
+					$customCond .= "(md_custom_cats LIKE '%{".$customArray[$i]."}%') ";			
+				} else {
+					$customCond .= "AND (md_custom_cats LIKE '%{".$customArray[$i]."}%') ";
+				}
+			}
+			$customCond .= ")";
+			array_push($whereCondArray, $customCond);
+		}
+		
+
+
+		//date condition
+		//if begin and end are set
+		//echo "<br> regTimeBegin: ".$this-> regTimeBegin." regTimeEnd: ".$this-> regTimeEnd."<br>";
+		
+		if ($this->regTimeBegin != NULL && $this->regTimeEnd != NULL){
+			$time ="(TO_TIMESTAMP(".$this->searchResources."_timestamp) BETWEEN '".$this->regTimeBegin."' AND '".$this->regTimeEnd."')";
+			array_push($whereCondArray, $time);
+			//only begin is set		
+		}
+		if ($this->regTimeBegin != NULL && $this->regTimeEnd == NULL){
+			$time ="(TO_TIMESTAMP(".$this->searchResources."_timestamp) > '".$this->regTimeBegin."')";
+			array_push($whereCondArray, $time);
+		}
+		if ($this->regTimeBegin == NULL && $this->regTimeEnd != NULL){
+			$time ="(TO_TIMESTAMP(".$this->searchResources."_timestamp) < '".$this->regTimeEnd."')";
+			array_push($whereCondArray, $time);
+		}
+
+ 
+		//department condition
+		//TODO: generate filter for new sql check if at least some department is requested
+		//generate array
+		//$this->registratingDepartments = explode(',',$this->registratingDepartments);
+		#if(count($this->registratingDepartments) > 0 & $this->registratingDepartments){
+		if($this->registratingDepartments != NULL){		
+			$dep = " department IN (".$this->registratingDepartments.") ";
+			array_push($whereCondArray, $dep);	
+		}
+		// Creating the WHERE clause, based on a array
+		if(count($whereCondArray) > 0){
+			$txt_whereCond = "";
+			for ($index = 0; $index < sizeof($whereCondArray); $index++) {
+				$array_element = $whereCondArray[$index];
+				if($isTextSearch == "true") {
+					$txt_whereCond .= " AND ".$array_element;
+				} else {
+					if($index>0){
+					$txt_whereCond .= " AND ".$array_element;		
+					} else {
+						$txt_whereCond .= " ".$array_element;	
+					}	
+				}
+			}
+			$whereStr .= $txt_whereCond;
+		}
+		//Add WHERE condition to search
+		$sql .= $whereStr;
+		//TODO ORDER BY in SQL - not necessary for counting things:
+		$sql .= $this->orderBy;
+		//Calculate Paging for OFFSET and LIMIT values:
+		$offset = ((integer)$this->maxResults) * ((integer)$this->searchPages -1);
+		$limit = (integer)$this->maxResults;
+		//defining range for paging
+		$sql .= " LIMIT ".$limit." OFFSET ".$offset."";
+		//Print out search SQL term
+		$e = new mb_exception("class_metadata.php: Search => SQL-Request of ".$this->searchResources." service metadata: ".$sql."");
+		//parameter: searchId -> can be used global, searchResources -> is only one type per instance!!-> global,which categories -> can be defined global! $whereStr
+		$n = $this->writeCategories($whereStr, $v, $t); 
+		//write counts to filesystem to avoid to many database connections
+		//only write them, if searchId is given - problem: searches with same searchId's maybe get wrong information
+		return array($sql, $v, $t, $n);
+	}
+
+
+
+
+
+
+
+
+
+
+/** Function to write a json file which includes the categories of the search result for each searchResource - wms/wfs/wmc/georss, new: it should also count the keyword distribution of the searchResource ans save it as a special json file!
+
+**/
+	private function writeCategories($whereStr, $v, $t) {
+		//generate count sql
+		//generate count of all entries	
+		$sqlN = "SELECT count(".$this->searchResources."_id) from ".$this->searchView." where ";
+		$sqlN .= $whereStr;
+		//Get total number of results 
+		$count = db_prep_query($sqlN, $v, $t);
+		$n = db_fetch_all($count);
+		#echo "<br>N: ".var_dump($n)."<br>";
+		$n = $n[0]['count'];
+		$e = new mb_notice("class_metadata.php: Search => SQL-Request of ".$this->searchResources." service metadata N: ".$sqlN." Number of found objects: ".$n);
+		if ($this->searchId != 'dummysearch') { //searchId is not the default id! - it has been explicitly defined 
+			//check if cat file already exists:
+			//filename to search for:
+			$filename = $this->tempFolder."/".$this->searchId."_".$this->searchResources."_cat.json";
+			$keyFilename = $this->tempFolder."/".$this->searchId."_".$this->searchResources."_keywords.json";
+			if (!file_exists($filename)  or $this->resultTarget == 'debug') { //TODO at the moment the cat file will be overwritten - change this in production system
+				//open category file for results
+				$this->catJSON = new stdClass;
+				$this->catJSON->searchMD = (object) array(
+					'searchId' => $this->searchId,
+					'n' => $n
+					);
+				//new: also generate a json object for the keyword distribution
+				$this->keyJSON = new stdClass;
+				$this->keyJSON->tagCloud = (object) array(
+					'searchId' => $this->searchId,
+					'maxFontSize' => $this->maxFontSize,
+					'maxObjects' => $this->maxObjects,
+					'title' => $this->keywordTitle,
+					'tags' => array()
+					);
+				$this->inc = $this->maxFontSize/$this->maxObjects;//maybe 10 or 5 or ...
+				//generate the list of category counts
+				$sqlCat = array();
+				//generate the sql for the keyword count
+				$sqlKeyword = "select keyword.keyword, COUNT(*) "; 
+				$sqlKeyword .= "FROM (select ";
+				$sqlKeyword .= $this->databaseIdColumnName;
+				$sqlKeyword .= " FROM ".$this->searchView." WHERE ".$whereStr.") as a";
+				$sqlKeyword .= " INNER JOIN ".$this->databaseTableName."_keyword ON (";
+				$sqlKeyword .= $this->databaseTableName."_keyword.fkey_".$this->databaseIdColumnName." = a.";
+				$sqlKeyword .= $this->databaseIdColumnName.") ";
+				$sqlKeyword .= "INNER JOIN keyword ON (keyword.keyword_id=".$this->databaseTableName."_keyword.fkey_keyword_id) WHERE (keyword.keyword NOTNULL AND keyword.keyword <> '')";
+				$sqlKeyword .= "GROUP BY keyword.keyword  ORDER BY COUNT DESC LIMIT  ".$this->maxObjects;
+				//do sql select for keyword cloud
+				$resKeyword = db_prep_query($sqlKeyword, $v, $t);
+				$keywordCounts = db_fetch_all($resKeyword);
+				
+				if (count($keywordCounts) > 0) {
+					$this->maxWeight = $keywordCounts[0]['count'];
+					for ($j = 0; $j < count($keywordCounts); $j++) {
+						if ($this->scale == 'linear'){
+							//order in a linear scale desc
+							 $keywordCounts[$j]['count'] = $this->maxFontSize-($j*$this->inc);
+						} else {
+							//set weight prop to count 
+							 $keywordCounts[$j]['count'] = $keywordCounts[$j]['count']*$this->maxFontSize/$this->maxWeight;
+						}
+					}
+					//$this->maxWeight = $keywordCounts[0]['count'];
+					shuffle($keywordCounts);
+					for ($j = 0; $j < count($keywordCounts); $j++) {
+						$this->keyJSON->tagCloud->tags[$j]->title = $keywordCounts[$j]['keyword'];
+						//generate the weight:
+						//if ($this->scale == 'linear'){
+							//order in a linear scale desc
+							 $this->keyJSON->tagCloud->tags[$j]->weight = $keywordCounts[$j]['count'];
+						//} else {
+							//set weight prop to count 
+							// $this->keyJSON->tagCloud->tags[$j]->weight = $keywordCounts[$j]['count']*$this->maxFontSize/$this->maxWeight;
+						//}
+						//$this->keyJSON->tags[$j]->weight = $keywordCounts[$j]['count'];
+
+						$paramValue = $this->getValueForParam('searchText', $this->searchURL);	
+						//delete resources part from query and set some new one
+						$searchUrlKeywords = $this->delTotalFromQuery('searchResources',$this->searchURL);
+						//append the resource parameter:
+						$searchUrlKeywords .= '&searchResources='.$this->searchResources;
+						$e = new mb_exception("class_metadata_new: value ".$paramValue." for searchText param found");
+						$paramValue = urldecode($paramValue);
+						if ($paramValue == false) {
+							$this->keyJSON->tagCloud->tags[$j]->url = $searchUrlKeywords."&searchText=".$keywordCounts[$j]['keyword'];
+						} else {
+							$this->keyJSON->tagCloud->tags[$j]->url = $this->addToQuery('searchText',$searchUrlKeywords,$keywordCounts[$j]['keyword'],$paramValue);
+						}
+					}
+				}
+				//encode json!
+				$this->keyJSON = $this->json->encode($this->keyJSON);
+				//write clouds to file
+				if($keyFileHandle = fopen($keyFilename, "w")){
+					fwrite($keyFileHandle,$this->keyJSON);
+					fclose($keyFileHandle);
+					$e = new mb_notice("class_metadata: new ".$this->searchResources."_keyword_file created!");
+				} else {
+					$e = new mb_notice("class_metadata: cannot create ".$this->searchResources."_keyword_file!");
+				}
+				if ($this->resultTarget == 'debug') {
+					echo "<br>DEBUG: show keywords: <br>".$this->keyJSON."<br><br>";
+				}
+
+/** "$resourceId." from ".$wms_view." where ".$whereClause.") as a";
+				$sqlKeyword .= "(select keyword, count(*) from keyword INNER JOIN  layer_keyword  ON (layer_keyword.fkey_keyword_id = keyword.keyword_id) GROUP BY keyword.keyword) ";
+				$sqlKeyword .= " GROUP BY keyword.keyword)) as a WHERE a.keyword <> '' GROUP BY a.keyword ORDER BY sum DESC LIMIT $1";
+**/
+
+
+				//check if categories are defined for the resource
+				if ($this->resourceClasses != NULL) {
+					$this->catJSON->searchMD->category = array();
+					for ($i = 0; $i < count($this->resourceClasses); $i++) {
+						//TODO: not to set the classification?
+						$this->catJSON->searchMD->category[$i]->title = $this->resourceClassifications[$i]['title'];
+						$sqlCat[$i] = "SELECT ".$this->resourceClassifications[$i]['tablename'];
+						$sqlCat[$i] .= ".".$this->resourceClassifications[$i]['tablename']."_id, ";
+						$sqlCat[$i] .= " ".$this->resourceClassifications[$i]['tablename'].".";
+						$sqlCat[$i] .= $this->resourceClassifications[$i]['tablename']."_code_";
+						$sqlCat[$i] .= $this->languageCode.", COUNT(*) FROM ".$this->searchView;
+						
+						//first join for connection table
+						$sqlCat[$i] .= " INNER JOIN ".$this->resourceClassifications[$i]['relation_'.$this->searchResources];
+						$sqlCat[$i] .= " ON (";
+						$sqlCat[$i] .= $this->resourceClassifications[$i]['relation_'.$this->searchResources].".fkey_";
+						$sqlCat[$i] .= $this->resourceClassifications[$i]['id_'.$this->searchResources]."=".$this->searchView;
+						$sqlCat[$i] .= ".".$this->resourceClassifications[$i]['id_'.$this->searchResources];
+						$sqlCat[$i] .= ") INNER JOIN ";
+						$sqlCat[$i] .= $this->resourceClassifications[$i]['tablename']." ON (";
+						$sqlCat[$i] .= $this->resourceClassifications[$i]['tablename'].".";
+						$sqlCat[$i] .= $this->resourceClassifications[$i]['tablename']."_id=";
+						$sqlCat[$i] .= $this->resourceClassifications[$i]['relation_'.$this->searchResources].".fkey_";
+						$sqlCat[$i] .= $this->resourceClassifications[$i]['tablename']."_id)";
+						$sqlCat[$i] .= " WHERE ".$whereStr."  GROUP BY ";
+
+						$sqlCat[$i] .= $this->resourceClassifications[$i]['tablename'].".";
+						$sqlCat[$i] .= $this->resourceClassifications[$i]['tablename']."_id,";
+						$sqlCat[$i] .= $this->resourceClassifications[$i]['tablename'].".";
+						$sqlCat[$i] .= $this->resourceClassifications[$i]['tablename']."_code_".$this->languageCode." ORDER BY ";
+						$sqlCat[$i] .= $this->resourceClassifications[$i]['tablename']."_id";
+						$sqlCategory = $sqlCat[$i];
+
+						//call sql for count of category
+						$res = db_prep_query($sqlCategory, $v, $t);
+						$categoryCounts = db_fetch_all($res);
+						//if none found: $categoryCounts=false
+						#echo "<br>count sub categories :".$categoryCounts."<br>";
+						if ($categoryCounts) {
+						//write results in json object
+						if (count($categoryCounts) > 0) {
+							#echo "<br>count main categories".count($categoryCounts)."<br>";
+							#echo "<br>vardump main categories".var_dump($categoryCounts)."<br>";
+							$this->catJSON->searchMD->category[$i]->subcat = array();
+							for ($j = 0; $j < count($categoryCounts); $j++) {
+								$this->catJSON->searchMD->category[$i]->subcat[$j]->id = $categoryCounts[$j][$this->resourceClassifications[$i]['tablename']."_id"];
+								$this->catJSON->searchMD->category[$i]->subcat[$j]->title = $categoryCounts[$j][$this->resourceClassifications[$i]['tablename']."_code_".$this->languageCode];
+								$this->catJSON->searchMD->category[$i]->subcat[$j]->count = $categoryCounts[$j]['count'];
+								//delete requestParam for this category and for id - cause a new search is started from searchURL
+								$filteredSearchString = $this->delTotalFromQuery('searchId',$this->searchURL);
+								//uncomment the following line if a or category search is intended
+								//$filteredSearchString = $this->delTotalFromQuery($this->resourceClassifications[$i]['requestName'],$filteredSearchString);
+								//TODO: maybe adopt this to do a and search and not a or like it is done now
+								//check if category search was requested and rewrite the search url
+								//get the value of the param as string or false if not set!
+								$paramValue = $this->getValueForParam($this->resourceClassifications[$i]['requestName'], $filteredSearchString);
+								$paramValue = urldecode($paramValue);
+								if ($paramValue == false) {
+									//add new category to search
+
+								//set filter for this categoryid
+								$filteredSearchString .= "&".$this->resourceClassifications[$i]['requestName']."=".$categoryCounts[$j][$this->resourceClassifications[$i]['tablename']."_id"];
+								
+								
+								} else {
+									//rewrite the searchUrl
+									$filteredSearchString = $this->addToQuery($this->resourceClassifications[$i]['requestName'],$filteredSearchString,$categoryCounts[$j][$this->resourceClassifications[$i]['tablename']."_id"],$paramValue);
+								}
+
+								$this->catJSON->searchMD->category[$i]->subcat[$j]->filterLink = $filteredSearchString;
+							}
+						}
+						} else {
+							#$this->catJSON->searchMD->category[$i]->subcat = array();
+						}
+						$e = new mb_notice("class_metadata: countsql: ".$sqlCat[$i]);
+					}
+				}
+
+				$this->catJSON = $this->json->encode($this->catJSON);
+				//write categories files only when file is requested and the searchid was not used before!
+				if ($this->resultTarget == 'file') {
+					if($catFileHandle = fopen($filename, "w")){
+						fwrite($catFileHandle,$this->catJSON);
+						fclose($catFileHandle);
+						$e = new mb_notice("class_metadata: new ".$this->searchResources."_class_file created!");
+					} else {
+						$e = new mb_notice("class_metadata: cannot create ".$this->searchResources."_cat_file!");
+					}
+					
+				} 
+				if ($this->resultTarget == 'debug') {
+					echo "<br>DEBUG: show categories: <br>".$this->catJSON."<br><br>";
+				}
+			} else {
+				$e = new mb_exception("class_metadata: ".$this->searchResources."_class_file: ".$filename." already exists - no new one is generated!");				
+			}	
+		} else {
+			if ($this->resultTarget == 'debug') {
+				echo "<br>DEBUG: Standard ID dummysearch was invoked - classifications won't be counted!<br>";
+			}
+			$e = new mb_exception("class_metadata: standard dummysearch was invoked - classifications won't be counted!");	
+		}			
+		return $n;
+	}
+
+
+
+
+	private function generateWFSResultXML($wfsDoc, $res) {
+		$c = $this->wfsDoc->createElement("category");
+		$results = $this->wfsDoc->getElementsByTagName("result");
+		foreach ($results as $result) {
+			$result->appendChild($c);
+			$c->setAttribute('name', "WFS");
+			$c->setAttribute('count', "0");
+		}
+		$i = 0;
+		while($row = db_fetch_array($res)){
+			$m = $this->wfsDoc->createElement('member');
+			$m->setAttribute('wfs_id', $row['wfs_id']);
+			$m->setAttribute('layer_pos', "");
+			$c->appendChild($m);	 // member categorie 1 (first member)
+			// epsg - TODO adopt
+			$epsg = $this->wfsDoc->createElement('epsg');
+			$m->appendChild($epsg);	
+			$equalEPSG = $row['featuretype_srs'];
+                       	$isequal = "false";
+		        if ($equalEPSG == $this->search_epsg){
+				$isequal = "true";		
+		        }	
+		       	//Insert end
+			$epsg_text = $this->wfsDoc->createTextNode($isequal);
+			$epsg->appendChild($epsg_text);
+			// country codes
+			$state = $this->wfsDoc->createElement('federalstate');
+			$m->appendChild($state);
+			$spatialSource = "";
+			$stateorprovince = $row['administrativearea']; 
+			if ($stateorprovince == "NULL" || $stateorprovince == "") {
+				$spatialSource = $row['country'];
+			} else {
+				$spatialSource = $row['administrativearea'];
+			}
+			$countr_code_text = $this->wfsDoc->createTextNode($spatialSource);
+			$state->appendChild($countr_code_text);
+			//type
+			$type = $this->wfsDoc->createElement('type');
+			$m->appendChild($type);
+			$ttype = $this->wfsDoc->createTextNode("wfs");
+			$type->appendChild($ttype);
+                        //wfs_id
+			$wfsid = $this->wfsDoc->createElement('wfs_id');
+			$m->appendChild($wfsid);
+			$twfsid = $this->wfsDoc->createTextNode($row['wfs_id']);
+			$wfsid->appendChild($twfsid);
+			//id
+			$id = $this->wfsDoc->createElement('featuretype_id');
+			$m->appendChild($id);
+			$tid = $this->wfsDoc->createTextNode($row['featuretype_id']);
+			$id->appendChild($tid);
+			//title
+			$title = $this->wfsDoc->createElement('featuretype_title');
+			$m->appendChild($title);
+			$ttitle = $this->wfsDoc->createTextNode($row['featuretype_title']);
+			$title->appendChild($ttitle);
+			//abstract
+			$abst = $this->wfsDoc->createElement('featuretype_abstract');
+			$m->appendChild($abst);  
+			$tabst = $this->wfsDoc->createTextNode($row['featuretype_abstract']);
+			$abst->appendChild($tabst);
+			// accesscontraints				
+			$ac = $this->wfsDoc->createElement('accessconstraints');
+			$m->appendChild($ac);	
+//			$myac = $this->getAccessConstraints($this->cat[$i]['member'][$ii]['wms_id'], $this->cat[$i]['member'][$ii]['accessconstraints'], $this->cat[$i]['member'][$ii]['layer_id']);				
+			$myac = $this->wfsDoc->createTextNode($row['accessconstraints']);							
+			$ac->appendChild($myac);
+			// termsofuse				
+			$ter = $this->wfsDoc->createElement('termsofuse');
+			$m->appendChild($ter);
+			$myter =  $this->wfsDoc->createTextNode($row['termsofuse']);				
+			$ter->appendChild($myter);
+			//date
+			$date = $this->wfsDoc->createElement('date');
+			$m->appendChild($date);
+			$tdate = $this->wfsDoc->createTextNode(date("d.m.Y",$row['wfs_timestamp']));
+			$date->appendChild($tdate);	
+			// Geomtype
+			$geo = $this->wfsDoc->createElement('geomtype');
+			$m->appendChild($geo);
+			//$geo_text = $this->getGeoType($row['wfs_id'], $row['featuretype_id']);
+			$geo_text = $this->wfsDoc->createTextNode($row['element_type']);
+			//$ge =  $this->wfsDoc->createTextNode($geo_text);
+			$geo->appendChild($geo_text);
+			//department
+			$dm = $this->wfsDoc->createElement('department');
+			$m->appendChild($dm);
+			$tdm = $this->wfsDoc->createTextNode($row['mb_group_name']);
+			$dm->appendChild($tdm);
+			//permission  		 Leseberechtigung des Benutzers(true), sonst Email zur Beantragung(email)
+			$per = $this->wfsDoc->createElement('permission');
+			$m->appendChild($per);
+			$per_text = $this->getPermissionValueForWFS($row['wfs_id'], $row['wfs_conf_id']);
+			$pe =  $this->wfsDoc->createTextNode($per_text);
+			$per->appendChild($pe);
+			//wfs_conf_id
+			$conf_id = $this->wfsDoc->createElement('wfs_conf_id');
+			$m->appendChild($conf_id);
+			$c_id = $this->wfsDoc->createTextNode($row['wfs_conf_id']);
+			$conf_id->appendChild($c_id);
+			//wfs_conf_title
+			$conf_title = $this->wfsDoc->createElement('wfs_conf_title');
+			$m->appendChild($conf_title);
+			$conf_title_text = $this->wfsDoc->createTextNode($row['wfs_conf_abstract']);
+			$conf_title->appendChild($conf_title_text);
+			//wfs_conf_abstract
+			$conf_abstract = $this->wfsDoc->createElement('wfs_conf_abstract');
+			$m->appendChild($conf_abstract);
+			$c_abstract = $this->wfsDoc->createTextNode($row['wfs_conf_description']);
+			$conf_abstract->appendChild($c_abstract);
+			//wfs_conf_modul
+			$conf_modul = $this->wfsDoc->createElement('wfs_conf_modul');
+			$m->appendChild($conf_modul);
+			$c_modul = $this->wfsDoc->createTextNode($row['modultype']);
+			$conf_modul->appendChild($c_modul);
+			$i++;
+		}
+		$c->setAttribute('count', $i);
+	}
+
+	private function getPermissionValueForWFS($wfs_id, $wfs_conf_id){
+		//TODO: Set Email of owner into view for ressource - so it don't have to be searched?
+		$return_permission = "";
+		//get permission
+		$admin = new administration();
+		$myWFSconfs = $admin->getWfsConfByPermission($this->userId);
+		$this->myWFSConfs = $myWFSconfs;
+		for ($index = 0; $index < sizeof($this->myWFSConfs); $index++) {
+			$array_element = $this->myWFSConfs[$index];
+		}
+		if (in_array($wfs_conf_id, $this->myWFSConfs)){
+			$return_permission = "true";
+		} else {
+			$sql = "SELECT wfs.wfs_id, mb_user.mb_user_email as email FROM wfs, mb_user where wfs.wfs_owner=mb_user.mb_user_id "."and wfs.wfs_id=$1";
+			$v = array($wfs_id);
+			$t = array('i');
+			$res = db_prep_query($sql, $v, $t);
+			// get email
+			$mail = "";
+			while($row = db_fetch_array($res)){
+				$mail = $row['email'];
+				$return_permission = $mail; 
+			}
+		}
+		return $return_permission;
+	}
+
+	private function getPermissionValueForLayer($layerId,$wmsId){
+		//TODO: Set Email of owner into view for ressource - so it don't have to be searched?
+		$return_permission="";
+		#$admin = new administration();
+		#$permission = $admin->getLayerPermission($wms_id, $layer_name, $this->userId);
+		#echo "<br>wms_id: ".$wms_id."<br>";
+		#echo "<br>layer_name: ".$layer_name."<br>";
+		#echo "<br>user_id: ".$this->userId."<br>";
+		#echo "<br>Permission: ".$permission."<br>";
+               # var_dump($this->accessableLayers);
+		if (in_array($layerId, $this->accessableLayers)){
+			$return_permission = "true";
+			return $return_permission;
+		} else {
+			$sql = "SELECT mb_user.mb_user_email as email FROM wms, mb_user WHERE wms.wms_owner=mb_user.mb_user_id";
+			$sql .= " AND wms.wms_id=$1";
+			$v = array($wmsId);
+			$t = array('i');
+			$res = db_prep_query($sql, $v, $t);
+			// get email
+			$mail="";
+			while($row = db_fetch_array($res)){
+				$mail = $row['email'];
+				$return_permission = $mail; 
+			}
+		return $return_permission;
+		}
+	}	
+
+	
+
+	private function generateSearchStringArray() {
+		//'wfs test array' -> ('wfs' 'test' 'array')
+		$asstr = array();
+		if ($this->searchText != "false"){
+			$asstr = split(",",$this->searchText);
+			//delete left and right whitespaces
+			for ($i=0; $i<count($asstr);$i++) {
+				$asstr[$i]=ltrim($asstr[$i]);
+				$asstr[$i]=rtrim($asstr[$i]);
+			}	
+		}
+		return $asstr;
+	}			
+		
+	//out of php doc - test if it is faster than normal array_search	
+	private function fast_in_array($elem, $array) {
+   		$top = sizeof($array) -1;
+   		$bot = 0;
+		while($top >= $bot) {
+			$p = floor(($top + $bot) / 2);
+			if ($array[$p] < $elem) $bot = $p + 1;
+			elseif ($array[$p] > $elem) $top = $p - 1;
+			else return TRUE;
+		}
+    	return FALSE;
+	}
+	/*
+	* filtering an array
+	*/
+	private function filter_by_value ($array, $index, $value){
+        	if(is_array($array) && count($array)>0) {
+            		foreach(array_keys($array) as $key){
+                		$temp[$key] = $array[$key][$index];
+                		if ($temp[$key] == $value){
+                    			$newarray[$key] = $array[$key];
+                		}
+           		}
+          	}
+      	return $newarray;
+    	} 
+
+	//function to get the parent of the given layer by crawling the layertree upwards
+	private function getLayerParent ($layerArray, $index){
+		//only layers of one service should be in $layerArray
+		#$parentExists = false;
+		#var_dump($layerArray);
+		$layerIDKey = $layerArray['layer_id'][$index];	
+		#echo ("layerIDKey= ".$layerIDKey."<br>");
+		$layerParentPos = $layerArray['layer_parent'][$index];//get first parent object position
+		#echo ("layerParentPos= ".$layerParentPos."<br>");
+		#echo("<br>number of sublayers ".count(flipDiagonally($layerArray))."<br>");
+		#echo("<br>size of layerArray['layer_pos']: ".count($layerArray['layer_pos'])."<br>");
+		#var_dump($layerArray['layer_pos']);
+		#echo "<br>flipped layerArray: <br> ";
+		#var_dump(flipDiagonally($layerArray));
+		#echo "<br>";		
+
+		if ($layerParentPos == '') {
+			//root layer directly found
+			return $index;
+		}
+		#echo ("layerParentPos= ".$layerParentPos."<br>");
+		//Initialize index of layer parent - first it references the layer itself
+		$layerParentIndex = $index;
+		//loop to search higher parent objects - maybe this can be faster if the loop is not used over all sublayer elements! Do a while loop instead!
+		$highestParentLayerNotFound = true;
+		while ($highestParentLayerNotFound) {
+			#echo("<br>i= ".$i."<br>");
+			#echo("<br>layerParentPosNew= ".$layerParentPos."<br>");
+			$layerParentIndexNew = array_search((string)$layerParentPos, $layerArray['layer_pos']);
+			#echo("<br>layerParentIndexNew= ".$layerParentIndexNew."<br>");
+			if ($layerParentIndexNew != false) {
+				//some parent has been found
+				$layerParentIndex = $layerParentIndexNew;
+				$layerParentPos = $layerArray['layer_parent'][$layerParentIndex];
+				if ($layerParentPos == '') {
+					$highestParentLayerNotFound = false;
+					return $layerParentIndex; //a real root layer was found!
+				}
+				
+				#$layerParentIndex = array_search($layerParentPos, $layerArray['layer_pos']);
+			} else {
+				$highestParentLayerNotFound = false; //no higher layer could be found
+				return $layerParentIndex;
+			}
+		}
+		return $layerParentIndex;  
+    	} 
+
+
+	//function to write the child elements to the resulting wms object -> object is given by reference
+	private function writeWMSChilds($layerIdArray, $rootLayerPos, $subLayers, &$servObject) {
+		#echo "test";
+		#echo "<br>subLayers:<br>";
+		#var_dump($subLayers);
+		#echo "<br>";
+		$childLayers = $this->filter_by_value($subLayers, 'layer_parent', $rootLayerPos); //the root layer position in the sublayer array was located before. In this step, all layers will be pulled out of sublayer, where root layer position is parent object
+		#echo "<br<childLayers:<br>";
+		#var_dump($childLayers);
+		#echo "<br>";
+		#echo "test";
+		#print_r($childLayers);
+		#print_r($childLayers);
+		$countsublayer = 0;
+		//if child exists create a new layer array for these 
+		if (count($childLayers) != 0) {
+			$servObject->layer = array();
+		}
+		foreach ($childLayers as $child){	
+			#echo "<br>countsublayer: ".$countsublayer."<br>";
+			#echo "<br>Child id: ".$child['layer_id']."<br>";
+			#echo "<br>Child pos: ".$child['layer_pos']."<br>";
+			$servObject->layer[$countsublayer]->id = $child['layer_id'];
+			$servObject->layer[$countsublayer]->title = $child['layer_title'];
+			$servObject->layer[$countsublayer]->abstract = $child['layer_abstract'];
+			$servObject->layer[$countsublayer]->previewURL = "http://".$this->hostName."/mapbender/x_geoportal/mod_layerPreview.php?id=".$child['layer_id'];
+			$servObject->layer[$countsublayer]->mdLink = "http://".$this->hostName."/mapbender/php/mod_showMetadata.php?resource=layer&layout=tabs&id=".$child['layer_id'];
+			if ($child['layer_name'] == ''){
+				$servObject->layer[$countsublayer]->loadable = 0;
+			} else {
+				$servObject->layer[$countsublayer]->loadable = 1;
+			}
+			//give info for inspire categories - not relevant for other services or instances of mapbender TODO: comment it if the mapbender installation is not used to generate inspire output
+			if ($child['md_inspire_cats'] == ''){
+				$servObject->layer[$countsublayer]->inspire = 0;
+			}
+			else {
+				$servObject->layer[$countsublayer]->inspire = 1;
+			}
+			//get info about queryable or not
+			if ($child['layer_queryable'] == 1){
+				$servObject->layer[$countsublayer]->queryable = 1;
+			}
+			else {
+				$servObject->layer[$countsublayer]->queryable = 0;
+			}
+				
+			$servObject->layer[$countsublayer]->loadCount = $child['load_count'];
+			$servObject->layer[$countsublayer]->bbox = $child['bbox'];
+			$servObject->layer[$countsublayer]->permission = $this->getPermissionValueForLayer($child['layer_id'],$child['wms_id']); //TODO: make this much faster!!!! - is done by collecting all accessable resources once. Maybe this has to be adopted if the count of the resources become higher
+			//call this function itself - search sublayers in the layer object.
+			$layerIdArray = $this->writeWMSChilds($layerIdArray, $child['layer_pos'], $subLayers, $servObject->layer[$countsublayer]);//TODO create a timeout condition !
+			array_push($layerIdArray, $child['layer_id']); //child have been identified and recursively written 
+			#var_dump($layerIdArray);#
+			#echo "<br>";
+			$countsublayer ++;
+		}
+		return $layerIdArray;
+	}
+
+
+
+	
+	private function hasConstraints($type,$id) {
+		if ($type == "wms") {
+			$sql = "SELECT wms.accessconstraints, wms.fees, wms.wms_network_access , wms.wms_pricevolume, wms.wms_proxylog, termsofuse.name,";
+			$sql .= " termsofuse.termsofuse_id, termsofuse.symbollink, termsofuse.description,termsofuse.descriptionlink from wms LEFT OUTER JOIN";
+			$sql .= "  wms_termsofuse ON  (wms.wms_id = wms_termsofuse.fkey_wms_id) LEFT OUTER JOIN termsofuse ON";
+			$sql .= " (wms_termsofuse.fkey_termsofuse_id=termsofuse.termsofuse_id) where wms.wms_id = $1";
+}
+		if ($type == "wfs") {
+			$sql = "SELECT accessconstraints, fees, wfs_network_access , termsofuse.name,";
+			$sql .= " termsofuse.termsofuse_id ,termsofuse.symbollink, termsofuse.description,termsofuse.descriptionlink from wfs LEFT OUTER JOIN";
+			$sql .= "  wfs_termsofuse ON  (wfs.wfs_id = wfs_termsofuse.fkey_wfs_id) LEFT OUTER JOIN termsofuse ON";
+			$sql .= " (wfs_termsofuse.fkey_termsofuse_id=termsofuse.termsofuse_id) where wfs.wfs_id = $1";	
+}
+		$v = array();
+		$t = array();
+
+
+		array_push($t, "i");
+		array_push($v, $id);
+
+		$res = db_prep_query($sql,$v,$t);
+
+		$row = db_fetch_array($res);
+
+
+
+		if ((isset($row[$type.'_proxylog']) & $row[$type.'_proxylog'] != 0) or strtoupper($row['accessconstraints']) != "NONE" or strtoupper($row['fees']) != "NONE" or isset($row['termsofuse_id']) ) {
+		//service has some constraints defined!
+		//give symbol and true
+		//termsofuse symbol or exclamation mark
+			if (isset($row['termsofuse_id']) & $row['symbollink'] != "") {
+ 				$symbolLink = $row['symbollink'];
+			} else {
+				$symbolLink = "http://".$this->hostName."/portal/fileadmin/design/icn_warn.png";
+			}
+			$hasConstraints = true;
+			#$disclaimerLink = $_SERVER['HTTP_HOST']."/mapbender/php/mod_getServiceDisclaimer.php?type=".$type."&id=".$id;
+			#$symbolMouseOver = "Nutzungsbedingungen"; //TODO internationalize it
+
+		} else {
+		//give symbol and false
+		//green symbol
+			$symbolLink = "http://".$this->hostName."/portal/fileadmin/design/icn_ok.png";
+       			#$disclaimerLink = "";
+			$hasConstraints = false;
+			#$symbolMouseOver = "Frei zugänglich"; //TODO internationalize it
+		}
+
+		//generate json output:
+		#$json = new Mapbender_JSON;
+		#$returnJSON = new stdClass;
+		#$returnJSON->serviceConstraints = (object) array(
+				#'hasConstraints' => $hasConstraints,
+				#'disclaimerLink' => $disclaimerLink, 
+				#'symbolLink' => $symbolLink,
+				#'symbolMouseOver' => $symbolMouseOver
+		#	);
+		#$returnJSON = $json->encode($returnJSON);
+		#echo $returnJSON;
+		return array($hasConstraints, $symbolLink);
+	}
+	//function to delete one of the comma separated values from one get request
+	//
+	//
+	//
+	//
+	private function delFromQuery($paramName,$queryString,$string,$queryArray,$queryList) {
+		//check if if count searchArray = 1
+		if (count($queryArray) == 1){
+			//remove request parameter from url by regexpr or replace
+			$str2search = $paramName."=".$queryList;
+			$str2exchange = "";
+			$queryStringNew = str_replace($str2search, $str2exchange, $queryString);
+			$queryStringNew = str_replace("&&", "&", $queryStringNew);
+		} else {
+		//there are more than one filter - reduce the filter  
+			$objectList = "";
+			for($i=0; $i < count($queryArray); $i++){
+				if ($queryArray[$i] != $string){
+					$objectList .= $queryArray[$i].",";		
+				} 
+			}
+			//remove last comma
+			$objectList = rtrim($objectList, ",");
+			$str2search = $paramName."=".$queryList;
+			$str2exchange = $paramName."=".$objectList;
+			$queryStringNew = str_replace($str2search, $str2exchange, $queryString);
+		}
+	return $queryStringNew;
+	}
+	
+
+	
+	private function getValueForParam($paramName,$queryString) {
+		#another approach:
+		parse_str($queryString, $allQueries);
+		if (isset($allQueries[$paramName]) & $allQueries[$paramName] != '') {
+			return $allQueries[$paramName];
+		} else {
+			return false;
+		}
+
+
+#		old version
+
+/*		#TODO: check if last and first ampersand was set before
+		$queryString = "&".$queryString."&";
+		#$pattern = '/\b'.$paramName.'=([a-z0-9-]+)\&?/';
+		$pattern = '/\b&'.$paramName.'\=[^&]+&?/';
+		#$pattern = '/^&'.$paramName.'=[a-zA-ZöäüÖÄÜß,]*&$/';
+		$e = new mb_exception("class_metadata_new.php: look for pattern: ".$pattern."  in ".$queryString);
+ 		if (!preg_match($pattern, $queryString, $matches)){
+			
+			return false;
+		} else {
+			//some param found
+			//delete $paramName= and the last ampersand!
+			if (count($matches) == 1) {
+				$requestString = $matches[0];
+				$requestString = ltrim($requestString,"&".$paramName."=");
+				$requestString = rtrim($requestString,'&');
+
+				return $requestString;
+			} else {
+				$e = new mb_exception("class_metadata_new.php: There are parameter ambiguities!");
+				#echo "Parameter Ambiguities found!";
+				die();
+			}
+		}*/
+	}	
+
+	private function addToQuery($paramName,$queryString,$string,$queryList) {
+		//test if string was part of query before, if so, don't extent the query
+		//TODO: the strings come from json and so they are urlencoded! maybe we have to decode them to find the commata
+		$queryListComma = urldecode($queryList);
+		$queryListC = ",".$queryListComma.",";
+		$pattern = ','.$string.',';	
+ 		if (!preg_match($pattern, $queryListC)){
+			//append the new element
+			$queryListNew = $queryListC.$string;
+			//echo "query string new: ".$queryListNew."<br>";
+			//delete the commatas
+			$queryListNew = ltrim($queryListNew,',');
+			//generate the new query string
+			$queryStringNew = str_replace($paramName.'='.$queryList,$paramName.'='.$queryListNew,$queryString);
+			//echo "query string new: ".$queryListNew."<br>";
+			//dump old and new querystring for debugging
+			//$this->logit("class_metadata_new: queryString_old:".$queryString);
+			//$this->logit("class_metadata_new: queryString_new:".$queryStringNew);
+			return $queryStringNew;
+		} else {
+			//$this->logit("class_metadata_new: queryString unchanged:".$queryString);
+			//return the old one!
+			return $queryString;
+		}
+	}
+	//for debugging purposes
+	private function logit($text){
+	 	if($h = fopen("/tmp/class_metadata_new.log","a")){
+					$content = $text .chr(13).chr(10);
+					if(!fwrite($h,$content)){
+						#exit;
+					}
+					fclose($h);
+				}
+	 	
+	 }
+
+
+
+
+	private function delTotalFromQuery($paramName,$queryString) {
+		$queryString = "&".$queryString;
+		#echo "<br>queryString: ".$queryString."<br>";
+		$queryStringNew = preg_replace('/\b'.$paramName.'\=[^&]+&?/',"",$queryString);
+		$queryStringNew = ltrim($queryStringNew,'&');
+		$queryStringNew = rtrim($queryStringNew,'&');
+		return $queryStringNew;
+	}	
+		
+}
+?>

Deleted: branches/mapbender/http/classes/class_wmc.php
===================================================================
--- trunk/mapbender/http/classes/class_wmc.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/http/classes/class_wmc.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,1762 +0,0 @@
-<?php
-# $Id$
-# http://www.mapbender.org/index.php/class_wmc.php
-# 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__) . "/../classes/class_wms.php");
-require_once(dirname(__FILE__) . "/../classes/class_wfs_configuration.php");
-require_once(dirname(__FILE__) . "/../classes/class_layer_monitor.php");
-require_once(dirname(__FILE__) . "/../classes/class_point.php");
-require_once(dirname(__FILE__) . "/../classes/class_bbox.php");
-require_once(dirname(__FILE__) . "/../classes/class_json.php");
-require_once(dirname(__FILE__) . "/../classes/class_map.php");
-require_once(dirname(__FILE__) . "/../classes/class_administration.php");
-require_once(dirname(__FILE__) . "/../classes/class_wmcToXml.php");
-require_once(dirname(__FILE__) . "/../classes/class_user.php");
-
-/**
- * Implementation of a Web Map Context Document, WMC 1.1.0
- * 
- * Use cases:
- * 
- * Instantiation (1) create a WMC object from a WMC XML document
- * 		$myWmc = new wmc();
- * 		$myWmc->createFromXml($xml);
- * 
- *    If you want to create a WMC object from a WMC in the database
- *    	$xml = wmc::getDocument($wmcId);
- * 		$myWmc = new wmc();
- * 		$myWmc->createFromXml($xml);
- *    
- * 
- * Instantiation (2) create a WMC from the client side
- * 		$myWmc = new wmc();
- * 		$myWmc->createFromJs($mapObject, $generalTitle, $extensionData);
- * 	
- * 	  	(creates a WMC from the JS data and then creates an object from that WMC)
- * 
- * Output (1) (do Instantiation first) Load a WMC into client
- * 		This will return an array of JS statements
- *  
- * 		$myWmc->toJavaScript();
- * 
- * Output (2) (do Instantiation first) Merge with another WMC, then load
- * 	
- * 		$myWmc->merge($anotherWmcXml);
- * 		$myWmc->toJavaScript();
- * 
- */
-class wmc {
-	/**
-	 * Representing the main map in a map application
-	 * @var Map
-	 */
-	var $mainMap;
-
-	/**
-	 * Representing an (optional) overview map in a map application
-	 * @var Map
-	 */
-	var $overviewMap;
-
-	/**
-	 * @var Array
-	 */
-	var $generalExtensionArray = array();
-
-	/**
-	 * The XML representation of this WMC.
-	 * @var String
-	 */
-	var $xml;
-	
-	// constants
-	var $saveWmcAsFile = false;
-	var $extensionNamespace = "mapbender";
-	var $extensionNamespaceUrl = "http://www.mapbender.org/context";
-		
-	// set in constructor
-	var $wmc_id;
-	var $userId;
-    var $timestamp;
-    var $public;
-
-	// set during parsing
-	var $wmc_version;
-	var $wmc_name;
-	var $wmc_title;
-	var $wmc_abstract;
-	var $wmc_srs;
-	var $wmc_extent;
-	var $wmc_keyword = array();
-	var $wmc_contactposition;
-	var $wmc_contactvoicetelephone;
-	var $wmc_contactemail;
-	var $wmc_contactfacsimiletelephone;
-	var $wmc_contactperson;
-	var $wmc_contactorganization;
-	var $wmc_contactaddresstype;
-	var $wmc_contactaddress;
-	var $wmc_contactcity;
-	var $wmc_contactstateorprovince;
-	var $wmc_contactpostcode;
-	var $wmc_contactcountry;
-	var $wmc_logourl;
-	var $wmc_logourl_format;
-	var $wmc_logourl_type;
-	var $wmc_logourl_width;
-	var $wmc_logourl_height;
-	var $wmc_descriptionurl;
-	var $wmc_descriptionurl_format;
-	var $wmc_descriptionurl_type;
-
-	var $inspireCats; 
-
-	public function __construct () {
-		$this->userId = Mapbender::session()->get("mb_user_id");
-		$this->wmc_id = time();
-		$this->timestamp = time();
-	} 
-	
-	// ---------------------------------------------------------------------------
-	// INSTANTIATION
-	// ---------------------------------------------------------------------------
-
-	/**
-	 * Parses the XML string and instantiates the WMC object.
-	 * 
-	 * @param $xml String
-	 */
-	public function createFromXml ($xml) {
-		return $this->createObjFromWMC_xml($xml);
-	}
-
-	/**
-	 * Loads a WMC from the database.
-	 * 
-	 * @param integer $wmc_id the ID of the WMC document in the database table "mb_user_wmc"
-	 */
-	function createFromDb($wmcId){
-		$doc = wmc::getDocument($wmcId);
-		if ($doc === false) {
-			return false;
-		}
-		$this->createObjFromWMC_xml($doc);
-        $sql = "SELECT wmc_timestamp, wmc_title, wmc_public " . 
-			"FROM mb_user_wmc WHERE wmc_id = $1 AND (fkey_user_id = $2 OR wmc_public = 1)";
-        $v = array($wmcId, Mapbender::session()->get("mb_user_id"));
-        $t = array("s", "i");
-        
-        $res = db_prep_query($sql,$v,$t);
-        if(db_error()) { return false; }
-        if($row = db_fetch_row($res)) {
-          $this->wmc_id = $wmcId;
-          $this->timestamp = $row[0];
-          $this->title = $row[1];
-          $this->public = $row[2];
-        
-        }
-		else {
-			return false;
-		}
-		return true;
-	}
-
-	public function createFromApplication ($appId) {
-		// get the map objects "overview" and "mapframe1"
-		$this->mainMap = map::selectMainMapByApplication($appId);
-		$this->overviewMap = map::selectOverviewMapByApplication($appId);
-		$this->createXml();
-		$this->saveAsFile();
-	}
-
-	/**
-	 * Creates a WMC object from a JS map object {@see map_obj.js}
-	 * 
-	 * @param object $mapObject a map object
-	 * @param integer $user_id the ID of the current user
-	 * @param string $generalTitle the desired title of the WMC
-	 * @param object $extensionData data exclusive to Mapbender, which will be 
-	 * 								mapped into the extension part of the WMC
-	 */
-	public function createFromJs($mapObject, $generalTitle,$extensionData, $id=null) {
-	
-		if (count($mapObject) > 2) {
-			$e = new mb_exception("Save WMC only works for two concurrent map frames (overview plus main) at the moment.");
-		}
-		
-		// set extension data		
-		$this->generalExtensionArray = $extensionData;
-
-		if ($id) {
-			//set id
-			$this->wmc_id = $id;
-		}
-		
-		// set title
-		$this->wmc_title = $generalTitle;
-		
-		// create the map objects
-		for ($i = 0; $i < count($mapObject); $i++) {
-			$currentMap = new Map();
-			$currentMap->createFromJs($mapObject[$i]);
-
-			if (isset($mapObject[$i]->isOverview)) {
-				$this->overviewMap = $currentMap;
-			}
-			else {
-				$this->mainMap = $currentMap;
-			}
-		}
-
-		
-		// create XML
-		$this->createXml();
-
-		$this->saveAsFile();
-		return true;
-	}
-	
-	// ---------------------------------------------------------------------------
-	// DATABASE FUNCTIONS
-	// ---------------------------------------------------------------------------
-	public function getPublicWmcIds () {
-		$sql = "SELECT wmc_id FROM mb_user_wmc ";
-		$sql .= "WHERE wmc_public = 1 GROUP BY wmc_id";
-		$res_wmc = db_query($sql);
-
-  		$wmcArray = array();
-		while($row = db_fetch_array($res_wmc)){
-			array_push($wmcArray, $row["wmc_id"]);
-		}
-		return $wmcArray;
-	}
-
-	public function getAccessibleWmcs ($user) {
-		$wmcArray = array();
-		
-		// get WMC ids 
-		$wmcOwnerArray = $user->getWmcByOwner();
-		
-		$publicWmcIdArray = $this->getPublicWmcIds();
-		
-		return array_keys( array_flip(array_merge($wmcOwnerArray, $publicWmcIdArray)));
-	}
-
-
-
-	public function selectByUser ($user) {
-		$wmcArray = array();
-		
-		// get WMC ids 
-		$wmcOwnerArray = $user->getWmcByOwner();
-		
-		$publicWmcIdArray = self::getPublicWmcIds();
-		
-		$wmcIdArray = array_keys( array_flip(array_merge($wmcOwnerArray, $publicWmcIdArray)));
-
-		// get WMC data
-		$v = array();
-		$t = array();
-		$wmcIdList = "";
-	
-		for ($i = 0; $i < count($wmcIdArray); $i++) {
-			if ($i > 0) { 
-				$wmcIdList .= ",";
-			}
-			$wmcIdList .= "$".($i+1);
-			array_push($v, $wmcIdArray[$i]);
-			array_push($t, 's');
-		}
-	
-		if ($wmcIdList !== "") {
-			$sql = "SELECT DISTINCT wmc_id, wmc_title, wmc_timestamp, wmc_timestamp_create, wmc_public, abstract FROM mb_user_wmc ";
-			$sql .= "WHERE wmc_id IN (" . $wmcIdList . ") ";
-			$sql .=	"ORDER BY wmc_timestamp DESC";
-		
-			$res = db_prep_query($sql, $v, $t);
-			while($row = db_fetch_assoc($res)){
-				$currentResult = array();
-				$currentResult["id"] = $row["wmc_id"];
-				$currentResult["abstract"] = $row["abstract"];
-				$currentResult["title"] = administration::convertIncomingString($row["wmc_title"]);
-				$currentResult["timestamp"] = date("M d Y H:i:s", $row["wmc_timestamp"]); 
-				$currentResult["timestamp_create"] = date("M d Y H:i:s", $row["wmc_timestamp_create"]); 
-				$currentResult["isPublic"] = $row["wmc_public"] == 1? true: false;
-				$currentResult["disabled"] = ((
-					in_array($currentResult["id"], $publicWmcIdArray) && 
-					!in_array($currentResult["id"], $wmcOwnerArray)) || $user->isPublic()) ?
-					true : false;
-					
-				// get categories
-				$currentResult["categories"] = $this->getCategoriesById($currentResult["id"], $user);
-				$currentResult["keywords"] = $this->getKeywordsById($currentResult["id"], $user);
-				array_push($wmcArray, $currentResult);
-			}
-		}
-		return $wmcArray;
-	}
-
-	private function getKeywordsById ($id, $user) {
-		$wmcArray = $this->getAccessibleWmcs($user);
-		if (!in_array($id, $wmcArray)) {
-			return array();
-		}
-		
-		$keywordArray = array();
-		
-		$sql = "SELECT DISTINCT k.keyword FROM keyword AS k, wmc_keyword AS w " . 
-			"WHERE w.fkey_keyword_id = k.keyword_id AND w.fkey_wmc_id = $1";
-		$v = array($id);
-		$t = array("s");
-		$res = db_prep_query($sql, $v, $t);
-		while ($row = db_fetch_array($res)) {
-			$keywordArray[]= $row["keyword"];
-		}
-		return $keywordArray;
-	}
-
-	private function getCategoriesById ($id, $user) {
-		$wmcArray = $this->getAccessibleWmcs($user);
-		if (!in_array($id, $wmcArray)) {
-			return array();
-		}
-		
-		$keywordArray = array();
-		
-		$sql = "SELECT DISTINCT t.md_topic_category_id FROM " . 
-			"md_topic_category AS t, wmc_md_topic_category AS w " . 
-			"WHERE w.fkey_md_topic_category_id = t.md_topic_category_id " . 
-			"AND w.fkey_wmc_id = $1";
-		$v = array($id);
-		$t = array("s");
-		$res = db_prep_query($sql, $v, $t);
-		while ($row = db_fetch_array($res)) {
-			$keywordArray[]= $row["md_topic_category_id"];
-		}
-		return $keywordArray;
-	}
-
-    private function compareWms ($a, $b) {
-		if ($a["id"] === $b["id"]) return 0;
-        return -1;
-    }
-	public function getAllWms () {
-		$wmsArray = $this->mainMap->getWmsArray();
-		$resultObj = array();
-		$usedIds = array();
-		for ($i = 0; $i < count($wmsArray); $i++) {
-			if (in_array($wmsArray[$i]->wms_id, $usedIds)) {
-				continue;
-			}
-			$resultObj[]= array(
-				"title" => $wmsArray[$i]->wms_title, 
-				"id" => is_null($wmsArray[$i]->wms_id) ? null : intval($wmsArray[$i]->wms_id),
-				"index" => $i
-			);
-			$usedIds[]= $wmsArray[$i]->wms_id;
-		}
-		return $resultObj;	
-	}
-
-	public function getWmsWithoutId () {
-		$wmsArray = $this->getAllWms();		
-		$resultObj = array();
-		
-		for ($i = 0; $i < count($wmsArray); $i++) {
-			if (is_numeric($wmsArray[$i]["id"])) {
-				continue;
-			}
-			$resultObj[]= array(
-				"title" => $wmsArray[$i]["title"], 
-				"id" => $wmsArray[$i]["id"],
-				"index" => $i
-			);
-		}
-		return $resultObj;	
-	}
-	
-	public function getWmsWithId () {
-		return array_values(array_udiff(
-			$this->getAllWms(), 
-			$this->getWmsWithoutId(),
-			array("wmc", "compareWms")
-		));
-	}
-	
-	public function getValidWms () {
-		$inv = $this->getInvalidWms();
-		$withId = $this->getWmsWithId();
-		return array_values(array_udiff(
-			$withId, 
-			$inv,
-			array("wmc", "compareWms")
-		));
-	}
-	
-	public function getInvalidWms () {
-		$resultObj = array();
-
-		$wmsArray = $this->getWmsWithId();
-		for ($i = 0; $i < count($wmsArray); $i++) {
-			
-			$sql = "SELECT COUNT(wms_id) FROM wms WHERE wms_id = $1";
-			$v = array($wmsArray[$i]["id"]);
-			$t = array('i');
-			$res = db_prep_query($sql, $v, $t);
-			$layerRow = db_fetch_row($res);
-			if (intval($layerRow[0]) === 0) {
-				$resultObj[]= array(
-					"title" => $wmsArray[$i]["title"], 
-					"id" => intval($wmsArray[$i]["id"]),
-					"index" => $wmsArray[$i]["index"]
-				);
-			}		
-		}
-		return $resultObj;
-	}
-	
-	public function getWmsWithPermission ($user) {
-		$wmsArray = $this->getValidWms();		
-		$resultObj = array();
-
-		for ($i = 0; $i < count($wmsArray); $i++) {
-			$currentWmsId = intval($wmsArray[$i]["id"]);
-
-			if ($user->isWmsAccessible($currentWmsId)) {
-				$resultObj[]= array(
-					"title" => $wmsArray[$i]["title"], 
-					"id" => intval($currentWmsId),
-					"index" => $wmsArray[$i]["index"]
-				);
-			}			
-		}
-		return $resultObj;	
-	}
-	
-	public function getWmsWithoutPermission ($user) {
-		return array_values(array_udiff(
-			$this->getValidWms(), 
-			$this->getWmsWithPermission($user),
-			array("wmc", "compareWms")
-		));
-	}
-	
-	public function getAvailableWms ($user) {
-		return array_values(array_udiff(
-			$this->getWmsWithPermission($user), 
-			$this->getUnavailableWms(),
-			array("wmc", "compareWms")
-		));
-	}
-	
-	public function getUnavailableWms ($user) {
-		$wmsArray = $this->getWmsWithPermission($user);
-		$resultObj = array();
-		
-		for ($i = 0; $i < count($wmsArray); $i++) {
-			$currentWmsId = $wmsArray[$i]["id"];
-
-			$sql = "SELECT last_status FROM mb_wms_availability WHERE fkey_wms_id = $1"; 
-			$v = array($currentWmsId);
-			$t = array("i");
-			$res = db_prep_query($sql, $v, $t);
-			$statusRow = db_fetch_row($res);
-			$status = intval($statusRow[0]);
-			if (isset($status) && $status < 0) {
-				$resultObj[]= array(
-					"title" => $wmsArray[$i]["title"], 
-					"id" => $currentWmsId,
-					"index" => $wmsArray[$i]["index"]
-				);
-			}
-		}
-		return $resultObj;		
-	}
-
-	public function updateUrlsFromDb () {
-		$query_mbWMSId = "/wmc:ViewContext/wmc:LayerList/wmc:Layer/wmc:Extension/mapbender:wms_id";
-		try {
-			$WMCDoc = DOMDocument::loadXML($this->toXml());
-		} 
-		catch (Exception $E) {
-			new mb_exception("WMC XML is broken.");
-		}   
-		
-		$xpath = new DOMXPath($WMCDoc);
-		$xpath->registerNamespace("wmc","http://www.opengis.net/context");
-		$xpath->registerNamespace("mapbender","http://www.mapbender.org/context");
-		$xpath->registerNamespace("xlink","http://www.w3.org/1999/xlink");
-		
-		$WMSIdList = $xpath->query($query_mbWMSId);
-		foreach($WMSIdList as $WMSId) {
-			$id =  $WMSId->nodeValue;
-			$sql = "SELECT wms_timestamp,wms_getmap,wms_getlegendurl " . 
-				"FROM wms WHERE wms_id = $1 AND " . 
-				"wms_owsproxy <> NULL AND wms_owsproxy <> ''";
-			$v = array($id);
-			$t = array("t");
-			
-			$res = db_prep_query($sql,$v,$t);
-			if (db_error()) {
-				true; 
-			} //FIMXE: PROPER ERROR MESSAGE
-			
-			if($row = db_fetch_array($res)) {
-				$wms_timestamp = $row["wms_timestamp"];
-				if ($this->timestamp < $wms_timestamp) {
-				// wmc is fresh, life is good
-				}
-				else{
-					$MapResources = $xpath->query("../../wmc:Server/wmc:OnlineResource",$WMSId);
-					foreach($MapResources as $MapResource) {
-						$MapResource->setAttribute("xlink:href",$row["wms_getmap"]);
-					}
-					
-					$LegendResources = $xpath->query("../../wmc:StyleList/wmc:Style/wmc:LegendURL/wmc:OnlineResource",$WMSId);
-					foreach ($LegendResources as $LegendResource) {
-						$base = $row["wms_getlegendurl"];
-						$origurl = explode('&', $LegendResource->getAttribute("xlink:href"),2);
-						$url = $base . $origurl[1]; 
-						$LegendResource->setAttribute("xlink:href",$url);
-					}
-				}
-			}
-		}
-		$updatedWMC = $WMCDoc->saveXML();
-		$this->update_existing($updatedWMC,$wmsId);
-		return $updatedWMC;
-	}
-
-	/**
-	 * Stores this WMC in the database. The WMC has to be instantiated first, see above.
-	 * 
-	 * @return mixed[] an assoc array with attributes "success" (boolean) and "message" (String).
-	 */
-	public function insert ($overwrite) {
-		$result = array();
-		
-		if ($this->userId && $this->xml && $this->wmc_title) {
-			try {
-				$user = new user($this->userId);
-			} 
-			catch (Exception $E) {
-				$errMsg = "Error while saving WMC document " . $this->wmc_title . "': Invalud UserId";
-				$result["success"] = false;
-				$result["message"] = $errMsg;
-				$e = new mb_exception("mod_insertWMCIntoDB: " . $errMsg);
-				return $result;
-			}
-		
-			$overwrite  = ($user->isPublic())? false: $overwrite;
-		
-			//put keywords into Document
-			try {
-				$WMCDoc = DOMDocument::loadXML($this->toXml());
-			} 
-			catch (Exception $E) {
-				new mb_exception("WMC XML is broken.");
-			}   
-
-			$NewDoc = new DOMDocument();
-		   
-			$xpath = new DOMXPath($WMCDoc);
-			$xpath->registerNamespace("wmc","http://www.opengis.net/context");
-			$xpath->registerNamespace("mapbender","http://www.mapbender.org/context");
-			$xpath->registerNamespace("xlink","http://www.w3.org/1999/xlink");
-
-			$query_KeywordList = "/wmc:ViewContext/wmc:General/wmc:KeywordList";
-			$query_general = "/wmc:ViewContext/wmc:General";
-			$DocKeywordLists = $xpath->query($query_KeywordList);
-			// we just use a single <general> element
-			
-			$NewKeywordList = new DOMElement('KeywordList','','http://opengis.net/context');
-			$NewDoc->appendChild($NewKeywordList);
-	 		foreach($this->keyword as $keyword){
-				$Keyword = new DOMElement('Keyword',$keyword, 'http://opengis.net/context');
-				$NewKeywordList->appendChild($Keyword);
-			}
-			
-			$generalList = $xpath->query($query_general);	
-			$general = $generalList->item(0);
-			if($DocKeywordLists->item(0)){
-				$general->replaceChild($NewKeywordList,$DocKeywordList->item(0));
-			}else{
-				$tmpNode = $WMCDoc->importNode($NewKeywordList,true);
-				$general->appendChild($tmpNode);
-
-			}
-			
-			$this->xml  = $WMCDoc->saveXML();
-			
-			db_begin();
-		
-			if($overwrite) {
-		
-	            $findsql = "SELECT fkey_user_id,wmc_title,wmc_timestamp, wmc_id FROM mb_user_wmc WHERE fkey_user_id = $1 AND wmc_id = $2 ORDER BY wmc_timestamp DESC LIMIT 1;";
-	            $v = array($this->userId, $this->wmc_id);
-	            $t = array("i","i");
-	        
-	            $res = db_prep_query($findsql,$v,$t);
-				if (db_error()) {
-					$errMsg = "Error while saving WMC document '" . $this->wmc_title . "': " . db_error();
-					$result["success"] = false;
-					$result["message"] = $errMsg;
-					$e = new mb_exception("mod_insertWMCIntoDB: " . $errMsg);
-	                return $result;
-				}
-	
-	            if($row = db_fetch_row($res)) {
-					$sql = "UPDATE mb_user_wmc SET wmc = $1, wmc_timestamp = $2, abstract = $3, srs = $4, minx = $5, miny = $6,".
-						" maxx = $7, maxy = $8, wmc_title = $9 WHERE fkey_user_id = $10 AND wmc_id=$11 AND wmc_timestamp = $12;";
-					$v = array($this->xml, time(), $this->wmc_abstract, $this->wmc_srs, $this->wmc_extent->minx, $this->wmc_extent->minx,
-						 $this->wmc_extent->maxx, $this->wmc_extent->maxy ,administration::convertOutgoingString($this->wmc_title), $this->userId, $this->wmc_id,$row[2]);
-					$t = array("s", "s","s","s","i","i","i","i", "s", "i", "i","s");
-					// need the database Id
-					$wmc_DB_ID = $row[3];
-					$delsql = "DELETE FROM wmc_md_topic_category WHERE fkey_wmc_id = $1;";
-					$delv = array($wmc_DB_ID);
-					$delt = array("s");
-					db_prep_query($delsql, $delv,$delt);
-						
-					$delkwsql = "DELETE FROM wmc_keyword WHERE fkey_wmc_id = $1;";
-					$delkwv = array($wmc_DB_ID);
-					$delkwt = array("s");
-					db_prep_query($delkwsql, $delkwv,$delkwt);
-						
-					
-					
-				}
-				else{
-					$sql = "INSERT INTO mb_user_wmc (" . 
-						"wmc_id, fkey_user_id, wmc, wmc_title, wmc_public, wmc_timestamp, wmc_timestamp_create, " . 
-						"abstract, srs, minx, miny, maxx, maxy ".
-						") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13);";
-					$v = array($this->wmc_id, $this->userId, $this->xml, administration::convertOutgoingString($this->wmc_title), $user->isPublic()?1:0,time(),time(),
-						$this->wmc_abstract, $this->wmc_srs, $this->wmc_extent->minx,  $this->wmc_extent->miny, $this->wmc_extent->maxx, $this->wmc_extent->maxy);
-					$t = array("s", "i", "s", "s", "i", "s","s", "s","s","i","i","i", "i");
-				}
-			}
-			else{
-				
-				$sql = "INSERT INTO mb_user_wmc (" . 
-					"wmc_id, fkey_user_id, wmc, wmc_title, wmc_public, wmc_timestamp, wmc_timestamp_create, " . 
-					"abstract, srs, minx, miny, maxx, maxy ".
-					") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13);";
-				$v = array($this->wmc_id, $this->userId, $this->xml, administration::convertOutgoingString($this->wmc_title), $user->isPublic()?1:0, time(),time(),
-						$this->wmc_abstract, $this->wmc_srs, $this->wmc_extent->minx,  $this->wmc_extent->miny, $this->wmc_extent->maxx, $this->wmc_extent->maxy);
-				$t = array("s", "i", "s", "s", "i", "s","s", "s","s","i","i","i", "i");
-				
-			}
-			
-		
-			  $res = db_prep_query($sql, $v, $t);
-			  if (db_error()) {
-				  $errMsg = "Error while saving WMC document '" . $this->wmc_title . "': " . db_error();
-				  $result["success"] = false;
-				  $result["message"] = $errMsg;
-				  $e = new mb_exception("mod_insertWMCIntoDB: " . $errMsg);
-			  }
-			  else {
-				  
-				// because the wmc id is created each time a wmc is instantiated $this->wmc_id has nothing to do with the database wmc_id
-				// this is some duct tape to fix it :-(
-				// see also above where wmc_DB_ID is defined if we need to update
-				if(!isset($wmc_DB_ID)) { $wmc_DB_ID = $this->wmc_id; }
-				
-				// update keywords
-			  	foreach($this->keyword as $keyword){
-
-					// if a keyword does not yet exist, create it
-			  		$keywordExistsSql = "SELECT keyword FROM keyword WHERE keyword = $1";
-				 	$keywordCreateSql = "INSERT INTO keyword (keyword) VALUES($1);"; 
-				 	$v = array($keyword);
-				 	$t = array("s");
-				 	$res =  db_prep_query($keywordExistsSql,$v,$t);
-				 	if(db_num_rows($res) == 0){
-						$res = db_prep_query($keywordCreateSql,$v,$t);
-				 		if($a = db_error()){
-				 		}
-				 	}	
-			
-						
-	
-					$keywordsql = "INSERT INTO wmc_keyword (fkey_keyword_id,fkey_wmc_id) SELECT keyword.keyword_id,$1 FROM keyword WHERE keyword = $2 AND NOT EXISTS (SELECT fkey_wmc_id FROM wmc_keyword	WHERE fkey_wmc_id = $3 );";
-					$v = array($wmc_DB_ID, $keyword,$wmc_DB_ID);
-					$t = array("s","s","s");
-					$res = db_prep_query($keywordsql, $v, $t);
-					if($a = db_error()){
-					}
-				  
-				}
-				// update categories
-				$this->inspireCats = $this->inspireCats? $this->inspireCats: array();
-				foreach($this->inspireCats as $catId)
-				{
-
-					$catSql = "INSERT INTO wmc_md_topic_category (fkey_wmc_id, fkey_md_topic_category_id) VALUES ($1,$2)";
-					$v = array($wmc_DB_ID, $catId);
-					$t = array("s","s");
-					$res = db_prep_query($catSql, $v, $t);
-		
-				}
-	  
-				  $result["success"] = true;
-				  $msg = "WMC document '" . $this->wmc_title . "' has been saved.";
-				  $result["message"] = $msg;
-				  $e = new mb_notice("mod_insertWMCIntoDB: WMC  '" . $this->wmc_title . "' saved successfully.");
-			  }
-		}
-		else {
-			$result["success"] = false;
-			$errMsg = "missing parameters (user_id: ".$this->userId.", title: " . $this->wmc_title . ")";
-			$result["message"] = $errMsg;
-			$e = new mb_exception("mod_insertWMCIntoDB: " . $errMsg .")");
-		}
-        db_commit();
-		return $result;
-	}
-    
-
-    /*
-    * overwrites an exact version of a wmc in the database
-    */
-    public function update_existing($xml,$id)
-    {
-      $sql = "UPDATE mb_user_wmc SET wmc = $1 WHERE wmc_id = $2";
-      $v = array($xml,$id);
-      $t = array("s","i");
-      $res = db_prep_query($sql,$v,$t);
-      if(db_error()) { $e = new mb_exception("There was an error saving an updated WMC"); }
-    }
-	
-	/**
-	 * deletes a {@link http://www.mapbender.org/index.php/WMC 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 successful?
-	 */
-	public static function delete ($wmcId, $userId) {
-		if (!isset($userId) || $userId === null) {
-			$userId = Mapbender::session()->get("mb_user_id");
-		}
-
-        try {
-          $user = new user($userId);
-        } catch (Exception $E) {
-          return $false;
-        }
-        
-        if($user->isPublic())
-        {
-            return $false;
-        }
-
-		$sql = "DELETE FROM mb_user_wmc ";
-		$sql .= "WHERE fkey_user_id = $1 AND wmc_id = $2";
-		$v = array($userId, $wmcId);
-		$t = array('i', 's');
-		$res = db_prep_query($sql, $v, $t);
-		if ($res) {
-			return true;
-		}
-		return false;
-	}
-
-	/**
-	 * Returns a WMC document
-	 * @return String|boolean The document if it exists; else false
-	 * @param $id String the WMC id
-	 */
-	public static function getDocument ($id) {
-		$sql = "SELECT wmc FROM mb_user_wmc WHERE wmc_id = $1 AND " . 
-			"(fkey_user_id = $2 OR wmc_public = 1)";
-		$v = array($id, Mapbender::session()->get("mb_user_id"));
-		$t = array('s', 'i');
-		$res = db_prep_query($sql,$v,$t);
-		$row = db_fetch_array($res);
-		if ($row) {
-			return $row["wmc"];
-		}
-		return false;
-	}
-
-	/**
-	 * Returns a WMC document
-	 * @return String|boolean The document if it exists; else false
-	 * @param $id String the WMC id
-	 */
-	public static function getDocumentByTitle ($title) {
-		$sql = "SELECT wmc FROM mb_user_wmc WHERE wmc_title = $1 AND " . 
-			"(fkey_user_id = $2 OR wmc_public = 1)";
-		$v = array($title, Mapbender::session()->get("mb_user_id"));
-		$t = array('s', 'i');
-		$res = db_prep_query($sql,$v,$t);
-		$row = db_fetch_array($res);
-		if ($row) {
-			return $row["wmc"];
-		}
-		return false;
-	}
-
-    /*
-    * sets the WMC's public flag
-    * @param $public boolean wether access should be public
-    */
-    public function setPublic($public)
-    {
-	  $currentUser = new User(Mapbender::session()->get("mb_user_id"));
-	  if ($currentUser->isPublic()) {
-			return false;
-	  }
-      $wmcId = $this->wmc_Id;
-      $public = $public ? 1 :0;
-      $sql = "UPDATE mb_user_wmc SET wmc_public = $1 WHERE wmc_id = $2 AND fkey_user_id = $3;";
-      $v = array($public,$wmcId, $currentUser->id);
-      $t = array("i","s","i");
-      $res = db_prep_query($sql,$v,$t);
-      if(db_error()){
-        return false;
-      }
-      return true;
-    }
-	// ---------------------------------------------------------------------------
-	// GETTER FUNCTIONS
-	// ---------------------------------------------------------------------------
-	
-	/**
-	 * @return string the title of the WMC.
-	 */
-	public function getTitle() {
-		return $this->wmc_title;
-	}
-
-	private function getLayerWithoutIdArray () {
-		$layerWithoutWmsIdArray = array();
-		$layerWithoutLayerIdArray = array();
-		
-		// check if WMS IDs exist
-		$wmsArray = $this->mainMap->getWmsArray();
-		for ($i = 0; $i < count($wmsArray); $i++) {
-			$currentWms = $wmsArray[$i];		
-			if (!is_numeric($currentWms[$currentId])) {
-				array_push($layerWithoutWmsIdArray, $currentId);
-			}
-		}
-		
-		// check if layer IDs exist
-		for ($i = 0; $i < count($layerIdArray); $i++) {
-			$currentId = $layerIdArray[$i];
-			if (!is_numeric($this->wmc_layer_id[$currentId])) {
-				array_push($layerWithoutLayerIdArray, $currentId);
-			}
-		}
-		$noIdArray = array_unique(array_merge($layerWithoutWmsIdArray, $layerWithoutLayerIdArray));
-		return $noIdArray;
-	}
-
-
-	// ---------------------------------------------------------------------------
-	// OUTPUT FUNCTIONS
-	// ---------------------------------------------------------------------------
-	
-	/**
-	 * Wrapper function, returns XML at the moment
-	 * @return String
-	 */
-	public function __toString() {
-		return $this->toXml();
-	}
-
-	/**
-	 * Returns the XML document if available
-	 * 
-	 * @return String The XML document; if unavailable, null is returned.
-	 */
-	public function toXml () {
-//		if (!$this->xml) {
-			$this->createXml();
-//		}
-		return $this->xml;
-	}
-
-	private function incrementLoadCount ($wms) {
-		// counts how often a layer has been loaded
-		$monitor = new Layer_load_count();
-		foreach ($wms->objLayer as $l) {
-			$monitor->increment($l->layer_uid);
-		}
-	}
-
-	public function wmsToJavaScript() {
-		$wmsArray = $this->mainMap->getWmsArray();
-
-		$wmcJsArray = array();
-		for ($i = 0; $i < count($wmsArray); $i++) {
-			$currentWms = $wmsArray[$i];
-	
-			$wmcJsArray[] = $currentWms->createJsObjFromWMS_();
-			$this->incrementLoadCount($currentWms);
-		}
-		return $wmcJsArray;
-	}
-	
-	public function featuretypeConfToJavaScript() {
-		$wfsConfIds = $this->generalExtensionArray['WFSCONFIDSTRING'];
-		$featuretypeConfs = array();
-		$featuretypeConfArray = is_string($wfsConfIds) ? 
-			explode(",", $wfsConfIds) : array();
-		for ($i = 0; $i < count($featuretypeConfArray); $i++) {
-			$featuretypeConf = WfsConfiguration::createFromDb($featuretypeConfArray[$i]);
-			array_push($featuretypeConfs,$featuretypeConf);
-		}
-		$featuretypeConfObj = new Mapbender_JSON();
-		$featuretypeConfObj = $featuretypeConfObj->encode($featuretypeConfs);
-		return $featuretypeConfObj;
-	}
-	/**
-	 * Returns an array of JavaScript statements
-	 * 
-	 * @return String[]
-	 */
-	public function toJavaScript () {
-		$skipWmsArray = array();
-		if (func_num_args() === 1) {
-			$skipWmsArray = func_get_arg(0);
-		}
-
-		// will contain the JS code to create the maps
-		// representing the state stored in this WMC
-		$wmcJsArray = array();
-		
-		// set general extension data
-		if (count($this->generalExtensionArray) > 0) {
-			$json = new Mapbender_JSON();
-			array_push($wmcJsArray, "restoredWmcExtensionData = " . $json->encode($this->generalExtensionArray) . ";"); 
-		}
-		
-		// reset WMS data
-		array_push($wmcJsArray, "wms = [];");
-		array_push($wmcJsArray, "wms_layer_count = 0;");
-
-		// add WMS for main map frame
-		$wmsArray = $this->mainMap->getWmsArray();
-
-		// find the WMS in the main map which is equal to the WMS
-		// in the overview map
-		$overviewWmsIndex = null;
-		$ovWmsArray = array();
-		if ($this->overviewMap !== null) {
-			$ovWmsArray = $this->overviewMap->getWmsArray();
-			$overviewWmsIndex = 0;
-			for ($i = 0; $i < count($ovWmsArray); $i++) {
-				for ($j = 0; $j < count($wmsArray); $j++) {
-					if ($ovWmsArray[$i]->equals($wmsArray[$j]) && !in_array($j, $skipWmsArray)) {
-						$overviewWmsIndex = $j;	
-						$wmsIndexOverview = $i;					
-						break;
-					}
-				}
-			}
-		}
-
-		// for all wms...
-		for ($i = 0; $i < count($wmsArray); $i++) {
-			if (in_array($i, $skipWmsArray)) {
-				continue;
-			}
-			array_push($wmcJsArray, $wmsArray[$i]->createJsObjFromWMS_());
-			$this->incrementLoadCount($wmsArray[$i]);
-		}
-		
-		// delete existing map objects...
-//		array_push($wmcJsArray, "mb_mapObj = [];");
-
-		// .. and add the overview map (if exists) and set map request
-		if ($this->overviewMap !== null) {
-			$wmcJsArray = array_merge(
-				$wmcJsArray, 
-				$this->overviewMap->toJavaScript(
-					"{wms:wms,wmsIndexOverview:" . $overviewWmsIndex . "}"
-				)
-			);
-		}
-
-		// .. and add main map ..
-		$wmcJsArray = array_merge(
-			$wmcJsArray, 
-			$this->mainMap->toJavaScript(
-				"{wms:wms,wmsIndexOverview:null}"
-			)
-		);
-
-		// set visibility of ov map WMS (may be different from main)
-		if ($this->overviewMap !== null) {
-			for ($i = 0; $i < count($ovWmsArray[$wmsIndexOverview]->objLayer); $i++) {
-				$visStr = "Mapbender.modules['".$this->overviewMap->getFrameName().
-//					"'].wms[" .$wmsIndexOverview . "].handleLayer(" . 
-// The above doesn't work.
-// But there is only one WMS in the overview anyway! The index 0 is hard wired for now.
-					"'].wms[0].handleLayer(" . 
-					"'" . $ovWmsArray[$wmsIndexOverview]->objLayer[$i]->layer_name . "', " . 
-					"'visible', " . 
-					($ovWmsArray[$wmsIndexOverview]->objLayer[$i]->gui_layer_visible ? 1 : 0) . ");";
-				array_push($wmcJsArray, $visStr);
-			}
-			array_push($wmcJsArray, "Mapbender.modules['".$this->overviewMap->getFrameName().
-					"'].restateLayers(" . $ovWmsArray[$wmsIndexOverview]->wms_id . ");");
-		}
-
-		// .. request the map
-		array_push($wmcJsArray, "Mapbender.modules['".$this->mainMap->getFrameName().
-					"'].setMapRequest();");
-		if ($this->overviewMap !== null) {
-			array_push($wmcJsArray, "Mapbender.modules['".$this->overviewMap->getFrameName().
-					"'].setMapRequest();");
-		}
-
-		array_push($wmcJsArray, "eventAfterLoadWMS.trigger();");
-		return $wmcJsArray;
-	}
-	
-	// ------------------------------------------------------------------------
-	// manipulation
-	// ------------------------------------------------------------------------
-	/**
-	 * Merges this WMC with another WMC.
-	 * The settings of the other WMC overwrite the settings of this WMC.
-	 * 
-	 * @return void
-	 * @param $xml2 Object
-	 */
-	public function merge ($xml2) {
-		$someWmc = new wmc();
-		$someWmc->createFromXml($xml2);
-
-		$this->mainMap->merge($someWmc->mainMap);
-		if (isset($this->overviewMap) && isset($someWmc->overviewMap)) {
-			$this->overviewMap->merge($someWmc->overviewMap);
-		}
-	}
-
-	/**
-	 * Appends the layers of another WMC to this WMC.
-	 * 
-	 * @return void
-	 * @param $xml2 Object
-	 */
-	public function append ($xml2) {
-		$someWmc = new wmc();
-		$someWmc->createFromXml($xml2);
-
-		$this->mainMap->append($someWmc->mainMap);
-		if (isset($this->overviewMap) && isset($someWmc->overviewMap)) {
-			// There is only one WMS in the overview map; merge, not append
-			$this->overviewMap->merge($someWmc->overviewMap);
-		}
-	}
-
-	/**
-	 * Adds a WMS to this WMC
-	 * 
-	 * @return 
-	 */
-	public function appendWmsArray ($wmsArray) {
-		return $this->mainMap->appendWmsArray($wmsArray);
-	}
-	
-	/**
-	 * Merges a WMS into this WMC
-	 * 
-	 * @return 
-	 */
-	public function mergeWmsArray ($wmsArray) {
-		if (func_num_args() > 1) {
-			$options = func_get_arg(1);
-			$this->mainMap->mergeWmsArray($wmsArray, $options);
-		}
-		return $this->mainMap->mergeWmsArray($wmsArray);
-	}
-
-// ---------------------------------------------------------------------------
-// private functions
-// ---------------------------------------------------------------------------
-
-	/**
-	 * Loads a WMC from an actual WMC XML document.
-	 * Uses WMS class.
-	 * 
-	 * @param string $data the data from the XML file
-	 */
-	protected function createObjFromWMC_xml($data){
-		// store xml 
-		$this->xml = $data;
-	
-		$values = administration::parseXml($data);
-
-		//
-		// Local variables that indicate which section of the WMC
-		// is currently parsed.
-		//
-		$extension = false;		$general = false;		$layerlist = false;
-		$layer = false;  		$formatlist = false;	$dataurl = false;
-		$metadataurl = false; 	$stylelist = false;
-
-		//
-		// reset WMC data
-		//
-		$this->mainMap = new Map();
-		$this->overviewMap = null;
-		$this->generalExtensionArray = array();
-		
-		$layerlistArray = array();
-		$layerlistArray["main"] = array();
-		$layerlistArray["overview"] = array();
-
-		foreach ($values as $element) {
-			$tag = strtoupper(administration::sepNameSpace($element[tag]));
-			$tagLowerCase = administration::sepNameSpace($element[tag]);
-			$type = $element[type];
-			$attributes = $element[attributes];
-			$value = mb_utf8_decode(html_entity_decode($element[value]));
-			
-			if ($tag == "VIEWCONTEXT" && $type == "open") {
-				$this->wmc_id = $attributes["id"];
-				$this->wmc_version = $attributes["version"];
-			}
-			if ($tag == "GENERAL" && $type == "open") {
-				$general = true;
-			}
-			if ($tag == "LAYERLIST" && $type == "open") {
-				$layerlist = true;
-			}
-			if ($general) {
-				if ($tag == "WINDOW") {
-					$this->mainMap->setWidth($attributes["width"]);
-					$this->mainMap->setHeight($attributes["height"]);
-				}
-				if ($tag == "BOUNDINGBOX") {
-					$bbox = new Mapbender_bbox($attributes["minx"], $attributes["miny"], $attributes["maxx"], $attributes["maxy"], $attributes["SRS"]);
-					$this->mainMap->setExtent($bbox);
-				}
-				if ($tag == "NAME") {
-					$this->wmc_name = $value;
-				}
-				if ($tag == "TITLE") {
-					$this->wmc_title = $value;
-				}
-				if ($tag == "ABSTRACT") {
-					$this->wmc_abstract = $value;
-				}
-				if ($tag == "CONTACTINFORMATION" && $type == "open") {
-					$contactinformation = true;
-				}
-				if ($contactinformation) {
-					if ($tag == "CONTACTPOSITION") {
-						$this->wmc_contactposition = $value;
-					}
-					if ($tag == "CONTACTVOICETELEPHONE") {
-						$this->wmc_contactvoicetelephone = $value;
-					}
-					if ($tag == "CONTACTFACSIMILETELEPHONE") {
-						$this->wmc_contactfacsimiletelephone = $value;
-					}
-					if ($tag == "CONTACTELECTRONICMAILADDRESS") {
-						$this->wmc_contactemail = $value;
-					}
-					if ($tag == "CONTACTPERSONPRIMARY" && $type == "open") {
-						$contactpersonprimary = true;
-					}
-					if ($contactpersonprimary) {
-						if ($tag == "CONTACTPERSON") {
-							$this->wmc_contactperson = $value;
-						}
-						if ($tag == "CONTACTORGANIZATION") {
-							$this->wmc_contactorganization = $value;;
-						}
-						if ($tag == "CONTACTPERSONPRIMARY" && $type == "close") {
-							$contactpersonprimary = false;
-						}
-					}
-					if ($tag == "CONTACTADDRESS" && $type == "open") {
-						$contactaddress = true;
-					}
-					if ($contactaddress) {
-						if ($tag == "ADDRESSTYPE") {
-							$this->wmc_contactaddresstype = $value;
-						}
-						if ($tag == "ADDRESS") {
-							$this->wmc_contactaddress = $value;
-						}
-						if ($tag == "CITY") {
-							$this->wmc_contactcity = $value;
-						}
-						if ($tag == "STATEORPROVINCE") {
-							$this->wmc_contactstateorprovince = $value;
-						}
-						if ($tag == "POSTCODE"){
-							$this->wmc_contactpostcode = $value;
-						}
-						if ($tag == "COUNTRY") {
-							$this->wmc_contactcountry = $value;
-						}
-						if ($tag == "CONTACTADDRESS" && $type == "close") {
-							$contactaddress = false;
-						}
-					}
-				}
-				if ($tag == "LOGOURL" && $type == "open") {
-						$logourl = true;
-						$this->wmc_logourl_width = $attributes["width"];
-						$this->wmc_logourl_height = $attributes["height"];
-						$this->wmc_logourl_format = $attributes["format"];
-				}
-				if ($logourl) {
-					if ($tag == "LOGOURL" && $type == "close") {
-						$logourl = false;
-					}
-					if ($tag == "ONLINERESOURCE") {
-						$this->wmc_logourl_type = $attributes["xlink:type"];
-						$this->wmc_logourl = $attributes["xlink:href"];
-					}
-				}
-				if ($tag == "DESCRIPTIONURL" && $type == "open") {
-						$descriptionurl = true;
-						$this->wmc_descriptionurl_format = $attributes["format"];
-				}
-				if ($descriptionurl) {
-					if ($tag == "DESCRIPTIONURL" && $type == "close"){
-						$descriptionurl = false;
-					}
-					if ($tag == "ONLINERESOURCE") {
-						$this->wmc_descriptionurl_type = $attributes["xlink:type"];
-						$this->wmc_descriptionurl = $attributes["xlink:href"];
-					}
-				}
-				if ($tag == "KEYWORDLIST" && $type == "open") {
-					$keywordlist = true;
-				}
-				if ($keywordlist) {
-					if ($tag == "KEYWORDLIST" && $type == "close") {
-						$keywordlist = false;
-						$cnt_keyword = -1;
-					}
-					if ($tag == "KEYWORD") {
-						$cnt_keyword++;
-						$this->wmc_keyword[$cnt_keyword] = $value;
-					}
-				}
-				if ($tag == "EXTENSION" && $type == "close") {
-					$generalExtension = false;
-					//
-					// After the general extension tag is closed,
-					// we have all necessary information to CREATE
-					// the map objects that are contained in this
-					// WMC.
-					//
-					$this->setMapData();
-				}
-				if ($generalExtension) {
-					if ($value !== "") {
-						if (isset($this->generalExtensionArray[$tag])) {
-							if (!is_array($this->generalExtensionArray[$tag])) {
-								$firstValue = $this->generalExtensionArray[$tag];
-								$this->generalExtensionArray[$tag] = array();
-								array_push($this->generalExtensionArray[$tag], $firstValue);
-							}	
-							array_push($this->generalExtensionArray[$tag], $value);
-						}
-						else {
-							$this->generalExtensionArray[$tag] = $value;									
-						}
-					}
-				}
-				if ($tag == "EXTENSION" && $type == "open") {
-					$generalExtension = true;
-				}
-				if ($tag == "GENERAL" && $type == "close") {
-		   			$general = false;
-			 	}
-			}
-			if ($layerlist) {
-				if ($tag == "LAYERLIST" && $type == "close") {
-				   $layerlist = false;
-				}
-				if ($tag == "LAYER" && $type == "open") {
-					//
-					// The associative array currentLayer holds all 
-					// data of the currently processed layer.
-					// The data will be set in the classes' WMS
-					// object when the layer tag is closed.
-					//
-					$currentLayer = array();
-					
-					$currentLayer["queryable"] = $attributes["queryable"];
-					if ($attributes["hidden"] == "1") {
-						$currentLayer["visible"] = 0;
-					}
-					else {
-						$currentLayer["visible"] = 1;
-					}
-					$currentLayer["format"] = array();
-					$currentLayer["style"] = array();
-					$layer = true;
-				}
-				if ($layer) {
-					if ($tag == "LAYER" && $type == "close") {
-
-						//
-						// After a layer tag is closed,
-						// we have all necessary information to CREATE
-						// a layer object and append it to the WMS object
-						//
-						if (isset($currentLayer["extension"]["OVERVIEWHIDDEN"])) {
-							array_push($layerlistArray["overview"], $currentLayer);		
-						}
-						$modifiedLayer = $currentLayer;
-						unset($modifiedLayer["extension"]["OVERVIEWHIDDEN"]);
-						array_push($layerlistArray["main"], $modifiedLayer);											
-				 		$layer = false;
-					}
-					if ($formatlist) {
-						if ($tag == "FORMAT") {
-						 	array_push($currentLayer["format"], array("current" => $attributes["current"], "name" => $value));
-							if ($attributes["current"] == "1") {
-								$currentLayer["formatIndex"] = count($currentLayer["format"]) - 1;
-							}
-						 }
-						 if ($tag == "FORMATLIST" && $type == "close") {
-							 $formatlist = false;
-						 }
-					 }
-					 elseif ($metadataurl) {
-						if ($tag == "ONLINERESOURCE") {
-							$currentLayer["metadataurl"] = $attributes["xlink:href"];
-						}
-						if ($tag == "METADATAURL" && $type == "close") {
-							$metadataurl = false;
-						}
-					 }
-					 elseif ($dataurl) {
-						if ($tag == "ONLINERESOURCE") {
-						 	$currentLayer["dataurl"] = $attributes["xlink:href"];
-						}
-						 if ($tag == "DATAURL" && $type == "close") {
-							$dataurl = false;
-						 }
-					 }
-					 elseif ($stylelist) {
-						if ($style) {
-							$index = count($currentLayer["style"]) - 1;
-							if ($tag == "STYLE" && $type == "close") {
-								$style = false;
-							}
-							if ($tag == "SLD" && $type == "open") {
-								$sld = true;
-							}
-							if ($sld) {
-								if ($tag == "SLD" && $type == "close") {
-									$sld = false;
-								}
-								if ($tag == "ONLINERESOURCE") {
-									$currentLayer["style"][$index]["sld_type"] = $attributes["xlink:type"];
-									$currentLayer["style"][$index]["sld_url"] = $attributes["xlink:href"];
-								}
-								if ($tag == "TITLE") {
-									$currentLayer["style"][$index]["sld_title"] = $value;
-								}
-							}
-							else {
-								if ($tag == "NAME"){
-									$currentLayer["style"][$index]["name"] = $value ? $value : "default";
-								}
-								if ($tag == "TITLE") {
-									$currentLayer["style"][$index]["title"] = $value ? $value : "default";
-								}
-								if ($legendurl) {
-									if ($tag == "LEGENDURL" && $type == "close") {
-										$legendurl = false;
-									}
-									if ($tag == "ONLINERESOURCE") {
-									 	$currentLayer["style"][$index]["legendurl_type"] = $attributes["xlink:type"];
-									 	$currentLayer["style"][$index]["legendurl"] = $attributes["xlink:href"];
-									}
-								}
-								if ($tag == "LEGENDURL" && $type == "open") {
-								 	$legendurl = true;
-								 	$currentLayer["style"][$index]["legendurl_width"] = $attributes["width"];
-								 	$currentLayer["style"][$index]["legendurl_height"] = $attributes["height"];
-								 	$currentLayer["style"][$index]["legendurl_format"] = $attributes["format"];
-								}
-							}
-						}
-						if ($tag == "STYLE" && $type == "open") {
-							$style = true;
-							array_push($currentLayer["style"], array("current" => $attributes["current"]));
-							if ($attributes["current"] == "1") {
-								$currentLayer["styleIndex"] = count($currentLayer["style"]) - 1;
-							}
-						}
-						if ($tag == "STYLELIST" && $type == "close") {
-							$stylelist = false;
-						}
-					}
-					else {
-						if ($tag == "SERVER" && $type == "open") {
-							 $server = true;
-							 $currentLayer["service"] = $attributes["service"];
-							 $currentLayer["version"] = $attributes["version"];
-							 $currentLayer["wms_title"] = $attributes["title"];
-						}
-						if ($server) {
-							if ($tag == "SERVER" && $type == "close") {
-						 		$server = false;
-						 	}
-							if ($tag == "ONLINERESOURCE") {
-						 		$currentLayer["url"] = $attributes["xlink:href"];
-							}
-						}
-						if ($tag == "NAME") {
-					 		$currentLayer["name"] = $value;
-						}
-						if ($tag == "TITLE") {
-					 		$currentLayer["title"] = $value;
-						}
-						if ($tag == "ABSTRACT") {
-					 		$currentLayer["abstract"] = $value;
-						}
-						if ($tag == "SRS") {
-							$currentLayer["epsg"] = explode(" ", $value);						 	
-						}
-						if ($tag == "EXTENSION" && $type == "close") {
-							$extension = false;
-						}
-						if ($extension == true){
-//							if ($value !== "") {
-								if (isset($currentLayer["extension"][$tag])) {
-									if (!is_array($currentLayer["extension"][$tag])) {
-										$firstValue = $currentLayer["extension"][$tag];
-										$currentLayer["extension"][$tag] = array();
-										array_push($currentLayer["extension"][$tag], $firstValue);
-									}	
-									array_push($currentLayer["extension"][$tag], $value);
-								}
-								else {
-									$currentLayer["extension"][$tag] = $value;									
-								}
-//							}
-						}
-						if ($tag == "EXTENSION" && $type == "open") {
-							$currentLayer["extension"] = array();
-							$extension = true;
-						}
-						if ($tag == "METADATAURL" && $type == "open") {
-							$metadataurl = true;
-						}
-						if ($tag == "DATAURL" && $type == "open") {
-							$dataurl = true;
-						}
-						if ($tag == "FORMATLIST" && $type == "open") {
-							$formatlist = true;
-						}
-						if ($tag == "STYLELIST" && $type == "open") {
-							$stylelist = true;
-						}
-					}
-				}
-			}
-		}
-		
-		// set WMS data
-		
-		$layerlistCompleteArray = array_merge($layerlistArray["main"], $layerlistArray["overview"]);
-
-		for ($i = 0; $i < count($layerlistCompleteArray); $i++) {
-			$this->setLayerData($layerlistCompleteArray[$i]);
-		}
-
-		$wmsArr = $this->mainMap->getWmsArray();
-		for ($i = 0; $i < count($wmsArr); $i++) {
-			$wmsArr[$i]->updateAllOwsProxyUrls();
-		}
-		return true;
-	}
-
-	/**
-	 * Saves the current WMC in the log folder.
-	 * 
-	 * @return string the filename of the WMC document.
-	 */
-	private function saveAsFile() {
-		if ($this->saveWmcAsFile) {
-			$filename = "wmc_" . date("Y_m_d_H_i_s") . ".xml";
-			$logfile = "../tmp/" . $filename;
-			
-			if($h = fopen($logfile,"a")){
-				$content = $this->xml;
-				if(!fwrite($h,$content)){
-					$e = new mb_exception("class_wmc.php: failed to write wmc.");
-					return false;
-				}
-				fclose($h);
-			}
-			$e = new mb_notice("class_wmc: saving WMC as file " . $filename . "; You can turn this behaviour off in class_wmc.php");
-			return $filename;
-		}
-		return null;
-	}
-	
-	/**
-	 * Called during WMC parsing; sets the data of a single layer.
-	 * 
-	 * @return 
-	 * @param $currentLayer Array an associative array with layer data
-	 */
-	private function setLayerData ($currentLayer) {
-		$currentMap = $this->mainMap;
-		$currentMapIsOverview = false;
-
-		if (isset($currentLayer["extension"]["OVERVIEWHIDDEN"])) {
-			$currentMap = $this->overviewMap;
-			$currentMapIsOverview = true;
-		}
-
-		if (is_null($currentMap)) {
-			$e = new mb_exception('class_wmc.php: setLayerData: $currentMap is null. Aborting.');
-			return null;
-		}
-
-		$wmsArray = $currentMap->getWmsArray();
-
-		//
-		// check if current layer belongs to an existing WMS.
-		// If yes, store the index of this WMS in $wmsIndex.
-		// If not, set the value to null.
-		//
-		$wmsIndex = null;
-
-		// find last WMS with the same online resource
-		for ($i = count($wmsArray) - 1; $i >= 0; $i--) {
-			if (isset($currentLayer["url"]) && 
-				$currentLayer["url"] == $wmsArray[$i]->wms_getmap) {
-					$wmsIndex = $i;
-					break;
-			}
-		}
-
-		// Even if this WMS has been found before it could still
-		// be a duplicate! We would have to create a new WMS and 
-		// not append this layer to that WMS.
-		// For the overview layer we never add a new wms.
-		// check if this layer is an overview layer. If yes, skip this layer.
-		if ($wmsIndex !== null && !$currentMapIsOverview) {
-
-			// check if this WMS has a layer equal to the current layer.
-			// If yes, this is a new WMS. If not, append this layer
-			// to the existing WMS.
-			$matchingWmsLayerArray = $this->wmsArray[$wmsIndex]->objLayer;
-			
-			for ($i = 0; $i < count($matchingWmsLayerArray); $i++) {
-				if ($matchingWmsLayerArray[$i]->layer_name == $currentLayer["name"]) {
-
-					// by re-setting the index to null, a new WMS will be 
-					// added below.
-					$wmsIndex = null;
-					break;
-				}
-			}
-		}
-
-		// if yes, create a new WMS ...
-		if ($wmsIndex === null) {
-			$wmsIndex = 0;
-			$wms = new wms();
-
-			//
-			// set WMS data
-			//
-			$wms->wms_id = $currentLayer["extension"]["WMS_ID"]; // TO DO: how about WMS without ID?
-			$wms->wms_version = $currentLayer["version"];
-			$wms->wms_title = $currentLayer["wms_title"];
-			$wms->wms_abstract = $currentLayer["abstract"];
-			$wms->wms_getmap = $currentLayer["url"];
-			$wms->wms_getfeatureinfo = $currentLayer["url"]; // TODO : Add correct data
-			
-			$styleIndex = $currentLayer["styleIndex"];
-			$wms->wms_getlegendurl = $currentLayer["style"][$styleIndex]["legendurl"];
-
-			$wms->wms_filter = ""; // TODO : Add correct data
-
-			$formatIndex = $currentLayer["formatIndex"];
-			$wms->gui_wms_mapformat = $currentLayer["format"][$formatIndex]["name"];
-
-			$wms->gui_wms_featureinfoformat = "text/html"; // TODO : Add correct data
-			$wms->gui_wms_exceptionformat = "application/vnd.ogc.se_xml"; // TODO : Add correct data
-			$wms->gui_wms_epsg = $this->mainMap->getEpsg();
-			$wms->gui_wms_visible = $currentLayer["extension"]["WMS_VISIBLE"];
-			$wms->gui_wms_opacity = 100; // TODO : Add correct data
-			$wms->gui_wms_sldurl = $currentLayer["style"][$styleIndex]["sld_url"];
-			$wms->wms_srs = $currentLayer["epsg"];
-			$wms->gui_epsg = $currentLayer["epsg"];
-			//
-			// set data formats
-			//
-			for ($i = 0; $i < count($currentLayer["format"]); $i++) {
-				array_push($wms->data_type, "map");							
-				array_push($wms->data_format, $currentLayer["format"][$i]["name"]);							
-			}
-
-			// add WMS
-			array_push($wmsArray, $wms);
-
-			// the index of the WMS we just added
-			$wmsIndex = count($wmsArray) - 1;
-		}
-
-		// add layer to existing WMS ...
-		$currentWms = $wmsArray[$wmsIndex];
-		$currentWms->newLayer($currentLayer, null);
-		$currentMap->setWmsArray($wmsArray);
-		return true;
-	}
-	
-	/**
-	 * Called during WMC parsing; sets the maps within a WMC.
-	 * 
-	 * @return 
-	 */
-	private function setMapData () {
-		if ($this->generalExtensionArray["OV_WIDTH"] && 
-			$this->generalExtensionArray["OV_HEIGHT"] &&
-			$this->generalExtensionArray["OV_FRAMENAME"] &&
-			$this->generalExtensionArray["OV_MINX"] &&
-			$this->generalExtensionArray["OV_MINY"] &&
-			$this->generalExtensionArray["OV_MAXX"] &&
-			$this->generalExtensionArray["OV_MAXY"] &&
-			$this->generalExtensionArray["OV_SRS"]) {
-			
-			$this->overviewMap = new Map();
-			$this->overviewMap->setWidth(
-				// this should not be an array, but sometimes it is.
-				// I can't find the reason at the moment, consider
-				// this a workaround
-				is_array($this->generalExtensionArray["OV_WIDTH"]) ?
-					$this->generalExtensionArray["OV_WIDTH"][0] : 
-					$this->generalExtensionArray["OV_WIDTH"]
-			);
-			$this->overviewMap->setHeight(
-				// this should not be an array, but sometimes it is.
-				// I can't find the reason at the moment, consider
-				// this a workaround
-				is_array($this->generalExtensionArray["OV_HEIGHT"]) ? 
-					$this->generalExtensionArray["OV_HEIGHT"][0] :
-					$this->generalExtensionArray["OV_HEIGHT"]
-			);
-			$this->overviewMap->setFrameName(
-				// this should not be an array, but sometimes it is.
-				// I can't find the reason at the moment, consider
-				// this a workaround
-				is_array($this->generalExtensionArray["OV_FRAMENAME"]) ?
-					$this->generalExtensionArray["OV_FRAMENAME"][0] :
-					$this->generalExtensionArray["OV_FRAMENAME"]
-			);
-			$this->overviewMap->setIsOverview(true);
-
-			$bbox = new Mapbender_bbox($this->generalExtensionArray["OV_MINX"], $this->generalExtensionArray["OV_MINY"], $this->generalExtensionArray["OV_MAXX"], $this->generalExtensionArray["OV_MAXY"], $this->generalExtensionArray["OV_SRS"]);
-			$this->overviewMap->setExtent($bbox);
-		}
-		if ($this->generalExtensionArray["EPSG"] && 
-			$this->generalExtensionArray["MINX"] && 		
-			$this->generalExtensionArray["MINY"] && 		
-			$this->generalExtensionArray["MAXX"] && 		
-			$this->generalExtensionArray["MAXY"]) {
-
-			$mainEpsgArray = array();
-			$mainMinXArray = array();
-			$mainMinYArray = array();
-			$mainMaxXArray = array();
-			$mainMaxYArray = array();
-			if (!is_array($this->generalExtensionArray["EPSG"])) {
-				$mainEpsgArray[0] = $this->generalExtensionArray["EPSG"];
-				$mainMinXArray[0] = $this->generalExtensionArray["MINX"];
-				$mainMinYArray[0] = $this->generalExtensionArray["MINY"];
-				$mainMaxXArray[0] = $this->generalExtensionArray["MAXX"];
-				$mainMaxYArray[0] = $this->generalExtensionArray["MAXY"];
-			}
-			else {
-				$mainEpsgArray = $this->generalExtensionArray["EPSG"];
-				$mainMinXArray = $this->generalExtensionArray["MINX"];
-				$mainMinYArray = $this->generalExtensionArray["MINY"];
-				$mainMaxXArray = $this->generalExtensionArray["MAXX"];
-				$mainMaxYArray = $this->generalExtensionArray["MAXY"];
-			}
-
-			for ($i=0; $i < count($mainEpsgArray); $i++) {
-				$box = new Mapbender_bbox(
-					floatval($mainMinXArray[$i]), floatval($mainMinYArray[$i]), 
-					floatval($mainMaxXArray[$i]), floatval($mainMaxYArray[$i]),
-					$mainEpsgArray[$i]
-				);				
-				$this->mainMap->addZoomFullExtent($box);
-			}
-		}			
-
-		if ($this->generalExtensionArray["MAIN_FRAMENAME"]) {
-			$this->mainMap->setFrameName(
-				// this should not be an array, but sometimes it is.
-				// I can't find the reason at the moment, consider
-				// this a workaround
-				is_array($this->generalExtensionArray["MAIN_FRAMENAME"]) ?
-					$this->generalExtensionArray["MAIN_FRAMENAME"][0] :
-					$this->generalExtensionArray["MAIN_FRAMENAME"]
-			);
-		}
-		else {
-			$this->mainMap->setFrameName("mapframe1");
-		}
-		return true;
-	}
-
-	/**
-	 * Creates a WMC document (XML) from the current object
-	 * 
-	 * @return String XML
-	 */
-	private function createXml() {
-		$wmcToXml = new WmcToXml($this);
-		$this->xml = $wmcToXml->getXml();
-	}
-} 
-
-/**
- * @deprecated
- */
-function mb_utf8_encode ($str) {
-//	if(CHARSET=="UTF-8") return utf8_encode($str);
-	return $str;
-}
-
-/**
- * @deprecated
- */
-function mb_utf8_decode ($str) {
-//	if(CHARSET=="UTF-8") return utf8_decode($str);
-	return $str;
-}
-?>

Copied: branches/mapbender/http/classes/class_wmc.php (from rev 6951, trunk/mapbender/http/classes/class_wmc.php)
===================================================================
--- branches/mapbender/http/classes/class_wmc.php	                        (rev 0)
+++ branches/mapbender/http/classes/class_wmc.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -0,0 +1,1764 @@
+<?php
+# $Id$
+# http://www.mapbender.org/index.php/class_wmc.php
+# 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__) . "/../classes/class_wms.php");
+require_once(dirname(__FILE__) . "/../classes/class_wfs_configuration.php");
+require_once(dirname(__FILE__) . "/../classes/class_layer_monitor.php");
+require_once(dirname(__FILE__) . "/../classes/class_point.php");
+require_once(dirname(__FILE__) . "/../classes/class_bbox.php");
+require_once(dirname(__FILE__) . "/../classes/class_json.php");
+require_once(dirname(__FILE__) . "/../classes/class_map.php");
+require_once(dirname(__FILE__) . "/../classes/class_administration.php");
+require_once(dirname(__FILE__) . "/../classes/class_wmcToXml.php");
+require_once(dirname(__FILE__) . "/../classes/class_user.php");
+
+/**
+ * Implementation of a Web Map Context Document, WMC 1.1.0
+ * 
+ * Use cases:
+ * 
+ * Instantiation (1) create a WMC object from a WMC XML document
+ * 		$myWmc = new wmc();
+ * 		$myWmc->createFromXml($xml);
+ * 
+ *    If you want to create a WMC object from a WMC in the database
+ *    	$xml = wmc::getDocument($wmcId);
+ * 		$myWmc = new wmc();
+ * 		$myWmc->createFromXml($xml);
+ *    
+ * 
+ * Instantiation (2) create a WMC from the client side
+ * 		$myWmc = new wmc();
+ * 		$myWmc->createFromJs($mapObject, $generalTitle, $extensionData);
+ * 	
+ * 	  	(creates a WMC from the JS data and then creates an object from that WMC)
+ * 
+ * Output (1) (do Instantiation first) Load a WMC into client
+ * 		This will return an array of JS statements
+ *  
+ * 		$myWmc->toJavaScript();
+ * 
+ * Output (2) (do Instantiation first) Merge with another WMC, then load
+ * 	
+ * 		$myWmc->merge($anotherWmcXml);
+ * 		$myWmc->toJavaScript();
+ * 
+ */
+class wmc {
+	/**
+	 * Representing the main map in a map application
+	 * @var Map
+	 */
+	var $mainMap;
+
+	/**
+	 * Representing an (optional) overview map in a map application
+	 * @var Map
+	 */
+	var $overviewMap;
+
+	/**
+	 * @var Array
+	 */
+	var $generalExtensionArray = array();
+
+	/**
+	 * The XML representation of this WMC.
+	 * @var String
+	 */
+	var $xml;
+	
+	// constants
+	var $saveWmcAsFile = false;
+	var $extensionNamespace = "mapbender";
+	var $extensionNamespaceUrl = "http://www.mapbender.org/context";
+		
+	// set in constructor
+	var $wmc_id;
+	var $userId;
+    var $timestamp;
+    var $public;
+
+	// set during parsing
+	var $wmc_version;
+	var $wmc_name;
+	var $wmc_title;
+	var $wmc_abstract;
+	var $wmc_srs;
+	var $wmc_extent;
+	var $wmc_keyword = array();
+	var $wmc_contactposition;
+	var $wmc_contactvoicetelephone;
+	var $wmc_contactemail;
+	var $wmc_contactfacsimiletelephone;
+	var $wmc_contactperson;
+	var $wmc_contactorganization;
+	var $wmc_contactaddresstype;
+	var $wmc_contactaddress;
+	var $wmc_contactcity;
+	var $wmc_contactstateorprovince;
+	var $wmc_contactpostcode;
+	var $wmc_contactcountry;
+	var $wmc_logourl;
+	var $wmc_logourl_format;
+	var $wmc_logourl_type;
+	var $wmc_logourl_width;
+	var $wmc_logourl_height;
+	var $wmc_descriptionurl;
+	var $wmc_descriptionurl_format;
+	var $wmc_descriptionurl_type;
+
+	var $inspireCats; 
+
+	public function __construct () {
+		$this->userId = Mapbender::session()->get("mb_user_id");
+		$this->wmc_id = time();
+		$this->timestamp = time();
+	} 
+	
+	// ---------------------------------------------------------------------------
+	// INSTANTIATION
+	// ---------------------------------------------------------------------------
+
+	/**
+	 * Parses the XML string and instantiates the WMC object.
+	 * 
+	 * @param $xml String
+	 */
+	public function createFromXml ($xml) {
+		return $this->createObjFromWMC_xml($xml);
+	}
+
+	/**
+	 * Loads a WMC from the database.
+	 * 
+	 * @param integer $wmc_id the ID of the WMC document in the database table "mb_user_wmc"
+	 */
+	function createFromDb($wmcId){
+		$doc = wmc::getDocument($wmcId);
+		if ($doc === false) {
+			return false;
+		}
+		$this->createObjFromWMC_xml($doc);
+        $sql = "SELECT wmc_timestamp, wmc_title, wmc_public " . 
+			"FROM mb_user_wmc WHERE wmc_id = $1 AND (fkey_user_id = $2 OR wmc_public = 1)";
+        $v = array($wmcId, Mapbender::session()->get("mb_user_id"));
+        $t = array("s", "i");
+        
+        $res = db_prep_query($sql,$v,$t);
+        if(db_error()) { return false; }
+        if($row = db_fetch_row($res)) {
+          $this->wmc_id = $wmcId;
+          $this->timestamp = $row[0];
+          $this->title = $row[1];
+          $this->public = $row[2];
+        
+        }
+		else {
+			return false;
+		}
+		return true;
+	}
+
+	public function createFromApplication ($appId) {
+		// get the map objects "overview" and "mapframe1"
+		$this->mainMap = map::selectMainMapByApplication($appId);
+		$this->overviewMap = map::selectOverviewMapByApplication($appId);
+		$this->createXml();
+		$this->saveAsFile();
+	}
+
+	/**
+	 * Creates a WMC object from a JS map object {@see map_obj.js}
+	 * 
+	 * @param object $mapObject a map object
+	 * @param integer $user_id the ID of the current user
+	 * @param string $generalTitle the desired title of the WMC
+	 * @param object $extensionData data exclusive to Mapbender, which will be 
+	 * 								mapped into the extension part of the WMC
+	 */
+	public function createFromJs($mapObject, $generalTitle,$extensionData, $id=null) {
+	
+		if (count($mapObject) > 2) {
+			$e = new mb_exception("Save WMC only works for two concurrent map frames (overview plus main) at the moment.");
+		}
+		
+		// set extension data		
+		$this->generalExtensionArray = $extensionData;
+
+		if ($id) {
+			//set id
+			$this->wmc_id = $id;
+		}
+		
+		// set title
+		$this->wmc_title = $generalTitle;
+		
+		// create the map objects
+		for ($i = 0; $i < count($mapObject); $i++) {
+			$currentMap = new Map();
+			$currentMap->createFromJs($mapObject[$i]);
+
+			if (isset($mapObject[$i]->isOverview)) {
+				$this->overviewMap = $currentMap;
+			}
+			else {
+				$this->mainMap = $currentMap;
+			}
+		}
+
+		
+		// create XML
+		$this->createXml();
+
+		$this->saveAsFile();
+		return true;
+	}
+	
+	// ---------------------------------------------------------------------------
+	// DATABASE FUNCTIONS
+	// ---------------------------------------------------------------------------
+	public function getPublicWmcIds () {
+		$sql = "SELECT wmc_id FROM mb_user_wmc ";
+		$sql .= "WHERE wmc_public = 1 GROUP BY wmc_id";
+		$res_wmc = db_query($sql);
+
+  		$wmcArray = array();
+		while($row = db_fetch_array($res_wmc)){
+			array_push($wmcArray, $row["wmc_id"]);
+		}
+		return $wmcArray;
+	}
+
+	public function getAccessibleWmcs ($user) {
+		$wmcArray = array();
+		
+		// get WMC ids 
+		$wmcOwnerArray = $user->getWmcByOwner();
+		
+		$publicWmcIdArray = $this->getPublicWmcIds();
+		
+		return array_keys( array_flip(array_merge($wmcOwnerArray, $publicWmcIdArray)));
+	}
+
+
+
+	public function selectByUser ($user) {
+		$wmcArray = array();
+		
+		// get WMC ids 
+		$wmcOwnerArray = $user->getWmcByOwner();
+		
+		$publicWmcIdArray = self::getPublicWmcIds();
+		
+		$wmcIdArray = array_keys( array_flip(array_merge($wmcOwnerArray, $publicWmcIdArray)));
+
+		// get WMC data
+		$v = array();
+		$t = array();
+		$wmcIdList = "";
+	
+		for ($i = 0; $i < count($wmcIdArray); $i++) {
+			if ($i > 0) { 
+				$wmcIdList .= ",";
+			}
+			$wmcIdList .= "$".($i+1);
+			array_push($v, $wmcIdArray[$i]);
+			array_push($t, 's');
+		}
+	
+		if ($wmcIdList !== "") {
+			$sql = "SELECT DISTINCT wmc_id, wmc_title, wmc_timestamp, wmc_timestamp_create, wmc_public, abstract FROM mb_user_wmc ";
+			$sql .= "WHERE wmc_id IN (" . $wmcIdList . ") ";
+			$sql .=	"ORDER BY wmc_timestamp DESC";
+		
+			$res = db_prep_query($sql, $v, $t);
+			while($row = db_fetch_assoc($res)){
+				$currentResult = array();
+				$currentResult["id"] = $row["wmc_id"];
+				$currentResult["abstract"] = $row["abstract"];
+				$currentResult["title"] = administration::convertIncomingString($row["wmc_title"]);
+				$currentResult["timestamp"] = date("M d Y H:i:s", $row["wmc_timestamp"]); 
+				$currentResult["timestamp_create"] = date("M d Y H:i:s", $row["wmc_timestamp_create"]); 
+				$currentResult["isPublic"] = $row["wmc_public"] == 1? true: false;
+				$currentResult["disabled"] = ((
+					in_array($currentResult["id"], $publicWmcIdArray) && 
+					!in_array($currentResult["id"], $wmcOwnerArray)) || $user->isPublic()) ?
+					true : false;
+					
+				// get categories
+				$currentResult["categories"] = $this->getCategoriesById($currentResult["id"], $user);
+				$currentResult["keywords"] = $this->getKeywordsById($currentResult["id"], $user);
+				array_push($wmcArray, $currentResult);
+			}
+		}
+		return $wmcArray;
+	}
+
+	private function getKeywordsById ($id, $user) {
+		$wmcArray = $this->getAccessibleWmcs($user);
+		if (!in_array($id, $wmcArray)) {
+			return array();
+		}
+		
+		$keywordArray = array();
+		
+		$sql = "SELECT DISTINCT k.keyword FROM keyword AS k, wmc_keyword AS w " . 
+			"WHERE w.fkey_keyword_id = k.keyword_id AND w.fkey_wmc_id = $1";
+		$v = array($id);
+		$t = array("s");
+		$res = db_prep_query($sql, $v, $t);
+		while ($row = db_fetch_array($res)) {
+			$keywordArray[]= $row["keyword"];
+		}
+		return $keywordArray;
+	}
+
+	private function getCategoriesById ($id, $user) {
+		$wmcArray = $this->getAccessibleWmcs($user);
+		if (!in_array($id, $wmcArray)) {
+			return array();
+		}
+		
+		$keywordArray = array();
+		
+		$sql = "SELECT DISTINCT t.md_topic_category_id FROM " . 
+			"md_topic_category AS t, wmc_md_topic_category AS w " . 
+			"WHERE w.fkey_md_topic_category_id = t.md_topic_category_id " . 
+			"AND w.fkey_wmc_id = $1";
+		$v = array($id);
+		$t = array("s");
+		$res = db_prep_query($sql, $v, $t);
+		while ($row = db_fetch_array($res)) {
+			$keywordArray[]= $row["md_topic_category_id"];
+		}
+		return $keywordArray;
+	}
+
+    private function compareWms ($a, $b) {
+		if ($a["id"] === $b["id"]) return 0;
+        return -1;
+    }
+	public function getAllWms () {
+		$wmsArray = $this->mainMap->getWmsArray();
+		$resultObj = array();
+		$usedIds = array();
+		for ($i = 0; $i < count($wmsArray); $i++) {
+			if (in_array($wmsArray[$i]->wms_id, $usedIds)) {
+				continue;
+			}
+			$resultObj[]= array(
+				"title" => $wmsArray[$i]->wms_title, 
+				"id" => is_null($wmsArray[$i]->wms_id) ? null : intval($wmsArray[$i]->wms_id),
+				"index" => $i
+			);
+			$usedIds[]= $wmsArray[$i]->wms_id;
+		}
+		return $resultObj;	
+	}
+
+	public function getWmsWithoutId () {
+		$wmsArray = $this->getAllWms();		
+		$resultObj = array();
+		
+		for ($i = 0; $i < count($wmsArray); $i++) {
+			if (is_numeric($wmsArray[$i]["id"])) {
+				continue;
+			}
+			$resultObj[]= array(
+				"title" => $wmsArray[$i]["title"], 
+				"id" => $wmsArray[$i]["id"],
+				"index" => $i
+			);
+		}
+		return $resultObj;	
+	}
+	
+	public function getWmsWithId () {
+		return array_values(array_udiff(
+			$this->getAllWms(), 
+			$this->getWmsWithoutId(),
+			array("wmc", "compareWms")
+		));
+	}
+	
+	public function getValidWms () {
+		$inv = $this->getInvalidWms();
+		$withId = $this->getWmsWithId();
+		return array_values(array_udiff(
+			$withId, 
+			$inv,
+			array("wmc", "compareWms")
+		));
+	}
+	
+	public function getInvalidWms () {
+		$resultObj = array();
+
+		$wmsArray = $this->getWmsWithId();
+		for ($i = 0; $i < count($wmsArray); $i++) {
+			
+			$sql = "SELECT COUNT(wms_id) FROM wms WHERE wms_id = $1";
+			$v = array($wmsArray[$i]["id"]);
+			$t = array('i');
+			$res = db_prep_query($sql, $v, $t);
+			$layerRow = db_fetch_row($res);
+			if (intval($layerRow[0]) === 0) {
+				$resultObj[]= array(
+					"title" => $wmsArray[$i]["title"], 
+					"id" => intval($wmsArray[$i]["id"]),
+					"index" => $wmsArray[$i]["index"]
+				);
+			}		
+		}
+		return $resultObj;
+	}
+	
+	public function getWmsWithPermission ($user) {
+		$wmsArray = $this->getValidWms();		
+		$resultObj = array();
+
+		for ($i = 0; $i < count($wmsArray); $i++) {
+			$currentWmsId = intval($wmsArray[$i]["id"]);
+
+			if ($user->isWmsAccessible($currentWmsId)) {
+				$resultObj[]= array(
+					"title" => $wmsArray[$i]["title"], 
+					"id" => intval($currentWmsId),
+					"index" => $wmsArray[$i]["index"]
+				);
+			}			
+		}
+		return $resultObj;	
+	}
+	
+	public function getWmsWithoutPermission ($user) {
+		return array_values(array_udiff(
+			$this->getValidWms(), 
+			$this->getWmsWithPermission($user),
+			array("wmc", "compareWms")
+		));
+	}
+	
+	public function getAvailableWms ($user) {
+		return array_values(array_udiff(
+			$this->getWmsWithPermission($user), 
+			$this->getUnavailableWms(),
+			array("wmc", "compareWms")
+		));
+	}
+	
+	public function getUnavailableWms ($user) {
+		$wmsArray = $this->getWmsWithPermission($user);
+		$resultObj = array();
+		
+		for ($i = 0; $i < count($wmsArray); $i++) {
+			$currentWmsId = $wmsArray[$i]["id"];
+
+			$sql = "SELECT last_status FROM mb_wms_availability WHERE fkey_wms_id = $1"; 
+			$v = array($currentWmsId);
+			$t = array("i");
+			$res = db_prep_query($sql, $v, $t);
+			$statusRow = db_fetch_row($res);
+			$status = intval($statusRow[0]);
+			if (isset($status) && $status < 0) {
+				$resultObj[]= array(
+					"title" => $wmsArray[$i]["title"], 
+					"id" => $currentWmsId,
+					"index" => $wmsArray[$i]["index"]
+				);
+			}
+		}
+		return $resultObj;		
+	}
+
+	public function updateUrlsFromDb () {
+		$query_mbWMSId = "/wmc:ViewContext/wmc:LayerList/wmc:Layer/wmc:Extension/mapbender:wms_id";
+		try {
+			$WMCDoc = DOMDocument::loadXML($this->toXml());
+		} 
+		catch (Exception $E) {
+			new mb_exception("WMC XML is broken.");
+		}   
+		
+		$xpath = new DOMXPath($WMCDoc);
+		$xpath->registerNamespace("wmc","http://www.opengis.net/context");
+		$xpath->registerNamespace("mapbender","http://www.mapbender.org/context");
+		$xpath->registerNamespace("xlink","http://www.w3.org/1999/xlink");
+		
+		$WMSIdList = $xpath->query($query_mbWMSId);
+		foreach($WMSIdList as $WMSId) {
+			$id =  $WMSId->nodeValue;
+			$sql = "SELECT wms_timestamp,wms_getmap,wms_getlegendurl " . 
+				"FROM wms WHERE wms_id = $1 AND " . 
+				"wms_owsproxy <> NULL AND wms_owsproxy <> ''";
+			$v = array($id);
+			$t = array("t");
+			
+			$res = db_prep_query($sql,$v,$t);
+			if (db_error()) {
+				true; 
+			} //FIMXE: PROPER ERROR MESSAGE
+			
+			if($row = db_fetch_array($res)) {
+				$wms_timestamp = $row["wms_timestamp"];
+				if ($this->timestamp < $wms_timestamp) {
+				// wmc is fresh, life is good
+				}
+				else{
+					$MapResources = $xpath->query("../../wmc:Server/wmc:OnlineResource",$WMSId);
+					foreach($MapResources as $MapResource) {
+						$MapResource->setAttribute("xlink:href",$row["wms_getmap"]);
+					}
+					
+					$LegendResources = $xpath->query("../../wmc:StyleList/wmc:Style/wmc:LegendURL/wmc:OnlineResource",$WMSId);
+					foreach ($LegendResources as $LegendResource) {
+						$base = $row["wms_getlegendurl"];
+						$origurl = explode('&', $LegendResource->getAttribute("xlink:href"),2);
+						$url = $base . $origurl[1]; 
+						$LegendResource->setAttribute("xlink:href",$url);
+					}
+				}
+			}
+		}
+		$updatedWMC = $WMCDoc->saveXML();
+		$this->update_existing($updatedWMC,$wmsId);
+		return $updatedWMC;
+	}
+
+	/**
+	 * Stores this WMC in the database. The WMC has to be instantiated first, see above.
+	 * 
+	 * @return mixed[] an assoc array with attributes "success" (boolean) and "message" (String).
+	 */
+	public function insert ($overwrite) {
+		$result = array();
+		
+		if ($this->userId && $this->xml && $this->wmc_title) {
+			try {
+				$user = new user($this->userId);
+			} 
+			catch (Exception $E) {
+				$errMsg = "Error while saving WMC document " . $this->wmc_title . "': Invalud UserId";
+				$result["success"] = false;
+				$result["message"] = $errMsg;
+				$e = new mb_exception("mod_insertWMCIntoDB: " . $errMsg);
+				return $result;
+			}
+		
+			$overwrite  = ($user->isPublic())? false: $overwrite;
+		
+			//put keywords into Document
+			try {
+				$WMCDoc = DOMDocument::loadXML($this->toXml());
+			} 
+			catch (Exception $E) {
+				new mb_exception("WMC XML is broken.");
+			}   
+
+			$NewDoc = new DOMDocument();
+		   
+			$xpath = new DOMXPath($WMCDoc);
+			$xpath->registerNamespace("wmc","http://www.opengis.net/context");
+			$xpath->registerNamespace("mapbender","http://www.mapbender.org/context");
+			$xpath->registerNamespace("xlink","http://www.w3.org/1999/xlink");
+
+			$query_KeywordList = "/wmc:ViewContext/wmc:General/wmc:KeywordList";
+			$query_general = "/wmc:ViewContext/wmc:General";
+			$DocKeywordLists = $xpath->query($query_KeywordList);
+			// we just use a single <general> element
+			
+			$NewKeywordList = new DOMElement('KeywordList','','http://opengis.net/context');
+			$NewDoc->appendChild($NewKeywordList);
+	 		foreach($this->keyword as $keyword){
+				$Keyword = new DOMElement('Keyword',$keyword, 'http://opengis.net/context');
+				$NewKeywordList->appendChild($Keyword);
+			}
+			
+			$generalList = $xpath->query($query_general);	
+			$general = $generalList->item(0);
+			if($DocKeywordLists->item(0)){
+				$general->replaceChild($NewKeywordList,$DocKeywordList->item(0));
+			}else{
+				$tmpNode = $WMCDoc->importNode($NewKeywordList,true);
+				$general->appendChild($tmpNode);
+
+			}
+			
+			$this->xml  = $WMCDoc->saveXML();
+			
+			db_begin();
+		
+			if($overwrite) {
+		
+	            $findsql = "SELECT fkey_user_id,wmc_title,wmc_timestamp, wmc_id FROM mb_user_wmc WHERE fkey_user_id = $1 AND wmc_id = $2 ORDER BY wmc_timestamp DESC LIMIT 1;";
+	            $v = array($this->userId, $this->wmc_id);
+	            $t = array("i","i");
+	        
+	            $res = db_prep_query($findsql,$v,$t);
+				if (db_error()) {
+					$errMsg = "Error while saving WMC document '" . $this->wmc_title . "': " . db_error();
+					$result["success"] = false;
+					$result["message"] = $errMsg;
+					$e = new mb_exception("mod_insertWMCIntoDB: " . $errMsg);
+	                return $result;
+				}
+	
+	            if($row = db_fetch_row($res)) {
+					$sql = "UPDATE mb_user_wmc SET wmc = $1, wmc_timestamp = $2, abstract = $3, srs = $4, minx = $5, miny = $6,".
+						" maxx = $7, maxy = $8, wmc_title = $9 WHERE fkey_user_id = $10 AND wmc_id=$11 AND wmc_timestamp = $12;";
+					$v = array($this->xml, time(), $this->wmc_abstract, $this->wmc_srs, $this->wmc_extent->minx, $this->wmc_extent->minx,
+						 $this->wmc_extent->maxx, $this->wmc_extent->maxy ,administration::convertOutgoingString($this->wmc_title), $this->userId, $this->wmc_id,$row[2]);
+					$t = array("s", "s","s","s","i","i","i","i", "s", "i", "i","s");
+					// need the database Id
+					$wmc_DB_ID = $row[3];
+					$delsql = "DELETE FROM wmc_md_topic_category WHERE fkey_wmc_id = $1;";
+					$delv = array($wmc_DB_ID);
+					$delt = array("s");
+					db_prep_query($delsql, $delv,$delt);
+						
+					$delkwsql = "DELETE FROM wmc_keyword WHERE fkey_wmc_id = $1;";
+					$delkwv = array($wmc_DB_ID);
+					$delkwt = array("s");
+					db_prep_query($delkwsql, $delkwv,$delkwt);
+						
+					
+					
+				}
+				else{
+					$sql = "INSERT INTO mb_user_wmc (" . 
+						"wmc_id, fkey_user_id, wmc, wmc_title, wmc_public, wmc_timestamp, wmc_timestamp_create, " . 
+						"abstract, srs, minx, miny, maxx, maxy ".
+						") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13);";
+					$v = array($this->wmc_id, $this->userId, $this->xml, administration::convertOutgoingString($this->wmc_title), $user->isPublic()?1:0,time(),time(),
+						$this->wmc_abstract, $this->wmc_srs, $this->wmc_extent->minx,  $this->wmc_extent->miny, $this->wmc_extent->maxx, $this->wmc_extent->maxy);
+					$t = array("s", "i", "s", "s", "i", "s","s", "s","s","i","i","i", "i");
+				}
+			}
+			else{
+				
+				$sql = "INSERT INTO mb_user_wmc (" . 
+					"wmc_id, fkey_user_id, wmc, wmc_title, wmc_public, wmc_timestamp, wmc_timestamp_create, " . 
+					"abstract, srs, minx, miny, maxx, maxy ".
+					") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13);";
+				$v = array($this->wmc_id, $this->userId, $this->xml, administration::convertOutgoingString($this->wmc_title), $user->isPublic()?1:0, time(),time(),
+						$this->wmc_abstract, $this->wmc_srs, $this->wmc_extent->minx,  $this->wmc_extent->miny, $this->wmc_extent->maxx, $this->wmc_extent->maxy);
+				$t = array("s", "i", "s", "s", "i", "s","s", "s","s","i","i","i", "i");
+				
+			}
+			
+		
+			  $res = db_prep_query($sql, $v, $t);
+			  if (db_error()) {
+				  $errMsg = "Error while saving WMC document '" . $this->wmc_title . "': " . db_error();
+				  $result["success"] = false;
+				  $result["message"] = $errMsg;
+				  $e = new mb_exception("mod_insertWMCIntoDB: " . $errMsg);
+			  }
+			  else {
+				  
+				// because the wmc id is created each time a wmc is instantiated $this->wmc_id has nothing to do with the database wmc_id
+				// this is some duct tape to fix it :-(
+				// see also above where wmc_DB_ID is defined if we need to update
+				if(!isset($wmc_DB_ID)) { $wmc_DB_ID = $this->wmc_id; }
+				
+				// update keywords
+			  	foreach($this->keyword as $keyword){
+
+					// if a keyword does not yet exist, create it
+			  		$keywordExistsSql = "SELECT keyword FROM keyword WHERE keyword = $1";
+				 	$keywordCreateSql = "INSERT INTO keyword (keyword) VALUES($1);"; 
+				 	$v = array($keyword);
+				 	$t = array("s");
+				 	$res =  db_prep_query($keywordExistsSql,$v,$t);
+				 	if(db_num_rows($res) == 0){
+						$res = db_prep_query($keywordCreateSql,$v,$t);
+				 		if($a = db_error()){
+				 		}
+				 	}	
+			
+						
+	
+					$keywordsql = "INSERT INTO wmc_keyword (fkey_keyword_id,fkey_wmc_id) SELECT keyword.keyword_id,$1 FROM keyword WHERE keyword = $2 AND NOT EXISTS (SELECT fkey_wmc_id FROM wmc_keyword	WHERE fkey_wmc_id = $3 );";
+					$v = array($wmc_DB_ID, $keyword,$wmc_DB_ID);
+					$t = array("s","s","s");
+					$res = db_prep_query($keywordsql, $v, $t);
+					if($a = db_error()){
+					}
+				  
+				}
+				// update categories
+				$this->inspireCats = $this->inspireCats? $this->inspireCats: array();
+				foreach($this->inspireCats as $catId)
+				{
+
+					$catSql = "INSERT INTO wmc_md_topic_category (fkey_wmc_id, fkey_md_topic_category_id) VALUES ($1,$2)";
+					$v = array($wmc_DB_ID, $catId);
+					$t = array("s","s");
+					$res = db_prep_query($catSql, $v, $t);
+		
+				}
+	  
+				  $result["success"] = true;
+				  $msg = "WMC document '" . $this->wmc_title . "' has been saved.";
+				  $result["message"] = $msg;
+				  $e = new mb_notice("mod_insertWMCIntoDB: WMC  '" . $this->wmc_title . "' saved successfully.");
+			  }
+		}
+		else {
+			$result["success"] = false;
+			$errMsg = "missing parameters (user_id: ".$this->userId.", title: " . $this->wmc_title . ")";
+			$result["message"] = $errMsg;
+			$e = new mb_exception("mod_insertWMCIntoDB: " . $errMsg .")");
+		}
+        db_commit();
+		return $result;
+	}
+    
+
+    /*
+    * overwrites an exact version of a wmc in the database
+    */
+    public function update_existing($xml,$id)
+    {
+      $sql = "UPDATE mb_user_wmc SET wmc = $1 WHERE wmc_id = $2";
+      $v = array($xml,$id);
+      $t = array("s","i");
+      $res = db_prep_query($sql,$v,$t);
+      if(db_error()) { $e = new mb_exception("There was an error saving an updated WMC"); }
+    }
+	
+	/**
+	 * deletes a {@link http://www.mapbender.org/index.php/WMC 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 successful?
+	 */
+	public static function delete ($wmcId, $userId) {
+		if (!isset($userId) || $userId === null) {
+			$userId = Mapbender::session()->get("mb_user_id");
+		}
+
+        try {
+          $user = new user($userId);
+        } catch (Exception $E) {
+          return $false;
+        }
+        
+        if($user->isPublic())
+        {
+            return $false;
+        }
+
+		$sql = "DELETE FROM mb_user_wmc ";
+		$sql .= "WHERE fkey_user_id = $1 AND wmc_id = $2";
+		$v = array($userId, $wmcId);
+		$t = array('i', 's');
+		$res = db_prep_query($sql, $v, $t);
+		if ($res) {
+			return true;
+		}
+		return false;
+	}
+
+	/**
+	 * Returns a WMC document
+	 * @return String|boolean The document if it exists; else false
+	 * @param $id String the WMC id
+	 */
+	public static function getDocument ($id) {
+		$sql = "SELECT wmc FROM mb_user_wmc WHERE wmc_id = $1 AND " . 
+			"(fkey_user_id = $2 OR wmc_public = 1)";
+		$v = array($id, Mapbender::session()->get("mb_user_id"));
+		$t = array('s', 'i');
+		$res = db_prep_query($sql,$v,$t);
+		$row = db_fetch_array($res);
+		if ($row) {
+			return $row["wmc"];
+		}
+		return false;
+	}
+
+	/**
+	 * Returns a WMC document
+	 * @return String|boolean The document if it exists; else false
+	 * @param $id String the WMC id
+	 */
+	public static function getDocumentByTitle ($title) {
+		$sql = "SELECT wmc FROM mb_user_wmc WHERE wmc_title = $1 AND " . 
+			"(fkey_user_id = $2 OR wmc_public = 1)";
+		$v = array($title, Mapbender::session()->get("mb_user_id"));
+		$t = array('s', 'i');
+		$res = db_prep_query($sql,$v,$t);
+		$row = db_fetch_array($res);
+		if ($row) {
+			return $row["wmc"];
+		}
+		return false;
+	}
+
+    /*
+    * sets the WMC's public flag
+    * @param $public boolean wether access should be public
+    */
+    public function setPublic($public)
+    {
+	  $currentUser = new User(Mapbender::session()->get("mb_user_id"));
+	  if ($currentUser->isPublic()) {
+			return false;
+	  }
+      $wmcId = $this->wmc_Id;
+      $public = $public ? 1 :0;
+      $sql = "UPDATE mb_user_wmc SET wmc_public = $1 WHERE wmc_id = $2 AND fkey_user_id = $3;";
+      $v = array($public,$wmcId, $currentUser->id);
+      $t = array("i","s","i");
+      $res = db_prep_query($sql,$v,$t);
+      if(db_error()){
+        return false;
+      }
+      return true;
+    }
+	// ---------------------------------------------------------------------------
+	// GETTER FUNCTIONS
+	// ---------------------------------------------------------------------------
+	
+	/**
+	 * @return string the title of the WMC.
+	 */
+	public function getTitle() {
+		return $this->wmc_title;
+	}
+
+	private function getLayerWithoutIdArray () {
+		$layerWithoutWmsIdArray = array();
+		$layerWithoutLayerIdArray = array();
+		
+		// check if WMS IDs exist
+		$wmsArray = $this->mainMap->getWmsArray();
+		for ($i = 0; $i < count($wmsArray); $i++) {
+			$currentWms = $wmsArray[$i];		
+			if (!is_numeric($currentWms[$currentId])) {
+				array_push($layerWithoutWmsIdArray, $currentId);
+			}
+		}
+		
+		// check if layer IDs exist
+		for ($i = 0; $i < count($layerIdArray); $i++) {
+			$currentId = $layerIdArray[$i];
+			if (!is_numeric($this->wmc_layer_id[$currentId])) {
+				array_push($layerWithoutLayerIdArray, $currentId);
+			}
+		}
+		$noIdArray = array_unique(array_merge($layerWithoutWmsIdArray, $layerWithoutLayerIdArray));
+		return $noIdArray;
+	}
+
+
+	// ---------------------------------------------------------------------------
+	// OUTPUT FUNCTIONS
+	// ---------------------------------------------------------------------------
+	
+	/**
+	 * Wrapper function, returns XML at the moment
+	 * @return String
+	 */
+	public function __toString() {
+		return $this->toXml();
+	}
+
+	/**
+	 * Returns the XML document if available
+	 * 
+	 * @return String The XML document; if unavailable, null is returned.
+	 */
+	public function toXml () {
+//		if (!$this->xml) {
+			$this->createXml();
+//		}
+		return $this->xml;
+	}
+
+	private function incrementLoadCount ($wms) {
+		// counts how often a layer has been loaded
+		$monitor = new Layer_load_count();
+		foreach ($wms->objLayer as $l) {
+			$monitor->increment($l->layer_uid);
+		}
+	}
+
+	public function wmsToJavaScript() {
+		$wmsArray = $this->mainMap->getWmsArray();
+
+		$wmcJsArray = array();
+		for ($i = 0; $i < count($wmsArray); $i++) {
+			$currentWms = $wmsArray[$i];
+	
+			$wmcJsArray[] = $currentWms->createJsObjFromWMS_();
+			$this->incrementLoadCount($currentWms);
+		}
+		return $wmcJsArray;
+	}
+	
+	public function featuretypeConfToJavaScript() {
+		$wfsConfIds = $this->generalExtensionArray['WFSCONFIDSTRING'];
+		$featuretypeConfs = array();
+		$featuretypeConfArray = is_string($wfsConfIds) ? 
+			explode(",", $wfsConfIds) : array();
+		for ($i = 0; $i < count($featuretypeConfArray); $i++) {
+			$featuretypeConf = WfsConfiguration::createFromDb($featuretypeConfArray[$i]);
+			array_push($featuretypeConfs,$featuretypeConf);
+		}
+		$featuretypeConfObj = new Mapbender_JSON();
+		$featuretypeConfObj = $featuretypeConfObj->encode($featuretypeConfs);
+		return $featuretypeConfObj;
+	}
+	/**
+	 * Returns an array of JavaScript statements
+	 * 
+	 * @return String[]
+	 */
+	public function toJavaScript () {
+		$skipWmsArray = array();
+		if (func_num_args() === 1) {
+			$skipWmsArray = func_get_arg(0);
+		}
+
+		// will contain the JS code to create the maps
+		// representing the state stored in this WMC
+		$wmcJsArray = array();
+		
+		// set general extension data
+		if (count($this->generalExtensionArray) > 0) {
+			$json = new Mapbender_JSON();
+			array_push($wmcJsArray, "restoredWmcExtensionData = " . $json->encode($this->generalExtensionArray) . ";"); 
+		}
+		
+		// reset WMS data
+		array_push($wmcJsArray, "wms = [];");
+		array_push($wmcJsArray, "wms_layer_count = 0;");
+
+		// add WMS for main map frame
+		$wmsArray = $this->mainMap->getWmsArray();
+
+		// find the WMS in the main map which is equal to the WMS
+		// in the overview map
+		$overviewWmsIndex = null;
+		$ovWmsArray = array();
+		if ($this->overviewMap !== null) {
+			$ovWmsArray = $this->overviewMap->getWmsArray();
+			$overviewWmsIndex = 0;
+			for ($i = 0; $i < count($ovWmsArray); $i++) {
+				for ($j = 0; $j < count($wmsArray); $j++) {
+					if ($ovWmsArray[$i]->equals($wmsArray[$j]) && !in_array($j, $skipWmsArray)) {
+						$overviewWmsIndex = $j;	
+						$wmsIndexOverview = $i;					
+						break;
+					}
+				}
+			}
+		}
+
+		// for all wms...
+		for ($i = 0; $i < count($wmsArray); $i++) {
+			if (in_array($i, $skipWmsArray)) {
+				continue;
+			}
+			array_push($wmcJsArray, $wmsArray[$i]->createJsObjFromWMS_());
+			$this->incrementLoadCount($wmsArray[$i]);
+		}
+		
+		// delete existing map objects...
+//		array_push($wmcJsArray, "mb_mapObj = [];");
+
+		// .. and add the overview map (if exists) and set map request
+		if ($this->overviewMap !== null) {
+			$wmcJsArray = array_merge(
+				$wmcJsArray, 
+				$this->overviewMap->toJavaScript(
+					"{wms:wms,wmsIndexOverview:" . $overviewWmsIndex . "}"
+				)
+			);
+		}
+
+		// .. and add main map ..
+		$wmcJsArray = array_merge(
+			$wmcJsArray, 
+			$this->mainMap->toJavaScript(
+				"{wms:wms,wmsIndexOverview:null}"
+			)
+		);
+
+		// set visibility of ov map WMS (may be different from main)
+		if ($this->overviewMap !== null) {
+			for ($i = 0; $i < count($ovWmsArray[$wmsIndexOverview]->objLayer); $i++) {
+				$visStr = "Mapbender.modules['".$this->overviewMap->getFrameName().
+//					"'].wms[" .$wmsIndexOverview . "].handleLayer(" . 
+// The above doesn't work.
+// But there is only one WMS in the overview anyway! The index 0 is hard wired for now.
+					"'].wms[0].handleLayer(" . 
+					"'" . $ovWmsArray[$wmsIndexOverview]->objLayer[$i]->layer_name . "', " . 
+					"'visible', " . 
+					($ovWmsArray[$wmsIndexOverview]->objLayer[$i]->gui_layer_visible ? 1 : 0) . ");";
+				array_push($wmcJsArray, $visStr);
+			}
+			array_push($wmcJsArray, "Mapbender.modules['".$this->overviewMap->getFrameName().
+					"'].restateLayers(" . $ovWmsArray[$wmsIndexOverview]->wms_id . ");");
+		}
+
+		// .. request the map
+		array_push($wmcJsArray, "Mapbender.modules['".$this->mainMap->getFrameName().
+					"'].setMapRequest();");
+		if ($this->overviewMap !== null) {
+			array_push($wmcJsArray, "Mapbender.modules['".$this->overviewMap->getFrameName().
+					"'].setMapRequest();");
+		}
+
+		array_push($wmcJsArray, "eventAfterLoadWMS.trigger();");
+		return $wmcJsArray;
+	}
+	
+	// ------------------------------------------------------------------------
+	// manipulation
+	// ------------------------------------------------------------------------
+	/**
+	 * Merges this WMC with another WMC.
+	 * The settings of the other WMC overwrite the settings of this WMC.
+	 * 
+	 * @return void
+	 * @param $xml2 Object
+	 */
+	public function merge ($xml2) {
+		$someWmc = new wmc();
+		$someWmc->createFromXml($xml2);
+
+		$this->mainMap->merge($someWmc->mainMap);
+		if (isset($this->overviewMap) && isset($someWmc->overviewMap)) {
+			$this->overviewMap->merge($someWmc->overviewMap);
+		}
+	}
+
+	/**
+	 * Appends the layers of another WMC to this WMC.
+	 * 
+	 * @return void
+	 * @param $xml2 Object
+	 */
+	public function append ($xml2) {
+		$someWmc = new wmc();
+		$someWmc->createFromXml($xml2);
+
+		$this->mainMap->append($someWmc->mainMap);
+		if (isset($this->overviewMap) && isset($someWmc->overviewMap)) {
+			// There is only one WMS in the overview map; merge, not append
+			$this->overviewMap->merge($someWmc->overviewMap);
+		}
+	}
+
+	/**
+	 * Adds a WMS to this WMC
+	 * 
+	 * @return 
+	 */
+	public function appendWmsArray ($wmsArray) {
+		return $this->mainMap->appendWmsArray($wmsArray);
+	}
+	
+	/**
+	 * Merges a WMS into this WMC
+	 * 
+	 * @return 
+	 */
+	public function mergeWmsArray ($wmsArray) {
+		if (func_num_args() > 1) {
+			$options = func_get_arg(1);
+			return $this->mainMap->mergeWmsArray($wmsArray, $options);
+		}
+		return $this->mainMap->mergeWmsArray($wmsArray);
+	}
+
+// ---------------------------------------------------------------------------
+// private functions
+// ---------------------------------------------------------------------------
+
+	/**
+	 * Loads a WMC from an actual WMC XML document.
+	 * Uses WMS class.
+	 * 
+	 * @param string $data the data from the XML file
+	 */
+	protected function createObjFromWMC_xml($data){
+		// store xml 
+		$this->xml = $data;
+	
+		$values = administration::parseXml($data);
+		if (!$values) {
+			throw new Exception("WMC document could not be parsed.");
+		}
+		//
+		// Local variables that indicate which section of the WMC
+		// is currently parsed.
+		//
+		$extension = false;		$general = false;		$layerlist = false;
+		$layer = false;  		$formatlist = false;	$dataurl = false;
+		$metadataurl = false; 	$stylelist = false;
+
+		//
+		// reset WMC data
+		//
+		$this->mainMap = new Map();
+		$this->overviewMap = null;
+		$this->generalExtensionArray = array();
+		
+		$layerlistArray = array();
+		$layerlistArray["main"] = array();
+		$layerlistArray["overview"] = array();
+
+		foreach ($values as $element) {
+			$tag = strtoupper(administration::sepNameSpace($element[tag]));
+			$tagLowerCase = administration::sepNameSpace($element[tag]);
+			$type = $element[type];
+			$attributes = $element[attributes];
+			$value = mb_utf8_decode(html_entity_decode($element[value]));
+			
+			if ($tag == "VIEWCONTEXT" && $type == "open") {
+				$this->wmc_id = $attributes["id"];
+				$this->wmc_version = $attributes["version"];
+			}
+			if ($tag == "GENERAL" && $type == "open") {
+				$general = true;
+			}
+			if ($tag == "LAYERLIST" && $type == "open") {
+				$layerlist = true;
+			}
+			if ($general) {
+				if ($tag == "WINDOW") {
+					$this->mainMap->setWidth($attributes["width"]);
+					$this->mainMap->setHeight($attributes["height"]);
+				}
+				if ($tag == "BOUNDINGBOX") {
+					$bbox = new Mapbender_bbox($attributes["minx"], $attributes["miny"], $attributes["maxx"], $attributes["maxy"], $attributes["SRS"]);
+					$this->mainMap->setExtent($bbox);
+				}
+				if ($tag == "NAME") {
+					$this->wmc_name = $value;
+				}
+				if ($tag == "TITLE") {
+					$this->wmc_title = $value;
+				}
+				if ($tag == "ABSTRACT") {
+					$this->wmc_abstract = $value;
+				}
+				if ($tag == "CONTACTINFORMATION" && $type == "open") {
+					$contactinformation = true;
+				}
+				if ($contactinformation) {
+					if ($tag == "CONTACTPOSITION") {
+						$this->wmc_contactposition = $value;
+					}
+					if ($tag == "CONTACTVOICETELEPHONE") {
+						$this->wmc_contactvoicetelephone = $value;
+					}
+					if ($tag == "CONTACTFACSIMILETELEPHONE") {
+						$this->wmc_contactfacsimiletelephone = $value;
+					}
+					if ($tag == "CONTACTELECTRONICMAILADDRESS") {
+						$this->wmc_contactemail = $value;
+					}
+					if ($tag == "CONTACTPERSONPRIMARY" && $type == "open") {
+						$contactpersonprimary = true;
+					}
+					if ($contactpersonprimary) {
+						if ($tag == "CONTACTPERSON") {
+							$this->wmc_contactperson = $value;
+						}
+						if ($tag == "CONTACTORGANIZATION") {
+							$this->wmc_contactorganization = $value;;
+						}
+						if ($tag == "CONTACTPERSONPRIMARY" && $type == "close") {
+							$contactpersonprimary = false;
+						}
+					}
+					if ($tag == "CONTACTADDRESS" && $type == "open") {
+						$contactaddress = true;
+					}
+					if ($contactaddress) {
+						if ($tag == "ADDRESSTYPE") {
+							$this->wmc_contactaddresstype = $value;
+						}
+						if ($tag == "ADDRESS") {
+							$this->wmc_contactaddress = $value;
+						}
+						if ($tag == "CITY") {
+							$this->wmc_contactcity = $value;
+						}
+						if ($tag == "STATEORPROVINCE") {
+							$this->wmc_contactstateorprovince = $value;
+						}
+						if ($tag == "POSTCODE"){
+							$this->wmc_contactpostcode = $value;
+						}
+						if ($tag == "COUNTRY") {
+							$this->wmc_contactcountry = $value;
+						}
+						if ($tag == "CONTACTADDRESS" && $type == "close") {
+							$contactaddress = false;
+						}
+					}
+				}
+				if ($tag == "LOGOURL" && $type == "open") {
+						$logourl = true;
+						$this->wmc_logourl_width = $attributes["width"];
+						$this->wmc_logourl_height = $attributes["height"];
+						$this->wmc_logourl_format = $attributes["format"];
+				}
+				if ($logourl) {
+					if ($tag == "LOGOURL" && $type == "close") {
+						$logourl = false;
+					}
+					if ($tag == "ONLINERESOURCE") {
+						$this->wmc_logourl_type = $attributes["xlink:type"];
+						$this->wmc_logourl = $attributes["xlink:href"];
+					}
+				}
+				if ($tag == "DESCRIPTIONURL" && $type == "open") {
+						$descriptionurl = true;
+						$this->wmc_descriptionurl_format = $attributes["format"];
+				}
+				if ($descriptionurl) {
+					if ($tag == "DESCRIPTIONURL" && $type == "close"){
+						$descriptionurl = false;
+					}
+					if ($tag == "ONLINERESOURCE") {
+						$this->wmc_descriptionurl_type = $attributes["xlink:type"];
+						$this->wmc_descriptionurl = $attributes["xlink:href"];
+					}
+				}
+				if ($tag == "KEYWORDLIST" && $type == "open") {
+					$keywordlist = true;
+				}
+				if ($keywordlist) {
+					if ($tag == "KEYWORDLIST" && $type == "close") {
+						$keywordlist = false;
+						$cnt_keyword = -1;
+					}
+					if ($tag == "KEYWORD") {
+						$cnt_keyword++;
+						$this->wmc_keyword[$cnt_keyword] = $value;
+					}
+				}
+				if ($tag == "EXTENSION" && $type == "close") {
+					$generalExtension = false;
+					//
+					// After the general extension tag is closed,
+					// we have all necessary information to CREATE
+					// the map objects that are contained in this
+					// WMC.
+					//
+					$this->setMapData();
+				}
+				if ($generalExtension) {
+					if ($value !== "") {
+						if (isset($this->generalExtensionArray[$tag])) {
+							if (!is_array($this->generalExtensionArray[$tag])) {
+								$firstValue = $this->generalExtensionArray[$tag];
+								$this->generalExtensionArray[$tag] = array();
+								array_push($this->generalExtensionArray[$tag], $firstValue);
+							}	
+							array_push($this->generalExtensionArray[$tag], $value);
+						}
+						else {
+							$this->generalExtensionArray[$tag] = $value;									
+						}
+					}
+				}
+				if ($tag == "EXTENSION" && $type == "open") {
+					$generalExtension = true;
+				}
+				if ($tag == "GENERAL" && $type == "close") {
+		   			$general = false;
+			 	}
+			}
+			if ($layerlist) {
+				if ($tag == "LAYERLIST" && $type == "close") {
+				   $layerlist = false;
+				}
+				if ($tag == "LAYER" && $type == "open") {
+					//
+					// The associative array currentLayer holds all 
+					// data of the currently processed layer.
+					// The data will be set in the classes' WMS
+					// object when the layer tag is closed.
+					//
+					$currentLayer = array();
+					
+					$currentLayer["queryable"] = $attributes["queryable"];
+					if ($attributes["hidden"] == "1") {
+						$currentLayer["visible"] = 0;
+					}
+					else {
+						$currentLayer["visible"] = 1;
+					}
+					$currentLayer["format"] = array();
+					$currentLayer["style"] = array();
+					$layer = true;
+				}
+				if ($layer) {
+					if ($tag == "LAYER" && $type == "close") {
+
+						//
+						// After a layer tag is closed,
+						// we have all necessary information to CREATE
+						// a layer object and append it to the WMS object
+						//
+						if (isset($currentLayer["extension"]["OVERVIEWHIDDEN"])) {
+							array_push($layerlistArray["overview"], $currentLayer);		
+						}
+						$modifiedLayer = $currentLayer;
+						unset($modifiedLayer["extension"]["OVERVIEWHIDDEN"]);
+						array_push($layerlistArray["main"], $modifiedLayer);											
+				 		$layer = false;
+					}
+					if ($formatlist) {
+						if ($tag == "FORMAT") {
+						 	array_push($currentLayer["format"], array("current" => $attributes["current"], "name" => $value));
+							if ($attributes["current"] == "1") {
+								$currentLayer["formatIndex"] = count($currentLayer["format"]) - 1;
+							}
+						 }
+						 if ($tag == "FORMATLIST" && $type == "close") {
+							 $formatlist = false;
+						 }
+					 }
+					 elseif ($metadataurl) {
+						if ($tag == "ONLINERESOURCE") {
+							$currentLayer["metadataurl"] = $attributes["xlink:href"];
+						}
+						if ($tag == "METADATAURL" && $type == "close") {
+							$metadataurl = false;
+						}
+					 }
+					 elseif ($dataurl) {
+						if ($tag == "ONLINERESOURCE") {
+						 	$currentLayer["dataurl"] = $attributes["xlink:href"];
+						}
+						 if ($tag == "DATAURL" && $type == "close") {
+							$dataurl = false;
+						 }
+					 }
+					 elseif ($stylelist) {
+						if ($style) {
+							$index = count($currentLayer["style"]) - 1;
+							if ($tag == "STYLE" && $type == "close") {
+								$style = false;
+							}
+							if ($tag == "SLD" && $type == "open") {
+								$sld = true;
+							}
+							if ($sld) {
+								if ($tag == "SLD" && $type == "close") {
+									$sld = false;
+								}
+								if ($tag == "ONLINERESOURCE") {
+									$currentLayer["style"][$index]["sld_type"] = $attributes["xlink:type"];
+									$currentLayer["style"][$index]["sld_url"] = $attributes["xlink:href"];
+								}
+								if ($tag == "TITLE") {
+									$currentLayer["style"][$index]["sld_title"] = $value;
+								}
+							}
+							else {
+								if ($tag == "NAME"){
+									$currentLayer["style"][$index]["name"] = $value ? $value : "default";
+								}
+								if ($tag == "TITLE") {
+									$currentLayer["style"][$index]["title"] = $value ? $value : "default";
+								}
+								if ($legendurl) {
+									if ($tag == "LEGENDURL" && $type == "close") {
+										$legendurl = false;
+									}
+									if ($tag == "ONLINERESOURCE") {
+									 	$currentLayer["style"][$index]["legendurl_type"] = $attributes["xlink:type"];
+									 	$currentLayer["style"][$index]["legendurl"] = $attributes["xlink:href"];
+									}
+								}
+								if ($tag == "LEGENDURL" && $type == "open") {
+								 	$legendurl = true;
+								 	$currentLayer["style"][$index]["legendurl_width"] = $attributes["width"];
+								 	$currentLayer["style"][$index]["legendurl_height"] = $attributes["height"];
+								 	$currentLayer["style"][$index]["legendurl_format"] = $attributes["format"];
+								}
+							}
+						}
+						if ($tag == "STYLE" && $type == "open") {
+							$style = true;
+							array_push($currentLayer["style"], array("current" => $attributes["current"]));
+							if ($attributes["current"] == "1") {
+								$currentLayer["styleIndex"] = count($currentLayer["style"]) - 1;
+							}
+						}
+						if ($tag == "STYLELIST" && $type == "close") {
+							$stylelist = false;
+						}
+					}
+					else {
+						if ($tag == "SERVER" && $type == "open") {
+							 $server = true;
+							 $currentLayer["service"] = $attributes["service"];
+							 $currentLayer["version"] = $attributes["version"];
+							 $currentLayer["wms_title"] = $attributes["title"];
+						}
+						if ($server) {
+							if ($tag == "SERVER" && $type == "close") {
+						 		$server = false;
+						 	}
+							if ($tag == "ONLINERESOURCE") {
+						 		$currentLayer["url"] = $attributes["xlink:href"];
+							}
+						}
+						if ($tag == "NAME") {
+					 		$currentLayer["name"] = $value;
+						}
+						if ($tag == "TITLE") {
+					 		$currentLayer["title"] = $value;
+						}
+						if ($tag == "ABSTRACT") {
+					 		$currentLayer["abstract"] = $value;
+						}
+						if ($tag == "SRS") {
+							$currentLayer["epsg"] = explode(" ", $value);						 	
+						}
+						if ($tag == "EXTENSION" && $type == "close") {
+							$extension = false;
+						}
+						if ($extension == true){
+//							if ($value !== "") {
+								if (isset($currentLayer["extension"][$tag])) {
+									if (!is_array($currentLayer["extension"][$tag])) {
+										$firstValue = $currentLayer["extension"][$tag];
+										$currentLayer["extension"][$tag] = array();
+										array_push($currentLayer["extension"][$tag], $firstValue);
+									}	
+									array_push($currentLayer["extension"][$tag], $value);
+								}
+								else {
+									$currentLayer["extension"][$tag] = $value;									
+								}
+//							}
+						}
+						if ($tag == "EXTENSION" && $type == "open") {
+							$currentLayer["extension"] = array();
+							$extension = true;
+						}
+						if ($tag == "METADATAURL" && $type == "open") {
+							$metadataurl = true;
+						}
+						if ($tag == "DATAURL" && $type == "open") {
+							$dataurl = true;
+						}
+						if ($tag == "FORMATLIST" && $type == "open") {
+							$formatlist = true;
+						}
+						if ($tag == "STYLELIST" && $type == "open") {
+							$stylelist = true;
+						}
+					}
+				}
+			}
+		}
+		
+		// set WMS data
+		
+		$layerlistCompleteArray = array_merge($layerlistArray["main"], $layerlistArray["overview"]);
+
+		for ($i = 0; $i < count($layerlistCompleteArray); $i++) {
+			$this->setLayerData($layerlistCompleteArray[$i]);
+		}
+
+		$wmsArr = $this->mainMap->getWmsArray();
+		for ($i = 0; $i < count($wmsArr); $i++) {
+			$wmsArr[$i]->updateAllOwsProxyUrls();
+		}
+		return true;
+	}
+
+	/**
+	 * Saves the current WMC in the log folder.
+	 * 
+	 * @return string the filename of the WMC document.
+	 */
+	private function saveAsFile() {
+		if ($this->saveWmcAsFile) {
+			$filename = "wmc_" . date("Y_m_d_H_i_s") . ".xml";
+			$logfile = "../tmp/" . $filename;
+			
+			if($h = fopen($logfile,"a")){
+				$content = $this->xml;
+				if(!fwrite($h,$content)){
+					$e = new mb_exception("class_wmc.php: failed to write wmc.");
+					return false;
+				}
+				fclose($h);
+			}
+			$e = new mb_notice("class_wmc: saving WMC as file " . $filename . "; You can turn this behaviour off in class_wmc.php");
+			return $filename;
+		}
+		return null;
+	}
+	
+	/**
+	 * Called during WMC parsing; sets the data of a single layer.
+	 * 
+	 * @return 
+	 * @param $currentLayer Array an associative array with layer data
+	 */
+	private function setLayerData ($currentLayer) {
+		$currentMap = $this->mainMap;
+		$currentMapIsOverview = false;
+
+		if (isset($currentLayer["extension"]["OVERVIEWHIDDEN"])) {
+			$currentMap = $this->overviewMap;
+			$currentMapIsOverview = true;
+		}
+
+		if (is_null($currentMap)) {
+			$e = new mb_exception('class_wmc.php: setLayerData: $currentMap is null. Aborting.');
+			return null;
+		}
+
+		$wmsArray = $currentMap->getWmsArray();
+
+		//
+		// check if current layer belongs to an existing WMS.
+		// If yes, store the index of this WMS in $wmsIndex.
+		// If not, set the value to null.
+		//
+		$wmsIndex = null;
+
+		// find last WMS with the same online resource
+		for ($i = count($wmsArray) - 1; $i >= 0; $i--) {
+			if (isset($currentLayer["url"]) && 
+				$currentLayer["url"] == $wmsArray[$i]->wms_getmap) {
+					$wmsIndex = $i;
+					break;
+			}
+		}
+
+		// Even if this WMS has been found before it could still
+		// be a duplicate! We would have to create a new WMS and 
+		// not append this layer to that WMS.
+		// For the overview layer we never add a new wms.
+		// check if this layer is an overview layer. If yes, skip this layer.
+		if ($wmsIndex !== null && !$currentMapIsOverview) {
+
+			// check if this WMS has a layer equal to the current layer.
+			// If yes, this is a new WMS. If not, append this layer
+			// to the existing WMS.
+			$matchingWmsLayerArray = $this->wmsArray[$wmsIndex]->objLayer;
+			
+			for ($i = 0; $i < count($matchingWmsLayerArray); $i++) {
+				if ($matchingWmsLayerArray[$i]->layer_name == $currentLayer["name"]) {
+
+					// by re-setting the index to null, a new WMS will be 
+					// added below.
+					$wmsIndex = null;
+					break;
+				}
+			}
+		}
+
+		// if yes, create a new WMS ...
+		if ($wmsIndex === null) {
+			$wmsIndex = 0;
+			$wms = new wms();
+
+			//
+			// set WMS data
+			//
+			$wms->wms_id = $currentLayer["extension"]["WMS_ID"]; // TO DO: how about WMS without ID?
+			$wms->wms_version = $currentLayer["version"];
+			$wms->wms_title = $currentLayer["wms_title"];
+			$wms->wms_abstract = $currentLayer["abstract"];
+			$wms->wms_getmap = $currentLayer["url"];
+			$wms->wms_getfeatureinfo = $currentLayer["url"]; // TODO : Add correct data
+			
+			$styleIndex = $currentLayer["styleIndex"];
+			$wms->wms_getlegendurl = $currentLayer["style"][$styleIndex]["legendurl"];
+
+			$wms->wms_filter = ""; // TODO : Add correct data
+
+			$formatIndex = $currentLayer["formatIndex"];
+			$wms->gui_wms_mapformat = $currentLayer["format"][$formatIndex]["name"];
+
+			$wms->gui_wms_featureinfoformat = "text/html"; // TODO : Add correct data
+			$wms->gui_wms_exceptionformat = "application/vnd.ogc.se_xml"; // TODO : Add correct data
+			$wms->gui_wms_epsg = $this->mainMap->getEpsg();
+			$wms->gui_wms_visible = $currentLayer["extension"]["WMS_VISIBLE"];
+			$wms->gui_wms_opacity = 100; // TODO : Add correct data
+			$wms->gui_wms_sldurl = $currentLayer["style"][$styleIndex]["sld_url"];
+			$wms->wms_srs = $currentLayer["epsg"];
+			$wms->gui_epsg = $currentLayer["epsg"];
+			//
+			// set data formats
+			//
+			for ($i = 0; $i < count($currentLayer["format"]); $i++) {
+				array_push($wms->data_type, "map");							
+				array_push($wms->data_format, $currentLayer["format"][$i]["name"]);							
+			}
+
+			// add WMS
+			array_push($wmsArray, $wms);
+
+			// the index of the WMS we just added
+			$wmsIndex = count($wmsArray) - 1;
+		}
+
+		// add layer to existing WMS ...
+		$currentWms = $wmsArray[$wmsIndex];
+		$currentWms->newLayer($currentLayer, null);
+		$currentMap->setWmsArray($wmsArray);
+		return true;
+	}
+	
+	/**
+	 * Called during WMC parsing; sets the maps within a WMC.
+	 * 
+	 * @return 
+	 */
+	private function setMapData () {
+		if ($this->generalExtensionArray["OV_WIDTH"] && 
+			$this->generalExtensionArray["OV_HEIGHT"] &&
+			$this->generalExtensionArray["OV_FRAMENAME"] &&
+			$this->generalExtensionArray["OV_MINX"] &&
+			$this->generalExtensionArray["OV_MINY"] &&
+			$this->generalExtensionArray["OV_MAXX"] &&
+			$this->generalExtensionArray["OV_MAXY"] &&
+			$this->generalExtensionArray["OV_SRS"]) {
+			
+			$this->overviewMap = new Map();
+			$this->overviewMap->setWidth(
+				// this should not be an array, but sometimes it is.
+				// I can't find the reason at the moment, consider
+				// this a workaround
+				is_array($this->generalExtensionArray["OV_WIDTH"]) ?
+					$this->generalExtensionArray["OV_WIDTH"][0] : 
+					$this->generalExtensionArray["OV_WIDTH"]
+			);
+			$this->overviewMap->setHeight(
+				// this should not be an array, but sometimes it is.
+				// I can't find the reason at the moment, consider
+				// this a workaround
+				is_array($this->generalExtensionArray["OV_HEIGHT"]) ? 
+					$this->generalExtensionArray["OV_HEIGHT"][0] :
+					$this->generalExtensionArray["OV_HEIGHT"]
+			);
+			$this->overviewMap->setFrameName(
+				// this should not be an array, but sometimes it is.
+				// I can't find the reason at the moment, consider
+				// this a workaround
+				is_array($this->generalExtensionArray["OV_FRAMENAME"]) ?
+					$this->generalExtensionArray["OV_FRAMENAME"][0] :
+					$this->generalExtensionArray["OV_FRAMENAME"]
+			);
+			$this->overviewMap->setIsOverview(true);
+
+			$bbox = new Mapbender_bbox($this->generalExtensionArray["OV_MINX"], $this->generalExtensionArray["OV_MINY"], $this->generalExtensionArray["OV_MAXX"], $this->generalExtensionArray["OV_MAXY"], $this->generalExtensionArray["OV_SRS"]);
+			$this->overviewMap->setExtent($bbox);
+		}
+		if ($this->generalExtensionArray["EPSG"] && 
+			$this->generalExtensionArray["MINX"] && 		
+			$this->generalExtensionArray["MINY"] && 		
+			$this->generalExtensionArray["MAXX"] && 		
+			$this->generalExtensionArray["MAXY"]) {
+
+			$mainEpsgArray = array();
+			$mainMinXArray = array();
+			$mainMinYArray = array();
+			$mainMaxXArray = array();
+			$mainMaxYArray = array();
+			if (!is_array($this->generalExtensionArray["EPSG"])) {
+				$mainEpsgArray[0] = $this->generalExtensionArray["EPSG"];
+				$mainMinXArray[0] = $this->generalExtensionArray["MINX"];
+				$mainMinYArray[0] = $this->generalExtensionArray["MINY"];
+				$mainMaxXArray[0] = $this->generalExtensionArray["MAXX"];
+				$mainMaxYArray[0] = $this->generalExtensionArray["MAXY"];
+			}
+			else {
+				$mainEpsgArray = $this->generalExtensionArray["EPSG"];
+				$mainMinXArray = $this->generalExtensionArray["MINX"];
+				$mainMinYArray = $this->generalExtensionArray["MINY"];
+				$mainMaxXArray = $this->generalExtensionArray["MAXX"];
+				$mainMaxYArray = $this->generalExtensionArray["MAXY"];
+			}
+
+			for ($i=0; $i < count($mainEpsgArray); $i++) {
+				$box = new Mapbender_bbox(
+					floatval($mainMinXArray[$i]), floatval($mainMinYArray[$i]), 
+					floatval($mainMaxXArray[$i]), floatval($mainMaxYArray[$i]),
+					$mainEpsgArray[$i]
+				);				
+				$this->mainMap->addZoomFullExtent($box);
+			}
+		}			
+
+		if ($this->generalExtensionArray["MAIN_FRAMENAME"]) {
+			$this->mainMap->setFrameName(
+				// this should not be an array, but sometimes it is.
+				// I can't find the reason at the moment, consider
+				// this a workaround
+				is_array($this->generalExtensionArray["MAIN_FRAMENAME"]) ?
+					$this->generalExtensionArray["MAIN_FRAMENAME"][0] :
+					$this->generalExtensionArray["MAIN_FRAMENAME"]
+			);
+		}
+		else {
+			$this->mainMap->setFrameName("mapframe1");
+		}
+		return true;
+	}
+
+	/**
+	 * Creates a WMC document (XML) from the current object
+	 * 
+	 * @return String XML
+	 */
+	private function createXml() {
+		$wmcToXml = new WmcToXml($this);
+		$this->xml = $wmcToXml->getXml();
+	}
+} 
+
+/**
+ * @deprecated
+ */
+function mb_utf8_encode ($str) {
+//	if(CHARSET=="UTF-8") return utf8_encode($str);
+	return $str;
+}
+
+/**
+ * @deprecated
+ */
+function mb_utf8_decode ($str) {
+//	if(CHARSET=="UTF-8") return utf8_decode($str);
+	return $str;
+}
+?>

Deleted: branches/mapbender/http/classes/class_wms.php
===================================================================
--- trunk/mapbender/http/classes/class_wms.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/http/classes/class_wms.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,2820 +0,0 @@
-<?php
-# License:
-# Copyright (c) 2009, Open Source Geospatial Foundation
-# This program is dual licensed under the GNU General Public License 
-# and Simplified BSD license.  
-# http://svn.osgeo.org/mapbender/trunk/mapbender/license/license.txt
-
-require_once dirname(__FILE__) . "/../../core/globalSettings.php";
-require_once dirname(__FILE__) . "/class_connector.php";
-require_once dirname(__FILE__) . "/class_user.php";
-require_once dirname(__FILE__) . "/class_administration.php";
-require_once dirname(__FILE__) . "/class_georss_factory.php";
-require_once dirname(__FILE__) . "/../classes/class_universal_wms_factory.php";
-
-class wms {
-	var $lastURL;
-	var $wms_id;
-	var $wms_status;
-	var $wms_version;
-	var $wms_title;
-	var $wms_abstract;
-	var $wms_getcapabilities;
-	var $wms_getcapabilities_doc;
-	var $wms_getmap;
-	var $wms_getfeatureinfo;
-	var $wms_getlegendurl;
-	var $wms_upload_url;
-	var $wms_timestamp;
-	var $wms_timestamp_create;
-	var $wms_srs = array();
-	var $wms_termsofuse;
-	  
-	var $fees;
-	var $accessconstraints;
-	var $contactperson;
-	var $contactposition;
-	var $contactorganization;
-	var $address;
-	var $city;
-	var $stateorprovince;
-	var $postcode;
-	var $country;
-	var $contactvoicetelephone;
-	var $contactfacsimiletelephone;
-	var $contactelectronicmailaddress;
-	  
-	var $wms_keyword = array();
-	var $data_type = array(); 
-	var $data_format = array();
-	var $objLayer = array(); 
-	  
-	var $wms_supportsld;
-	var $wms_userlayer;
-	var $wms_userstyle;
-	var $wms_remotewfs;
-		
-	var $gui_wms_mapformat;
-	var $gui_wms_featureinfoformat;
-	var $gui_wms_exceptionformat;
-	var $gui_wms_epsg;
-	var $gui_wms_sldurl;
-	  
-	var $default_epsg = 0;
-	var $overwrite = true;
-	
-	// write a GeoRSS feed?
-	const GEORSS = true;
-	// append items to the feed when a new WMS is inserted?
-	const GEORSS_APPEND_ON_INSERT = true;
-	// append items to the feed when an existing WMS is updated?
-	const GEORSS_APPEND_ON_UPDATE = true;
-	// append items to the feed only when an existing WMS is updated 
-	// and new layers have been added?
-	const GEORSS_APPEND_ON_UPDATE_NEWLAYERS = true;
-	  
-	function wms() {
-	} 
-    /**
-     *
-     * @generate RSS formated date 
-     *
-     * @param int $timestamp The UNIX_TIMESTAMP
-     *
-     * @return string
-     *
-     */
-    private static function rssDate($timestamp=null)
-    {
-        /*** set the timestamp ***/
-        $timestamp = ($timestamp==null) ? time() : $timestamp;
-
-        /*** Mon, 02 Jul 2009 11:36:45 +0000 ***/
-        return date(DATE_RSS, $timestamp);
-    }
-    
-	public static function getWmsMetadataUrl ($wmsId) {
-		return preg_replace(
-			"/(.*)frames\/login.php/", 
-			"$1php/mod_layerMetadata.php?id=", 
-			LOGIN
-		) . $wmsId;
-	}
-
-	public static function isOwsProxyUrl ($getmap) {
-//		$e = new mb_notice("isOwsProxyUrl? " . $getmap);
-		$result = preg_match("/^.*owsproxy.([^i][\w\d]+)\/([\w\d]{32})\/?.*$/", $getmap);
-//		$e = new mb_notice("result: " . $result);
-		return $result;
-	}
-
-	private function replaceSessionIdInOwsProxyUrl ($getMap) {
-//		$e = new mb_notice("replaceSessionIdInOwsProxyUrl: ");
-		$e = new mb_notice("before: " . $getMap);
-		$pattern = '/(^.*owsproxy.)([^i][\w\d]+)(\/)([\w\d]{32})(\/?.*)$/';
-		$getMap1= preg_replace($pattern, "$1",$getMap);
-		$getMap2=  preg_replace($pattern, "$3$4$5",$getMap);
-		$getMap = $getMap1.session_id().$getMap2;
-		$e = new mb_notice("after: " . $getMap);
-		return $getMap;
-	}
-	
-	public static function getHashFromOwsProxyUrl ($getMap) {
-//		$e = new mb_notice("replaceSessionIdInOwsProxyUrl: " . $getMap);
-		$result = preg_replace("/^.*owsproxy.([^i][\w\d]+)\/([\w\d]{32})\/?.*$/", "$2", $getMap);
-//		$e = new mb_notice("result: " . $result);
-		return $result;
-	}
-	
-	private function getWmsIdByOwsProxyHash($md5) {
-		$sql = "SELECT wms_id FROM wms WHERE wms_owsproxy = $1";
-		$v = array($md5);
-		$t = array("s");
-		$res = db_prep_query($sql, $v, $t);
-		$row = db_fetch_row($res);
-		if ($row["wms_id"]) {
-			return $row["wms_id"];
-		}
-		return null;
-	}
-	
-	private function updateOwsProxyUrl ($url) {
-		// is OWS proxy URL?
-		if (wms::isOwsProxyUrl($url)) {
-
-			// No WMS id could be found
-			if (!$this->wms_id) {
-				$e = new mb_notice("No WMS id could be found!");
-				return $url;
-			}			
-			// Update session id in OWS proxy URL
-			$new_proxy_url = $this->replaceSessionIdInOwsProxyUrl($url);
-
-			// If new url is a valid proxy URL, return true
-			if ($this->isOwsProxyUrl($new_proxy_url)) {
-				return $new_proxy_url;
-			}
-			else {
-//				$e = new mb_notice("new URL is not an OWS proxy URL!");
-			}
-			// new URL is not an OWS proxy URL; 
-			// some error must have occured.
-			// no update
-			return $url;
-		}
-		// no OWS proxy URL, no update necessary
-//		$e = new mb_notice("URL is not an OWS proxy URL!");
-		return $url;
-	}
-	
-	function updateAllOwsProxyUrls () {
-		$wmsId = $this->wms_id;
-
-		// if WMS id is unknown, try to 
-		// find it via OWS proxy entry
-		//FIXME -Funktion berichtigen 
-		if (!$wmsId) {
-			$md5 = wms::getHashFromOwsProxyUrl($url);
-			if ($md5) {
-				$wmsId = $this->getWmsIdByOwsProxyHash($md5);
-				if (!is_null($wmsId)) {
-					$this->wms_id = $wmsId;
-				}
-			}
-		}
-
-		$this->wms_getmap = 
-			$this->updateOwsProxyUrl($this->wms_getmap);
-		$this->wms_getfeatureinfo = 
-			$this->updateOwsProxyUrl($this->wms_getfeatureinfo);
-		$this->wms_getlegendurl = 
-			$this->updateOwsProxyUrl($this->wms_getlegendurl);
-		
-		for ($i = 0; $i < count($this->objLayer); $i++) {
-			for ($j = 0; $j < count($this->objLayer[$i]->layer_style); $j++) {
-				$this->objLayer[$i]->layer_style[$j]["legendurl"] = 
-					$this->updateOwsProxyUrl($this->objLayer[$i]->layer_style[$j]["legendurl"]);
-			}
-		}
-	}
-	
-	public static function getConjunctionCharacter ($url) {
-		if (mb_strpos($url, "?") !== false) { 
-			if (mb_substr($url, mb_strlen($url)-1, 1) == "?") { 
-				return "";
-			}
-			else if (mb_substr($url, mb_strlen($url)-1, 1) == "&"){
-				return "";
-			}
-			else {
-				return "&";
-			}
-		}
-		else {
-			return "?";
-		}
-		return "";
-	}
-
-	public function getLayerById ($id) {
-		for ($i = 0; $i < count($this->objLayer); $i++) {
-			if (strval($this->objLayer[$i]->layer_uid) === strval($id)) {
-				return $this->objLayer[$i];
-			}
-		}
-		return null;
-	}
-
-	public function getLayerByPos ($pos) {
-		for ($i = 0; $i < count($this->objLayer); $i++) {
-			if (strval($this->objLayer[$i]->layer_pos) === strval($pos)) {
-				return $this->objLayer[$i];
-			}
-		}
-		return null;
-	}
-
-	function createOlObjFromWMS($base){
-	 	if(!$this->wms_title || $this->wms_title == ""){
-			echo "alert('Error: no valid capabilities-document !!');";
-			die; exit;
-		}
-		// wms_title and abstract have previously been urlencoded
-		// this solution may not yet be the ultimate one
-		
-		$add_wms_string  = "var wms_".$this->wms_id." = new OpenLayers.Layer.WMS(";
-		// WMS-title
-		$add_wms_string .= "'" . addslashes($this->wms_title) . "',";
-		// Base-URL of service
-		$add_wms_string .= "'" . $this->wms_getmap ."',";
-		// Additional URL params
-		$add_wms_string .= "{layers:'";
-		for($i=1;$i<count($this->objLayer);$i++){
-			$add_wms_string .= addslashes($this->objLayer[$i]->layer_name);
-			if($i!=count($this->objLayer)-1) {
-				$add_wms_string .= ",";
-			}
-		}
-		$add_wms_string .= "',";
-		// This is hardcoded, exactly as for Mapbender WMS
-		$add_wms_string .= "transparent: 'true',";
-		$add_wms_string .= "format: '".$this->gui_wms_mapformat."'},";
-		// OpenLayers-Layer options
-		$add_wms_string .= "{";
-		$add_wms_string .= 	"transitionEffect:'resize',";
-		$add_wms_string .= 	"ratio:1.2,";
-		$add_wms_string .= 	"singleTile:true,";
-		// baselayer?				
-		if($base) {
-			$add_wms_string .= 	"isBaseLayer:true,";
-		} else {
-			$add_wms_string .= 	"isBaseLayer:false,";
-		}
-		// visible or not?
-		if($this->gui_wms_visible=="1") {
-			$add_wms_string .= 	"visibility:true,";
-		} else {
-			$add_wms_string .= 	"visibility:false,";
-		}
-		// initial transparency
-		$add_wms_string .= 	"opacity:" . strval(round($this->gui_wms_opacity/100, 2));
-		
-		$add_wms_string .= "}";
-		$add_wms_string .= ");";
-		
-		$queryLayers = array();
-		for ($i = 0; $i < count($this->objLayer); $i++) {
-			$layer = $this->objLayer[$i];
-			if ($layer->layer_queryable 
-				&& $layer->gui_layer_queryable 
-				&& $layer->gui_layer_querylayer
-			) {
-				$queryLayers[]= $layer->layer_name;
-			}
-		}
-		$queryLayerString = implode(",", $queryLayers);
-		$add_wms_string .= "wms_" . $this->wms_id . ".params.QUERY_LAYERS = '$queryLayerString';";
-
-		// TODO why ol_map
-		$add_wms_string .= "ol_map.addLayer(wms_".$this->wms_id.");";
-		echo $add_wms_string;
-	}	
-	
-	/**
-	 * Compares this WMS to another WMS.
-	 * 
-	 * @return boolean false, if
-	 * 					- the capabilities URLs don't match
-	 * 					- the layer count is different
-	 * 					- the layer names are different
-	 * 
-	 * @param $anotherWms wms this is just another WMS object
-	 */
-	public function equals ($anotherWms) {
-		// If the getMap URLs are not equal, the WMS are not equal.
-		if ($this->wms_getmap != $anotherWms->wms_getmap) {
-//			$e = new mb_notice($this . " != " . $anotherWms . " (getMap URL)");
-			return false;
-		}
-
-		// If the layer count is different, the WMS are not equal.
-		if (count($this->objLayer) != count($anotherWms->objLayer)) {
-//			$e = new mb_notice($this . " != " . $anotherWms . " (layer count: " . count($this->objLayer) . ":" . count($anotherWms->objLayer). ")");
-			return false;
-		}
-		
-		// If the layer names are different, the WMS are not equal.
-		for ($i = 0; $i < count($this->objLayer); $i++) {
-			$name1 = $this->objLayer[$i]->layer_name;
-			$name2 = $anotherWms->objLayer[$i]->layer_name;
-			if ($name1 != $name2) {
-//				$e = new mb_notice($this . " != " . $anotherWms . " (layer names, " . $name1 . " vs. " . $name2 . ")");
-				return false;
-			}
-		}
-		
-//		$e = new mb_notice($this . " == " . $anotherWms);
-		return true;
-	}  
-	
-	/**
-	 * Removes duplicate WMS from an array of WMS. To find duplicates,
-	 * two WMS are compared via equals().
-	 * 
-	 * @return wms[]
-	 * @param $wmsArray wms[]
-	 */
-	public static function merge ($wmsArray) {
-//		$e = new mb_notice("before: " . implode(", ", $wmsArray));
-		if (!is_array($wmsArray)) {
-			$e = new mb_notice("class_wms.php: merge(): parameter is NOT an array.");
-			return array();
-		}
-		if (count($wmsArray) == 0) {
-			$e = new mb_notice("class_wms.php: merge(): parameter is an EMPTY array.");
-			return array();
-		}
-		
-		$newWmsArray = array();
-		
-		while (count($wmsArray) > 0) {
-			$currentWms = array_pop($wmsArray);
-			
-			$isNewWms = true;
-
-			if (get_class($currentWms) != "wms") {
-				$e = new mb_notice("class_wms.php: merge(): current WMS is not a WMS object, but a " . get_class($currentWms));
-			}
-			else {
-				for ($i = 0; $i < count($newWmsArray) && $isNewWms; $i++) {
-					if ($currentWms->equals($newWmsArray[$i])) {
-						$isNewWms = false;
-					}
-				}
-				if ($isNewWms) {
-					$e = new mb_notice("adding WMS " . $currentWms);
-					array_push($newWmsArray, $currentWms);
-				}
-				else {
-					//newWmsArray contains currentWms
-					// --> TODO: check which layers have to be merged into the existing WMS 
-				}
-			}
-		}
-		// reversal of the array, because the elements were popped 
-		// from another array before.
-		$e = new mb_notice("after: " . implode(", ", array_reverse($newWmsArray)));
-		return array_reverse($newWmsArray);
-	}
-
-	private function formatExists ($type, $format) {
-		for ($i = 0; $i < count($this->data_type); $i++) {
-			if ($type == $this->data_type[$i] && $format == $this->data_format[$i]) {
-				$e = new mb_warning("WMS format already exists ($type, $format). Violation of WMS spec. Ignoring this WMS format.");
-				return true;
-			}
-		}
-		return false;
-	}
-	
-	public function __toString () {
-		return $this->wms_title;
-	}
-	
-	function createObjFromXML($url){
-		if (func_num_args() == 2) { //new for HTTP Authentication
-            		$auth = func_get_arg(1);
-			$x = new connector($url,$auth);
-		}
-		else {
-			$x = new connector($url);
-		}
-		$data = $x->file;
-		if ($data=='401') {
-			echo "<br>HTTP Error:<b>".$data." - Authorization required. This seems to be a service which needs HTTP Authentication!</b><br>";
-		}
-		if(!$data){
-			$this->wms_status = false;
-			return false;
-		}
-		else {
-			$this->wms_status = true;
-		}
-			
-		$values = null;
-		$tags = null;
-		$admin = new administration();
-		$this->wms_getcapabilities_doc = $data;
-		$this->wms_upload_url = $url;
-		
-		$this->wms_id = "";
-		$parser = xml_parser_create("");
-		xml_parser_set_option($parser,XML_OPTION_CASE_FOLDING,0);
-		xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,1);
-		xml_parser_set_option($parser,XML_OPTION_TARGET_ENCODING,CHARSET);
-		xml_parse_into_struct($parser,$data,$values,$tags);
-
-		$code = xml_get_error_code($parser);
-		if ($code) {
-			$line = xml_get_current_line_number($parser); 
-			$mb_exception = new mb_exception(xml_error_string($code) .  " in line " . $line);
-		}
-		
-		xml_parser_free($parser);
-		
-		$section = null;
-		$format = null;
-		$cnt_format = 0;
-		$parent = array();
-		$myParent = array();
-		$cnt_layer = -1;
-		$request = null; 
-		$layer_style = array();
-		$cnt_styles = -1;
-		
-		$this->wms_getfeatureinfo = "";
-		$this->gui_wms_featureinfoformat = "";
-
-		foreach ($values as $element) {
-			if(mb_strtoupper($element[tag]) == "WMT_MS_CAPABILITIES" && $element[type] == "open"){
-				$this->wms_version = $element[attributes][version];
-			}
-			if(mb_strtoupper($element[tag]) == "TITLE" && $element[level] == '3'){
-				$this->wms_title = $this->stripEndlineAndCarriageReturn($element[value]);
-			}
-			if(mb_strtoupper($element[tag]) == "ABSTRACT" && $element[level] == '3'){
-				$this->wms_abstract = $this->stripEndlineAndCarriageReturn($element[value]);
-			}
-			if(mb_strtolower($element[tag]) == "fees"){
-				$this->fees = $element[value];
-			}
-			if(mb_strtolower($element[tag]) == "accessconstraints"){
-				$this->accessconstraints = $element[value];
-			}
-			if(mb_strtolower($element[tag]) == "contactperson"){
-				$this->contactperson = $element[value];
-			}
-			if(mb_strtolower($element[tag]) == "contactposition"){
-				$this->contactposition = $element[value];
-			}
-			if(mb_strtolower($element[tag]) == "contactorganization"){
-				$this->contactorganization = $element[value];
-			}
-			if(mb_strtolower($element[tag]) == "address"){
-				$this->address = $element[value];
-			}
-			if(mb_strtolower($element[tag]) == "city"){
-				$this->city = $element[value];
-			}
-			if(mb_strtolower($element[tag]) == "stateorprovince"){
-				$this->stateorprovince = $element[value];
-			}
-			if(mb_strtolower($element[tag]) == "postcode"){
-				$this->postcode = $element[value];
-			}
-			if(mb_strtolower($element[tag]) == "country"){
-				$this->country = $element[value];
-			}
-			if(mb_strtolower($element[tag]) == "contactvoicetelephone"){
-				$this->contactvoicetelephone = $element[value];
-			}
-			if(mb_strtolower($element[tag]) == "contactfacsimiletelephone"){
-				$this->contactfacsimiletelephone = $element[value];
-			}
-			if(mb_strtolower($element[tag]) == "contactelectronicmailaddress"){
-				$this->contactelectronicmailaddress = $element[value];
-			}
-	  		if(mb_strtolower($element[tag]) == "keyword" && $section != 'layer'){
-				$this->wms_keyword[count($this->wms_keyword)] = $element[value];
-			}
-			
-			/*map section*/
-			if($this->wms_version == "1.0.0"){
-		 		if(mb_strtoupper($element[tag]) == "MAP" && $element[type] == "open"){
-					$section = "map";
-				}
-				if($section == "map" && mb_strtoupper($element[tag]) == "GET"){
-					$this->wms_getmap = $element[attributes][onlineResource];
-				}
-				if($section == "map" && mb_strtoupper($element[tag]) == "FORMAT" && $element[type] == "open"){
-					$format = "map";
-				}
-				if(mb_strtoupper($element[tag]) != "FORMAT" && $section == "map" && $format == "map"){
-					if (!$this->formatExists("map", trim($element[tag]))) {
-						$this->data_type[$cnt_format] = "map";
-						$this->data_format[$cnt_format] = trim($element[tag]);
-						$cnt_format++;
-					}
-				}
-				if(mb_strtoupper($element[tag]) == "FORMAT" && $element[type] == "close"){
-					$format = "";
-				}
-				if(mb_strtoupper($element[tag]) == "MAP" && $element[type] == "close"){
-					$section = "";
-				}
-			}
-			else{
-				if(mb_strtoupper($element[tag]) == "GETMAP" && $element[type] == "open"){
-					$section = "map";
-				}
-				if($section == "map" && mb_strtoupper($element[tag]) == "GET" && $element[type] == "open"){
-					$request = "get";
-				}
-				if($section == "map" && $request == "get" && mb_strtoupper($element[tag]) == "ONLINERESOURCE"){
-					$this->wms_getmap = $element[attributes]["xlink:href"];
-				}
-				if($section == "map" && mb_strtoupper($element[tag]) == "FORMAT"){
-					if (!$this->formatExists("map", trim($element[value]))) {
-						$this->data_type[$cnt_format] = "map";
-						$this->data_format[$cnt_format] = trim($element[value]);
-						$cnt_format++;
-					}
-				}
-				if($section == "map" && mb_strtoupper($element[tag]) == "GET" && $element[type] == "close"){
-					$request = "";
-				}
-				if(mb_strtoupper($element[tag]) == "GETMAP" && $element[type] == "close"){
-					$section = "";
-				}
-			}
-			/*capabilities section*/
-			if($this->wms_version == "1.0.0"){
-				if(mb_strtoupper($element[tag]) == "CAPABILITIES" && $element[type] == "open"){
-					$section = "capabilities";
-				}
-				if($section == "capabilities" && mb_strtoupper($element[tag]) == "GET"){
-					$this->wms_getcapabilities = $element[attributes][onlineResource];
-				}
-				if(mb_strtoupper($element[tag]) == "CAPABILITIES" && $element[type] == "close"){
-					$section = "";
-				}
-			}
-			else{
-				if(mb_strtoupper($element[tag]) == "GETCAPABILITIES" && $element[type] == "open"){
-					$section = "capabilities";
-				}
-				if($section == "capabilities" && mb_strtoupper($element[tag]) == "GET" && $element[type] == "open"){
-					$request = "get";
-				}
-				if($section == "capabilities" && $request == "get" && mb_strtoupper($element[tag]) == "ONLINERESOURCE"){
-					$this->wms_getcapabilities = $element[attributes]["xlink:href"];
-				}
-				if($section == "capabilities" && mb_strtoupper($element[tag]) == "GET" && $element[type] == "close"){
-					$request = "";
-				}
-				if(mb_strtoupper($element[tag]) == "GETCAPABILITIES" && $element[type] == "close"){
-					$section = "";
-				}
-			}
-			/*featureInfo section*/
-			if($this->wms_version == "1.0.0"){
-				if(mb_strtoupper($element[tag]) == "FEATUREINFO" && $element[type] == "open"){
-					$section = "featureinfo";
-				}
-				if($section == "featureinfo" && mb_strtoupper($element[tag]) == "GET"){
-					$this->wms_getfeatureinfo = $element[attributes][onlineResource];
-				}
-				if($section == "featureinfo" && mb_strtoupper($element[tag]) == "FORMAT" && $element[type] == "open"){
-					$format = "featureinfo";
-				}
-				if(mb_strtoupper($element[tag]) != "FORMAT" && $section == "featureinfo" && $format == "featureinfo"){
-					if (!$this->formatExists("featureinfo", trim($element[tag]))) {
-						$this->data_type[$cnt_format] = "featureinfo";
-						$this->data_format[$cnt_format] = trim($element[tag]);
-						$cnt_format++;
-					}
-				}
-				if(mb_strtoupper($element[tag]) == "FORMAT" && $element[type] == "close"){
-					$format = "";
-				}
-				if(mb_strtoupper($element[tag]) == "FEATUREINFO" && $element[type] == "close"){
-					$section = "";
-				}
-			}
-			else{
-				if(mb_strtoupper($element[tag]) == "GETFEATUREINFO" && $element[type] == "open"){
-					$section = "featureinfo";
-				}
-				if($section == "featureinfo" && mb_strtoupper($element[tag]) == "GET" && $element[type] == "open"){
-					$request = "get";
-				}
-				if($section == "featureinfo" && $request == "get" && mb_strtoupper($element[tag]) == "ONLINERESOURCE"){
-					$this->wms_getfeatureinfo = $element[attributes]["xlink:href"];
-				}
-				if($section == "featureinfo" && mb_strtoupper($element[tag]) == "FORMAT"){
-					if (!$this->formatExists("featureinfo", trim($element[value]))) {
-						$this->data_type[$cnt_format] = "featureinfo";
-						$this->data_format[$cnt_format] = trim($element[value]);
-						$cnt_format++;
-					}
-				}
-				if($section == "featureinfo" && mb_strtoupper($element[tag]) == "GET" && $element[type] == "close"){
-					$request = "";
-				}
-				if(mb_strtoupper($element[tag]) == "GETFEATUREINFO" && $element[type] == "close"){
-					$section = "";
-				}
-			}
-			/*exception section*/
-			if($this->wms_version == "1.0.0"){
-				if(mb_strtoupper($element[tag]) == "EXCEPTION" && $element[type] == "open"){
-					$section = "exception";
-				}
-				if($section == "exception" && mb_strtoupper($element[tag]) == "FORMAT" && $element[type] == "open"){
-					$format = "exception";
-				}
-				if(mb_strtoupper($element[tag]) != "FORMAT" && $section == "exception" && $format == "exception"){
-					$this->data_type[$cnt_format] = "exception";
-					$this->data_format[$cnt_format] = trim($element[tag]);
-					$cnt_format++;
-				}
-				if($section == "exception" && mb_strtoupper($element[tag]) == "FORMAT" && $element[type] == "close"){
-					$format = "";
-				}
-				if(mb_strtoupper($element[tag]) == "EXCEPTION" && $element[type] == "close"){
-					$section = "";
-				}
-			}
-			else{
-				if(mb_strtoupper($element[tag]) == "EXCEPTION" && $element[type] == "open"){
-					$section = "exception";
-				}
-				if($section == "exception" && mb_strtoupper($element[tag]) == "FORMAT"){
-					$this->data_type[$cnt_format] = "exception";
-					$this->data_format[$cnt_format] = trim($element[value]);
-					$cnt_format++;
-				}
-				if(mb_strtoupper($element[tag]) == "EXCEPTION" && $element[type] == "close"){
-					$section = "";
-				}
-			}
-	      /*legend section*/
-	      if($this->wms_version == "1.0.0"){
-	      
-	      }
-	      else{
-	        if(mb_strtoupper($element[tag]) == "GETLEGENDGRAPHIC" && $element[type] == "open"){
-				$section = "legend";
-			}
-	        if($section == "legend" && mb_strtoupper($element[tag]) == "GET" && $element[type] == "open"){
-				$request = "get";
-			}
-			if($section == "legend" && $request == "get" && mb_strtoupper($element[tag]) == "ONLINERESOURCE"){
-				$this->wms_getlegendurl = $element[attributes]["xlink:href"];
-			}
-	        if($section == "legend" && mb_strtoupper($element[tag]) == "GET" && $element[type] == "close"){
-				$request = "";
-			}
-			if(mb_strtoupper($element[tag]) == "GETLEGENDGRAPHIC" && $element[type] == "close"){
-				$section = "";
-			}         
-	      }
-			/* sld section */	      
-			if(mb_strtoupper($element[tag]) == "USERDEFINEDSYMBOLIZATION" && $element[type] == "complete"){
-				$this->wms_supportsld = $element[attributes]["SupportSLD"];
-				$this->wms_userlayer = $element[attributes]["UserLayer"];
-				$this->wms_userstyle = $element[attributes]["UserStyle"];
-				$this->wms_remotewfs = $element[attributes]["RemoteWFS"];
-			}
-	      	      
-			/*layer section*/				
-			if(mb_strtoupper($element[tag]) == "LAYER"){
-				$section = "layer";
-				if ($element[type] == "open") {
-					$cnt_epsg = -1;
-					$cnt_layer++;
-					$parent[$element[level]+1] = $cnt_layer;
-					$myParent[$cnt_layer]= $parent[$element[level]];
-					$this->addLayer($cnt_layer,$myParent[$cnt_layer]);
-					$this->objLayer[$cnt_layer]->layer_queryable = $element[attributes][queryable];
-				}
-				if ($element[type] == "close") {
-				
-				}
-			}
-			/* attribution */
-			if(mb_strtoupper($element[tag]) == "ATTRIBUTION"){
-				if ($element[type] == "open") {
-					$section = "attribution";
-				}
-				if ($element[type] == "close") {
-					$section = "layer";
-				}
-			}
-			/* styles */
-			if(mb_strtoupper($element[tag]) == "STYLE"){
-				$section = "style";
-				if($cnt_layer != $layer_style){
-					$layer_style = $cnt_layer;
-					$cnt_styles = -1;
-				}
-				if ($element[type] == "open") {
-					$cnt_styles++;
-				}
-				if ($element[type] == "close") {
-					$section = "layer";
-				}
-			}
-			if($section == "style"){
-				if(mb_strtoupper($element[tag]) == "NAME"){
-					$this->objLayer[$cnt_layer]->layer_style[$cnt_styles]["name"] = ($element[value] ? $element[value] : 'default');
-				}
-				if(mb_strtoupper($element[tag]) == "TITLE"){
-					$this->objLayer[$cnt_layer]->layer_style[$cnt_styles]["title"] = ($element[value] ? $element[value] : '');
-				}
-	      		if(mb_strtoupper($element[tag]) == "LEGENDURL" && $element[type] == "open"){
-					$legendurl = true;
-				}
-				if($legendurl && mb_strtoupper($element[tag]) == "FORMAT"){
-					$this->objLayer[$cnt_layer]->layer_style[$cnt_styles]["legendurlformat"] = $element[value];
-				}
-				if($legendurl && mb_strtoupper($element[tag]) == "ONLINERESOURCE"){
-					$this->objLayer[$cnt_layer]->layer_style[$cnt_styles]["legendurl"] = $element[attributes]["xlink:href"];
-				}
-			    if(mb_strtoupper($element[tag]) == "LEGENDURL" && $element[type] == "close"){
-					$legendurl = false;
-				}   
-			}
-			/* end of styles */
-			if($section == "layer"){
-				if(mb_strtoupper($element[tag]) == "NAME"){
-					$this->objLayer[$cnt_layer]->layer_name = $element[value];
-				}
-				if(mb_strtoupper($element[tag]) == "TITLE"){
-					$this->objLayer[$cnt_layer]->layer_title = $this->stripEndlineAndCarriageReturn($element[value]);
-				}
-				if(mb_strtoupper($element[tag]) == "ABSTRACT"){
-					$this->objLayer[$cnt_layer]->layer_abstract = $this->stripEndlineAndCarriageReturn($element[value]);
-				}
-				if(mb_strtoupper($element[tag]) == "KEYWORD"){
-					array_push($this->objLayer[$cnt_layer]->layer_keyword, trim($element[value]));
-				}
-	      		if(mb_strtoupper($element[tag]) == "DATAURL" && $element[type] == "open"){
-					$dataurl = true;
-				}
-				if($dataurl && mb_strtoupper($element[tag]) == "ONLINERESOURCE"){
-					$this->objLayer[$cnt_layer]->layer_dataurl_href = $element[attributes]["xlink:href"];
-				}
-			    if(mb_strtoupper($element[tag]) == "DATAURL" && $element[type] == "close"){
-					$dataurl = false;
-				}   
-				
-				if(mb_strtoupper($element[tag]) == "METADATAURL" && $element[type] == "open"){
-					$metadataurl = true;
-				}
-				if($metadataurl && mb_strtoupper($element[tag]) == "ONLINERESOURCE"){
-					$this->objLayer[$cnt_layer]->layer_metadataurl = $element[attributes]["xlink:href"];
-				}
-			    if(mb_strtoupper($element[tag]) == "METADATAURL" && $element[type] == "close"){
-					$metadataurl = false;
-				}   
-				
-				if(mb_strtoupper($element[tag]) == "SRS"){
-					// unique srs only, see http://www.mapbender.org/index.php/Arrays_with_unique_entries
-					$this->wms_srs = array_keys(array_flip(array_merge($this->wms_srs, explode(" ", strtoupper($element[value])))));
-				}						      
-				if(mb_strtoupper($element[tag]) == "LATLONBOUNDINGBOX"){
-					$cnt_epsg++;
-					$this->objLayer[$cnt_layer]->layer_epsg[$cnt_epsg]["epsg"] = "EPSG:4326";
-					$this->objLayer[$cnt_layer]->layer_epsg[$cnt_epsg]["minx"] = $element[attributes][minx];
-					$this->objLayer[$cnt_layer]->layer_epsg[$cnt_epsg]["miny"] = $element[attributes][miny];
-					$this->objLayer[$cnt_layer]->layer_epsg[$cnt_epsg]["maxx"] = $element[attributes][maxx];
-					$this->objLayer[$cnt_layer]->layer_epsg[$cnt_epsg]["maxy"] = $element[attributes][maxy];
-				}
-				if(mb_strtoupper($element[tag]) == "BOUNDINGBOX" && $element[attributes][SRS] != "EPSG:4326"){
-					$cnt_epsg++;
-					$this->objLayer[$cnt_layer]->layer_epsg[$cnt_epsg]["epsg"] = $element[attributes][SRS];
-					$this->objLayer[$cnt_layer]->layer_epsg[$cnt_epsg]["minx"] = $element[attributes][minx];
-					$this->objLayer[$cnt_layer]->layer_epsg[$cnt_epsg]["miny"] = $element[attributes][miny];
-					$this->objLayer[$cnt_layer]->layer_epsg[$cnt_epsg]["maxx"] = $element[attributes][maxx];
-					$this->objLayer[$cnt_layer]->layer_epsg[$cnt_epsg]["maxy"] = $element[attributes][maxy];
-					// a default epsg for mapbender
-					if($cnt_layer == 0 && $this->default_epsg == 0 && mb_strlen(trim($element[attributes][SRS]))>= 10){
-						$this->default_epsg = $cnt_epsg;
-					}
-				}
-				if(mb_strtoupper($element[tag]) == "SCALEHINT"){
-					if($element[attributes][max]>1000) $max = 0; else $max = $element[attributes][max]; 	
-					if($element[attributes][min]>1000) $min = 0; else $min = $element[attributes][min]; 	
-					$this->objLayer[$cnt_layer]->layer_minscale = round(($min * 2004.3976484406788493955738891127));
-					$this->objLayer[$cnt_layer]->layer_maxscale = round(($max * 2004.3976484406788493955738891127));
-				}
-			} 
-			else {
-				continue;
-			}
-		}
-		if(!$this->wms_title || $this->wms_title == "" || !$this->wms_getmap || $this->wms_getmap == ""){
-			$this->wms_status = false;
-			$this->optimizeWMS();
-			$e = new mb_exception("class_wms: createObjFromXML: WMS " . $url . " could not be loaded.");
-			return false;
-		}
-		else{
-			$this->wms_status = true;
-			$this->optimizeWMS();
-			$e = new mb_notice("class_wms: createObjFromXML: WMS " . $url . " has been loaded successfully.");
-			return true;
-		}
-	}
-	/**
-	 * private function
-	 */
-	function optimizeWMS() {
-		/*define defaults for wms-version 1.0.0*/
-		$map_default_ok = false;
-		$featureinfo_default_ok = false;
-		$exception_default_ok = false;
-		if($this->wms_version == "1.0.0"){
-			$map_default = "PNG";
-			$featureinfo_default = "MIME";
-			$exception_default = "INIMAGE";
-		}
-		/*define defaults for wms-version 1.1.0 and 1.1.1*/
-		else{
-			$map_default = "image/png";
-			$featureinfo_default = "text/html";
-			$exception_default = "application/vnd.ogc.se_inimage";
-		}
-		#some default
-		$this->gui_wms_visible = 1;
-		$this->gui_wms_opacity = 100;
-		/*if the rootlayer has no epsg...*/
-		if($this->objLayer[0]->layer_epsg[0]["epsg"] == ""){
-			$this->objLayer[0]->layer_epsg = $this->objLayer[1]->layer_epsg;
-			for($i=0;$i<count($this->objLayer[0]->layer_epsg);$i++){
-				for($j=1; $j<count($this->objLayer); $j++){
-					if($this->objLayer[0]->layer_epsg[$i]["epsg"] == $this->objLayer[$j]->layer_epsg[$i]["epsg"]){
-						if($this->objLayer[$j]->layer_epsg[$i]["minx"]<$this->objLayer[0]->layer_epsg[$i]["minx"]){
-							$this->objLayer[0]->layer_epsg[$i]["minx"] = $this->objLayer[$j]->layer_epsg[$i]["minx"];
-						}
-						if($this->objLayer[$j]->layer_epsg[$i]["miny"]<$this->objLayer[0]->layer_epsg[$i]["miny"]){
-							$this->objLayer[0]->layer_epsg[$i]["miny"] = $this->objLayer[$j]->layer_epsg[$i]["miny"];
-						}
-						if($this->objLayer[$j]->layer_epsg[$i]["maxx"]>$this->objLayer[0]->layer_epsg[$i]["maxx"]){
-							$this->objLayer[0]->layer_epsg[$i]["maxx"] = $this->objLayer[$j]->layer_epsg[$i]["maxx"];
-						}
-						if($this->objLayer[$j]->layer_epsg[$i]["maxy"]>$this->objLayer[0]->layer_epsg[$i]["maxy"]){
-							$this->objLayer[0]->layer_epsg[$i]["maxy"] = $this->objLayer[$j]->layer_epsg[$i]["maxy"];
-						}
-					}
-				}
-			}
-		}
-		for($i=0;$i<count($this->objLayer);$i++){
-			if(count($this->objLayer[$i]->layer_epsg) == 0 && count($this->objLayer[0]->layer_epsg) > 0){
-				$this->objLayer[$i]->layer_epsg = $this->objLayer[0]->layer_epsg; 
-			}
-			if(!is_int($this->objLayer[$i]->layer_parent)){
-				$this->objLayer[$i]->layer_abstract = $this->wms_abstract;
-				for ($r = 0; $r < count($this->wms_keyword); $r++) {
-					array_push($this->objLayer[$i]->layer_keyword, trim($this->wms_keyword[$r]));
-				}
-			}
-			if($this->objLayer[$i]->layer_name == ""){
-				$this->objLayer[$i]->layer_name = $this->objLayer[$i]->layer_title;
-			}
-			if($this->objLayer[$i]->layer_minscale == ""){
-				$this->objLayer[$i]->layer_minscale = 0;
-			}
-			if($this->objLayer[$i]->layer_maxscale == ""){
-				$this->objLayer[$i]->layer_maxscale = 0;
-			}
-			if($this->objLayer[$i]->layer_queryable == ""){
-				$this->objLayer[$i]->layer_queryable = 0;
-			}
-			$this->objLayer[$i]->gui_layer_minscale = $this->objLayer[$i]->layer_minscale;
-			$this->objLayer[$i]->gui_layer_maxscale = $this->objLayer[$i]->layer_maxscale;
-			$this->objLayer[$i]->layer_searchable = 1;
-		}
-		for($i=0;$i<count($this->data_format);$i++){
-			if(mb_strtolower($this->data_type[$i]) == 'map' && mb_strtoupper($this->data_format[$i]) == mb_strtoupper($map_default)){
-				$this->gui_wms_mapformat = mb_strtolower($map_default);
-				$map_default_ok = true;
-			}
-			if(mb_strtolower($this->data_type[$i]) == 'featureinfo' && mb_strtoupper($this->data_format[$i]) == mb_strtoupper($featureinfo_default)){
-				$this->gui_wms_featureinfoformat = mb_strtolower($featureinfo_default);
-				$featureinfo_default_ok = true;
-			}		
-			if(mb_strtolower($this->data_type[$i]) == 'exception' && mb_strtolower($this->data_format[$i]) == mb_strtolower($exception_default)){
-				$this->gui_wms_exceptionformat = mb_strtolower($exception_default);
-				$exception_default_ok = true;
-			}		
-		}
-		if($map_default_ok == false){
-			for($i=0;$i<count($this->data_format);$i++){
-				if(mb_strtolower($this->data_type[$i]) == "map" ){$this->gui_wms_mapformat = $this->data_format[$i]; break;}
-			}
-		}
-		if($featureinfo_default_ok == false){
-			for($i=0;$i<count($this->data_format);$i++){
-				if(mb_strtolower($this->data_type[$i]) == "featureinfo" ){$this->gui_wms_featureinfoformat = $this->data_format[$i]; break;}
-			}
-		}
-		if($exception_default_ok == false){
-			for($i=0;$i<count($this->data_format);$i++){
-				if(mb_strtolower($this->data_type[$i]) == "exception" ){$this->gui_wms_exceptionformat = $this->data_format[$i]; break;}
-			}
-		}
-		
-		if(count($this->objLayer[0]->layer_epsg)>1){
-			$this->gui_wms_epsg = $this->objLayer[0]->layer_epsg[$this->default_epsg][epsg];
-		}
-		else{
-			$this->gui_wms_epsg = $this->objLayer[0]->layer_epsg[0][epsg];
-		}
-		/*the queryable layers*/
-		for($i=0; $i<count($this->objLayer); $i++){
-			if($this->objLayer[$i]->layer_queryable == 1){
-				$this->objLayer[$i]->gui_layer_queryable = 1;
-			}
-			else{
-				$this->objLayer[$i]->gui_layer_queryable = 0;
-			}
-		}
-		for($i=0; $i<count($this->objLayer); $i++){
-				$this->objLayer[$i]->layer_pos=$i;
-		}
-		
-		// check if gui_layer_title isset
-		for($i=0; $i<count($this->objLayer); $i++){
-			$this->objLayer[$i]->gui_layer_title = $this->objLayer[$i]->gui_layer_title != "" ?
-				$this->objLayer[$i]->gui_layer_title :
-				$this->objLayer[$i]->layer_title;
-		}
-		
-		/* fill sld variables when empty */
-		if($this->wms_supportsld == ""){
-				$this->wms_supportsld = 0;
-		}
-		if($this->wms_userlayer == ""){
-				$this->wms_userlayer = 0;
-		}
-		if($this->wms_userstyle == ""){
-				$this->wms_userstyle = 0;
-		}
-		if($this->wms_remotewfs == ""){
-				$this->wms_remotewfs = 0;
-		}
-	  }
-	
-	function displayWMS(){
-		echo "<br>id: " . $this->wms_id . " <br>";
-		echo "version: " . $this->wms_version . " <br>";
-		echo "title: " . $this->wms_title . " <br>";
-		echo "abstract: " . $this->wms_abstract . " <br>";
-		echo "maprequest: " . $this->wms_getmap . " <br>";
-		echo "capabilitiesrequest: " . $this->wms_getcapabilities . " <br>";
-		echo "featureinforequest: " . $this->wms_getfeatureinfo . " <br>";
-		echo "gui_wms_mapformat: " . $this->gui_wms_mapformat . " <br>";
-		echo "gui_wms_featureinfoformat: " . $this->gui_wms_featureinfoformat . " <br>";
-		echo "gui_wms_exceptionformat: " . $this->gui_wms_exceptionformat . " <br>";	
-		echo "gui_wms_epsg: " . $this->gui_wms_epsg . " <br>";
-		echo "wms_srs: " . implode(", ", $this->wms_srs) . " <br>";
-		echo "gui_wms_visible: " . $this->gui_wms_visible . " <br>";
-		echo "gui_wms_opacity: " . $this->gui_wms_opacity . " <br>";
-		echo "support_sld: " . $this->wms_supportsld . " <br>";
-		
-		for($i=0; $i<count($this->data_type);$i++){
-			echo $this->data_type[$i]. " -> ".$this->data_format[$i]. "<br>";
-		}
-		for($i=0; $i<count($this->objLayer); $i++){
-			echo "<hr>";
-			echo "id: <b>".$this->objLayer[$i]->layer_id ."</b> parent: <b>".$this->objLayer[$i]->layer_parent."</b> name: <b>".$this->objLayer[$i]->layer_name;
-			echo "</b> title: <b>".$this->objLayer[$i]->layer_title. "</b> queryable: <b>".$this->objLayer[$i]->layer_queryable."</b> minScale: <b>". $this->objLayer[$i]->layer_minscale."</b> maxScale: <b>".$this->objLayer[$i]->layer_maxscale."</b>";
-			echo "<br>dataurl: <b>".$this->objLayer[$i]->layer_dataurl_href. "</b>";
-			echo "<br>metadataurl: <b>".$this->objLayer[$i]->layer_metadataurl. "</b>";
-			echo "<table border='1'>";
-			for($j=0; $j<count($this->objLayer[$i]->layer_epsg);$j++){
-				echo "<tr><td>".$this->objLayer[$i]->layer_epsg[$j][epsg]."</td><td>".$this->objLayer[$i]->layer_epsg[$j][minx]."</td>";
-				echo "<td>".$this->objLayer[$i]->layer_epsg[$j][miny]."</td><td>".$this->objLayer[$i]->layer_epsg[$j][maxx]."</td>";
-				echo "<td>".$this->objLayer[$i]->layer_epsg[$j][maxy]."</td></tr>";
-			}
-			echo "</table>";
-			echo "layerstyle:";
-			echo "<table border='1'>";
-			echo "<tr><td>name</td><td>title</td><td>legendurl</td><td>legendurlformat</td></tr>";
-			for($j=0; $j<count($this->objLayer[$i]->layer_style);$j++){
-				echo "<tr><td>".$this->objLayer[$i]->layer_style[$j][name]."</td><td>".$this->objLayer[$i]->layer_style[$j][title]."</td><td>".$this->objLayer[$i]->layer_style[$j][legendurl]."</td><td>".$this->objLayer[$i]->layer_style[$j][legendurlformat]."</td></tr>";
-			}
-			echo "</table>";
-	        echo "<hr>";
-	        echo "<hr>";
-		}
-	} 
-	  function addLayer($id,$parent){	
-		$this->objLayer[count($this->objLayer)] = new layer($id,$parent);
-	  }
-	  /**
-	   * private function
-	   */
-	  function stripEndlineAndCarriageReturn($string) {
-	  	return preg_replace("/\n/", "", preg_replace("/\r/", " ", $string));
-	  }
-		function createJsObjFromWMS($parent=0){
-			echo $this->createJsObjFromWMS_($parent);
-		}
-		
-
-	function newLayer ($currentLayer, $currentExtent) {
-		$pos = $currentLayer["extension"]["LAYER_POS"];
-		$parent = $currentLayer["extension"]["LAYER_PARENT"];
-		$this->addLayer($pos, $parent); 
-
-		// set layer data
-		$layerIndex = count($this->objLayer) - 1;
-		$newLayer = $this->objLayer[$layerIndex];
-		$newLayer->layer_uid = $currentLayer["extension"]["LAYER_ID"];
-		$newLayer->layer_name = $currentLayer["name"];
-		$newLayer->layer_title = $currentLayer["title"];
-		$newLayer->gui_layer_title = $currentLayer["title"];
-		$newLayer->layer_dataurl_href = $currentLayer["dataurl"];
-		$newLayer->layer_pos = $currentLayer["extension"]["LAYER_POS"];
-		$newLayer->layer_queryable = $currentLayer["queryable"];
-		$newLayer->layer_minscale = $currentLayer["extension"]["MINSCALE"];
-		$newLayer->layer_maxscale = $currentLayer["extension"]["MAXSCALE"];
-		$newLayer->layer_metadataurl = $currentLayer["metadataurl"];
-//		$newLayer->layer_searchable = $currentLayer["searchable"];
-		$newLayer->gui_layer_wms_id = $currentLayer["extension"]["WMS_ID"];
-		$newLayer->gui_layer_status = $currentLayer["extension"]["GUI_STATUS"];
-		$newLayer->gui_layer_style = ""; // TODO: Add correct data
-		$newLayer->gui_layer_selectable = $currentLayer["extension"]["GUI_SELECTABLE"];
-		if (isset($currentLayer["extension"]["OVERVIEWHIDDEN"])) {
-			$newLayer->gui_layer_visible = ($currentLayer["extension"]["OVERVIEWHIDDEN"] === "1") ? false : true;
-		}
-		else {
-			$newLayer->gui_layer_visible = $currentLayer["visible"];
-		}
-		if (isset($currentLayer["extension"]["WFSFEATURETYPE"])) {
-			$newLayer->gui_layer_wfs_featuretype = strval($currentLayer["extension"]["WFSFEATURETYPE"]);
-		}
-		else {
-			$newLayer->gui_layer_wfs_featuretype = "";
-		}
-		$newLayer->gui_layer_queryable = $currentLayer["extension"]["GUI_QUERYABLE"];
-		$newLayer->gui_layer_querylayer = $currentLayer["extension"]["QUERYLAYER"];
-		$newLayer->gui_layer_minscale = $currentLayer["extension"]["GUI_MINSCALE"];
-		$newLayer->gui_layer_maxscale = $currentLayer["extension"]["GUI_MAXSCALE"];
-		$newLayer->layer_abstract = $currentLayer["abstract"];
-
-		//
-		// set layer epsg
-		//
-		$tmpEpsgArray= array();
-		$newLayer->layer_epsg = array();
-		if ($currentLayer["extension"]["EPSG"]) {
-			$layerEpsgArray = array();
-			$layerMinXArray = array();
-			$layerMinYArray = array();
-			$layerMaxXArray = array();
-			$layerMaxYArray = array();
-			if (!is_array($currentLayer["extension"]["EPSG"])) {
-				$layerEpsgArray[0] = $currentLayer["extension"]["EPSG"];
-				$layerMinXArray[0] = $currentLayer["extension"]["MINX"];
-				$layerMinYArray[0] = $currentLayer["extension"]["MINY"];
-				$layerMaxXArray[0] = $currentLayer["extension"]["MAXX"];
-				$layerMaxYArray[0] = $currentLayer["extension"]["MAXY"];
-			}
-			else {
-				$layerEpsgArray = $currentLayer["extension"]["EPSG"];
-				$layerMinXArray = $currentLayer["extension"]["MINX"];
-				$layerMinYArray = $currentLayer["extension"]["MINY"];
-				$layerMaxXArray = $currentLayer["extension"]["MAXX"];
-				$layerMaxYArray = $currentLayer["extension"]["MAXY"];
-			}
-
-			for ($i=0; $i < count($layerEpsgArray); $i++) {
-				$currentLayerEpsg = array();
-				$currentLayerEpsg["epsg"] = $layerEpsgArray[$i];
-				$tmpEpsgArray[]= $layerEpsgArray[$i];
-				if ($layerMinXArray[$i] == 0
-					&& $layerMinYArray[$i] == 0
-					&& $layerMaxXArray[$i] == 0
-					&& $layerMaxYArray[$i] == 0
-					) {
-					$currentLayerEpsg["minx"] = null;
-					$currentLayerEpsg["miny"] = null; 
-					$currentLayerEpsg["maxx"] = null;
-					$currentLayerEpsg["maxy"] = null;
-				}
-				else {
-					$currentLayerEpsg["minx"] = floatval($layerMinXArray[$i]);
-					$currentLayerEpsg["miny"] = floatval($layerMinYArray[$i]); 
-					$currentLayerEpsg["maxx"] = floatval($layerMaxXArray[$i]);
-					$currentLayerEpsg["maxy"] = floatval($layerMaxYArray[$i]);
-				}
-				array_push($newLayer->layer_epsg, $currentLayerEpsg);
-			}
-		}
-		for ($i = 0; $i < count($currentLayer["epsg"]); $i++) {
-			if (!in_array($currentLayer["epsg"][$i], $tmpEpsgArray)) {
-				$newLayer->layer_epsg[]= array(
-					"epsg" => $currentLayer["epsg"][$i],
-					"minx" => null,
-					"miny" => null,
-					"maxx" => null,
-					"maxy" => null
-				);
-			}
-		}
-
-		//
-		// set layer style
-		//
-		for ($i = 0; $i < count($currentLayer["style"]); $i++) {
-			$layerStyleIndex = count($newLayer->gui_layer_style) - 1;
-			$newLayer->layer_style[$layerStyleIndex] = array();
-			$newLayer->layer_style[$layerStyleIndex]["name"] = $currentLayer["style"][$i]["name"];
-			$newLayer->layer_style[$layerStyleIndex]["title"] = $currentLayer["style"][$i]["title"];	
-			$newLayer->layer_style[$layerStyleIndex]["legendurl"] = $currentLayer["style"][$i]["legendurl"];
-			$newLayer->layer_style[$layerStyleIndex]["legendurl_format"] = $currentLayer["style"][$i]["legendurl_type"];
-		}
-	}
-	
-	  function createJsObjFromWMS_($parent=0){
-		$str = "";
-	  	if(!$this->wms_title || $this->wms_title == ""){
-			$str .= "alert('Error: no valid capabilities-document !!');";
-			die; exit;
-		}
-			if($parent){
-				$str .=  "parent.";
-			}
-			// wms_title and abstract have previously been urlencoded
-			// this solution may not yet be the ultimate one
-			
-			$add_wms_string = "add_wms(" .
-					"'" . $this->wms_id ."'," .
-					"'" . $this->wms_version ."'," .
-					"'" . addslashes($this->wms_title) . "'," .
-					"'" . addslashes($this->wms_abstract) ."'," .
-					"'" . $this->wms_getmap ."'," .
-					"'" . $this->wms_getfeatureinfo ."'," .
-					"'" . $this->wms_getlegendurl ."'," .
-					"'" . $this->wms_filter ."'," .
-					"'" . $this->gui_wms_mapformat . "'," .
-					"'" . $this->gui_wms_featureinfoformat . "'," .
-					"'" . $this->gui_wms_exceptionformat . "'," .
-					"'" . $this->gui_wms_epsg ."'," .
-					"'" . $this->gui_wms_visible ."'," .
-					"'" . $this->gui_wms_opacity ."'," .
-					"'" . $this->gui_wms_sldurl ."" .
-					"');";
-			$str .=  $add_wms_string;
-			
-		for($i=0;$i<count($this->data_format);$i++){
-			if($parent){
-				$str .=  "parent.";
-			}		
-			$str .= "wms_add_data_type_format('". $this->data_type[$i] ."','". $this->data_format[$i] ."');";		
-		}
-		for($i=0; $i<count($this->objLayer); $i++){
-			if($parent){
-				$str .= "parent.";
-			}
-			$str .=  "wms_add_layer('". 
-				$this->objLayer[$i]->layer_parent ."','". 
-				$this->objLayer[$i]->layer_uid ."','". 
-				addslashes($this->objLayer[$i]->layer_name) . "','". 
-				addslashes($this->objLayer[$i]->layer_title) ."','". 
-				$this->objLayer[$i]->layer_dataurl_href ."','". 
-				$this->objLayer[$i]->layer_pos ."','". 
-				$this->objLayer[$i]->layer_queryable ."','". 
-				$this->objLayer[$i]->layer_minscale . "','". 
-				$this->objLayer[$i]->layer_maxscale ."','". 
-				$this->objLayer[$i]->layer_metadataurl ."','". 
-// will be added later, not needed now
-//				$this->objLayer[$i]->layer_searchable ."','". 
-				$this->objLayer[$i]->gui_layer_wms_id ."','". 
-				$this->objLayer[$i]->gui_layer_status ."','".
-				$this->objLayer[$i]->gui_layer_style ."','".  
-				$this->objLayer[$i]->gui_layer_selectable ."','". 
-				$this->objLayer[$i]->gui_layer_visible ."','". 
-				$this->objLayer[$i]->gui_layer_queryable ."','". 
-				$this->objLayer[$i]->gui_layer_querylayer ."','". 
-				$this->objLayer[$i]->gui_layer_minscale ."','". 
-				$this->objLayer[$i]->gui_layer_maxscale ."','".
-				$this->objLayer[$i]->gui_layer_wfs_featuretype ."','".
-				$this->objLayer[$i]->gui_layer_title ."');";
-				
-			for($j=0; $j<count($this->objLayer[$i]->layer_epsg);$j++){
-				$currentEpsg = $this->objLayer[$i]->layer_epsg[$j];
-				if($i==0){
-					if($parent){
-						$str .= "parent.";
-					}
-					$str .= "wms_addSRS('". 
-						$currentEpsg["epsg"] ."',". 
-						(is_null($currentEpsg["minx"]) ? "null" : $currentEpsg["minx"]) .",". 
-						(is_null($currentEpsg["miny"]) ? "null" : $currentEpsg["miny"]) .",". 
-						(is_null($currentEpsg["maxx"]) ? "null" : $currentEpsg["maxx"]) .",". 
-						(is_null($currentEpsg["maxy"]) ? "null" : $currentEpsg["maxy"]) .");";
-				}
-				if (!is_null($currentEpsg["epsg"])) {
-					if($parent){
-						$str .=  "parent.";
-					}
-					$str .= "layer_addEpsg('". 
-						$currentEpsg["epsg"] ."',". 
-						(is_null($currentEpsg["minx"]) ? "null" : $currentEpsg["minx"]) .",". 
-						(is_null($currentEpsg["miny"]) ? "null" : $currentEpsg["miny"]) .",". 
-						(is_null($currentEpsg["maxx"]) ? "null" : $currentEpsg["maxx"]) .",". 
-						(is_null($currentEpsg["maxy"]) ? "null" : $currentEpsg["maxy"]) .");";
-				}
-			}
-			for($j=0; $i==0 && $j<count($this->wms_srs);$j++){
-				$found = false;
-				for ($k = 0; $k < count($this->objLayer[$i]->layer_epsg); $k++){
-					if ($this->objLayer[$i]->layer_epsg[$k]["epsg"] === $this->wms_srs[$j]) {
-						$found = true;
-						break;
-					}
-				}
-				if ($found) {
-					continue;
-				}
-				
-				if($parent){
-					$str .= "parent.";
-				}
-				$str .= "wms_addSRS('". 
-				$this->wms_srs[$j] ."', null, null, null, null);\n";
-			}
-			for($j=0; $j<count($this->objLayer[$i]->layer_style);$j++){
-				if($parent){
-				$str .= "parent.";
-				}
-				$str .= "wms_addLayerStyle('".$this->objLayer[$i]->layer_style[$j]["name"].
-					"', '".$this->objLayer[$i]->layer_style[$j]["title"].
-					"', ".$j.
-					",".$i.
-					",'".$this->objLayer[$i]->layer_style[$j]["legendurl"].
-					"', '".$this->objLayer[$i]->layer_style[$j]["legendurlformat"]."');";
-			}
-		}
-		return $str;
-	  }
-	  
-	  function createJsLayerObjFromWMS($parent=0, $layer_name){
-	  	if(!$this->wms_title || $this->wms_title == ""){
-			echo " alert('Error: no valid capabilities-document !!');";
-			die; exit;
-		}
-			if($parent){
-				echo "parent.";
-			}
-			// wms_title and abstract have previously been urlencoded
-			// this solution may not yet be the ultimate one
-			print("add_wms('". 
-			$this->wms_id ."','".
-			$this->wms_version ."','".
-			preg_replace("/'/", "", $this->wms_title) ."','".
-			preg_replace("/'/", "", $this->wms_abstract) ."','". 
-			$this->wms_getmap ."','" .
-			$this->wms_getfeatureinfo ."','".
-			$this->wms_getlegendurl ."','".
-			$this->wms_filter ."','".
-			$this->gui_wms_mapformat ."','". 
-			$this->gui_wms_featureinfoformat ."','". 
-			$this->gui_wms_exceptionformat . "','". 
-			$this->gui_wms_epsg ."','". 
-			$this->gui_wms_visible ."','".
-			$this->gui_wms_opacity ."','".
-			$this->gui_wms_sldurl ."');");
-			
-		for($i=0;$i<count($this->data_format);$i++){
-			if($parent){
-				echo "parent.";
-			}		
-			echo "wms_add_data_type_format('". $this->data_type[$i] ."','". $this->data_format[$i] ."');";		
-		}
-		for($i=0; $i<count($this->objLayer); $i++){
-			if($this->objLayer[$i]->layer_name == $layer_name|| $this->objLayer[$i]->layer_pos == 0){
-			
-				if($parent){
-					echo "parent.";
-				}
-			 print ("wms_add_layer('". 
-				$this->objLayer[$i]->layer_parent ."','". 
-				$this->objLayer[$i]->layer_uid ."','". 
-				$this->objLayer[$i]->layer_name . "','". 
-				addslashes($this->objLayer[$i]->layer_title) ."','". 
-				$this->objLayer[$i]->layer_dataurl_href ."','". 
-				$this->objLayer[$i]->layer_pos ."','". 
-				$this->objLayer[$i]->layer_queryable ."','". 
-				$this->objLayer[$i]->layer_minscale . "','". 
-				$this->objLayer[$i]->layer_maxscale ."','". 
-				$this->objLayer[$i]->layer_metadataurl ."','". 
-// will be added later, not needed now
-//				$this->objLayer[$i]->layer_searchable ."','". 
-				$this->objLayer[$i]->gui_layer_wms_id ."','". 
-				$this->objLayer[$i]->gui_layer_status ."','".
-				$this->objLayer[$i]->gui_layer_style ."','". 
-				$this->objLayer[$i]->gui_layer_selectable ."','". 
-				$this->objLayer[$i]->gui_layer_visible ."','". 
-				$this->objLayer[$i]->gui_layer_queryable ."','". 
-				$this->objLayer[$i]->gui_layer_querylayer ."','". 
-				$this->objLayer[$i]->gui_layer_minscale ."','". 
-				$this->objLayer[$i]->gui_layer_maxscale ."','".
-				$this->objLayer[$i]->gui_layer_wfs_featuretype ."','".
-				$this->objLayer[$i]->gui_layer_title ."');");
-			for($j=0; $j<count($this->objLayer[$i]->layer_epsg);$j++){
-				if($i==0){
-					if($parent){
-					echo "parent.";
-					}
-					print("wms_addSRS('". 
-						$this->objLayer[$i]->layer_epsg[$j]["epsg"] ."','". 
-						$this->objLayer[$i]->layer_epsg[$j]["minx"] ."','". 
-						$this->objLayer[$i]->layer_epsg[$j]["miny"] ."','". 
-						$this->objLayer[$i]->layer_epsg[$j]["maxx"] ."','". 
-						$this->objLayer[$i]->layer_epsg[$j]["maxy"] ."');");
-				}
-				if($parent){
-				echo "parent.";
-				}
-				print("layer_addEpsg('". 
-					$this->objLayer[$i]->layer_epsg[$j]["epsg"] ."','". 
-					$this->objLayer[$i]->layer_epsg[$j]["minx"] ."','". 
-					$this->objLayer[$i]->layer_epsg[$j]["miny"] ."','". 
-					$this->objLayer[$i]->layer_epsg[$j]["maxx"] ."','". 
-					$this->objLayer[$i]->layer_epsg[$j]["maxy"] ."');");
-			}
-			for($j=0; $j<count($this->objLayer[$i]->layer_style);$j++){
-				if($parent){
-				echo "parent.";
-				}
-				print("wms_addLayerStyle('".$this->objLayer[$i]->layer_style[$j]["name"]."', '".$this->objLayer[$i]->layer_style[$j]["title"]."', ".$j.",".$i.",'".$this->objLayer[$i]->layer_style[$j]["legendurl"]."', '".$this->objLayer[$i]->layer_style[$j]["legendurlformat"]."');");
-			}
-		   }	
-		}
-	  }
-	  
-	  
-	/**
-	* writeObjInDB
-	*
-	* this function exports the information from the xml to the mapbender database 
-	*/
-	function writeObjInDB($gui_id){
-		global $con;
-		if (func_num_args() == 2) { //new for HTTP Authentication
-			$auth = func_get_arg(1);
-			$username = $auth['username'];
-			$password = $auth['password'];
-			$authType = $auth['auth_type'];
-		}
-		else {
-			$username = '';
-			$password = '';
-			$authType = '';		
-		}
-		$admin = new administration();
-
-		$this->checkObj();
-		db_begin();
-	
-		# TABLE wms
-		$sql = "INSERT INTO wms (wms_version, wms_title, wms_abstract, wms_getcapabilities, wms_getmap, ";
-		$sql.= "wms_getfeatureinfo, wms_getlegendurl, wms_getcapabilities_doc, wms_upload_url, fees, ";
-		$sql .= "accessconstraints, contactperson, contactposition, contactorganization, address, city, ";
-		$sql .= "stateorprovince, postcode, country, contactvoicetelephone, contactfacsimiletelephone, contactelectronicmailaddress, ";
-		$sql .= "wms_owner,wms_timestamp,wms_timestamp_create,wms_username,wms_password,wms_auth_type,";
-		$sql .= "wms_supportsld, wms_userlayer, wms_userstyle, wms_remotewfs) ";
-		$sql .= "VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$30,$31,$32)";
-		$v = array(
-			$this->wms_version,
-			$this->wms_title,
-			$this->wms_abstract,
-			$this->wms_getcapabilities,
-			$this->wms_getmap,
-			$this->wms_getfeatureinfo,
-			$this->wms_getlegendurl,
-			$admin->char_encode($this->wms_getcapabilities_doc),
-			$this->wms_upload_url,
-			$this->fees,
-			$this->accessconstraints,
-			$this->contactperson,
-			$this->contactposition,
-			$this->contactorganization,
-			$this->address,
-			$this->city,
-			$this->stateorprovince,
-			$this->postcode,
-			$this->country,
-			$this->contactvoicetelephone,
-			$this->contactfacsimiletelephone,
-			$this->contactelectronicmailaddress,
-			Mapbender::session()->get('mb_user_id'),
-			strtotime("now"),
-			strtotime("now"),
-			$username,
-			$password,
-			$authType,
-			$this->wms_supportsld,
-			$this->wms_userlayer,
-			$this->wms_userstyle,
-			$this->wms_remotewfs
-		);
-		$t = array(
-			's','s','s','s','s','s','s','s','s','s','s','s','s','s','s','s',
-			's','s','s','s','s','s','i','i','i','s','s','s','s','s','s','s'
-		);
-		$res = db_prep_query($sql,$v,$t);
-		if(!$res){
-			db_rollback();
-			return null;
-		}
-		
-		$myWMS = db_insert_id($con,'wms', 'wms_id');
-
-		if ($authType != '') { //some authentication is needed! 
-			$admin = new administration();
-			echo "WMS ID: ".$myWMS;
-			$admin->setWMSOWSstring($myWMS, 1);
-		}
-
-		# TABLE layer and gui_layer
-		
-		for($i=0; $i<count($this->objLayer); $i++){
-			$this->insertLayer($i,$myWMS,$gui_id);
-			$this->insertGuiLayer($i,$myWMS,$gui_id);
-		}	
-			
-		
-		#TABLE wms_srs
-		$this->insertSRS($myWMS);	
-		
-		# TABLE wms_format	
-		$this->insertFormat($myWMS);	
-			
-		# TABLE gui_wms
-		
-		$sql ="SELECT MAX(gui_wms_position) AS pos FROM gui_wms WHERE fkey_gui_id = $1";
-		$v = array($gui_id);
-		$t = array('s');
-		$res = db_prep_query($sql,$v,$t);
-		if (db_result($res, 0,"pos") > -1) {
-			$position = db_result($res, 0,"pos") + 1;
-		} 
-		else { 
-			$position = 0; 
-		}
-		
-		$sql ="INSERT INTO gui_wms (fkey_gui_id, fkey_wms_id, gui_wms_position, gui_wms_mapformat, ";
-		$sql .= "gui_wms_featureinfoformat, gui_wms_exceptionformat, gui_wms_epsg)";
-		$sql .= "VALUES($1,$2,$3,$4,$5,$6,$7)";
-		$v = array(
-			$gui_id,
-			$myWMS,
-			$position,
-			$this->gui_wms_mapformat,
-			$this->gui_wms_featureinfoformat,
-			$this->gui_wms_exceptionformat,
-			$this->gui_wms_epsg
-		);
-		$t = array('s','i','i','s','s','s','s');
-		$res = db_prep_query($sql,$v,$t);
-		if(!$res){
-			db_rollback();	
-			return null;
-		}
-		db_commit();
-
-		//
-		// update GeoRSS feed
-		//
-		$geoRssFactory = new GeoRssFactory();
-		$geoRss = $geoRssFactory->loadOrCreate(GEO_RSS_FILE);
-		if (!is_null($geoRss)) {
-			$geoRssItem = new GeoRssItem();
-			$geoRssItem->setTitle("NEW: " . $this->wms_title);
-			$geoRssItem->setDescription($this->wms_abstract);
-			$geoRssItem->setUrl(self::getWmsMetadataUrl($myWMS));
-			$geoRssItem->setPubDate(self::rssDate());
-
-			for ($j = 0; $j < count($this->objLayer[0]->layer_epsg); $j++) {
-				$currentEpsg = $this->objLayer[0]->layer_epsg[$j];
-				if ($currentEpsg["epsg"] === "EPSG:4326") {
-					$currentBbox = new Mapbender_bbox(
-						$currentEpsg["minx"],
-						$currentEpsg["miny"],
-						$currentEpsg["maxx"],
-						$currentEpsg["maxy"],
-						$currentEpsg["epsg"]
-					);
-					$geoRssItem->setBbox($currentBbox);
-					break;
-				}
-			}
-
-			$geoRss->append($geoRssItem);
-			$geoRss->saveAsFile();
-		}
-	    
-	    #Changes JW
-	    $this->wms_id = $myWMS;
-	}
-	function insertLayer($i,$myWMS){
-		global $con;
-		$sql = <<<SQL
-
-INSERT INTO layer 
-(fkey_wms_id, layer_pos, layer_parent, layer_name, layer_title, 
-layer_queryable, layer_minscale, layer_maxscale, layer_dataurl,
-layer_metadataurl, layer_searchable, layer_abstract) 
-VALUES
-($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
-
-SQL;
-		if($this->objLayer[$i]->layer_id != null){
-			$tmpPos =  $this->objLayer[$i]->layer_id;
-		}
-		else {
-			$tmpPos .= 0;
-		}
-		if($this->objLayer[$i]->layer_parent == '' && $this->objLayer[$i]->layer_parent != '0'){
-			$this->objLayer[$i]->layer_parent = '';
-		}
-		$v = array($myWMS,$tmpPos,$this->objLayer[$i]->layer_parent,$this->objLayer[$i]->layer_name,
-				$this->objLayer[$i]->layer_title,
-				$this->objLayer[$i]->layer_queryable,$this->objLayer[$i]->layer_minscale,
-				$this->objLayer[$i]->layer_maxscale,$this->objLayer[$i]->layer_dataurl_href,
-				$this->objLayer[$i]->layer_metadataurl, $this->objLayer[$i]->layer_searchable,
-				$this->objLayer[$i]->layer_abstract);
-		$t = array('i','i','s','s','s','i','i','i','s','s','i','s');
-		$res = db_prep_query($sql,$v,$t);
-		if(!$res){
-			db_rollback();	
-		}
-		else {
-			# save the id of each layer: set param2 true		
-			$this->objLayer[$i]->db_id = db_insert_id($con, 'layer','layer_id');
-			$this->insertLayerEPSG($i);
-			
-			# TABLE layer_style for each layer
-			$this->insertLayerStyle($i);
-			
-			# insert Keywords
-			$this->insertLayerKeyword($i);	
-		
-		}
-	}
-	function updateLayer($i,$myWMS){
-		$sql = "SELECT layer_id FROM layer WHERE fkey_wms_id = $1 AND layer_name = $2";
-		$v = array($myWMS,$this->objLayer[$i]->layer_name);
-		$t = array('i','s');
-		$res = db_prep_query($sql,$v,$t);
-		if($row = db_fetch_array($res)){
-			$l_id = $row['layer_id'];	
-		}
-		else{
-			db_rollback();
-			$e = new mb_exception("Not found: ".$this->objLayer[$i]->layer_name);
-			return;	
-		}	
-		
-		$sql = "UPDATE layer SET ";
-		$sql .= "layer_pos = $1, ";
-		$sql .= "layer_parent = $2, ";
-		$sql .= "layer_title = $3, ";
-		$sql .= "layer_queryable = $4, ";
-		$sql .= "layer_minscale = $5, ";
-		$sql .= "layer_maxscale = $6, ";
-		$sql .= "layer_dataurl = $7, ";
-		$sql .= "layer_metadataurl = $8, ";
-		$sql .= "layer_searchable = $9, ";
-		$sql .= "layer_abstract = $10 ";
-		$sql .= "WHERE layer_id = $11";
-		
-		if($this->objLayer[$i]->layer_id != null){
-			$tmpPos =  $this->objLayer[$i]->layer_id;
-		}
-		else {
-			$tmpPos .= 0;
-		}
-		if($this->objLayer[$i]->layer_parent == '' && $this->objLayer[$i]->layer_parent != '0'){
-			$this->objLayer[$i]->layer_parent = '';
-		}
-		$v = array($tmpPos,$this->objLayer[$i]->layer_parent,
-				$this->objLayer[$i]->layer_title,
-				$this->objLayer[$i]->layer_queryable,$this->objLayer[$i]->layer_minscale,
-				$this->objLayer[$i]->layer_maxscale,$this->objLayer[$i]->layer_dataurl_href,
-				$this->objLayer[$i]->layer_metadataurl, $this->objLayer[$i]->layer_searchable,
-				$this->objLayer[$i]->layer_abstract, $l_id		
-			);
-		$t = array('i','s','s','i','i','i','s','s','i', 's','i');
-		$res = db_prep_query($sql,$v,$t);
-		if($this->overwrite == true){
-			$sql = "UPDATE layer SET ";
-			$sql .= "layer_title = $1, ";
-			$sql .= "layer_abstract = $2 ";
-			$sql .= "WHERE layer_id = $3";
-			
-			$v = array($this->objLayer[$i]->layer_title,$this->objLayer[$i]->layer_abstract, $l_id);
-			$t = array('s','s','i');
-			$res = db_prep_query($sql,$v,$t);
-		}
-		if(!$res){
-			db_rollback();	
-		}
-		else {
-			
-			# save the id of each layer: set param2 true
-			$this->objLayer[$i]->db_id = $l_id;
-			$this->insertLayerEPSG($i);
-			
-			# TABLE layer_style for each layer
-			$this->insertLayerStyle($i);
-			if($this->overwrite == true){
-				$this->insertLayerKeyword($i);
-				$this->insertLayerCategories($i);
-			}
-		}
-	}
-	function insertGuiLayer($i,$myWMS,$gui_id){
-		# table gui_layer
-		
-		$sql = "INSERT INTO gui_layer (fkey_gui_id, fkey_layer_id, gui_layer_wms_id, ";
-		$sql .= "gui_layer_status, gui_layer_selectable, gui_layer_visible, gui_layer_queryable, ";
-		$sql .= "gui_layer_querylayer,gui_layer_minscale,gui_layer_maxscale, gui_layer_priority, gui_layer_style, gui_layer_title) ";
-		$sql .= "VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)";
-		if(count($this->objLayer[$i]->layer_style)>0){
-			$layer_style_name = $this->objLayer[$i]->layer_style[0]["name"];
-		}
-		else{
-			$layer_style_name = NULL;
-		}
-		$v = array($gui_id,$this->objLayer[$i]->db_id,$myWMS,1,1,1,$this->objLayer[$i]->layer_queryable,
-			$this->objLayer[$i]->layer_queryable,$this->objLayer[$i]->layer_minscale,$this->objLayer[$i]->layer_maxscale,$i,$layer_style_name,$this->objLayer[$i]->gui_layer_title);
-		$t = array('s','i','i','i','i','i','i','i','i','i','i','s', 's');
-		$res = db_prep_query($sql,$v,$t);
-		#$e = new mb_exception("name des insert styles und fkey_layer_id: ".$layer_style_name." --- ".$this->objLayer[$i]->db_id);
-		if(!$res){
-			db_rollback();	
-		}	
-	}
-	function appendGuiLayer($i,$myWMS,$gui_id){
-		# table gui_layer
-		
-		$sql = "INSERT INTO gui_layer (fkey_gui_id, fkey_layer_id, gui_layer_wms_id, ";
-		$sql .= "gui_layer_status, gui_layer_selectable, gui_layer_visible, gui_layer_queryable, ";
-		$sql .= "gui_layer_querylayer,gui_layer_minscale,gui_layer_maxscale, gui_layer_priority, gui_layer_style, gui_layer_title) ";
-		$sql .= "VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)";
-		if(count($this->objLayer[$i]->layer_style)>0){
-			$layer_style_name = $this->objLayer[$i]->layer_style[0]["name"];
-		}
-		else{
-			$layer_style_name = NULL;
-		}
-		$v = array($gui_id,$this->objLayer[$i]->db_id,$myWMS,0,0,0,$this->objLayer[$i]->layer_queryable,
-			$this->objLayer[$i]->layer_queryable,$this->objLayer[$i]->layer_minscale,$this->objLayer[$i]->layer_maxscale,$i,$layer_style_name, $this->objLayer[$i]->gui_layer_title);
-		$t = array('s','i','i','i','i','i','i','i','i','i','i','s', 's');
-		$res = db_prep_query($sql,$v,$t);
-		if(!$res){
-			db_rollback();	
-		}	
-	}
-	function insertSRS($myWMS){
-		for($i=0; $i<count($this->wms_srs);$i++){
-			$sql ="INSERT INTO wms_srs (fkey_wms_id, wms_srs) values($1,$2)";		
-			$v = array($myWMS,mb_strtoupper($this->wms_srs[$i]));
-			$t = array('i','s');		
-			$res = db_prep_query($sql,$v,$t);
-			if(!$res){
-				db_rollback();	
-			}
-		}	
-	}
-	function insertTermsOfUse ($myWMS) {
-		if (!is_numeric($this->wms_termsofuse)) {
-			return;
-		}
-		$sql ="INSERT INTO wms_termsofuse (fkey_wms_id, fkey_termsofuse_id) ";
-		$sql .= " VALUES($1,$2)";
-		$v = array($myWMS,$this->wms_termsofuse);
-		$t = array('i','i');
-		$res = db_prep_query($sql,$v,$t);
-		if(!$res){
-			db_rollback();	
-		}
-		
-	}
-	function insertFormat($myWMS){
-		for($i=0; $i<count($this->data_type);$i++){
-			$sql ="INSERT INTO wms_format (fkey_wms_id, data_type, data_format) ";
-			$sql .= " VALUES($1,$2,$3)";
-			$v = array($myWMS,$this->data_type[$i],$this->data_format[$i]);
-			$t = array('i','s','s');
-			$res = db_prep_query($sql,$v,$t);
-			if(!$res){
-				db_rollback();	
-			}
-		}	
-	}
-	function insertLayerEPSG($i){
-		$sql = "DELETE FROM layer_epsg WHERE fkey_layer_id = $1";
-		$v = array($this->objLayer[$i]->db_id);
-		$t = array('i');
-		$res = db_prep_query($sql,$v,$t);
-		for($j=0; $j<count($this->objLayer[$i]->layer_epsg);$j++){
-			$sql = "INSERT INTO layer_epsg (fkey_layer_id, epsg, minx, miny, maxx, maxy) ";
-			$sql .= "VALUES($1,$2,$3,$4,$5,$6)";
-			$v = array($this->objLayer[$i]->db_id,$this->objLayer[$i]->layer_epsg[$j][epsg],
-				$this->objLayer[$i]->layer_epsg[$j][minx],$this->objLayer[$i]->layer_epsg[$j][miny],
-				$this->objLayer[$i]->layer_epsg[$j][maxx],$this->objLayer[$i]->layer_epsg[$j][maxy]
-				); 
-			$t = array('i','s','d','d','d','d');
-			$res = db_prep_query($sql,$v,$t);
-			if(!$res){
-				db_rollback();	
-			}
-		}
-	}
-	function insertLayerStyle($i){
-		$sql = "DELETE FROM layer_style WHERE fkey_layer_id = $1";
-		$v = array($this->objLayer[$i]->db_id);
-		$t = array('i');
-		$res = db_prep_query($sql,$v,$t);
-		for($j=0; $j<count($this->objLayer[$i]->layer_style);$j++){
-			$sql = "INSERT INTO layer_style (fkey_layer_id, name, title, legendurl, legendurlformat) ";
-			$sql .= "VALUES($1,$2,$3,$4,$5)";
-			$v = array($this->objLayer[$i]->db_id,$this->objLayer[$i]->layer_style[$j]["name"],
-					$this->objLayer[$i]->layer_style[$j]["title"],$this->objLayer[$i]->layer_style[$j]["legendurl"],
-					$this->objLayer[$i]->layer_style[$j]["legendurlformat"]				
-				);
-			$t = array('i','s','s','s','s');
-			$res = db_prep_query($sql,$v,$t);
-			if(!$res){
-				db_rollback();	
-			}
-		}
-	}
-	
-	function insertLayerCategories($i){
-		global $con;
-
-		$types = array("md_topic", "inspire", "custom");
-		foreach ($types as $cat) {
-			$sql = "DELETE FROM layer_{$cat}_category WHERE fkey_layer_id = $1";
-			$v = array($this->objLayer[$i]->db_id);
-			$t = array('i');
-			$res = db_prep_query($sql,$v,$t);
-			
-			$attr = "layer_{$cat}_category_id";
-			$k = $this->objLayer[$i]->$attr;
-			
-			for ($j = 0; $j < count($k); $j++) {
-				
-				$sql = "INSERT INTO layer_{$cat}_category (fkey_layer_id, fkey_{$cat}_category_id) VALUES ($1, $2)";
-				$v = array($this->objLayer[$i]->db_id, $k[$j]);
-				$t = array('i', 'i');
-				$res = db_prep_query($sql,$v,$t);
-				if(!$res){
-					db_rollback();	
-					return;
-				}
-			}
-		}
-	}	
-	
-	function insertLayerKeyword($i){
-		global $con;
-		$sql = "DELETE FROM layer_keyword WHERE fkey_layer_id = $1";
-		$v = array($this->objLayer[$i]->db_id);
-		$t = array('i');
-		$res = db_prep_query($sql,$v,$t);
-		
-//		var_dump($this);
-		$k = $this->objLayer[$i]->layer_keyword;
-//		var_dump($k);
-		for($j=0; $j<count($k); $j++){
-			$keyword_id = "";
-			
-			while ($keyword_id == "") {
-				$sql = "SELECT keyword_id FROM keyword WHERE UPPER(keyword) = UPPER($1)";
-				$v = array($k[$j]);
-				$t = array('s');
-				$res = db_prep_query($sql,$v,$t);
-				$row = db_fetch_array($res);
-			//print_r($row);
-				if ($row) {
-					$keyword_id = $row["keyword_id"];	
-				}
-				else {
-					$sql_insertKeyword = "INSERT INTO keyword (keyword)";
-					$sql_insertKeyword .= "VALUES ($1)";
-					$v1 = array($k[$j]);
-					$t1 = array('s');
-					$res_insertKeyword = db_prep_query($sql_insertKeyword,$v1,$t1);
-					if(!$res_insertKeyword){
-						db_rollback();	
-					}
-				}
-			}
-
-			// check if layer/keyword combination already exists
-			$sql_layerKeywordExists = "SELECT * FROM layer_keyword WHERE fkey_layer_id = $1 AND fkey_keyword_id = $2";
-			$v = array($this->objLayer[$i]->db_id, $keyword_id);
-			$t = array('i', 'i');
-			$res_layerKeywordExists = db_prep_query($sql_layerKeywordExists, $v, $t);
-			$row = db_fetch_array($res_layerKeywordExists);
-			//print_r($row);
-			if (!$row) {
-				$sql1 = "INSERT INTO layer_keyword (fkey_keyword_id,fkey_layer_id)";
-				$sql1 .= "VALUES ($1,$2)";
-				$v1 = array($keyword_id,$this->objLayer[$i]->db_id);
-				$t1 = array('i','i');
-				$res1 = db_prep_query($sql1,$v1,$t1);
-				if(!$res1){
-					db_rollback();	
-				}
-			}
-		}
-	}
-	function updateObjInDB($myWMS){
-		$admin = new administration();
-		db_begin();
-		
-		$sql = "UPDATE wms SET ";
-		$sql .= "wms_version = $1 ,";
-		$sql .= "wms_getcapabilities  = $2 ,";
-		$sql .= "wms_getmap  = $3 ,";
-		$sql .= "wms_getfeatureinfo  = $4 ,";
-		$sql .= "wms_getlegendurl  = $5 ,";
-		$sql .= "wms_getcapabilities_doc = $6 ,";
-		$sql .= "wms_upload_url = $7,  ";
-		$sql .= "wms_owner = $8, ";
-		$sql .= "wms_timestamp = $9, ";
-		$sql .= "wms_supportsld = $10, ";
-		$sql .= "wms_userlayer = $11, ";
-		$sql .= "wms_userstyle = $12, ";
-		$sql .= "wms_remotewfs = $13 ";
-		$sql .= " WHERE wms_id = $14";
-	
-		$v = array($this->wms_version,$this->wms_getcapabilities,
-			$this->wms_getmap,$this->wms_getfeatureinfo,$this->wms_getlegendurl,
-			$admin->char_encode($this->wms_getcapabilities_doc),$this->wms_upload_url,Mapbender::session()->get("mb_user_id"),strtotime("now"),
-			$this->wms_supportsld,$this->wms_userlayer,$this->wms_userstyle,$this->wms_remotewfs,$myWMS);
-		$t = array('s','s','s','s','s','s','s','i','i','s','s','s','s','i');
-	
-		$res = db_prep_query($sql,$v,$t);
-		if(!$res){
-			db_rollback();	
-		}
-		
-		if($this->overwrite == true){
-			$sql = "UPDATE wms SET ";
-			$sql .= "wms_title  = $1 ,";
-			$sql .= "wms_abstract  = $2 ,";
-			$sql .= "fees = $3, ";
-			$sql .= "accessconstraints = $4, ";
-			$sql .= "contactperson = $5, ";
-			$sql .= "contactposition = $6, ";
-			$sql .= "contactorganization = $7, ";
-			$sql .= "address = $8, ";
-			$sql .= "city = $9, ";
-			$sql .= "stateorprovince = $10, ";
-			$sql .= "postcode = $11, ";
-			$sql .= "country = $12, ";
-			$sql .= "contactvoicetelephone = $13, ";
-			$sql .= "contactfacsimiletelephone = $14, ";
-			$sql .= "contactelectronicmailaddress = $15 ";
-			$sql .= " WHERE wms_id = $16";
-		
-			$v = array($this->wms_title,$this->wms_abstract,$this->fees,$this->accessconstraints,
-				$this->contactperson,$this->contactposition,$this->contactorganization,$this->address,
-				$this->city,$this->stateorprovince,$this->postcode,$this->country,$this->contactvoicetelephone,
-				$this->contactfacsimiletelephone,$this->contactelectronicmailaddress,$myWMS);
-			$t = array('s','s','s','s','s','s','s','s','s','s','s','s','s','s','s','i');
-			$res = db_prep_query($sql,$v,$t);
-			if(!$res){
-				db_rollback();	
-			}
-		}
-		
-		# delete and refill wms_termsofuse
-		$sql = "DELETE FROM wms_termsofuse WHERE fkey_wms_id = $1 ";
-		$v = array($myWMS);
-		$t = array('i');
-		$res = db_prep_query($sql,$v,$t);
-		if(!$res){
-			db_rollback();	
-		}
-		$this->insertTermsOfUse($myWMS);
-		
-		# delete and refill srs and formats
-		$sql = "DELETE FROM wms_srs WHERE fkey_wms_id = $1 ";
-		$v = array($myWMS);
-		$t = array('i');
-		$res = db_prep_query($sql,$v,$t);
-		if(!$res){
-			db_rollback();	
-		}
-		$this->insertSRS($myWMS);
-		
-		$sql = "DELETE FROM wms_format WHERE fkey_wms_id = $1 ";
-		$v = array($myWMS);
-		$t = array('i');
-		$res = db_prep_query($sql,$v,$t);
-		if(!$res){
-			db_rollback();	
-		}
-		$this->insertFormat($myWMS);
-		
-		# update gui_wms
-		$this->update_gui_wms($myWMS);
-		
-		# update TABLE layer	
-		$oldLayerNameArray = array();
-		$v = array($myWMS);
-		$t = array('i');
-		$c = 2;
-		$sql = "SELECT layer_name, layer_title, layer_abstract FROM layer WHERE fkey_wms_id = $1 AND NOT layer_name IN(";
-		for($i=0; $i<count($this->objLayer); $i++){
-			if($i>0){$sql .= ',';}
-			$sql .= "$".$c;
-			array_push($v,$this->objLayer[$i]->layer_name);
-			array_push($t,'s');		
-			$c++;
-		}
-		$sql .= ")";
-		$res = db_prep_query($sql,$v,$t);
-		while ($row = db_fetch_array($res)) {
-			$oldLayerNameArray[]= array(
-				"name" => $row["layer_name"],
-				"title" => $row["layer_title"],
-				"abstract" => $row["layer_abstract"]
-			);
-			
-		}
-		
-		# delete all layer which are outdated
-		$v = array($myWMS);
-		$t = array('i');
-		$c = 2;
-		$sql = "DELETE FROM layer WHERE fkey_wms_id = $1 AND NOT layer_name IN(";
-		for($i=0; $i<count($this->objLayer); $i++){
-			if($i>0){$sql .= ',';}
-			$sql .= "$".$c;
-			array_push($v,$this->objLayer[$i]->layer_name);
-			array_push($t,'s');		
-			$c++;
-		}
-		$sql .= ")";
-		
-		$res = db_prep_query($sql,$v,$t);
-		if(!$res){
-			db_rollback();	
-		}
-			
-		# update or insert?
-		$sql = "SELECT layer_name FROM layer WHERE fkey_wms_id = $1";
-		$v = array($myWMS);
-		$t = array('i');
-		$res = db_prep_query($sql,$v,$t);
-		$exLayer = array();
-		while($row = db_fetch_array($res)){
-			array_push($exLayer,$row["layer_name"]);
-		}
-		
-		$sql = "SELECT fkey_gui_id FROM gui_wms WHERE fkey_wms_id = $1";
-		$v = array($myWMS);
-		$t = array('i');
-		$res = db_prep_query($sql,$v,$t);
-		$exGui = array();
-		while($row = db_fetch_array($res)){
-			array_push($exGui,$row["fkey_gui_id"]);
-		}
-		$newLayerArray = array();
-		for($i=0; $i<count($this->objLayer); $i++){
-			if(in_array($this->objLayer[$i]->layer_name,$exLayer)){
-				//echo "<br>update: ".$this->objLayer[$i]->layer_name;
-				$this->updateLayer($i,$myWMS);
-				for($j=0; $j<count($exGui); $j++){
-					$this->updateGuiLayer($i,$myWMS,$exGui[$j]);
-				}
-			}
-			else{
-				//echo "<br>append: ".$this->objLayer[$i]->layer_name;
-				$this->insertLayer($i,$myWMS);
-				$newLayerArray[]= $i;
-				for($j=0; $j<count($exGui); $j++){
-					$this->appendGuiLayer($i,$myWMS,$exGui[$j]);
-				}
-			}
-		}
-		db_commit();
-		//
-		// update GeoRSS feed
-		//
-		$geoRssFactory = new GeoRssFactory();
-		$geoRss = $geoRssFactory->loadOrCreate(GEO_RSS_FILE);
-		
-		if (!is_null($geoRss)) {
-
-			$geoRssItem = new GeoRssItem();
-			$geoRssItem->setTitle("UPDATED WMS: " . $this->wms_title);
-			$geoRssItem->setDescription($this->wms_abstract);
-			$geoRssItem->setUrl(self::getWmsMetadataUrl($myWMS));
-			$geoRssItem->setPubDate(self::rssDate());
-			for ($j = 0; $j < count($this->objLayer[0]->layer_epsg); $j++) {
-				$currentEpsg = $this->objLayer[0]->layer_epsg[$j];
-				if ($currentEpsg["epsg"] === "EPSG:4326") {
-					$currentBbox = new Mapbender_bbox(
-						$currentEpsg["minx"],
-						$currentEpsg["miny"],
-						$currentEpsg["maxx"],
-						$currentEpsg["maxy"],
-						$currentEpsg["epsg"]
-					);
-					$geoRssItem->setBbox($currentBbox);
-					break;
-				}
-			}
-			$geoRss->append($geoRssItem);
-
-			foreach ($newLayerArray as $newLayer) {
-				$currentLayer = $this->objLayer[$newLayer];
-				$geoRssItem = new GeoRssItem();
-				$geoRssItem->setTitle("ADDED LAYER: " . $currentLayer->layer_title);
-				$geoRssItem->setDescription($currentLayer->layer_abstract);
-				$geoRssItem->setUrl(layer::getLayerMetadataUrl($currentLayer->layer_id));
-				$geoRssItem->setPubDate(self::rssDate());
-				for ($j = 0; $j < count($currentLayer->layer_epsg); $j++) {
-					$currentEpsg = $currentLayer->layer_epsg[$j];
-					if ($currentEpsg["epsg"] === "EPSG:4326") {
-						$currentBbox = new Mapbender_bbox(
-							$currentEpsg["minx"],
-							$currentEpsg["miny"],
-							$currentEpsg["maxx"],
-							$currentEpsg["maxy"],
-							$currentEpsg["epsg"]
-						);
-						$geoRssItem->setBbox($currentBbox);
-						break;
-					}
-				}
-				$geoRss->append($geoRssItem);
-			}
-			foreach ($oldLayerNameArray as $oldLayer) {
-				$geoRssItem = new GeoRssItem();
-				$geoRssItem->setTitle("DELETED LAYER: " . $oldLayer["title"]);
-				$geoRssItem->setDescription($oldLayer["abstract"]);
-				$geoRssItem->setPubDate(self::rssDate());
-//				$geoRssItem->setUrl();
-				$geoRss->append($geoRssItem);
-			}
-			$geoRss->saveAsFile();
-		}
-		return;	
-	}
-
-	function updateGuiLayer($i,$myWMS,$gui_id){
-		$sql = "SELECT layer_id FROM layer WHERE fkey_wms_id = $1 AND layer_name = $2";
-		$v = array($myWMS,$this->objLayer[$i]->layer_name);
-		$t = array('i','s');
-		$res = db_prep_query($sql,$v,$t);
-		if($row = db_fetch_array($res)){
-			$l_id = $row['layer_id'];	
-		}
-		else{
-			db_rollback();
-			$e = new mb_exception("Not found: ".$this->objLayer[$i]->layer_name. " in gui: ".$gui_id);
-			return;	
-		}
-		
-		$sql = "SELECT * FROM gui_layer WHERE fkey_layer_id = $1 and fkey_gui_id = $2";
-		$v = array($l_id,$gui_id);
-		$t = array('i','s');
-		$res = db_prep_query($sql,$v,$t);		
-		while($row = db_fetch_array($res)){
-
-				$sql1 = "UPDATE gui_layer SET gui_layer_title = $1 ";
-				$sql1 .= "WHERE fkey_layer_id = $2 and fkey_gui_id = $3";
-				$v = array($this->objLayer[$i]->layer_title, $l_id,$gui_id);
-				$t = array('s', 'i','s');
-				$res1 = db_prep_query($sql1,$v,$t);
-				if(!$res1){
-					db_rollback();
-				}
-
-			if($this->objLayer[$i]->layer_queryable == 0){
-				$sql1 = "UPDATE gui_layer set gui_layer_queryable = 0, gui_layer_querylayer = 0 ";
-				$sql1 .= "WHERE fkey_layer_id = $1 and fkey_gui_id = $2";
-				$v = array($l_id,$gui_id);
-				$t = array('i','s');
-				$res1 = db_prep_query($sql1,$v,$t);
-				if(!$res1){
-					
-				db_rollback();
-				}
-			}
-			if($this->objLayer[$i]->layer_queryable == 1){
-				$sql1 = "UPDATE gui_layer set gui_layer_queryable = 1 ";
-				$sql1 .= "WHERE fkey_layer_id = $1 and fkey_gui_id = $2";
-				$v = array($l_id,$gui_id);
-				$t = array('i','s');
-				$res1 = db_prep_query($sql1,$v,$t);
-				if(!$res1){
-					
-					db_rollback();
-				}
-			}
-			if($row["gui_layer_minscale"] < $this->objLayer[$i]->layer_minscale){
-				$sql1 = "UPDATE gui_layer set gui_layer_minscale = $1 ";
-				$sql1 .= "WHERE fkey_layer_id = $2 and fkey_gui_id = $3";
-				$v = array($this->objLayer[$i]->layer_minscale,$l_id,$gui_id);
-				$t = array('i','i','s');
-				$res1 = db_prep_query($sql1,$v,$t);
-				if(!$res1){db_rollback();
-				}
-			}
-			if($row["gui_layer_maxscale"] > $this->objLayer[$i]->layer_maxscale){
-				$sql1 = "UPDATE gui_layer set gui_layer_maxscale = $1 ";
-				$sql1 .= "WHERE fkey_layer_id = $2 and fkey_gui_id = $3";
-				$v = array($this->objLayer[$i]->layer_maxscale,$l_id,$gui_id);
-				$t = array('i','i','s');
-				$res1 = db_prep_query($sql1,$v,$t);
-				if(!$res1){db_rollback();
-				}
-			}		
-		}
-	}
-	function update_gui_wms($myWMS){
-		$mySubmit = null;
-		$sql = "SELECT * FROM gui_wms where fkey_wms_id = $1";
-		$v = array($myWMS);
-		$t = array('i');
-		$res = db_prep_query($sql,$v,$t);
-		$cnt = 0;
-		while($row = db_fetch_array($res)){	
-			unset($mySubmit);
-			$myGUI[$cnt] = $row["fkey_gui_id"];
-
-			$sql = "UPDATE gui_wms SET ";
-			$v = array();
-			$t = array();
-			$paramCount = 0;		
-
-			for($i=0; $i<count($this->data_type); $i++){
-				# gui_wms_mapformat
-				if(mb_strtolower($this->data_type[$i]) == "map" && mb_strtolower($this->data_format[$i]) == mb_strtolower($row["gui_wms_mapformat"])){
-					$myMapFormat = true;
-				}
-				# gui_wms_featureinfoformat
-				if(mb_strtolower($this->data_type[$i]) == "featureinfo" && mb_strtolower($this->data_format[$i]) == mb_strtolower($row["gui_wms_featureinfoformat"])){
-					$myFeatureInfoFormat = true;
-				}
-				# gui_wms_exceptionformat
-				if(mb_strtolower($this->data_type[$i]) == "exception" && mb_strtolower($this->data_format[$i]) == mb_strtolower($row["gui_wms_exceptionformat"])){
-					$myExceptionFormat = true;
-				}
-			}
-			if(!$myMapFormat){
-				$paramCount++;
-				$sql .= "gui_wms_mapformat = $" . $paramCount . " ";
-				$mySubmit = true;
-				array_push($v, $this->gui_wms_mapformat);
-				array_push($t, "s");
-			}
-			if(!$myFeatureInfoFormat){
-				if($mySubmit){ $sql .= ",";}
-				$paramCount++;
-				$sql .= "gui_wms_featureinfoformat = $" . $paramCount . " ";
-				array_push($v, $this->gui_wms_featureinfoformat);
-				array_push($t, "s");
-				$mySubmit = true;
-			}
-			if(!$myExceptionFormat){
-				if($mySubmit){ $sql .= ",";}
-				$paramCount++;
-				$sql .= "gui_wms_exceptionformat = $" . $paramCount ." ";
-				array_push($v, $this->gui_wms_exceptionformat);
-				array_push($t, "s");
-				$mySubmit = true;
-			}
-				
-			# gui_wms_epsg
-			for($j=0; $j<count($this->objLayer[0]->layer_epsg);$j++){
-				if($this->objLayer[0]->layer_epsg[$j][epsg] == mb_strtoupper($row["gui_wms_epsg"])){
-					$myGUI_EPSG = true;
-				}
-			}
-			if(!$myGUI_EPSG){
-				if($mySubmit){ $sql .= ",";}
-				$paramCount++;
-				$sql .= "gui_wms_epsg = $" . $paramCount . " ";
-				array_push($v, $this->gui_wms_epsg);
-				array_push($t, "s");
-				$mySubmit = true;
-			}
-			$paramCount++;
-			$sql .= " WHERE fkey_gui_id = $" . $paramCount . " ";
-			array_push($v, $row["fkey_gui_id"]);
-			array_push($t, "s");
-
-			$paramCount++;
-			$sql .= "AND fkey_wms_id = $" . $paramCount;
-			array_push($v, $myWMS);
-			array_push($t, "i");
-			if($mySubmit){
-				$res = db_prep_query($sql,$v,$t);
-				if(!$res){
-					db_rollback();	
-					echo "<pre>".$sql."</pre><br> <br><p>";
-				 	echo db_error(); 
-				 	echo "<br /> UPDATE ERROR -> KILL PROCESS AND ROLLBACK....................no update<br><br>";
-					$e = new mb_exception("class_wms.php: transaction: Transaction aborted, rollback.");
-				}
-			}
-			$cnt++;
-		}	
-	}
-	function getVersion() {
-		return $this->wms_version;
-	}
-	
-	function getCapabilities() {
-		return $this->wms_getcapabilities;
-	}
-	
-	function getCapabilitiesDoc() {
-		return $this->wms_getcapabilities_doc;
-	}
-
-	/**
-	* creatObjfromDB
-	*
-	*/ 
-	  function createObjFromDB($gui_id,$wms_id){
-	
-		$sql = "Select * from gui_wms where fkey_wms_id = $1 AND fkey_gui_id = $2";
-		$v = array($wms_id,$gui_id);
-		$t = array('i','s');
-		$res = db_prep_query($sql,$v,$t);
-		
-		$count=0;
-		#$res_count=db_num_rows($res);
-	    
-	
-		while($row = db_fetch_array($res)){
-			$this->gui_wms_mapformat=$row["gui_wms_mapformat"];
-			$this->gui_wms_featureinfoformat=$row["gui_wms_featureinfoformat"];
-			$this->gui_wms_exceptionformat=$row["gui_wms_exceptionformat"];
-			$this->gui_wms_epsg=$row["gui_wms_epsg"];
-			$this->gui_wms_visible = $row["gui_wms_visible"];
-			$this->gui_wms_opacity = $row["gui_wms_opacity"];
-			$this->gui_wms_sldurl = $row["gui_wms_sldurl"];
-	  
-			$sql = "Select * from wms where wms_id = $1 ";
-			$v = array($wms_id);
-			$t = array('i');
-			$res_wms = db_prep_query($sql,$v,$t);
-			$count_wms=0;
-			while($row2 = db_fetch_array($res_wms)){
-				$this->wms_id = $row2["wms_id"];
-				$this->wms_version = $row2["wms_version"];
-				$this->wms_title = administration::convertIncomingString($this->stripEndlineAndCarriageReturn($row2["wms_title"]));
-				$this->wms_abstract = administration::convertIncomingString($this->stripEndlineAndCarriageReturn($row2["wms_abstract"]));
-				$wmsowsproxy = $row2["wms_owsproxy"];
-				#$wmsowsproxy = "test";
-				if($wmsowsproxy != ""){
-					$owsproxyurl = OWSPROXY."/".session_id()."/".$wmsowsproxy."?";
-					$this->wms_getmap = $owsproxyurl;
-					$this->wms_getcapabilities =  $owsproxyurl;
-					$this->wms_getfeatureinfo = $owsproxyurl;
-					$this->wms_getlegendurl = $owsproxyurl;
-				}
-				else{
-					$this->wms_getmap =  $row2["wms_getmap"];
-					$this->wms_getcapabilities =  $row2["wms_getcapabilities"];
-					$this->wms_getfeatureinfo = $row2["wms_getfeatureinfo"];
-					$this->wms_getlegendurl = $row2["wms_getlegendurl"];
-				}			
-				// TO DO: Capabilities document needs to 
-				// be encoded to the original encoding
-				// if different from the database encoding
-				$this->wms_getcapabilities_doc = $row2["wms_getcapabilities_doc"];
-				$this->wms_filter = $row2["wms_filter"];
-				$this->wms_supportsld = $row2["wms_supportsld"];
-				$this->wms_userlayer = $row2["wms_userlayer"];
-				$this->wms_userstyle = $row2["wms_userstyle"];
-				$this->wms_remotewfs = $row2["wms_remotewfs"];
-				$this->wms_timestamp_create = $row2["wms_timestamp_create"];
-				$this->fees = $row2["fees"];
-				$this->accessconstraints = $row2["accessconstraints"];
-				$this->contactperson = $row2["contactperson"];
-				$this->contactposition = $row2["contactposition"];
-				$this->contactvoicetelephone = $row2["contactvoicetelephone"];
-				$this->contactfacsimiletelephone = $row2["contactfacsimiletelephone"];
-				$this->contactorganization = $row2["contactorganization"];
-				$this->address = $row2["address"];
-				$this->city = $row2["city"];
-				$this->stateorprovince = $row2["stateorprovince"];
-				$this->postcode = $row2["postcode"];
-				$this->country = $row2["country"];
-				$this->contactelectronicmailaddress = $row2["contactelectronicmailaddress"];
-				
-				$count_wms++;
-			}
-	
-			### srs
-			$srs_sql = "SELECT * FROM wms_srs WHERE fkey_wms_id = $1 ";
-			$srs_v = array($wms_id);
-			$srs_t = array('i'); 
-			$srs_res = db_prep_query($srs_sql, $srs_v, $srs_t);
-			$this->wms_srs = array();
-			while($srs_row = db_fetch_array($srs_res)) {		
-				$this->wms_srs[]= $srs_row["wms_srs"];
-			}
-
-			### formats
-			$sql = "SELECT * FROM wms_format WHERE fkey_wms_id = $1 ";
-			$v = array($wms_id);
-			$t = array('i'); 
-			$res_wms = db_prep_query($sql,$v,$t);
-			$count_format=0;		
-			while($row3 = db_fetch_array($res_wms)){		
-				$this->data_type[$count_format] = $row3["data_type"];
-				$this->data_format[$count_format] = $row3["data_format"];
-				$count_format++;
-			}
-			$count++;
-		}
-		
-		#layer
-		$sql = "Select * from gui_layer where gui_layer_wms_id = $1 AND fkey_gui_id = $2 ";
-		$sql .= " AND gui_layer_status = 1 ORDER BY gui_layer_priority;";
-		$v = array($wms_id,$gui_id);
-		$t = array('i','s');
-		$res = db_prep_query($sql,$v,$t);
-		$count=0;
-		
-		while($row = db_fetch_array($res)){
-			$layer_id = $row["fkey_layer_id"];		
-			$sql = "Select * from layer where layer_id = $1";
-			$v = array($layer_id);
-			$t = array('i');
-			$res_layer = db_prep_query($sql,$v,$t);
-			$count_layer=0;
-			while($row2 = db_fetch_array($res_layer)){
-				$this->addLayer($row2["layer_pos"],$row2["layer_parent"]);
-				$layer_cnt=count($this->objLayer)-1;
-				$this->objLayer[$layer_cnt]->layer_uid = $layer_id;
-				$this->objLayer[$layer_cnt]->layer_name = administration::convertIncomingString($row2["layer_name"]);
-				$this->objLayer[$layer_cnt]->layer_title = administration::convertIncomingString($row2["layer_title"]);			
-				$this->objLayer[$layer_cnt]->layer_dataurl_href =$row2["layer_dataurl"];
-				$this->objLayer[$layer_cnt]->layer_metadataurl =$row2["layer_metadataurl"];
-				$this->objLayer[$layer_cnt]->layer_searchable =$row2["layer_searchable"];
-				$this->objLayer[$layer_cnt]->layer_pos =$row2["layer_pos"];						
-				$this->objLayer[$layer_cnt]->layer_queryable =$row2["layer_pos"];
-				$this->objLayer[$layer_cnt]->layer_queryable =$row2["layer_queryable"];
-				$this->objLayer[$layer_cnt]->layer_minscale =$row2["layer_minscale"];
-				$this->objLayer[$layer_cnt]->layer_maxscale = $row2["layer_maxscale"];
-				$count_layer++;
-			}
-			$this->objLayer[$layer_cnt]->layer_uid = $layer_id;
-			$this->objLayer[$layer_cnt]->gui_layer_wms_id = $row["gui_layer_wms_id"];
-			$this->objLayer[$layer_cnt]->gui_layer_selectable = $row["gui_layer_selectable"];
-			$this->objLayer[$layer_cnt]->gui_layer_title = $row["gui_layer_title"] != "" ? $row["gui_layer_title"] : $this->objLayer[$layer_cnt]->layer_title;
-			$this->objLayer[$layer_cnt]->gui_layer_visible = $row["gui_layer_visible"];
-			$this->objLayer[$layer_cnt]->gui_layer_queryable = $row["gui_layer_queryable"];
-			$this->objLayer[$layer_cnt]->gui_layer_querylayer = $row["gui_layer_querylayer"];
-			$this->objLayer[$layer_cnt]->gui_layer_minscale = $row["gui_layer_minscale"];
-			$this->objLayer[$layer_cnt]->gui_layer_maxscale = $row["gui_layer_maxscale"];
-			$this->objLayer[$layer_cnt]->gui_layer_style = $row["gui_layer_style"];
-			$this->objLayer[$layer_cnt]->gui_layer_wfs_featuretype = $row["gui_layer_wfs_featuretype"];
-
-			$sql = "Select * from layer_epsg where fkey_layer_id = $1 ORDER BY fkey_layer_id";
-			$v = array($layer_id);
-			$t = array('i');
-			$res_layer_epsg = db_prep_query($sql,$v,$t);
-			
-			$count_layer_epsg=0;
-			while($row2 = db_fetch_array($res_layer_epsg)){
-				$this->objLayer[$layer_cnt]->layer_epsg[$count_layer_epsg]["epsg"]=$row2["epsg"];
-				$this->objLayer[$layer_cnt]->layer_epsg[$count_layer_epsg]["minx"]=$row2["minx"];
-				$this->objLayer[$layer_cnt]->layer_epsg[$count_layer_epsg]["miny"]=$row2["miny"];
-				$this->objLayer[$layer_cnt]->layer_epsg[$count_layer_epsg]["maxx"]=$row2["maxx"];
-				$this->objLayer[$layer_cnt]->layer_epsg[$count_layer_epsg]["maxy"]=$row2["maxy"];
-				$count_layer_epsg++;
-			}
-			
-			### handle styles
-			$sql = "SELECT * FROM layer_style WHERE fkey_layer_id = $1 ";
-			$v = array($layer_id);
-			$t = array('i');
-			$res_style = db_prep_query($sql,$v,$t);
-			$count_layer_style = 0;
-			while($row2 = db_fetch_array($res_style)){
-				$this->objLayer[$layer_cnt]->layer_style[$count_layer_style]["name"] = $row2["name"] ? $row2["name"] : "default";
-				$this->objLayer[$layer_cnt]->layer_style[$count_layer_style]["title"]=$row2["title"];
-				if($wmsowsproxy != ""){
-					if($row2["legendurl"]!=''){
-						$this->objLayer[$layer_cnt]->layer_style[$count_layer_style]["legendurl"]=$owsproxyurl.
-						"REQUEST=getlegendgraphic&VERSION=".$this->wms_version."&LAYER=".$this->objLayer[$layer_cnt]->layer_name."&FORMAT=".$row2["legendurlformat"].
-						"&STYLE=".$row2["name"];
-					}
-				}
-				else{
-					if($row2["legendurl"]!=''){
-						$this->objLayer[$layer_cnt]->layer_style[$count_layer_style]["legendurl"]=$row2["legendurl"];
-						#$e = new mb_exception("legendurl = ".$this->objLayer[$layer_cnt]->layer_style[$count_layer_style]["legendurl"]);
-					}
-				}
-				$this->objLayer[$layer_cnt]->layer_style[$count_layer_style]["legendurlformat"]=$row2["legendurlformat"];
-				$count_layer_style++;
-			}
-			$count++;
-		}
-	   }
-	/** end createObjfromDB **/
-	
-	  /**
-	* creatObjfromDBNoGui
-	*
-	*/ 
-	  function createObjFromDBNoGui($wms_id){
-	   	$sql = "Select * from wms where wms_id = $1 ";
-		$v = array($wms_id);
-		$t = array('i');
-		$res_wms = db_prep_query($sql,$v,$t);
-		$count_wms=0;
-		while($row2 = db_fetch_array($res_wms)){
-			$this->wms_id = $row2["wms_id"];
-			$this->wms_version = $row2["wms_version"];
-			$this->wms_title = administration::convertIncomingString($this->stripEndlineAndCarriageReturn($row2["wms_title"]));
-			$this->wms_abstract = administration::convertIncomingString($this->stripEndlineAndCarriageReturn($row2["wms_abstract"]));
-			$wmsowsproxy = $row2["wms_owsproxy"];
-			#$wmsowsproxy = "test";
-			if($wmsowsproxy != ""){
-				$owsproxyurl = OWSPROXY."/".session_id()."/".$wmsowsproxy."?";
-				$this->wms_getmap = $owsproxyurl;
-				$this->wms_getcapabilities =  $owsproxyurl;
-				$this->wms_getfeatureinfo = $owsproxyurl;
-				$this->wms_getlegendurl = $owsproxyurl;
-			}
-			else{
-				$this->wms_getmap =  $row2["wms_getmap"];
-				$this->wms_getcapabilities =  $row2["wms_getcapabilities"];
-				$this->wms_getfeatureinfo = $row2["wms_getfeatureinfo"];
-				$this->wms_getlegendurl = $row2["wms_getlegendurl"];
-			}			
-			// TO DO: Capabilities document needs to 
-			// be encoded to the original encoding
-			// if different from the database encoding
-			$this->wms_getcapabilities_doc = $row2["wms_getcapabilities_doc"];
-			$this->wms_filter = $row2["wms_filter"];
-			$this->wms_supportsld = $row2["wms_supportsld"];
-			$this->wms_userlayer = $row2["wms_userlayer"];
-			$this->wms_userstyle = $row2["wms_userstyle"];
-			$this->wms_remotewfs = $row2["wms_remotewfs"];
-			$this->wms_timestamp = $row2["wms_timestamp"];
-			$this->wms_timestamp_create = $row2["wms_timestamp_create"];
-			$this->fees = $row2["fees"];
-			$this->accessconstraints = $row2["accessconstraints"];
-			$this->contactperson = $row2["contactperson"];
-			$this->contactposition = $row2["contactposition"];
-			$this->contactvoicetelephone = $row2["contactvoicetelephone"];
-			$this->contactfacsimiletelephone = $row2["contactfacsimiletelephone"];
-			$this->contactorganization = $row2["contactorganization"];
-			$this->address = $row2["address"];
-			$this->city = $row2["city"];
-			$this->stateorprovince = $row2["stateorprovince"];
-			$this->postcode = $row2["postcode"];
-			$this->country = $row2["country"];
-			$this->contactelectronicmailaddress = $row2["contactelectronicmailaddress"];
-			
-			#some default
-			$this->gui_wms_visible = 1;
-			$this->gui_wms_opacity = 100;
-			$this->gui_wms_epsg=$row["gui_wms_epsg"];
-			$this->gui_wms_sldurl = $row["gui_wms_sldurl"];
-			
-			if($this->wms_version == "1.0.0"){
-                    $this->gui_wms_mapformat = "PNG";
-                    $this->gui_wms_featureinfoformat = "MIME";
-                    $this->gui_wms_exceptionformat = "INIMAGE";
-            }
-            /*define defaults for wms-version 1.1.0 and 1.1.1*/
-            else{
-                    $this->gui_wms_mapformat = "image/png";
-                    $this->gui_wms_featureinfoformat = "text/html";
-                    $this->gui_wms_exceptionformat = "application/vnd.ogc.se_inimage";
-            }
-			
-			$count_wms++;
-		}
-	
-		### formats
-		$sql = "SELECT * FROM wms_format WHERE fkey_wms_id = $1 ";
-		$v = array($wms_id);
-		$t = array('i'); 
-		$res_wms = db_prep_query($sql,$v,$t);
-		$count_format=0;		
-		while($row3 = db_fetch_array($res_wms)){		
-			$this->data_type[$count_format] = $row3["data_type"];
-			$this->data_format[$count_format] = $row3["data_format"];
-			$count_format++;
-		}
-
-			
-		$sql = "Select * from layer where fkey_wms_id = $1";
-		$v = array($wms_id);
-		$t = array('i');
-		$res_layer = db_prep_query($sql,$v,$t);
-		$count_layer=0;
-		while($row2 = db_fetch_array($res_layer)){
-			$this->addLayer($row2["layer_pos"],$row2["layer_parent"]);
-			$layer_cnt=count($this->objLayer)-1;
-			$this->objLayer[$layer_cnt]->layer_uid = $row2["layer_id"];
-			$this->objLayer[$layer_cnt]->layer_name = administration::convertIncomingString($row2["layer_name"]);
-			$this->objLayer[$layer_cnt]->layer_title = administration::convertIncomingString($row2["layer_title"]);	
-			$this->objLayer[$layer_cnt]->gui_layer_title = $this->objLayer[$layer_cnt]->layer_title;			
-			$this->objLayer[$layer_cnt]->layer_dataurl_href =$row2["layer_dataurl"];
-			$this->objLayer[$layer_cnt]->layer_metadataurl =$row2["layer_metadataurl"];
-			$this->objLayer[$layer_cnt]->layer_searchable =$row2["layer_searchable"];
-			$this->objLayer[$layer_cnt]->layer_pos =$row2["layer_pos"];						
-			$this->objLayer[$layer_cnt]->layer_queryable =$row2["layer_pos"];
-			$this->objLayer[$layer_cnt]->layer_queryable =$row2["layer_queryable"];
-			$this->objLayer[$layer_cnt]->layer_minscale =$row2["layer_minscale"];
-			$this->objLayer[$layer_cnt]->layer_maxscale = $row2["layer_maxscale"];
-			
-			if($this->objLayer[$layer_cnt]->layer_minscale == ""){
-				$this->objLayer[$layer_cnt]->layer_minscale = 0;
-			}
-			if($this->objLayer[$layer_cnt]->layer_maxscale == ""){
-				$this->objLayer[$layer_cnt]->layer_maxscale = 0;
-			}
-			$this->objLayer[$layer_cnt]->gui_layer_minscale = $this->objLayer[$layer_cnt]->layer_minscale;
-			$this->objLayer[$layer_cnt]->gui_layer_maxscale = $this->objLayer[$layer_cnt]->layer_maxscale;
-			
-			$sql = "Select * from layer_epsg where fkey_layer_id = $1 ORDER BY fkey_layer_id";
-			$v = array($this->objLayer[$layer_cnt]->layer_uid);
-			$t = array('i');
-			$res_layer_epsg = db_prep_query($sql,$v,$t);
-			
-			$count_layer_epsg=0;
-			while($row2 = db_fetch_array($res_layer_epsg)){
-				$this->objLayer[$layer_cnt]->layer_epsg[$count_layer_epsg]["epsg"]=$row2["epsg"];
-				$this->objLayer[$layer_cnt]->layer_epsg[$count_layer_epsg]["minx"]=$row2["minx"];
-				$this->objLayer[$layer_cnt]->layer_epsg[$count_layer_epsg]["miny"]=$row2["miny"];
-				$this->objLayer[$layer_cnt]->layer_epsg[$count_layer_epsg]["maxx"]=$row2["maxx"];
-				$this->objLayer[$layer_cnt]->layer_epsg[$count_layer_epsg]["maxy"]=$row2["maxy"];
-				$count_layer_epsg++;
-			}
-			
-			### handle styles
-			$sql = "SELECT * FROM layer_style WHERE fkey_layer_id = $1 ";
-			$v = array($this->objLayer[$layer_cnt]->layer_uid);
-			$t = array('i');
-			$res_style = db_prep_query($sql,$v,$t);
-			$count_layer_style = 0;
-			while($row2 = db_fetch_array($res_style)){
-				$this->objLayer[$layer_cnt]->layer_style[$count_layer_style]["name"]=$row2["name"];
-				$this->objLayer[$layer_cnt]->layer_style[$count_layer_style]["title"]=$row2["title"];
-				if($wmsowsproxy != ""){
-					if($row2["legendurl"]!=''){
-						$this->objLayer[$layer_cnt]->layer_style[$count_layer_style]["legendurl"]=$owsproxyurl.
-						"REQUEST=getlegendgraphic&VERSION=".$this->wms_version."&LAYER=".$this->objLayer[$layer_cnt]->layer_name."&FORMAT=".$row2["legendurlformat"].
-						"&STYLE=".$row2["name"];
-					}
-				}
-				else{
-					if($row2["legendurl"]!=''){
-						$this->objLayer[$layer_cnt]->layer_style[$count_layer_style]["legendurl"]=$row2["legendurl"];
-						#$e = new mb_exception("legendurl = ".$this->objLayer[$layer_cnt]->layer_style[$count_layer_style]["legendurl"]);
-					}
-				}
-				$this->objLayer[$layer_cnt]->layer_style[$count_layer_style]["legendurlformat"]=$row2["legendurlformat"];
-				$count_layer_style++;
-			}
-						
-			$count_layer++;
-		}
-	
-   }
-	/** end createObjfromDBNoGui **/
-	
-	  /**
-	* function checkObjExistsInDB()
-	*
-	* this function checks wether the onlineresource already exists in the database.
-	*/ 
-	function checkObjExistsInDB(){
-	
-		$sql = "Select * from wms where wms_getcapabilities = $1";
-		$v = array($this->wms_getcapabilities);
-		$t = array('s');
-		$res = db_prep_query($sql,$v,$t);
-		$res_count= db_num_rows($res);	  
-		$wms_id=0;
-		if($res_count>0){
-			$count=0;
-			while($row = db_fetch_array($res)){
-				$wms_id=$row["wms_id"];
-				$count++;
-			}
-		}
-		return $wms_id;
-	}
-	
-	function displayDBInformation(){
-		echo $this->wms_getcapabilities;
-		$sql="Select * from wms where wms_getcapabilities = $1";
-		$v = array($this->wms_getcapabilities);
-		$t = array('s');
-		$res = db_prep_query($sql,$v,$t);
-		$count=0;
-		while($row = db_fetch_array($res)){
-		echo "count: ".$count."<br>";
-			$wms_id=$row["wms_id"];
-			echo "version: " .$wms_id." <br>";
-			echo "title: " .$row["wms_version"]. " <br>";
-			echo "abstract: " . $row["wms_title"] . " <br>";
-			echo "maprequest: " .$row["wms_abstract"] . " <br>";
-			echo "capabilitiesrequest: " . $row["wms_getcapabilities"] . " <br>";
-			echo "featureinforequest: " . $row["wms_getmap"]. " <br>";
-			echo "gui_wms_mapformat: " . $row["wms_getfeatureinfo"] . " <br>---------<br>";
-			$count++;
-		}
-	   echo "----<br> wms_id: ".$wms_id."<br>";
-	   
-	   $sql = "Select * from gui_wms where fkey_wms_id = $1";
-	   $v = array($wms_id);
-	   $t = array('i');
-	   echo "sql: ".$sql." <br>---------<br>";
-	   $res = db_prep_query($sql,$v,$t);
-	   $res_count= db_num_rows($res); 
-	   echo "result count: ".$res_count." <br>---------<br>";
-	   
-	   $count=0;
-	   while($row = db_fetch_array($res)){
-	    	echo "gui_wms_featureinfoformat: " . $row["gui_wms_featureinfoformat"]." <br>";
-	    	echo "gui_wms_exceptionformat: " .  $row["gui_wms_exceptionformat"]. " <br>";
-	    	echo "gui_wms_epsg: " .  $row["gui_wms_epsg"]. " <br>";
-	      $count++;
-	   }
-		
-	   #db_close($connect);
-	}
-
-	function checkObj(){
-		if($this->wms_getcapabilities == '' || $this->wms_getmap == '' ){
-			echo "<br>Missing parameters: <br>";
-			$this->displayWMS();
-			print_r($this);
-			echo "<br> Data not committed<br>";
-			die();
-		}
-	}
-	
-	public static function getWmsIdByLayerId ($id) {
-		$sql = "SELECT DISTINCT fkey_wms_id FROM layer WHERE layer_id = $1";
-		$res = db_prep_query($sql, array($id), array("i"));
-		$row = db_fetch_assoc($res);
-		if ($row) {
-			return $row["fkey_wms_id"];
-		}
-		return null;
-	}
-	
-	/**
-	 * Selects all WMS of the current user from the database.
-	 * Then it creates the corresponding WMS object and returns
-	 * these objects as an array.
-	 * 
-	 * @return wms[]
-	 * @param $appId String
-	 */
-	public static function selectMyWmsByApplication ($appId) {
-		// check if user is permitted to access the application
-		$currentUser = new User(Mapbender::session()->get("mb_user_id"));
-		$appArray = $currentUser->getApplicationsByPermission(false);
-		if (!in_array($appId, $appArray)) {
-			$e = new mb_warning("class_wms.php: selectMyWmsByApplication(): User '" . $currentUser . "' is not allowed to acces application '" . $appId . "'.");
-			return array();
-		}
-		
-		// get WMS of this application
-		$sql = "SELECT fkey_wms_id FROM gui_wms WHERE " . 
-				"fkey_gui_id = $1 ORDER BY gui_wms_position";
-		$v = array($appId);
-		$t = array('s');
-		$res = db_prep_query($sql,$v,$t);
-		
-		// instantiate PHP objects and store in array
-		$wmsArray = array();
-		while ($row = db_fetch_array($res)) {
-			$currentWms = new wms();
-			$currentWms->createObjFromDB($appId, $row["fkey_wms_id"]);
-			array_push($wmsArray, $currentWms);
-		}
-		return $wmsArray;
-	}
-}
-class layer extends wms {	
-	var $layer_id;
-	var $layer_parent;
-	var $layer_name;
-	var $layer_title;
-	var $layer_abstract;
-	var $layer_pos;
-	var $layer_queryable;
-	var $layer_minscale;
-	var $layer_maxscale;	
-    var $layer_dataurl_href;
-    var $layer_metadataurl;
-	var $layer_searchable;
-    var $layer_keyword = array();
-	var $layer_epsg = array();
-	var $layer_style = array();
-	var $layer_md_topic_category_id = array();
-	var $layer_inspire_category_id = array();
-	var $layer_custom_category_id = array();
-	
-	var $gui_layer_wms_id;
-	var $gui_layer_status = 1;
-	var $gui_layer_selectable = 1;
-	var $gui_layer_visible = 0;
-	var $gui_layer_queryable = 0;
-	var $gui_layer_querylayer = 0;
-	var $gui_layer_style = NULL;	
-	
-	function layer($id,$parent){
-		$this->layer_id = $id;
-		$this->layer_parent = $parent;	
-		//var_dump($this);	
-	}
-
-	public static function getLayerMetadataUrl ($layerId) {
-		return preg_replace(
-			"/(.*)frames\/login.php/", 
-			"$1php/mod_layerMetadata.php?id=", 
-			LOGIN
-		) . $layerId;
-	}
-
-	public function __toString () {
-		$e = new mb_exception("TITLE: " . $this->layer_title);
-		return $this->layer_title;
-	}
-	
-	public function getChildren () {
-		$children = array();
-		$wmsId = wms::getWmsIdByLayerId($this->layer_uid);
-		$wmsFactory = new UniversalWmsFactory();
-		$wms = $wmsFactory->createFromDb($wmsId);
-		if (!is_null($wms)) {
-			$currentLayer = $wms->getLayerById($this->layer_uid);
-			for ($i = 0; $i < count($wms->objLayer); $i++) {
-				$l = $wms->objLayer[$i];
-				if ($l->layer_parent === $currentLayer->layer_pos) {
-					// add this layer and add its children recursively
-					$children = array_merge($children, array($l), $l->getChildren());
-				}
-			}
-		}
-		return $children;
-	}
-	
-	public function getParents () {
-		$parents = array();
-		$wmsId = wms::getWmsIdByLayerId($this->layer_uid);
-		$wmsFactory = new UniversalWmsFactory();
-		$wms = $wmsFactory->createFromDb($wmsId);
-		if (!is_null($wms)) {
-			$currentLayer = $wms->getLayerById($this->layer_uid);
-			while (!is_null($currentLayer)) {
-				$pos = $currentLayer->layer_parent;
-				$currentLayer = $wms->getLayerByPos($pos);
-				if (!is_null($currentLayer)) {
-					$parents[]= $currentLayer;
-				}
-			}
-		}
-		return $parents;
-	}
-}
-?>

Copied: branches/mapbender/http/classes/class_wms.php (from rev 6953, trunk/mapbender/http/classes/class_wms.php)
===================================================================
--- branches/mapbender/http/classes/class_wms.php	                        (rev 0)
+++ branches/mapbender/http/classes/class_wms.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -0,0 +1,2874 @@
+<?php
+# License:
+# Copyright (c) 2009, Open Source Geospatial Foundation
+# This program is dual licensed under the GNU General Public License 
+# and Simplified BSD license.  
+# http://svn.osgeo.org/mapbender/trunk/mapbender/license/license.txt
+
+require_once dirname(__FILE__) . "/../../core/globalSettings.php";
+require_once dirname(__FILE__) . "/class_connector.php";
+require_once dirname(__FILE__) . "/class_user.php";
+require_once dirname(__FILE__) . "/class_administration.php";
+require_once dirname(__FILE__) . "/class_georss_factory.php";
+require_once dirname(__FILE__) . "/../classes/class_universal_wms_factory.php";
+
+class wms {
+	var $lastURL;
+	var $wms_id;
+	var $wms_status;
+	var $wms_version;
+	var $wms_title;
+	var $wms_abstract;
+	var $wms_getcapabilities;
+	var $wms_getcapabilities_doc;
+	var $wms_getmap;
+	var $wms_getfeatureinfo;
+	var $wms_getlegendurl;
+	var $wms_upload_url;
+	var $wms_timestamp;
+	var $wms_timestamp_create;
+	var $wms_srs = array();
+	var $wms_termsofuse;
+	  
+	var $fees;
+	var $accessconstraints;
+	var $contactperson;
+	var $contactposition;
+	var $contactorganization;
+	var $address;
+	var $city;
+	var $stateorprovince;
+	var $postcode;
+	var $country;
+	var $contactvoicetelephone;
+	var $contactfacsimiletelephone;
+	var $contactelectronicmailaddress;
+	  
+	var $wms_keyword = array();
+	var $data_type = array(); 
+	var $data_format = array();
+	var $objLayer = array(); 
+	  
+	var $wms_supportsld;
+	var $wms_userlayer;
+	var $wms_userstyle;
+	var $wms_remotewfs;
+		
+	var $gui_wms_mapformat;
+	var $gui_wms_featureinfoformat;
+	var $gui_wms_exceptionformat;
+	var $gui_wms_epsg;
+	var $gui_wms_sldurl;
+	  
+	var $default_epsg = 0;
+	var $overwrite = true;
+	
+	// write a GeoRSS feed?
+	const GEORSS = true;
+	// append items to the feed when a new WMS is inserted?
+	const GEORSS_APPEND_ON_INSERT = true;
+	// append items to the feed when an existing WMS is updated?
+	const GEORSS_APPEND_ON_UPDATE = true;
+	// append items to the feed only when an existing WMS is updated 
+	// and new layers have been added?
+	const GEORSS_APPEND_ON_UPDATE_NEWLAYERS = true;
+	  
+	function wms() {
+	} 
+    /**
+     *
+     * @generate RSS formated date 
+     *
+     * @param int $timestamp The UNIX_TIMESTAMP
+     *
+     * @return string
+     *
+     */
+    private static function rssDate($timestamp=null)
+    {
+        /*** set the timestamp ***/
+        $timestamp = ($timestamp==null) ? time() : $timestamp;
+
+        /*** Mon, 02 Jul 2009 11:36:45 +0000 ***/
+        return date(DATE_RSS, $timestamp);
+    }
+    
+	public static function getWmsMetadataUrl ($wmsId) {
+		return preg_replace(
+			"/(.*)frames\/login.php/", 
+			"$1php/mod_layerMetadata.php?id=", 
+			LOGIN
+		) . $wmsId;
+	}
+
+	public static function isOwsProxyUrl ($getmap) {
+//		$e = new mb_notice("isOwsProxyUrl? " . $getmap);
+		$result = preg_match("/^.*owsproxy.([^i][\w\d]+)\/([\w\d]{32})\/?.*$/", $getmap);
+//		$e = new mb_notice("result: " . $result);
+		return $result;
+	}
+
+	private function replaceSessionIdInOwsProxyUrl ($getMap) {
+//		$e = new mb_notice("replaceSessionIdInOwsProxyUrl: ");
+		$e = new mb_notice("before: " . $getMap);
+		$pattern = '/(^.*owsproxy.)([^i][\w\d]+)(\/)([\w\d]{32})(\/?.*)$/';
+		$getMap1= preg_replace($pattern, "$1",$getMap);
+		$getMap2=  preg_replace($pattern, "$3$4$5",$getMap);
+		$getMap = $getMap1.session_id().$getMap2;
+		$e = new mb_notice("after: " . $getMap);
+		return $getMap;
+	}
+	
+	public static function getHashFromOwsProxyUrl ($getMap) {
+//		$e = new mb_notice("replaceSessionIdInOwsProxyUrl: " . $getMap);
+		$result = preg_replace("/^.*owsproxy.([^i][\w\d]+)\/([\w\d]{32})\/?.*$/", "$2", $getMap);
+//		$e = new mb_notice("result: " . $result);
+		return $result;
+	}
+	
+	private function getWmsIdByOwsProxyHash($md5) {
+		$sql = "SELECT wms_id FROM wms WHERE wms_owsproxy = $1";
+		$v = array($md5);
+		$t = array("s");
+		$res = db_prep_query($sql, $v, $t);
+		$row = db_fetch_row($res);
+		if ($row["wms_id"]) {
+			return $row["wms_id"];
+		}
+		return null;
+	}
+	
+	private function updateOwsProxyUrl ($url) {
+		// is OWS proxy URL?
+		if (wms::isOwsProxyUrl($url)) {
+
+			// No WMS id could be found
+			if (!$this->wms_id) {
+				$e = new mb_notice("No WMS id could be found!");
+				return $url;
+			}			
+			// Update session id in OWS proxy URL
+			$new_proxy_url = $this->replaceSessionIdInOwsProxyUrl($url);
+
+			// If new url is a valid proxy URL, return true
+			if ($this->isOwsProxyUrl($new_proxy_url)) {
+				return $new_proxy_url;
+			}
+			else {
+//				$e = new mb_notice("new URL is not an OWS proxy URL!");
+			}
+			// new URL is not an OWS proxy URL; 
+			// some error must have occured.
+			// no update
+			return $url;
+		}
+		// no OWS proxy URL, no update necessary
+//		$e = new mb_notice("URL is not an OWS proxy URL!");
+		return $url;
+	}
+	
+	function updateAllOwsProxyUrls () {
+		$wmsId = $this->wms_id;
+
+		// if WMS id is unknown, try to 
+		// find it via OWS proxy entry
+		//FIXME -Funktion berichtigen 
+		if (!$wmsId) {
+			$md5 = wms::getHashFromOwsProxyUrl($url);
+			if ($md5) {
+				$wmsId = $this->getWmsIdByOwsProxyHash($md5);
+				if (!is_null($wmsId)) {
+					$this->wms_id = $wmsId;
+				}
+			}
+		}
+
+		$this->wms_getmap = 
+			$this->updateOwsProxyUrl($this->wms_getmap);
+		$this->wms_getfeatureinfo = 
+			$this->updateOwsProxyUrl($this->wms_getfeatureinfo);
+		$this->wms_getlegendurl = 
+			$this->updateOwsProxyUrl($this->wms_getlegendurl);
+		
+		for ($i = 0; $i < count($this->objLayer); $i++) {
+			for ($j = 0; $j < count($this->objLayer[$i]->layer_style); $j++) {
+				$this->objLayer[$i]->layer_style[$j]["legendurl"] = 
+					$this->updateOwsProxyUrl($this->objLayer[$i]->layer_style[$j]["legendurl"]);
+			}
+		}
+	}
+	
+	public static function getConjunctionCharacter ($url) {
+		if (mb_strpos($url, "?") !== false) { 
+			if (mb_substr($url, mb_strlen($url)-1, 1) == "?") { 
+				return "";
+			}
+			else if (mb_substr($url, mb_strlen($url)-1, 1) == "&"){
+				return "";
+			}
+			else {
+				return "&";
+			}
+		}
+		else {
+			return "?";
+		}
+		return "";
+	}
+
+	public function getLayerById ($id) {
+		$adm = new administration();
+		for ($i = 0; $i < count($this->objLayer); $i++) {
+			if (strval($this->objLayer[$i]->layer_uid) === strval($id)) {
+				if ($adm->getLayerPermission(
+							$this->wms_id, 
+							$this->objLayer[$i]->layer_name, 
+							Mapbender::session()->get("mb_user_id")
+				)) {
+					return $this->objLayer[$i];
+				}
+				else {
+					throw new Exception ("Access to layer denied.");
+				}
+			}
+		}
+		throw new Exception ("Layer not found.");
+	}
+
+	public function getLayerByPos ($pos) {
+		for ($i = 0; $i < count($this->objLayer); $i++) {
+			if (strval($this->objLayer[$i]->layer_pos) === strval($pos)) {
+				return $this->objLayer[$i];
+			}
+		}
+		return null;
+	}
+
+	function createOlObjFromWMS($base){
+	 	if(!$this->wms_title || $this->wms_title == ""){
+			echo "alert('Error: no valid capabilities-document !!');";
+			die; exit;
+		}
+		// wms_title and abstract have previously been urlencoded
+		// this solution may not yet be the ultimate one
+		
+		$add_wms_string  = "var wms_".$this->wms_id." = new OpenLayers.Layer.WMS(";
+		// WMS-title
+		$add_wms_string .= "'" . addslashes($this->wms_title) . "',";
+		// Base-URL of service
+		$add_wms_string .= "'" . $this->wms_getmap ."',";
+		// Additional URL params
+		$add_wms_string .= "{layers:'";
+		for($i=1;$i<count($this->objLayer);$i++){
+			$add_wms_string .= addslashes($this->objLayer[$i]->layer_name);
+			if($i!=count($this->objLayer)-1) {
+				$add_wms_string .= ",";
+			}
+		}
+		$add_wms_string .= "',";
+		// This is hardcoded, exactly as for Mapbender WMS
+		$add_wms_string .= "transparent: 'true',";
+		$add_wms_string .= "format: '".$this->gui_wms_mapformat."'},";
+		// OpenLayers-Layer options
+		$add_wms_string .= "{";
+		$add_wms_string .= 	"transitionEffect:'resize',";
+		$add_wms_string .= 	"ratio:1.2,";
+		$add_wms_string .= 	"singleTile:true,";
+		// baselayer?				
+		if($base) {
+			$add_wms_string .= 	"isBaseLayer:true,";
+		} else {
+			$add_wms_string .= 	"isBaseLayer:false,";
+		}
+		// visible or not?
+		if($this->gui_wms_visible=="1") {
+			$add_wms_string .= 	"visibility:true,";
+		} else {
+			$add_wms_string .= 	"visibility:false,";
+		}
+		// initial transparency
+		$add_wms_string .= 	"opacity:" . strval(round($this->gui_wms_opacity/100, 2));
+		
+		$add_wms_string .= "}";
+		$add_wms_string .= ");";
+		
+		$queryLayers = array();
+		for ($i = 0; $i < count($this->objLayer); $i++) {
+			$layer = $this->objLayer[$i];
+			if ($layer->layer_queryable 
+				&& $layer->gui_layer_queryable 
+				&& $layer->gui_layer_querylayer
+			) {
+				$queryLayers[]= $layer->layer_name;
+			}
+		}
+		$queryLayerString = implode(",", $queryLayers);
+		$add_wms_string .= "wms_" . $this->wms_id . ".params.QUERY_LAYERS = '$queryLayerString';";
+
+		// TODO why ol_map
+		$add_wms_string .= "ol_map.addLayer(wms_".$this->wms_id.");";
+		echo $add_wms_string;
+	}	
+	
+	/**
+	 * Compares this WMS to another WMS.
+	 * 
+	 * @return boolean false, if
+	 * 					- the capabilities URLs don't match
+	 * 					- the layer count is different
+	 * 					- the layer names are different
+	 * 
+	 * @param $anotherWms wms this is just another WMS object
+	 */
+	public function equals ($anotherWms) {
+		// If the getMap URLs are not equal, the WMS are not equal.
+		if ($this->wms_getmap != $anotherWms->wms_getmap) {
+//			$e = new mb_notice($this . " != " . $anotherWms . " (getMap URL)");
+			return false;
+		}
+
+		// If the layer count is different, the WMS are not equal.
+		if (count($this->objLayer) != count($anotherWms->objLayer)) {
+//			$e = new mb_notice($this . " != " . $anotherWms . " (layer count: " . count($this->objLayer) . ":" . count($anotherWms->objLayer). ")");
+// removing this check because you can also load single layers of WMS!
+// so you might load different layers of the WMS at different times,
+// they need to be grouped under the same WMS
+//			return false;
+		}
+		
+		// If the layer names are different, the WMS are not equal.
+		for ($i = 0; $i < count($this->objLayer); $i++) {
+			$name1 = $this->objLayer[$i]->layer_name;
+			$name2 = $anotherWms->objLayer[$i]->layer_name;
+			if ($name1 != $name2) {
+//				$e = new mb_notice($this . " != " . $anotherWms . " (layer names, " . $name1 . " vs. " . $name2 . ")");
+// removing this check because you can also load single layers of WMS!
+// so you might load different layers of the WMS at different times,
+// they need to be grouped under the same WMS
+//				return false;
+			}
+		}
+		
+//		$e = new mb_notice($this . " == " . $anotherWms);
+		return true;
+	}  
+	
+	/**
+	 * Removes duplicate WMS from an array of WMS. To find duplicates,
+	 * two WMS are compared via equals().
+	 * 
+	 * @return wms[]
+	 * @param $wmsArray wms[]
+	 */
+	public static function merge ($wmsArray) {
+//		$e = new mb_notice("before: " . implode(", ", $wmsArray));
+		if (!is_array($wmsArray)) {
+			$e = new mb_notice("class_wms.php: merge(): parameter is NOT an array.");
+			return array();
+		}
+		if (count($wmsArray) == 0) {
+			$e = new mb_notice("class_wms.php: merge(): parameter is an EMPTY array.");
+			return array();
+		}
+
+		$newWmsArray = array();
+
+		while (count($wmsArray) > 0) {
+			$currentWms = array_pop($wmsArray);
+
+			$isNewWms = true;
+
+			if (get_class($currentWms) != "wms") {
+				$e = new mb_notice("class_wms.php: merge(): current WMS is not a WMS object, but a " . get_class($currentWms));
+			}
+			else {
+				$index = null;
+				for ($i = 0; $i < count($newWmsArray) && $isNewWms; $i++) {
+					if ($currentWms->equals($newWmsArray[$i])) {
+						$isNewWms = false;
+						$index = $i;
+					}
+				}
+				if ($isNewWms) {
+					$e = new mb_notice("adding WMS " . $currentWms);
+					$newWmsArray[]= $currentWms;
+				}
+				else {
+					$existingWms = $newWmsArray[$index];
+
+					$len = count($currentWms->objLayer);
+					for ($i = 0; $i < $len; $i++) {
+						$currentWmsLayer = $currentWms->objLayer[$i];
+						$found = false;
+						$lenExist = count($existingWms->objLayer);
+						for ($j = 0; $j < $lenExist; $j++) {
+							$existingWmsLayer = $existingWms->objLayer[$j];
+							if ($currentWmsLayer->equals($existingWmsLayer)) {
+								$found = true;
+								break;
+							}
+							if ($existingWmsLayer->layer_pos > $currentWmsLayer->layer_pos) {
+								break;
+							}
+						}
+						if (!$found) {
+							array_splice($existingWms->objLayer, $j, 0, array($currentWmsLayer));
+						}
+					}
+				}
+			}
+		}
+		// reversal of the array, because the elements were popped 
+		// from another array before.
+		$e = new mb_notice("after: " . implode(", ", array_reverse($newWmsArray)));
+		return array_reverse($newWmsArray);
+	}
+
+	private function formatExists ($type, $format) {
+		for ($i = 0; $i < count($this->data_type); $i++) {
+			if ($type == $this->data_type[$i] && $format == $this->data_format[$i]) {
+				$e = new mb_warning("WMS format already exists ($type, $format). Violation of WMS spec. Ignoring this WMS format.");
+				return true;
+			}
+		}
+		return false;
+	}
+
+	public function __toString () {
+		return strval($this->wms_title);
+	}
+	
+	function createObjFromXML($url){
+		if (func_num_args() == 2) { //new for HTTP Authentication
+            		$auth = func_get_arg(1);
+			$x = new connector($url,$auth);
+		}
+		else {
+			$x = new connector($url);
+		}
+		$data = $x->file;
+		if ($data=='401') {
+			echo "<br>HTTP Error:<b>".$data." - Authorization required. This seems to be a service which needs HTTP Authentication!</b><br>";
+		}
+		if(!$data){
+			$this->wms_status = false;
+			return false;
+		}
+		else {
+			$this->wms_status = true;
+		}
+			
+		$values = null;
+		$tags = null;
+		$admin = new administration();
+		$this->wms_getcapabilities_doc = $data;
+		$this->wms_upload_url = $url;
+		
+		$this->wms_id = "";
+		$parser = xml_parser_create("");
+		xml_parser_set_option($parser,XML_OPTION_CASE_FOLDING,0);
+		xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,1);
+		xml_parser_set_option($parser,XML_OPTION_TARGET_ENCODING,CHARSET);
+		xml_parse_into_struct($parser,$data,$values,$tags);
+
+		$code = xml_get_error_code($parser);
+		if ($code) {
+			$line = xml_get_current_line_number($parser); 
+			$mb_exception = new mb_exception(xml_error_string($code) .  " in line " . $line);
+		}
+		
+		xml_parser_free($parser);
+		
+		$section = null;
+		$format = null;
+		$cnt_format = 0;
+		$parent = array();
+		$myParent = array();
+		$cnt_layer = -1;
+		$request = null; 
+		$layer_style = array();
+		$cnt_styles = -1;
+		
+		$this->wms_getfeatureinfo = "";
+		$this->gui_wms_featureinfoformat = "";
+
+		foreach ($values as $element) {
+			if(mb_strtoupper($element[tag]) == "WMT_MS_CAPABILITIES" && $element[type] == "open"){
+				$this->wms_version = $element[attributes][version];
+			}
+			if(mb_strtoupper($element[tag]) == "TITLE" && $element[level] == '3'){
+				$this->wms_title = $this->stripEndlineAndCarriageReturn($element[value]);
+			}
+			if(mb_strtoupper($element[tag]) == "ABSTRACT" && $element[level] == '3'){
+				$this->wms_abstract = $this->stripEndlineAndCarriageReturn($element[value]);
+			}
+			if(mb_strtolower($element[tag]) == "fees"){
+				$this->fees = $element[value];
+			}
+			if(mb_strtolower($element[tag]) == "accessconstraints"){
+				$this->accessconstraints = $element[value];
+			}
+			if(mb_strtolower($element[tag]) == "contactperson"){
+				$this->contactperson = $element[value];
+			}
+			if(mb_strtolower($element[tag]) == "contactposition"){
+				$this->contactposition = $element[value];
+			}
+			if(mb_strtolower($element[tag]) == "contactorganization"){
+				$this->contactorganization = $element[value];
+			}
+			if(mb_strtolower($element[tag]) == "address"){
+				$this->address = $element[value];
+			}
+			if(mb_strtolower($element[tag]) == "city"){
+				$this->city = $element[value];
+			}
+			if(mb_strtolower($element[tag]) == "stateorprovince"){
+				$this->stateorprovince = $element[value];
+			}
+			if(mb_strtolower($element[tag]) == "postcode"){
+				$this->postcode = $element[value];
+			}
+			if(mb_strtolower($element[tag]) == "country"){
+				$this->country = $element[value];
+			}
+			if(mb_strtolower($element[tag]) == "contactvoicetelephone"){
+				$this->contactvoicetelephone = $element[value];
+			}
+			if(mb_strtolower($element[tag]) == "contactfacsimiletelephone"){
+				$this->contactfacsimiletelephone = $element[value];
+			}
+			if(mb_strtolower($element[tag]) == "contactelectronicmailaddress"){
+				$this->contactelectronicmailaddress = $element[value];
+			}
+	  		if(mb_strtolower($element[tag]) == "keyword" && $section != 'layer'){
+				$this->wms_keyword[count($this->wms_keyword)] = $element[value];
+			}
+			
+			/*map section*/
+			if($this->wms_version == "1.0.0"){
+		 		if(mb_strtoupper($element[tag]) == "MAP" && $element[type] == "open"){
+					$section = "map";
+				}
+				if($section == "map" && mb_strtoupper($element[tag]) == "GET"){
+					$this->wms_getmap = $element[attributes][onlineResource];
+				}
+				if($section == "map" && mb_strtoupper($element[tag]) == "FORMAT" && $element[type] == "open"){
+					$format = "map";
+				}
+				if(mb_strtoupper($element[tag]) != "FORMAT" && $section == "map" && $format == "map"){
+					if (!$this->formatExists("map", trim($element[tag]))) {
+						$this->data_type[$cnt_format] = "map";
+						$this->data_format[$cnt_format] = trim($element[tag]);
+						$cnt_format++;
+					}
+				}
+				if(mb_strtoupper($element[tag]) == "FORMAT" && $element[type] == "close"){
+					$format = "";
+				}
+				if(mb_strtoupper($element[tag]) == "MAP" && $element[type] == "close"){
+					$section = "";
+				}
+			}
+			else{
+				if(mb_strtoupper($element[tag]) == "GETMAP" && $element[type] == "open"){
+					$section = "map";
+				}
+				if($section == "map" && mb_strtoupper($element[tag]) == "GET" && $element[type] == "open"){
+					$request = "get";
+				}
+				if($section == "map" && $request == "get" && mb_strtoupper($element[tag]) == "ONLINERESOURCE"){
+					$this->wms_getmap = $element[attributes]["xlink:href"];
+				}
+				if($section == "map" && mb_strtoupper($element[tag]) == "FORMAT"){
+					if (!$this->formatExists("map", trim($element[value]))) {
+						$this->data_type[$cnt_format] = "map";
+						$this->data_format[$cnt_format] = trim($element[value]);
+						$cnt_format++;
+					}
+				}
+				if($section == "map" && mb_strtoupper($element[tag]) == "GET" && $element[type] == "close"){
+					$request = "";
+				}
+				if(mb_strtoupper($element[tag]) == "GETMAP" && $element[type] == "close"){
+					$section = "";
+				}
+			}
+			/*capabilities section*/
+			if($this->wms_version == "1.0.0"){
+				if(mb_strtoupper($element[tag]) == "CAPABILITIES" && $element[type] == "open"){
+					$section = "capabilities";
+				}
+				if($section == "capabilities" && mb_strtoupper($element[tag]) == "GET"){
+					$this->wms_getcapabilities = $element[attributes][onlineResource];
+				}
+				if(mb_strtoupper($element[tag]) == "CAPABILITIES" && $element[type] == "close"){
+					$section = "";
+				}
+			}
+			else{
+				if(mb_strtoupper($element[tag]) == "GETCAPABILITIES" && $element[type] == "open"){
+					$section = "capabilities";
+				}
+				if($section == "capabilities" && mb_strtoupper($element[tag]) == "GET" && $element[type] == "open"){
+					$request = "get";
+				}
+				if($section == "capabilities" && $request == "get" && mb_strtoupper($element[tag]) == "ONLINERESOURCE"){
+					$this->wms_getcapabilities = $element[attributes]["xlink:href"];
+				}
+				if($section == "capabilities" && mb_strtoupper($element[tag]) == "GET" && $element[type] == "close"){
+					$request = "";
+				}
+				if(mb_strtoupper($element[tag]) == "GETCAPABILITIES" && $element[type] == "close"){
+					$section = "";
+				}
+			}
+			/*featureInfo section*/
+			if($this->wms_version == "1.0.0"){
+				if(mb_strtoupper($element[tag]) == "FEATUREINFO" && $element[type] == "open"){
+					$section = "featureinfo";
+				}
+				if($section == "featureinfo" && mb_strtoupper($element[tag]) == "GET"){
+					$this->wms_getfeatureinfo = $element[attributes][onlineResource];
+				}
+				if($section == "featureinfo" && mb_strtoupper($element[tag]) == "FORMAT" && $element[type] == "open"){
+					$format = "featureinfo";
+				}
+				if(mb_strtoupper($element[tag]) != "FORMAT" && $section == "featureinfo" && $format == "featureinfo"){
+					if (!$this->formatExists("featureinfo", trim($element[tag]))) {
+						$this->data_type[$cnt_format] = "featureinfo";
+						$this->data_format[$cnt_format] = trim($element[tag]);
+						$cnt_format++;
+					}
+				}
+				if(mb_strtoupper($element[tag]) == "FORMAT" && $element[type] == "close"){
+					$format = "";
+				}
+				if(mb_strtoupper($element[tag]) == "FEATUREINFO" && $element[type] == "close"){
+					$section = "";
+				}
+			}
+			else{
+				if(mb_strtoupper($element[tag]) == "GETFEATUREINFO" && $element[type] == "open"){
+					$section = "featureinfo";
+				}
+				if($section == "featureinfo" && mb_strtoupper($element[tag]) == "GET" && $element[type] == "open"){
+					$request = "get";
+				}
+				if($section == "featureinfo" && $request == "get" && mb_strtoupper($element[tag]) == "ONLINERESOURCE"){
+					$this->wms_getfeatureinfo = $element[attributes]["xlink:href"];
+				}
+				if($section == "featureinfo" && mb_strtoupper($element[tag]) == "FORMAT"){
+					if (!$this->formatExists("featureinfo", trim($element[value]))) {
+						$this->data_type[$cnt_format] = "featureinfo";
+						$this->data_format[$cnt_format] = trim($element[value]);
+						$cnt_format++;
+					}
+				}
+				if($section == "featureinfo" && mb_strtoupper($element[tag]) == "GET" && $element[type] == "close"){
+					$request = "";
+				}
+				if(mb_strtoupper($element[tag]) == "GETFEATUREINFO" && $element[type] == "close"){
+					$section = "";
+				}
+			}
+			/*exception section*/
+			if($this->wms_version == "1.0.0"){
+				if(mb_strtoupper($element[tag]) == "EXCEPTION" && $element[type] == "open"){
+					$section = "exception";
+				}
+				if($section == "exception" && mb_strtoupper($element[tag]) == "FORMAT" && $element[type] == "open"){
+					$format = "exception";
+				}
+				if(mb_strtoupper($element[tag]) != "FORMAT" && $section == "exception" && $format == "exception"){
+					$this->data_type[$cnt_format] = "exception";
+					$this->data_format[$cnt_format] = trim($element[tag]);
+					$cnt_format++;
+				}
+				if($section == "exception" && mb_strtoupper($element[tag]) == "FORMAT" && $element[type] == "close"){
+					$format = "";
+				}
+				if(mb_strtoupper($element[tag]) == "EXCEPTION" && $element[type] == "close"){
+					$section = "";
+				}
+			}
+			else{
+				if(mb_strtoupper($element[tag]) == "EXCEPTION" && $element[type] == "open"){
+					$section = "exception";
+				}
+				if($section == "exception" && mb_strtoupper($element[tag]) == "FORMAT"){
+					$this->data_type[$cnt_format] = "exception";
+					$this->data_format[$cnt_format] = trim($element[value]);
+					$cnt_format++;
+				}
+				if(mb_strtoupper($element[tag]) == "EXCEPTION" && $element[type] == "close"){
+					$section = "";
+				}
+			}
+	      /*legend section*/
+	      if($this->wms_version == "1.0.0"){
+	      
+	      }
+	      else{
+	        if(mb_strtoupper($element[tag]) == "GETLEGENDGRAPHIC" && $element[type] == "open"){
+				$section = "legend";
+			}
+	        if($section == "legend" && mb_strtoupper($element[tag]) == "GET" && $element[type] == "open"){
+				$request = "get";
+			}
+			if($section == "legend" && $request == "get" && mb_strtoupper($element[tag]) == "ONLINERESOURCE"){
+				$this->wms_getlegendurl = $element[attributes]["xlink:href"];
+			}
+	        if($section == "legend" && mb_strtoupper($element[tag]) == "GET" && $element[type] == "close"){
+				$request = "";
+			}
+			if(mb_strtoupper($element[tag]) == "GETLEGENDGRAPHIC" && $element[type] == "close"){
+				$section = "";
+			}         
+	      }
+			/* sld section */	      
+			if(mb_strtoupper($element[tag]) == "USERDEFINEDSYMBOLIZATION" && $element[type] == "complete"){
+				$this->wms_supportsld = $element[attributes]["SupportSLD"];
+				$this->wms_userlayer = $element[attributes]["UserLayer"];
+				$this->wms_userstyle = $element[attributes]["UserStyle"];
+				$this->wms_remotewfs = $element[attributes]["RemoteWFS"];
+			}
+	      	      
+			/*layer section*/				
+			if(mb_strtoupper($element[tag]) == "LAYER"){
+				$section = "layer";
+				if ($element[type] == "open") {
+					$cnt_epsg = -1;
+					$cnt_layer++;
+					$parent[$element[level]+1] = $cnt_layer;
+					$myParent[$cnt_layer]= $parent[$element[level]];
+					$this->addLayer($cnt_layer,$myParent[$cnt_layer]);
+					$this->objLayer[$cnt_layer]->layer_queryable = $element[attributes][queryable];
+				}
+				if ($element[type] == "close") {
+				
+				}
+			}
+			/* attribution */
+			if(mb_strtoupper($element[tag]) == "ATTRIBUTION"){
+				if ($element[type] == "open") {
+					$section = "attribution";
+				}
+				if ($element[type] == "close") {
+					$section = "layer";
+				}
+			}
+			/* styles */
+			if(mb_strtoupper($element[tag]) == "STYLE"){
+				$section = "style";
+				if($cnt_layer != $layer_style){
+					$layer_style = $cnt_layer;
+					$cnt_styles = -1;
+				}
+				if ($element[type] == "open") {
+					$cnt_styles++;
+				}
+				if ($element[type] == "close") {
+					$section = "layer";
+				}
+			}
+			if($section == "style"){
+				if(mb_strtoupper($element[tag]) == "NAME"){
+					$this->objLayer[$cnt_layer]->layer_style[$cnt_styles]["name"] = ($element[value] ? $element[value] : 'default');
+				}
+				if(mb_strtoupper($element[tag]) == "TITLE"){
+					$this->objLayer[$cnt_layer]->layer_style[$cnt_styles]["title"] = ($element[value] ? $element[value] : '');
+				}
+	      		if(mb_strtoupper($element[tag]) == "LEGENDURL" && $element[type] == "open"){
+					$legendurl = true;
+				}
+				if($legendurl && mb_strtoupper($element[tag]) == "FORMAT"){
+					$this->objLayer[$cnt_layer]->layer_style[$cnt_styles]["legendurlformat"] = $element[value];
+				}
+				if($legendurl && mb_strtoupper($element[tag]) == "ONLINERESOURCE"){
+					$this->objLayer[$cnt_layer]->layer_style[$cnt_styles]["legendurl"] = $element[attributes]["xlink:href"];
+				}
+			    if(mb_strtoupper($element[tag]) == "LEGENDURL" && $element[type] == "close"){
+					$legendurl = false;
+				}   
+			}
+			/* end of styles */
+			if($section == "layer"){
+				if(mb_strtoupper($element[tag]) == "NAME"){
+					$this->objLayer[$cnt_layer]->layer_name = $element[value];
+				}
+				if(mb_strtoupper($element[tag]) == "TITLE"){
+					$this->objLayer[$cnt_layer]->layer_title = $this->stripEndlineAndCarriageReturn($element[value]);
+				}
+				if(mb_strtoupper($element[tag]) == "ABSTRACT"){
+					$this->objLayer[$cnt_layer]->layer_abstract = $this->stripEndlineAndCarriageReturn($element[value]);
+				}
+				if(mb_strtoupper($element[tag]) == "KEYWORD"){
+					array_push($this->objLayer[$cnt_layer]->layer_keyword, trim($element[value]));
+				}
+	      		if(mb_strtoupper($element[tag]) == "DATAURL" && $element[type] == "open"){
+					$dataurl = true;
+				}
+				if($dataurl && mb_strtoupper($element[tag]) == "ONLINERESOURCE"){
+					$this->objLayer[$cnt_layer]->layer_dataurl_href = $element[attributes]["xlink:href"];
+				}
+			    if(mb_strtoupper($element[tag]) == "DATAURL" && $element[type] == "close"){
+					$dataurl = false;
+				}   
+				
+				if(mb_strtoupper($element[tag]) == "METADATAURL" && $element[type] == "open"){
+					$metadataurl = true;
+				}
+				if($metadataurl && mb_strtoupper($element[tag]) == "ONLINERESOURCE"){
+					$this->objLayer[$cnt_layer]->layer_metadataurl = $element[attributes]["xlink:href"];
+				}
+			    if(mb_strtoupper($element[tag]) == "METADATAURL" && $element[type] == "close"){
+					$metadataurl = false;
+				}   
+				
+				if(mb_strtoupper($element[tag]) == "SRS"){
+					// unique srs only, see http://www.mapbender.org/index.php/Arrays_with_unique_entries
+					$this->wms_srs = array_keys(array_flip(array_merge($this->wms_srs, explode(" ", strtoupper($element[value])))));
+				}						      
+				if(mb_strtoupper($element[tag]) == "LATLONBOUNDINGBOX"){
+					$cnt_epsg++;
+					$this->objLayer[$cnt_layer]->layer_epsg[$cnt_epsg]["epsg"] = "EPSG:4326";
+					$this->objLayer[$cnt_layer]->layer_epsg[$cnt_epsg]["minx"] = $element[attributes][minx];
+					$this->objLayer[$cnt_layer]->layer_epsg[$cnt_epsg]["miny"] = $element[attributes][miny];
+					$this->objLayer[$cnt_layer]->layer_epsg[$cnt_epsg]["maxx"] = $element[attributes][maxx];
+					$this->objLayer[$cnt_layer]->layer_epsg[$cnt_epsg]["maxy"] = $element[attributes][maxy];
+				}
+				if(mb_strtoupper($element[tag]) == "BOUNDINGBOX" && $element[attributes][SRS] != "EPSG:4326"){
+					$cnt_epsg++;
+					$this->objLayer[$cnt_layer]->layer_epsg[$cnt_epsg]["epsg"] = $element[attributes][SRS];
+					$this->objLayer[$cnt_layer]->layer_epsg[$cnt_epsg]["minx"] = $element[attributes][minx];
+					$this->objLayer[$cnt_layer]->layer_epsg[$cnt_epsg]["miny"] = $element[attributes][miny];
+					$this->objLayer[$cnt_layer]->layer_epsg[$cnt_epsg]["maxx"] = $element[attributes][maxx];
+					$this->objLayer[$cnt_layer]->layer_epsg[$cnt_epsg]["maxy"] = $element[attributes][maxy];
+					// a default epsg for mapbender
+					if($cnt_layer == 0 && $this->default_epsg == 0 && mb_strlen(trim($element[attributes][SRS]))>= 10){
+						$this->default_epsg = $cnt_epsg;
+					}
+				}
+				if(mb_strtoupper($element[tag]) == "SCALEHINT"){
+					if($element[attributes][max]>1000) $max = 0; else $max = $element[attributes][max]; 	
+					if($element[attributes][min]>1000) $min = 0; else $min = $element[attributes][min]; 	
+					$this->objLayer[$cnt_layer]->layer_minscale = round(($min * 2004.3976484406788493955738891127));
+					$this->objLayer[$cnt_layer]->layer_maxscale = round(($max * 2004.3976484406788493955738891127));
+				}
+			} 
+			else {
+				continue;
+			}
+		}
+		if(!$this->wms_title || $this->wms_title == "" || !$this->wms_getmap || $this->wms_getmap == ""){
+			$this->wms_status = false;
+			$this->optimizeWMS();
+			$e = new mb_exception("class_wms: createObjFromXML: WMS " . $url . " could not be loaded.");
+			return false;
+		}
+		else{
+			$this->wms_status = true;
+			$this->optimizeWMS();
+			$e = new mb_notice("class_wms: createObjFromXML: WMS " . $url . " has been loaded successfully.");
+			return true;
+		}
+	}
+	/**
+	 * private function
+	 */
+	function optimizeWMS() {
+		/*define defaults for wms-version 1.0.0*/
+		$map_default_ok = false;
+		$featureinfo_default_ok = false;
+		$exception_default_ok = false;
+		if($this->wms_version == "1.0.0"){
+			$map_default = "PNG";
+			$featureinfo_default = "MIME";
+			$exception_default = "INIMAGE";
+		}
+		/*define defaults for wms-version 1.1.0 and 1.1.1*/
+		else{
+			$map_default = "image/png";
+			$featureinfo_default = "text/html";
+			$exception_default = "application/vnd.ogc.se_inimage";
+		}
+		#some default
+		$this->gui_wms_visible = 1;
+		$this->gui_wms_opacity = 100;
+		/*if the rootlayer has no epsg...*/
+		if($this->objLayer[0]->layer_epsg[0]["epsg"] == ""){
+			$this->objLayer[0]->layer_epsg = $this->objLayer[1]->layer_epsg;
+			for($i=0;$i<count($this->objLayer[0]->layer_epsg);$i++){
+				for($j=1; $j<count($this->objLayer); $j++){
+					if($this->objLayer[0]->layer_epsg[$i]["epsg"] == $this->objLayer[$j]->layer_epsg[$i]["epsg"]){
+						if($this->objLayer[$j]->layer_epsg[$i]["minx"]<$this->objLayer[0]->layer_epsg[$i]["minx"]){
+							$this->objLayer[0]->layer_epsg[$i]["minx"] = $this->objLayer[$j]->layer_epsg[$i]["minx"];
+						}
+						if($this->objLayer[$j]->layer_epsg[$i]["miny"]<$this->objLayer[0]->layer_epsg[$i]["miny"]){
+							$this->objLayer[0]->layer_epsg[$i]["miny"] = $this->objLayer[$j]->layer_epsg[$i]["miny"];
+						}
+						if($this->objLayer[$j]->layer_epsg[$i]["maxx"]>$this->objLayer[0]->layer_epsg[$i]["maxx"]){
+							$this->objLayer[0]->layer_epsg[$i]["maxx"] = $this->objLayer[$j]->layer_epsg[$i]["maxx"];
+						}
+						if($this->objLayer[$j]->layer_epsg[$i]["maxy"]>$this->objLayer[0]->layer_epsg[$i]["maxy"]){
+							$this->objLayer[0]->layer_epsg[$i]["maxy"] = $this->objLayer[$j]->layer_epsg[$i]["maxy"];
+						}
+					}
+				}
+			}
+		}
+		for($i=0;$i<count($this->objLayer);$i++){
+			if(count($this->objLayer[$i]->layer_epsg) == 0 && count($this->objLayer[0]->layer_epsg) > 0){
+				$this->objLayer[$i]->layer_epsg = $this->objLayer[0]->layer_epsg; 
+			}
+			if(!is_int($this->objLayer[$i]->layer_parent)){
+				$this->objLayer[$i]->layer_abstract = $this->wms_abstract;
+				for ($r = 0; $r < count($this->wms_keyword); $r++) {
+					array_push($this->objLayer[$i]->layer_keyword, trim($this->wms_keyword[$r]));
+				}
+			}
+			if($this->objLayer[$i]->layer_name == ""){
+				$this->objLayer[$i]->layer_name = $this->objLayer[$i]->layer_title;
+			}
+			if($this->objLayer[$i]->layer_minscale == ""){
+				$this->objLayer[$i]->layer_minscale = 0;
+			}
+			if($this->objLayer[$i]->layer_maxscale == ""){
+				$this->objLayer[$i]->layer_maxscale = 0;
+			}
+			if($this->objLayer[$i]->layer_queryable == ""){
+				$this->objLayer[$i]->layer_queryable = 0;
+			}
+			$this->objLayer[$i]->gui_layer_minscale = $this->objLayer[$i]->layer_minscale;
+			$this->objLayer[$i]->gui_layer_maxscale = $this->objLayer[$i]->layer_maxscale;
+			$this->objLayer[$i]->layer_searchable = 1;
+		}
+		for($i=0;$i<count($this->data_format);$i++){
+			if(mb_strtolower($this->data_type[$i]) == 'map' && mb_strtoupper($this->data_format[$i]) == mb_strtoupper($map_default)){
+				$this->gui_wms_mapformat = mb_strtolower($map_default);
+				$map_default_ok = true;
+			}
+			if(mb_strtolower($this->data_type[$i]) == 'featureinfo' && mb_strtoupper($this->data_format[$i]) == mb_strtoupper($featureinfo_default)){
+				$this->gui_wms_featureinfoformat = mb_strtolower($featureinfo_default);
+				$featureinfo_default_ok = true;
+			}		
+			if(mb_strtolower($this->data_type[$i]) == 'exception' && mb_strtolower($this->data_format[$i]) == mb_strtolower($exception_default)){
+				$this->gui_wms_exceptionformat = mb_strtolower($exception_default);
+				$exception_default_ok = true;
+			}		
+		}
+		if($map_default_ok == false){
+			for($i=0;$i<count($this->data_format);$i++){
+				if(mb_strtolower($this->data_type[$i]) == "map" ){$this->gui_wms_mapformat = $this->data_format[$i]; break;}
+			}
+		}
+		if($featureinfo_default_ok == false){
+			for($i=0;$i<count($this->data_format);$i++){
+				if(mb_strtolower($this->data_type[$i]) == "featureinfo" ){$this->gui_wms_featureinfoformat = $this->data_format[$i]; break;}
+			}
+		}
+		if($exception_default_ok == false){
+			for($i=0;$i<count($this->data_format);$i++){
+				if(mb_strtolower($this->data_type[$i]) == "exception" ){$this->gui_wms_exceptionformat = $this->data_format[$i]; break;}
+			}
+		}
+		
+		if(count($this->objLayer[0]->layer_epsg)>1){
+			$this->gui_wms_epsg = $this->objLayer[0]->layer_epsg[$this->default_epsg][epsg];
+		}
+		else{
+			$this->gui_wms_epsg = $this->objLayer[0]->layer_epsg[0][epsg];
+		}
+		/*the queryable layers*/
+		for($i=0; $i<count($this->objLayer); $i++){
+			if($this->objLayer[$i]->layer_queryable == 1){
+				$this->objLayer[$i]->gui_layer_queryable = 1;
+			}
+			else{
+				$this->objLayer[$i]->gui_layer_queryable = 0;
+			}
+		}
+		for($i=0; $i<count($this->objLayer); $i++){
+				$this->objLayer[$i]->layer_pos=$i;
+		}
+		
+		// check if gui_layer_title isset
+		for($i=0; $i<count($this->objLayer); $i++){
+			$this->objLayer[$i]->gui_layer_title = $this->objLayer[$i]->gui_layer_title != "" ?
+				$this->objLayer[$i]->gui_layer_title :
+				$this->objLayer[$i]->layer_title;
+		}
+		
+		/* fill sld variables when empty */
+		if($this->wms_supportsld == ""){
+				$this->wms_supportsld = 0;
+		}
+		if($this->wms_userlayer == ""){
+				$this->wms_userlayer = 0;
+		}
+		if($this->wms_userstyle == ""){
+				$this->wms_userstyle = 0;
+		}
+		if($this->wms_remotewfs == ""){
+				$this->wms_remotewfs = 0;
+		}
+	  }
+	
+	function displayWMS(){
+		echo "<br>id: " . $this->wms_id . " <br>";
+		echo "version: " . $this->wms_version . " <br>";
+		echo "title: " . $this->wms_title . " <br>";
+		echo "abstract: " . $this->wms_abstract . " <br>";
+		echo "maprequest: " . $this->wms_getmap . " <br>";
+		echo "capabilitiesrequest: " . $this->wms_getcapabilities . " <br>";
+		echo "featureinforequest: " . $this->wms_getfeatureinfo . " <br>";
+		echo "gui_wms_mapformat: " . $this->gui_wms_mapformat . " <br>";
+		echo "gui_wms_featureinfoformat: " . $this->gui_wms_featureinfoformat . " <br>";
+		echo "gui_wms_exceptionformat: " . $this->gui_wms_exceptionformat . " <br>";	
+		echo "gui_wms_epsg: " . $this->gui_wms_epsg . " <br>";
+		echo "wms_srs: " . implode(", ", $this->wms_srs) . " <br>";
+		echo "gui_wms_visible: " . $this->gui_wms_visible . " <br>";
+		echo "gui_wms_opacity: " . $this->gui_wms_opacity . " <br>";
+		echo "support_sld: " . $this->wms_supportsld . " <br>";
+		
+		for($i=0; $i<count($this->data_type);$i++){
+			echo $this->data_type[$i]. " -> ".$this->data_format[$i]. "<br>";
+		}
+		for($i=0; $i<count($this->objLayer); $i++){
+			echo "<hr>";
+			echo "id: <b>".$this->objLayer[$i]->layer_id ."</b> parent: <b>".$this->objLayer[$i]->layer_parent."</b> name: <b>".$this->objLayer[$i]->layer_name;
+			echo "</b> title: <b>".$this->objLayer[$i]->layer_title. "</b> queryable: <b>".$this->objLayer[$i]->layer_queryable."</b> minScale: <b>". $this->objLayer[$i]->layer_minscale."</b> maxScale: <b>".$this->objLayer[$i]->layer_maxscale."</b>";
+			echo "<br>dataurl: <b>".$this->objLayer[$i]->layer_dataurl_href. "</b>";
+			echo "<br>metadataurl: <b>".$this->objLayer[$i]->layer_metadataurl. "</b>";
+			echo "<table border='1'>";
+			for($j=0; $j<count($this->objLayer[$i]->layer_epsg);$j++){
+				echo "<tr><td>".$this->objLayer[$i]->layer_epsg[$j][epsg]."</td><td>".$this->objLayer[$i]->layer_epsg[$j][minx]."</td>";
+				echo "<td>".$this->objLayer[$i]->layer_epsg[$j][miny]."</td><td>".$this->objLayer[$i]->layer_epsg[$j][maxx]."</td>";
+				echo "<td>".$this->objLayer[$i]->layer_epsg[$j][maxy]."</td></tr>";
+			}
+			echo "</table>";
+			echo "layerstyle:";
+			echo "<table border='1'>";
+			echo "<tr><td>name</td><td>title</td><td>legendurl</td><td>legendurlformat</td></tr>";
+			for($j=0; $j<count($this->objLayer[$i]->layer_style);$j++){
+				echo "<tr><td>".$this->objLayer[$i]->layer_style[$j][name]."</td><td>".$this->objLayer[$i]->layer_style[$j][title]."</td><td>".$this->objLayer[$i]->layer_style[$j][legendurl]."</td><td>".$this->objLayer[$i]->layer_style[$j][legendurlformat]."</td></tr>";
+			}
+			echo "</table>";
+	        echo "<hr>";
+	        echo "<hr>";
+		}
+	} 
+	  function addLayer($id,$parent){	
+		$this->objLayer[count($this->objLayer)] = new layer($id,$parent);
+	  }
+	  /**
+	   * private function
+	   */
+	  function stripEndlineAndCarriageReturn($string) {
+	  	return preg_replace("/\n/", "", preg_replace("/\r/", " ", $string));
+	  }
+		function createJsObjFromWMS($parent=0){
+			echo $this->createJsObjFromWMS_($parent);
+		}
+		
+
+	function newLayer ($currentLayer, $currentExtent) {
+		$pos = $currentLayer["extension"]["LAYER_POS"];
+		$parent = $currentLayer["extension"]["LAYER_PARENT"];
+		$this->addLayer($pos, $parent); 
+
+		// set layer data
+		$layerIndex = count($this->objLayer) - 1;
+		$newLayer = $this->objLayer[$layerIndex];
+		$newLayer->layer_uid = $currentLayer["extension"]["LAYER_ID"];
+		$newLayer->layer_name = $currentLayer["name"];
+		$newLayer->layer_title = $currentLayer["title"];
+		$newLayer->gui_layer_title = $currentLayer["title"];
+		$newLayer->layer_dataurl_href = $currentLayer["dataurl"];
+		$newLayer->layer_pos = $currentLayer["extension"]["LAYER_POS"];
+		$newLayer->layer_queryable = $currentLayer["queryable"];
+		$newLayer->layer_minscale = $currentLayer["extension"]["MINSCALE"];
+		$newLayer->layer_maxscale = $currentLayer["extension"]["MAXSCALE"];
+		$newLayer->layer_metadataurl = $currentLayer["metadataurl"];
+//		$newLayer->layer_searchable = $currentLayer["searchable"];
+		$newLayer->gui_layer_wms_id = $currentLayer["extension"]["WMS_ID"];
+		$newLayer->gui_layer_status = $currentLayer["extension"]["GUI_STATUS"];
+		$newLayer->gui_layer_style = ""; // TODO: Add correct data
+		$newLayer->gui_layer_selectable = $currentLayer["extension"]["GUI_SELECTABLE"];
+		if (isset($currentLayer["extension"]["OVERVIEWHIDDEN"])) {
+			$newLayer->gui_layer_visible = ($currentLayer["extension"]["OVERVIEWHIDDEN"] === "1") ? false : true;
+		}
+		else {
+			$newLayer->gui_layer_visible = $currentLayer["visible"];
+		}
+		if (isset($currentLayer["extension"]["WFSFEATURETYPE"])) {
+			$newLayer->gui_layer_wfs_featuretype = strval($currentLayer["extension"]["WFSFEATURETYPE"]);
+		}
+		else {
+			$newLayer->gui_layer_wfs_featuretype = "";
+		}
+		$newLayer->gui_layer_queryable = $currentLayer["extension"]["GUI_QUERYABLE"];
+		$newLayer->gui_layer_querylayer = $currentLayer["extension"]["QUERYLAYER"];
+		$newLayer->gui_layer_minscale = $currentLayer["extension"]["GUI_MINSCALE"];
+		$newLayer->gui_layer_maxscale = $currentLayer["extension"]["GUI_MAXSCALE"];
+		$newLayer->layer_abstract = $currentLayer["abstract"];
+
+		//
+		// set layer epsg
+		//
+		$tmpEpsgArray= array();
+		$newLayer->layer_epsg = array();
+		if ($currentLayer["extension"]["EPSG"]) {
+			$layerEpsgArray = array();
+			$layerMinXArray = array();
+			$layerMinYArray = array();
+			$layerMaxXArray = array();
+			$layerMaxYArray = array();
+			if (!is_array($currentLayer["extension"]["EPSG"])) {
+				$layerEpsgArray[0] = $currentLayer["extension"]["EPSG"];
+				$layerMinXArray[0] = $currentLayer["extension"]["MINX"];
+				$layerMinYArray[0] = $currentLayer["extension"]["MINY"];
+				$layerMaxXArray[0] = $currentLayer["extension"]["MAXX"];
+				$layerMaxYArray[0] = $currentLayer["extension"]["MAXY"];
+			}
+			else {
+				$layerEpsgArray = $currentLayer["extension"]["EPSG"];
+				$layerMinXArray = $currentLayer["extension"]["MINX"];
+				$layerMinYArray = $currentLayer["extension"]["MINY"];
+				$layerMaxXArray = $currentLayer["extension"]["MAXX"];
+				$layerMaxYArray = $currentLayer["extension"]["MAXY"];
+			}
+
+			for ($i=0; $i < count($layerEpsgArray); $i++) {
+				$currentLayerEpsg = array();
+				$currentLayerEpsg["epsg"] = $layerEpsgArray[$i];
+				$tmpEpsgArray[]= $layerEpsgArray[$i];
+				if ($layerMinXArray[$i] == 0
+					&& $layerMinYArray[$i] == 0
+					&& $layerMaxXArray[$i] == 0
+					&& $layerMaxYArray[$i] == 0
+					) {
+					$currentLayerEpsg["minx"] = null;
+					$currentLayerEpsg["miny"] = null; 
+					$currentLayerEpsg["maxx"] = null;
+					$currentLayerEpsg["maxy"] = null;
+				}
+				else {
+					$currentLayerEpsg["minx"] = floatval($layerMinXArray[$i]);
+					$currentLayerEpsg["miny"] = floatval($layerMinYArray[$i]); 
+					$currentLayerEpsg["maxx"] = floatval($layerMaxXArray[$i]);
+					$currentLayerEpsg["maxy"] = floatval($layerMaxYArray[$i]);
+				}
+				array_push($newLayer->layer_epsg, $currentLayerEpsg);
+			}
+		}
+		for ($i = 0; $i < count($currentLayer["epsg"]); $i++) {
+			if (!in_array($currentLayer["epsg"][$i], $tmpEpsgArray)) {
+				$newLayer->layer_epsg[]= array(
+					"epsg" => $currentLayer["epsg"][$i],
+					"minx" => null,
+					"miny" => null,
+					"maxx" => null,
+					"maxy" => null
+				);
+			}
+		}
+
+		//
+		// set layer style
+		//
+		for ($i = 0; $i < count($currentLayer["style"]); $i++) {
+			$layerStyleIndex = count($newLayer->gui_layer_style) - 1;
+			$newLayer->layer_style[$layerStyleIndex] = array();
+			$newLayer->layer_style[$layerStyleIndex]["name"] = $currentLayer["style"][$i]["name"];
+			$newLayer->layer_style[$layerStyleIndex]["title"] = $currentLayer["style"][$i]["title"];	
+			$newLayer->layer_style[$layerStyleIndex]["legendurl"] = $currentLayer["style"][$i]["legendurl"];
+			$newLayer->layer_style[$layerStyleIndex]["legendurl_format"] = $currentLayer["style"][$i]["legendurl_type"];
+		}
+	}
+	
+	  function createJsObjFromWMS_($parent=0){
+		$str = "";
+	  	if(!$this->wms_title || $this->wms_title == ""){
+			$str .= "alert('Error: no valid capabilities-document !!');";
+			die; exit;
+		}
+			if($parent){
+				$str .=  "parent.";
+			}
+			// wms_title and abstract have previously been urlencoded
+			// this solution may not yet be the ultimate one
+			
+			$add_wms_string = "add_wms(" .
+					"'" . $this->wms_id ."'," .
+					"'" . $this->wms_version ."'," .
+					"'" . addslashes($this->wms_title) . "'," .
+					"'" . addslashes($this->wms_abstract) ."'," .
+					"'" . $this->wms_getmap ."'," .
+					"'" . $this->wms_getfeatureinfo ."'," .
+					"'" . $this->wms_getlegendurl ."'," .
+					"'" . $this->wms_filter ."'," .
+					"'" . $this->gui_wms_mapformat . "'," .
+					"'" . $this->gui_wms_featureinfoformat . "'," .
+					"'" . $this->gui_wms_exceptionformat . "'," .
+					"'" . $this->gui_wms_epsg ."'," .
+					"'" . $this->gui_wms_visible ."'," .
+					"'" . $this->gui_wms_opacity ."'," .
+					"'" . $this->gui_wms_sldurl ."" .
+					"');";
+			$str .=  $add_wms_string;
+			
+		for($i=0;$i<count($this->data_format);$i++){
+			if($parent){
+				$str .=  "parent.";
+			}		
+			$str .= "wms_add_data_type_format('". $this->data_type[$i] ."','". $this->data_format[$i] ."');";		
+		}
+		for($i=0; $i<count($this->objLayer); $i++){
+			if($parent){
+				$str .= "parent.";
+			}
+			$str .=  "wms_add_layer('". 
+				$this->objLayer[$i]->layer_parent ."','". 
+				$this->objLayer[$i]->layer_uid ."','". 
+				addslashes($this->objLayer[$i]->layer_name) . "','". 
+				addslashes($this->objLayer[$i]->layer_title) ."','". 
+				$this->objLayer[$i]->layer_dataurl_href ."','". 
+				$this->objLayer[$i]->layer_pos ."','". 
+				$this->objLayer[$i]->layer_queryable ."','". 
+				$this->objLayer[$i]->layer_minscale . "','". 
+				$this->objLayer[$i]->layer_maxscale ."','". 
+				$this->objLayer[$i]->layer_metadataurl ."','". 
+// will be added later, not needed now
+//				$this->objLayer[$i]->layer_searchable ."','". 
+				$this->objLayer[$i]->gui_layer_wms_id ."','". 
+				$this->objLayer[$i]->gui_layer_status ."','".
+				$this->objLayer[$i]->gui_layer_style ."','".  
+				$this->objLayer[$i]->gui_layer_selectable ."','". 
+				$this->objLayer[$i]->gui_layer_visible ."','". 
+				$this->objLayer[$i]->gui_layer_queryable ."','". 
+				$this->objLayer[$i]->gui_layer_querylayer ."','". 
+				$this->objLayer[$i]->gui_layer_minscale ."','". 
+				$this->objLayer[$i]->gui_layer_maxscale ."','".
+				$this->objLayer[$i]->gui_layer_wfs_featuretype ."','".
+				$this->objLayer[$i]->gui_layer_title ."');";
+				
+			for($j=0; $j<count($this->objLayer[$i]->layer_epsg);$j++){
+				$currentEpsg = $this->objLayer[$i]->layer_epsg[$j];
+				if($i==0){
+					if($parent){
+						$str .= "parent.";
+					}
+					$str .= "wms_addSRS('". 
+						$currentEpsg["epsg"] ."',". 
+						(is_null($currentEpsg["minx"]) ? "null" : $currentEpsg["minx"]) .",". 
+						(is_null($currentEpsg["miny"]) ? "null" : $currentEpsg["miny"]) .",". 
+						(is_null($currentEpsg["maxx"]) ? "null" : $currentEpsg["maxx"]) .",". 
+						(is_null($currentEpsg["maxy"]) ? "null" : $currentEpsg["maxy"]) .");";
+				}
+				if (!is_null($currentEpsg["epsg"])) {
+					if($parent){
+						$str .=  "parent.";
+					}
+					$str .= "layer_addEpsg('". 
+						$currentEpsg["epsg"] ."',". 
+						(is_null($currentEpsg["minx"]) ? "null" : $currentEpsg["minx"]) .",". 
+						(is_null($currentEpsg["miny"]) ? "null" : $currentEpsg["miny"]) .",". 
+						(is_null($currentEpsg["maxx"]) ? "null" : $currentEpsg["maxx"]) .",". 
+						(is_null($currentEpsg["maxy"]) ? "null" : $currentEpsg["maxy"]) .");";
+				}
+			}
+			for($j=0; $i==0 && $j<count($this->wms_srs);$j++){
+				$found = false;
+				for ($k = 0; $k < count($this->objLayer[$i]->layer_epsg); $k++){
+					if ($this->objLayer[$i]->layer_epsg[$k]["epsg"] === $this->wms_srs[$j]) {
+						$found = true;
+						break;
+					}
+				}
+				if ($found) {
+					continue;
+				}
+				
+				if($parent){
+					$str .= "parent.";
+				}
+				$str .= "wms_addSRS('". 
+				$this->wms_srs[$j] ."', null, null, null, null);\n";
+			}
+			for($j=0; $j<count($this->objLayer[$i]->layer_style);$j++){
+				if($parent){
+				$str .= "parent.";
+				}
+				$str .= "wms_addLayerStyle('".$this->objLayer[$i]->layer_style[$j]["name"].
+					"', '".$this->objLayer[$i]->layer_style[$j]["title"].
+					"', ".$j.
+					",".$i.
+					",'".$this->objLayer[$i]->layer_style[$j]["legendurl"].
+					"', '".$this->objLayer[$i]->layer_style[$j]["legendurlformat"]."');";
+			}
+		}
+		return $str;
+	  }
+	  
+	  function createJsLayerObjFromWMS($parent=0, $layer_name){
+	  	if(!$this->wms_title || $this->wms_title == ""){
+			echo " alert('Error: no valid capabilities-document !!');";
+			die; exit;
+		}
+			if($parent){
+				echo "parent.";
+			}
+			// wms_title and abstract have previously been urlencoded
+			// this solution may not yet be the ultimate one
+			print("add_wms('". 
+			$this->wms_id ."','".
+			$this->wms_version ."','".
+			preg_replace("/'/", "", $this->wms_title) ."','".
+			preg_replace("/'/", "", $this->wms_abstract) ."','". 
+			$this->wms_getmap ."','" .
+			$this->wms_getfeatureinfo ."','".
+			$this->wms_getlegendurl ."','".
+			$this->wms_filter ."','".
+			$this->gui_wms_mapformat ."','". 
+			$this->gui_wms_featureinfoformat ."','". 
+			$this->gui_wms_exceptionformat . "','". 
+			$this->gui_wms_epsg ."','". 
+			$this->gui_wms_visible ."','".
+			$this->gui_wms_opacity ."','".
+			$this->gui_wms_sldurl ."');");
+			
+		for($i=0;$i<count($this->data_format);$i++){
+			if($parent){
+				echo "parent.";
+			}		
+			echo "wms_add_data_type_format('". $this->data_type[$i] ."','". $this->data_format[$i] ."');";		
+		}
+		for($i=0; $i<count($this->objLayer); $i++){
+			if($this->objLayer[$i]->layer_name == $layer_name|| $this->objLayer[$i]->layer_pos == 0){
+			
+				if($parent){
+					echo "parent.";
+				}
+			 print ("wms_add_layer('". 
+				$this->objLayer[$i]->layer_parent ."','". 
+				$this->objLayer[$i]->layer_uid ."','". 
+				$this->objLayer[$i]->layer_name . "','". 
+				addslashes($this->objLayer[$i]->layer_title) ."','". 
+				$this->objLayer[$i]->layer_dataurl_href ."','". 
+				$this->objLayer[$i]->layer_pos ."','". 
+				$this->objLayer[$i]->layer_queryable ."','". 
+				$this->objLayer[$i]->layer_minscale . "','". 
+				$this->objLayer[$i]->layer_maxscale ."','". 
+				$this->objLayer[$i]->layer_metadataurl ."','". 
+// will be added later, not needed now
+//				$this->objLayer[$i]->layer_searchable ."','". 
+				$this->objLayer[$i]->gui_layer_wms_id ."','". 
+				$this->objLayer[$i]->gui_layer_status ."','".
+				$this->objLayer[$i]->gui_layer_style ."','". 
+				$this->objLayer[$i]->gui_layer_selectable ."','". 
+				$this->objLayer[$i]->gui_layer_visible ."','". 
+				$this->objLayer[$i]->gui_layer_queryable ."','". 
+				$this->objLayer[$i]->gui_layer_querylayer ."','". 
+				$this->objLayer[$i]->gui_layer_minscale ."','". 
+				$this->objLayer[$i]->gui_layer_maxscale ."','".
+				$this->objLayer[$i]->gui_layer_wfs_featuretype ."','".
+				$this->objLayer[$i]->gui_layer_title ."');");
+			for($j=0; $j<count($this->objLayer[$i]->layer_epsg);$j++){
+				if($i==0){
+					if($parent){
+					echo "parent.";
+					}
+					print("wms_addSRS('". 
+						$this->objLayer[$i]->layer_epsg[$j]["epsg"] ."','". 
+						$this->objLayer[$i]->layer_epsg[$j]["minx"] ."','". 
+						$this->objLayer[$i]->layer_epsg[$j]["miny"] ."','". 
+						$this->objLayer[$i]->layer_epsg[$j]["maxx"] ."','". 
+						$this->objLayer[$i]->layer_epsg[$j]["maxy"] ."');");
+				}
+				if($parent){
+				echo "parent.";
+				}
+				print("layer_addEpsg('". 
+					$this->objLayer[$i]->layer_epsg[$j]["epsg"] ."','". 
+					$this->objLayer[$i]->layer_epsg[$j]["minx"] ."','". 
+					$this->objLayer[$i]->layer_epsg[$j]["miny"] ."','". 
+					$this->objLayer[$i]->layer_epsg[$j]["maxx"] ."','". 
+					$this->objLayer[$i]->layer_epsg[$j]["maxy"] ."');");
+			}
+			for($j=0; $j<count($this->objLayer[$i]->layer_style);$j++){
+				if($parent){
+				echo "parent.";
+				}
+				print("wms_addLayerStyle('".$this->objLayer[$i]->layer_style[$j]["name"]."', '".$this->objLayer[$i]->layer_style[$j]["title"]."', ".$j.",".$i.",'".$this->objLayer[$i]->layer_style[$j]["legendurl"]."', '".$this->objLayer[$i]->layer_style[$j]["legendurlformat"]."');");
+			}
+		   }	
+		}
+	  }
+	  
+	  
+	/**
+	* writeObjInDB
+	*
+	* this function exports the information from the xml to the mapbender database 
+	*/
+	function writeObjInDB($gui_id){
+		global $con;
+		if (func_num_args() == 2) { //new for HTTP Authentication
+			$auth = func_get_arg(1);
+			$username = $auth['username'];
+			$password = $auth['password'];
+			$authType = $auth['auth_type'];
+		}
+		else {
+			$username = '';
+			$password = '';
+			$authType = '';		
+		}
+		$admin = new administration();
+
+		$this->checkObj();
+		db_begin();
+	
+		# TABLE wms
+		$sql = "INSERT INTO wms (wms_version, wms_title, wms_abstract, wms_getcapabilities, wms_getmap, ";
+		$sql.= "wms_getfeatureinfo, wms_getlegendurl, wms_getcapabilities_doc, wms_upload_url, fees, ";
+		$sql .= "accessconstraints, contactperson, contactposition, contactorganization, address, city, ";
+		$sql .= "stateorprovince, postcode, country, contactvoicetelephone, contactfacsimiletelephone, contactelectronicmailaddress, ";
+		$sql .= "wms_owner,wms_timestamp,wms_timestamp_create,wms_username,wms_password,wms_auth_type,";
+		$sql .= "wms_supportsld, wms_userlayer, wms_userstyle, wms_remotewfs) ";
+		$sql .= "VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$30,$31,$32)";
+		$v = array(
+			$this->wms_version,
+			$this->wms_title,
+			$this->wms_abstract,
+			$this->wms_getcapabilities,
+			$this->wms_getmap,
+			$this->wms_getfeatureinfo,
+			$this->wms_getlegendurl,
+			$admin->char_encode($this->wms_getcapabilities_doc),
+			$this->wms_upload_url,
+			$this->fees,
+			$this->accessconstraints,
+			$this->contactperson,
+			$this->contactposition,
+			$this->contactorganization,
+			$this->address,
+			$this->city,
+			$this->stateorprovince,
+			$this->postcode,
+			$this->country,
+			$this->contactvoicetelephone,
+			$this->contactfacsimiletelephone,
+			$this->contactelectronicmailaddress,
+			Mapbender::session()->get('mb_user_id'),
+			strtotime("now"),
+			strtotime("now"),
+			$username,
+			$password,
+			$authType,
+			$this->wms_supportsld,
+			$this->wms_userlayer,
+			$this->wms_userstyle,
+			$this->wms_remotewfs
+		);
+		$t = array(
+			's','s','s','s','s','s','s','s','s','s','s','s','s','s','s','s',
+			's','s','s','s','s','s','i','i','i','s','s','s','s','s','s','s'
+		);
+		$res = db_prep_query($sql,$v,$t);
+		if(!$res){
+			db_rollback();
+			return null;
+		}
+		
+		$myWMS = db_insert_id($con,'wms', 'wms_id');
+
+		if ($authType != '') { //some authentication is needed! 
+			$admin = new administration();
+			echo "WMS ID: ".$myWMS;
+			$admin->setWMSOWSstring($myWMS, 1);
+		}
+
+		# TABLE layer and gui_layer
+		
+		for($i=0; $i<count($this->objLayer); $i++){
+			$this->insertLayer($i,$myWMS,$gui_id);
+			$this->insertGuiLayer($i,$myWMS,$gui_id);
+		}	
+			
+		
+		#TABLE wms_srs
+		$this->insertSRS($myWMS);	
+		
+		# TABLE wms_format	
+		$this->insertFormat($myWMS);	
+			
+		# TABLE gui_wms
+		
+		$sql ="SELECT MAX(gui_wms_position) AS pos FROM gui_wms WHERE fkey_gui_id = $1";
+		$v = array($gui_id);
+		$t = array('s');
+		$res = db_prep_query($sql,$v,$t);
+		if (db_result($res, 0,"pos") > -1) {
+			$position = db_result($res, 0,"pos") + 1;
+		} 
+		else { 
+			$position = 0; 
+		}
+		
+		$sql ="INSERT INTO gui_wms (fkey_gui_id, fkey_wms_id, gui_wms_position, gui_wms_mapformat, ";
+		$sql .= "gui_wms_featureinfoformat, gui_wms_exceptionformat, gui_wms_epsg)";
+		$sql .= "VALUES($1,$2,$3,$4,$5,$6,$7)";
+		$v = array(
+			$gui_id,
+			$myWMS,
+			$position,
+			$this->gui_wms_mapformat,
+			$this->gui_wms_featureinfoformat,
+			$this->gui_wms_exceptionformat,
+			$this->gui_wms_epsg
+		);
+		$t = array('s','i','i','s','s','s','s');
+		$res = db_prep_query($sql,$v,$t);
+		if(!$res){
+			db_rollback();	
+			return null;
+		}
+		db_commit();
+
+		//
+		// update GeoRSS feed
+		//
+		$geoRssFactory = new GeoRssFactory();
+		$geoRss = $geoRssFactory->loadOrCreate(GEO_RSS_FILE);
+		if (!is_null($geoRss)) {
+			$geoRssItem = new GeoRssItem();
+			$geoRssItem->setTitle("NEW: " . $this->wms_title);
+			$geoRssItem->setDescription($this->wms_abstract);
+			$geoRssItem->setUrl(self::getWmsMetadataUrl($myWMS));
+			$geoRssItem->setPubDate(self::rssDate());
+
+			for ($j = 0; $j < count($this->objLayer[0]->layer_epsg); $j++) {
+				$currentEpsg = $this->objLayer[0]->layer_epsg[$j];
+				if ($currentEpsg["epsg"] === "EPSG:4326") {
+					$currentBbox = new Mapbender_bbox(
+						$currentEpsg["minx"],
+						$currentEpsg["miny"],
+						$currentEpsg["maxx"],
+						$currentEpsg["maxy"],
+						$currentEpsg["epsg"]
+					);
+					$geoRssItem->setBbox($currentBbox);
+					break;
+				}
+			}
+
+			$geoRss->append($geoRssItem);
+			$geoRss->saveAsFile();
+		}
+	    
+	    #Changes JW
+	    $this->wms_id = $myWMS;
+	}
+	function insertLayer($i,$myWMS){
+		global $con;
+		$sql = <<<SQL
+
+INSERT INTO layer 
+(fkey_wms_id, layer_pos, layer_parent, layer_name, layer_title, 
+layer_queryable, layer_minscale, layer_maxscale, layer_dataurl,
+layer_metadataurl, layer_searchable, layer_abstract) 
+VALUES
+($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
+
+SQL;
+		if($this->objLayer[$i]->layer_id != null){
+			$tmpPos =  $this->objLayer[$i]->layer_id;
+		}
+		else {
+			$tmpPos .= 0;
+		}
+		if($this->objLayer[$i]->layer_parent == '' && $this->objLayer[$i]->layer_parent != '0'){
+			$this->objLayer[$i]->layer_parent = '';
+		}
+		$v = array($myWMS,$tmpPos,$this->objLayer[$i]->layer_parent,$this->objLayer[$i]->layer_name,
+				$this->objLayer[$i]->layer_title,
+				$this->objLayer[$i]->layer_queryable,$this->objLayer[$i]->layer_minscale,
+				$this->objLayer[$i]->layer_maxscale,$this->objLayer[$i]->layer_dataurl_href,
+				$this->objLayer[$i]->layer_metadataurl, $this->objLayer[$i]->layer_searchable,
+				$this->objLayer[$i]->layer_abstract);
+		$t = array('i','i','s','s','s','i','i','i','s','s','i','s');
+		$res = db_prep_query($sql,$v,$t);
+		if(!$res){
+			db_rollback();	
+		}
+		else {
+			# save the id of each layer: set param2 true		
+			$this->objLayer[$i]->db_id = db_insert_id($con, 'layer','layer_id');
+			$this->insertLayerEPSG($i);
+			
+			# TABLE layer_style for each layer
+			$this->insertLayerStyle($i);
+			
+			# insert Keywords
+			$this->insertLayerKeyword($i);	
+		
+		}
+	}
+	function updateLayer($i,$myWMS){
+		$sql = "SELECT layer_id FROM layer WHERE fkey_wms_id = $1 AND layer_name = $2";
+		$v = array($myWMS,$this->objLayer[$i]->layer_name);
+		$t = array('i','s');
+		$res = db_prep_query($sql,$v,$t);
+		if($row = db_fetch_array($res)){
+			$l_id = $row['layer_id'];	
+		}
+		else{
+			db_rollback();
+			$e = new mb_exception("Not found: ".$this->objLayer[$i]->layer_name);
+			return;	
+		}	
+		
+		$sql = "UPDATE layer SET ";
+		$sql .= "layer_pos = $1, ";
+		$sql .= "layer_parent = $2, ";
+		$sql .= "layer_title = $3, ";
+		$sql .= "layer_queryable = $4, ";
+		$sql .= "layer_minscale = $5, ";
+		$sql .= "layer_maxscale = $6, ";
+		$sql .= "layer_dataurl = $7, ";
+		$sql .= "layer_metadataurl = $8, ";
+		$sql .= "layer_searchable = $9, ";
+		$sql .= "layer_abstract = $10 ";
+		$sql .= "WHERE layer_id = $11";
+		
+		if($this->objLayer[$i]->layer_id != null){
+			$tmpPos =  $this->objLayer[$i]->layer_id;
+		}
+		else {
+			$tmpPos .= 0;
+		}
+		if($this->objLayer[$i]->layer_parent == '' && $this->objLayer[$i]->layer_parent != '0'){
+			$this->objLayer[$i]->layer_parent = '';
+		}
+		$v = array($tmpPos,$this->objLayer[$i]->layer_parent,
+				$this->objLayer[$i]->layer_title,
+				$this->objLayer[$i]->layer_queryable,$this->objLayer[$i]->layer_minscale,
+				$this->objLayer[$i]->layer_maxscale,$this->objLayer[$i]->layer_dataurl_href,
+				$this->objLayer[$i]->layer_metadataurl, $this->objLayer[$i]->layer_searchable,
+				$this->objLayer[$i]->layer_abstract, $l_id		
+			);
+		$t = array('i','s','s','i','i','i','s','s','i', 's','i');
+		$res = db_prep_query($sql,$v,$t);
+		if($this->overwrite == true){
+			$sql = "UPDATE layer SET ";
+			$sql .= "layer_title = $1, ";
+			$sql .= "layer_abstract = $2 ";
+			$sql .= "WHERE layer_id = $3";
+			
+			$v = array($this->objLayer[$i]->layer_title,$this->objLayer[$i]->layer_abstract, $l_id);
+			$t = array('s','s','i');
+			$res = db_prep_query($sql,$v,$t);
+		}
+		if(!$res){
+			db_rollback();	
+		}
+		else {
+			
+			# save the id of each layer: set param2 true
+			$this->objLayer[$i]->db_id = $l_id;
+			$this->insertLayerEPSG($i);
+			
+			# TABLE layer_style for each layer
+			$this->insertLayerStyle($i);
+			if($this->overwrite == true){
+				$this->insertLayerKeyword($i);
+				$this->insertLayerCategories($i);
+			}
+		}
+	}
+	function insertGuiLayer($i,$myWMS,$gui_id){
+		# table gui_layer
+		
+		$sql = "INSERT INTO gui_layer (fkey_gui_id, fkey_layer_id, gui_layer_wms_id, ";
+		$sql .= "gui_layer_status, gui_layer_selectable, gui_layer_visible, gui_layer_queryable, ";
+		$sql .= "gui_layer_querylayer,gui_layer_minscale,gui_layer_maxscale, gui_layer_priority, gui_layer_style, gui_layer_title) ";
+		$sql .= "VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)";
+		if(count($this->objLayer[$i]->layer_style)>0){
+			$layer_style_name = $this->objLayer[$i]->layer_style[0]["name"];
+		}
+		else{
+			$layer_style_name = NULL;
+		}
+		$v = array($gui_id,$this->objLayer[$i]->db_id,$myWMS,1,1,1,$this->objLayer[$i]->layer_queryable,
+			$this->objLayer[$i]->layer_queryable,$this->objLayer[$i]->layer_minscale,$this->objLayer[$i]->layer_maxscale,$i,$layer_style_name,$this->objLayer[$i]->gui_layer_title);
+		$t = array('s','i','i','i','i','i','i','i','i','i','i','s', 's');
+		$res = db_prep_query($sql,$v,$t);
+		#$e = new mb_exception("name des insert styles und fkey_layer_id: ".$layer_style_name." --- ".$this->objLayer[$i]->db_id);
+		if(!$res){
+			db_rollback();	
+		}	
+	}
+	function appendGuiLayer($i,$myWMS,$gui_id){
+		# table gui_layer
+		
+		$sql = "INSERT INTO gui_layer (fkey_gui_id, fkey_layer_id, gui_layer_wms_id, ";
+		$sql .= "gui_layer_status, gui_layer_selectable, gui_layer_visible, gui_layer_queryable, ";
+		$sql .= "gui_layer_querylayer,gui_layer_minscale,gui_layer_maxscale, gui_layer_priority, gui_layer_style, gui_layer_title) ";
+		$sql .= "VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)";
+		if(count($this->objLayer[$i]->layer_style)>0){
+			$layer_style_name = $this->objLayer[$i]->layer_style[0]["name"];
+		}
+		else{
+			$layer_style_name = NULL;
+		}
+		$v = array($gui_id,$this->objLayer[$i]->db_id,$myWMS,0,0,0,$this->objLayer[$i]->layer_queryable,
+			$this->objLayer[$i]->layer_queryable,$this->objLayer[$i]->layer_minscale,$this->objLayer[$i]->layer_maxscale,$i,$layer_style_name, $this->objLayer[$i]->gui_layer_title);
+		$t = array('s','i','i','i','i','i','i','i','i','i','i','s', 's');
+		$res = db_prep_query($sql,$v,$t);
+		if(!$res){
+			db_rollback();	
+		}	
+	}
+	function insertSRS($myWMS){
+		for($i=0; $i<count($this->wms_srs);$i++){
+			$sql ="INSERT INTO wms_srs (fkey_wms_id, wms_srs) values($1,$2)";		
+			$v = array($myWMS,mb_strtoupper($this->wms_srs[$i]));
+			$t = array('i','s');		
+			$res = db_prep_query($sql,$v,$t);
+			if(!$res){
+				db_rollback();	
+			}
+		}	
+	}
+	function insertTermsOfUse ($myWMS) {
+		if (!is_numeric($this->wms_termsofuse)) {
+			return;
+		}
+		$sql ="INSERT INTO wms_termsofuse (fkey_wms_id, fkey_termsofuse_id) ";
+		$sql .= " VALUES($1,$2)";
+		$v = array($myWMS,$this->wms_termsofuse);
+		$t = array('i','i');
+		$res = db_prep_query($sql,$v,$t);
+		if(!$res){
+			db_rollback();	
+		}
+		
+	}
+	function insertFormat($myWMS){
+		for($i=0; $i<count($this->data_type);$i++){
+			$sql ="INSERT INTO wms_format (fkey_wms_id, data_type, data_format) ";
+			$sql .= " VALUES($1,$2,$3)";
+			$v = array($myWMS,$this->data_type[$i],$this->data_format[$i]);
+			$t = array('i','s','s');
+			$res = db_prep_query($sql,$v,$t);
+			if(!$res){
+				db_rollback();	
+			}
+		}	
+	}
+	function insertLayerEPSG($i){
+		$sql = "DELETE FROM layer_epsg WHERE fkey_layer_id = $1";
+		$v = array($this->objLayer[$i]->db_id);
+		$t = array('i');
+		$res = db_prep_query($sql,$v,$t);
+		for($j=0; $j<count($this->objLayer[$i]->layer_epsg);$j++){
+			$sql = "INSERT INTO layer_epsg (fkey_layer_id, epsg, minx, miny, maxx, maxy) ";
+			$sql .= "VALUES($1,$2,$3,$4,$5,$6)";
+			$v = array($this->objLayer[$i]->db_id,$this->objLayer[$i]->layer_epsg[$j][epsg],
+				$this->objLayer[$i]->layer_epsg[$j][minx],$this->objLayer[$i]->layer_epsg[$j][miny],
+				$this->objLayer[$i]->layer_epsg[$j][maxx],$this->objLayer[$i]->layer_epsg[$j][maxy]
+				); 
+			$t = array('i','s','d','d','d','d');
+			$res = db_prep_query($sql,$v,$t);
+			if(!$res){
+				db_rollback();	
+			}
+		}
+	}
+	function insertLayerStyle($i){
+		$sql = "DELETE FROM layer_style WHERE fkey_layer_id = $1";
+		$v = array($this->objLayer[$i]->db_id);
+		$t = array('i');
+		$res = db_prep_query($sql,$v,$t);
+		for($j=0; $j<count($this->objLayer[$i]->layer_style);$j++){
+			$sql = "INSERT INTO layer_style (fkey_layer_id, name, title, legendurl, legendurlformat) ";
+			$sql .= "VALUES($1,$2,$3,$4,$5)";
+			$v = array($this->objLayer[$i]->db_id,$this->objLayer[$i]->layer_style[$j]["name"],
+					$this->objLayer[$i]->layer_style[$j]["title"],$this->objLayer[$i]->layer_style[$j]["legendurl"],
+					$this->objLayer[$i]->layer_style[$j]["legendurlformat"]				
+				);
+			$t = array('i','s','s','s','s');
+			$res = db_prep_query($sql,$v,$t);
+			if(!$res){
+				db_rollback();	
+			}
+		}
+	}
+	
+	function insertLayerCategories($i){
+		global $con;
+
+		$types = array("md_topic", "inspire", "custom");
+		foreach ($types as $cat) {
+			$sql = "DELETE FROM layer_{$cat}_category WHERE fkey_layer_id = $1";
+			$v = array($this->objLayer[$i]->db_id);
+			$t = array('i');
+			$res = db_prep_query($sql,$v,$t);
+			
+			$attr = "layer_{$cat}_category_id";
+			$k = $this->objLayer[$i]->$attr;
+			
+			for ($j = 0; $j < count($k); $j++) {
+				
+				$sql = "INSERT INTO layer_{$cat}_category (fkey_layer_id, fkey_{$cat}_category_id) VALUES ($1, $2)";
+				$v = array($this->objLayer[$i]->db_id, $k[$j]);
+				$t = array('i', 'i');
+				$res = db_prep_query($sql,$v,$t);
+				if(!$res){
+					db_rollback();	
+					return;
+				}
+			}
+		}
+	}	
+	
+	function insertLayerKeyword($i){
+		global $con;
+		$sql = "DELETE FROM layer_keyword WHERE fkey_layer_id = $1";
+		$v = array($this->objLayer[$i]->db_id);
+		$t = array('i');
+		$res = db_prep_query($sql,$v,$t);
+		
+//		var_dump($this);
+		$k = $this->objLayer[$i]->layer_keyword;
+//		var_dump($k);
+		for($j=0; $j<count($k); $j++){
+			$keyword_id = "";
+			
+			while ($keyword_id == "") {
+				$sql = "SELECT keyword_id FROM keyword WHERE UPPER(keyword) = UPPER($1)";
+				$v = array($k[$j]);
+				$t = array('s');
+				$res = db_prep_query($sql,$v,$t);
+				$row = db_fetch_array($res);
+			//print_r($row);
+				if ($row) {
+					$keyword_id = $row["keyword_id"];	
+				}
+				else {
+					$sql_insertKeyword = "INSERT INTO keyword (keyword)";
+					$sql_insertKeyword .= "VALUES ($1)";
+					$v1 = array($k[$j]);
+					$t1 = array('s');
+					$res_insertKeyword = db_prep_query($sql_insertKeyword,$v1,$t1);
+					if(!$res_insertKeyword){
+						db_rollback();	
+					}
+				}
+			}
+
+			// check if layer/keyword combination already exists
+			$sql_layerKeywordExists = "SELECT * FROM layer_keyword WHERE fkey_layer_id = $1 AND fkey_keyword_id = $2";
+			$v = array($this->objLayer[$i]->db_id, $keyword_id);
+			$t = array('i', 'i');
+			$res_layerKeywordExists = db_prep_query($sql_layerKeywordExists, $v, $t);
+			$row = db_fetch_array($res_layerKeywordExists);
+			//print_r($row);
+			if (!$row) {
+				$sql1 = "INSERT INTO layer_keyword (fkey_keyword_id,fkey_layer_id)";
+				$sql1 .= "VALUES ($1,$2)";
+				$v1 = array($keyword_id,$this->objLayer[$i]->db_id);
+				$t1 = array('i','i');
+				$res1 = db_prep_query($sql1,$v1,$t1);
+				if(!$res1){
+					db_rollback();	
+				}
+			}
+		}
+	}
+	function updateObjInDB($myWMS){
+		$admin = new administration();
+		db_begin();
+		
+		$sql = "UPDATE wms SET ";
+		$sql .= "wms_version = $1 ,";
+		$sql .= "wms_getcapabilities  = $2 ,";
+		$sql .= "wms_getmap  = $3 ,";
+		$sql .= "wms_getfeatureinfo  = $4 ,";
+		$sql .= "wms_getlegendurl  = $5 ,";
+		$sql .= "wms_getcapabilities_doc = $6 ,";
+		$sql .= "wms_upload_url = $7,  ";
+		$sql .= "wms_owner = $8, ";
+		$sql .= "wms_timestamp = $9, ";
+		$sql .= "wms_supportsld = $10, ";
+		$sql .= "wms_userlayer = $11, ";
+		$sql .= "wms_userstyle = $12, ";
+		$sql .= "wms_remotewfs = $13 ";
+		$sql .= " WHERE wms_id = $14";
+	
+		$v = array($this->wms_version,$this->wms_getcapabilities,
+			$this->wms_getmap,$this->wms_getfeatureinfo,$this->wms_getlegendurl,
+			$admin->char_encode($this->wms_getcapabilities_doc),$this->wms_upload_url,Mapbender::session()->get("mb_user_id"),strtotime("now"),
+			$this->wms_supportsld,$this->wms_userlayer,$this->wms_userstyle,$this->wms_remotewfs,$myWMS);
+		$t = array('s','s','s','s','s','s','s','i','i','s','s','s','s','i');
+	
+		$res = db_prep_query($sql,$v,$t);
+		if(!$res){
+			db_rollback();	
+		}
+		
+		if($this->overwrite == true){
+			$sql = "UPDATE wms SET ";
+			$sql .= "wms_title  = $1 ,";
+			$sql .= "wms_abstract  = $2 ,";
+			$sql .= "fees = $3, ";
+			$sql .= "accessconstraints = $4, ";
+			$sql .= "contactperson = $5, ";
+			$sql .= "contactposition = $6, ";
+			$sql .= "contactorganization = $7, ";
+			$sql .= "address = $8, ";
+			$sql .= "city = $9, ";
+			$sql .= "stateorprovince = $10, ";
+			$sql .= "postcode = $11, ";
+			$sql .= "country = $12, ";
+			$sql .= "contactvoicetelephone = $13, ";
+			$sql .= "contactfacsimiletelephone = $14, ";
+			$sql .= "contactelectronicmailaddress = $15 ";
+			$sql .= " WHERE wms_id = $16";
+		
+			$v = array($this->wms_title,$this->wms_abstract,$this->fees,$this->accessconstraints,
+				$this->contactperson,$this->contactposition,$this->contactorganization,$this->address,
+				$this->city,$this->stateorprovince,$this->postcode,$this->country,$this->contactvoicetelephone,
+				$this->contactfacsimiletelephone,$this->contactelectronicmailaddress,$myWMS);
+			$t = array('s','s','s','s','s','s','s','s','s','s','s','s','s','s','s','i');
+			$res = db_prep_query($sql,$v,$t);
+			if(!$res){
+				db_rollback();	
+			}
+		}
+		
+		# delete and refill wms_termsofuse
+		$sql = "DELETE FROM wms_termsofuse WHERE fkey_wms_id = $1 ";
+		$v = array($myWMS);
+		$t = array('i');
+		$res = db_prep_query($sql,$v,$t);
+		if(!$res){
+			db_rollback();	
+		}
+		$this->insertTermsOfUse($myWMS);
+		
+		# delete and refill srs and formats
+		$sql = "DELETE FROM wms_srs WHERE fkey_wms_id = $1 ";
+		$v = array($myWMS);
+		$t = array('i');
+		$res = db_prep_query($sql,$v,$t);
+		if(!$res){
+			db_rollback();	
+		}
+		$this->insertSRS($myWMS);
+		
+		$sql = "DELETE FROM wms_format WHERE fkey_wms_id = $1 ";
+		$v = array($myWMS);
+		$t = array('i');
+		$res = db_prep_query($sql,$v,$t);
+		if(!$res){
+			db_rollback();	
+		}
+		$this->insertFormat($myWMS);
+		
+		# update gui_wms
+		$this->update_gui_wms($myWMS);
+		
+		# update TABLE layer	
+		$oldLayerNameArray = array();
+		$v = array($myWMS);
+		$t = array('i');
+		$c = 2;
+		$sql = "SELECT layer_name, layer_title, layer_abstract FROM layer WHERE fkey_wms_id = $1 AND NOT layer_name IN(";
+		for($i=0; $i<count($this->objLayer); $i++){
+			if($i>0){$sql .= ',';}
+			$sql .= "$".$c;
+			array_push($v,$this->objLayer[$i]->layer_name);
+			array_push($t,'s');		
+			$c++;
+		}
+		$sql .= ")";
+		$res = db_prep_query($sql,$v,$t);
+		while ($row = db_fetch_array($res)) {
+			$oldLayerNameArray[]= array(
+				"name" => $row["layer_name"],
+				"title" => $row["layer_title"],
+				"abstract" => $row["layer_abstract"]
+			);
+			
+		}
+		
+		# delete all layer which are outdated
+		$v = array($myWMS);
+		$t = array('i');
+		$c = 2;
+		$sql = "DELETE FROM layer WHERE fkey_wms_id = $1 AND NOT layer_name IN(";
+		for($i=0; $i<count($this->objLayer); $i++){
+			if($i>0){$sql .= ',';}
+			$sql .= "$".$c;
+			array_push($v,$this->objLayer[$i]->layer_name);
+			array_push($t,'s');		
+			$c++;
+		}
+		$sql .= ")";
+		
+		$res = db_prep_query($sql,$v,$t);
+		if(!$res){
+			db_rollback();	
+		}
+			
+		# update or insert?
+		$sql = "SELECT layer_name FROM layer WHERE fkey_wms_id = $1";
+		$v = array($myWMS);
+		$t = array('i');
+		$res = db_prep_query($sql,$v,$t);
+		$exLayer = array();
+		while($row = db_fetch_array($res)){
+			array_push($exLayer,$row["layer_name"]);
+		}
+		
+		$sql = "SELECT fkey_gui_id FROM gui_wms WHERE fkey_wms_id = $1";
+		$v = array($myWMS);
+		$t = array('i');
+		$res = db_prep_query($sql,$v,$t);
+		$exGui = array();
+		while($row = db_fetch_array($res)){
+			array_push($exGui,$row["fkey_gui_id"]);
+		}
+		$newLayerArray = array();
+		for($i=0; $i<count($this->objLayer); $i++){
+			if(in_array($this->objLayer[$i]->layer_name,$exLayer)){
+				//echo "<br>update: ".$this->objLayer[$i]->layer_name;
+				$this->updateLayer($i,$myWMS);
+				for($j=0; $j<count($exGui); $j++){
+					$this->updateGuiLayer($i,$myWMS,$exGui[$j]);
+				}
+			}
+			else{
+				//echo "<br>append: ".$this->objLayer[$i]->layer_name;
+				$this->insertLayer($i,$myWMS);
+				$newLayerArray[]= $i;
+				for($j=0; $j<count($exGui); $j++){
+					$this->appendGuiLayer($i,$myWMS,$exGui[$j]);
+				}
+			}
+		}
+		db_commit();
+		//
+		// update GeoRSS feed
+		//
+		$geoRssFactory = new GeoRssFactory();
+		$geoRss = $geoRssFactory->loadOrCreate(GEO_RSS_FILE);
+		
+		if (!is_null($geoRss)) {
+
+			$geoRssItem = new GeoRssItem();
+			$geoRssItem->setTitle("UPDATED WMS: " . $this->wms_title);
+			$geoRssItem->setDescription($this->wms_abstract);
+			$geoRssItem->setUrl(self::getWmsMetadataUrl($myWMS));
+			$geoRssItem->setPubDate(self::rssDate());
+			for ($j = 0; $j < count($this->objLayer[0]->layer_epsg); $j++) {
+				$currentEpsg = $this->objLayer[0]->layer_epsg[$j];
+				if ($currentEpsg["epsg"] === "EPSG:4326") {
+					$currentBbox = new Mapbender_bbox(
+						$currentEpsg["minx"],
+						$currentEpsg["miny"],
+						$currentEpsg["maxx"],
+						$currentEpsg["maxy"],
+						$currentEpsg["epsg"]
+					);
+					$geoRssItem->setBbox($currentBbox);
+					break;
+				}
+			}
+			$geoRss->append($geoRssItem);
+
+			foreach ($newLayerArray as $newLayer) {
+				$currentLayer = $this->objLayer[$newLayer];
+				$geoRssItem = new GeoRssItem();
+				$geoRssItem->setTitle("ADDED LAYER: " . $currentLayer->layer_title);
+				$geoRssItem->setDescription($currentLayer->layer_abstract);
+				$geoRssItem->setUrl(layer::getLayerMetadataUrl($currentLayer->layer_id));
+				$geoRssItem->setPubDate(self::rssDate());
+				for ($j = 0; $j < count($currentLayer->layer_epsg); $j++) {
+					$currentEpsg = $currentLayer->layer_epsg[$j];
+					if ($currentEpsg["epsg"] === "EPSG:4326") {
+						$currentBbox = new Mapbender_bbox(
+							$currentEpsg["minx"],
+							$currentEpsg["miny"],
+							$currentEpsg["maxx"],
+							$currentEpsg["maxy"],
+							$currentEpsg["epsg"]
+						);
+						$geoRssItem->setBbox($currentBbox);
+						break;
+					}
+				}
+				$geoRss->append($geoRssItem);
+			}
+			foreach ($oldLayerNameArray as $oldLayer) {
+				$geoRssItem = new GeoRssItem();
+				$geoRssItem->setTitle("DELETED LAYER: " . $oldLayer["title"]);
+				$geoRssItem->setDescription($oldLayer["abstract"]);
+				$geoRssItem->setPubDate(self::rssDate());
+//				$geoRssItem->setUrl();
+				$geoRss->append($geoRssItem);
+			}
+			$geoRss->saveAsFile();
+		}
+		return;	
+	}
+
+	function updateGuiLayer($i,$myWMS,$gui_id){
+		$sql = "SELECT layer_id FROM layer WHERE fkey_wms_id = $1 AND layer_name = $2";
+		$v = array($myWMS,$this->objLayer[$i]->layer_name);
+		$t = array('i','s');
+		$res = db_prep_query($sql,$v,$t);
+		if($row = db_fetch_array($res)){
+			$l_id = $row['layer_id'];	
+		}
+		else{
+			db_rollback();
+			$e = new mb_exception("Not found: ".$this->objLayer[$i]->layer_name. " in gui: ".$gui_id);
+			return;	
+		}
+		
+		$sql = "SELECT * FROM gui_layer WHERE fkey_layer_id = $1 and fkey_gui_id = $2";
+		$v = array($l_id,$gui_id);
+		$t = array('i','s');
+		$res = db_prep_query($sql,$v,$t);		
+		while($row = db_fetch_array($res)){
+
+				$sql1 = "UPDATE gui_layer SET gui_layer_title = $1 ";
+				$sql1 .= "WHERE fkey_layer_id = $2 and fkey_gui_id = $3";
+				$v = array($this->objLayer[$i]->layer_title, $l_id,$gui_id);
+				$t = array('s', 'i','s');
+				$res1 = db_prep_query($sql1,$v,$t);
+				if(!$res1){
+					db_rollback();
+				}
+
+			if($this->objLayer[$i]->layer_queryable == 0){
+				$sql1 = "UPDATE gui_layer set gui_layer_queryable = 0, gui_layer_querylayer = 0 ";
+				$sql1 .= "WHERE fkey_layer_id = $1 and fkey_gui_id = $2";
+				$v = array($l_id,$gui_id);
+				$t = array('i','s');
+				$res1 = db_prep_query($sql1,$v,$t);
+				if(!$res1){
+					
+				db_rollback();
+				}
+			}
+			if($this->objLayer[$i]->layer_queryable == 1){
+				$sql1 = "UPDATE gui_layer set gui_layer_queryable = 1 ";
+				$sql1 .= "WHERE fkey_layer_id = $1 and fkey_gui_id = $2";
+				$v = array($l_id,$gui_id);
+				$t = array('i','s');
+				$res1 = db_prep_query($sql1,$v,$t);
+				if(!$res1){
+					
+					db_rollback();
+				}
+			}
+			if($row["gui_layer_minscale"] < $this->objLayer[$i]->layer_minscale){
+				$sql1 = "UPDATE gui_layer set gui_layer_minscale = $1 ";
+				$sql1 .= "WHERE fkey_layer_id = $2 and fkey_gui_id = $3";
+				$v = array($this->objLayer[$i]->layer_minscale,$l_id,$gui_id);
+				$t = array('i','i','s');
+				$res1 = db_prep_query($sql1,$v,$t);
+				if(!$res1){db_rollback();
+				}
+			}
+			if($row["gui_layer_maxscale"] > $this->objLayer[$i]->layer_maxscale){
+				$sql1 = "UPDATE gui_layer set gui_layer_maxscale = $1 ";
+				$sql1 .= "WHERE fkey_layer_id = $2 and fkey_gui_id = $3";
+				$v = array($this->objLayer[$i]->layer_maxscale,$l_id,$gui_id);
+				$t = array('i','i','s');
+				$res1 = db_prep_query($sql1,$v,$t);
+				if(!$res1){db_rollback();
+				}
+			}		
+		}
+	}
+	function update_gui_wms($myWMS){
+		$mySubmit = null;
+		$sql = "SELECT * FROM gui_wms where fkey_wms_id = $1";
+		$v = array($myWMS);
+		$t = array('i');
+		$res = db_prep_query($sql,$v,$t);
+		$cnt = 0;
+		while($row = db_fetch_array($res)){	
+			unset($mySubmit);
+			$myGUI[$cnt] = $row["fkey_gui_id"];
+
+			$sql = "UPDATE gui_wms SET ";
+			$v = array();
+			$t = array();
+			$paramCount = 0;		
+
+			for($i=0; $i<count($this->data_type); $i++){
+				# gui_wms_mapformat
+				if(mb_strtolower($this->data_type[$i]) == "map" && mb_strtolower($this->data_format[$i]) == mb_strtolower($row["gui_wms_mapformat"])){
+					$myMapFormat = true;
+				}
+				# gui_wms_featureinfoformat
+				if(mb_strtolower($this->data_type[$i]) == "featureinfo" && mb_strtolower($this->data_format[$i]) == mb_strtolower($row["gui_wms_featureinfoformat"])){
+					$myFeatureInfoFormat = true;
+				}
+				# gui_wms_exceptionformat
+				if(mb_strtolower($this->data_type[$i]) == "exception" && mb_strtolower($this->data_format[$i]) == mb_strtolower($row["gui_wms_exceptionformat"])){
+					$myExceptionFormat = true;
+				}
+			}
+			if(!$myMapFormat){
+				$paramCount++;
+				$sql .= "gui_wms_mapformat = $" . $paramCount . " ";
+				$mySubmit = true;
+				array_push($v, $this->gui_wms_mapformat);
+				array_push($t, "s");
+			}
+			if(!$myFeatureInfoFormat){
+				if($mySubmit){ $sql .= ",";}
+				$paramCount++;
+				$sql .= "gui_wms_featureinfoformat = $" . $paramCount . " ";
+				array_push($v, $this->gui_wms_featureinfoformat);
+				array_push($t, "s");
+				$mySubmit = true;
+			}
+			if(!$myExceptionFormat){
+				if($mySubmit){ $sql .= ",";}
+				$paramCount++;
+				$sql .= "gui_wms_exceptionformat = $" . $paramCount ." ";
+				array_push($v, $this->gui_wms_exceptionformat);
+				array_push($t, "s");
+				$mySubmit = true;
+			}
+				
+			# gui_wms_epsg
+			for($j=0; $j<count($this->objLayer[0]->layer_epsg);$j++){
+				if($this->objLayer[0]->layer_epsg[$j][epsg] == mb_strtoupper($row["gui_wms_epsg"])){
+					$myGUI_EPSG = true;
+				}
+			}
+			if(!$myGUI_EPSG){
+				if($mySubmit){ $sql .= ",";}
+				$paramCount++;
+				$sql .= "gui_wms_epsg = $" . $paramCount . " ";
+				array_push($v, $this->gui_wms_epsg);
+				array_push($t, "s");
+				$mySubmit = true;
+			}
+			$paramCount++;
+			$sql .= " WHERE fkey_gui_id = $" . $paramCount . " ";
+			array_push($v, $row["fkey_gui_id"]);
+			array_push($t, "s");
+
+			$paramCount++;
+			$sql .= "AND fkey_wms_id = $" . $paramCount;
+			array_push($v, $myWMS);
+			array_push($t, "i");
+			if($mySubmit){
+				$res = db_prep_query($sql,$v,$t);
+				if(!$res){
+					db_rollback();	
+					echo "<pre>".$sql."</pre><br> <br><p>";
+				 	echo db_error(); 
+				 	echo "<br /> UPDATE ERROR -> KILL PROCESS AND ROLLBACK....................no update<br><br>";
+					$e = new mb_exception("class_wms.php: transaction: Transaction aborted, rollback.");
+				}
+			}
+			$cnt++;
+		}	
+	}
+	function getVersion() {
+		return $this->wms_version;
+	}
+	
+	function getCapabilities() {
+		return $this->wms_getcapabilities;
+	}
+	
+	function getCapabilitiesDoc() {
+		return $this->wms_getcapabilities_doc;
+	}
+
+	/**
+	* creatObjfromDB
+	*
+	*/ 
+	  function createObjFromDB($gui_id,$wms_id){
+	
+		$sql = "Select * from gui_wms where fkey_wms_id = $1 AND fkey_gui_id = $2";
+		$v = array($wms_id,$gui_id);
+		$t = array('i','s');
+		$res = db_prep_query($sql,$v,$t);
+		
+		$count=0;
+		#$res_count=db_num_rows($res);
+	    
+	
+		while($row = db_fetch_array($res)){
+			$this->gui_wms_mapformat=$row["gui_wms_mapformat"];
+			$this->gui_wms_featureinfoformat=$row["gui_wms_featureinfoformat"];
+			$this->gui_wms_exceptionformat=$row["gui_wms_exceptionformat"];
+			$this->gui_wms_epsg=$row["gui_wms_epsg"];
+			$this->gui_wms_visible = $row["gui_wms_visible"];
+			$this->gui_wms_opacity = $row["gui_wms_opacity"];
+			$this->gui_wms_sldurl = $row["gui_wms_sldurl"];
+	  
+			$sql = "Select * from wms where wms_id = $1 ";
+			$v = array($wms_id);
+			$t = array('i');
+			$res_wms = db_prep_query($sql,$v,$t);
+			$count_wms=0;
+			while($row2 = db_fetch_array($res_wms)){
+				$this->wms_id = $row2["wms_id"];
+				$this->wms_version = $row2["wms_version"];
+				$this->wms_title = administration::convertIncomingString($this->stripEndlineAndCarriageReturn($row2["wms_title"]));
+				$this->wms_abstract = administration::convertIncomingString($this->stripEndlineAndCarriageReturn($row2["wms_abstract"]));
+				$wmsowsproxy = $row2["wms_owsproxy"];
+				#$wmsowsproxy = "test";
+				if($wmsowsproxy != ""){
+					$owsproxyurl = OWSPROXY."/".session_id()."/".$wmsowsproxy."?";
+					$this->wms_getmap = $owsproxyurl;
+					$this->wms_getcapabilities =  $owsproxyurl;
+					$this->wms_getfeatureinfo = $owsproxyurl;
+					$this->wms_getlegendurl = $owsproxyurl;
+				}
+				else{
+					$this->wms_getmap =  $row2["wms_getmap"];
+					$this->wms_getcapabilities =  $row2["wms_getcapabilities"];
+					$this->wms_getfeatureinfo = $row2["wms_getfeatureinfo"];
+					$this->wms_getlegendurl = $row2["wms_getlegendurl"];
+				}			
+				// TO DO: Capabilities document needs to 
+				// be encoded to the original encoding
+				// if different from the database encoding
+				$this->wms_getcapabilities_doc = $row2["wms_getcapabilities_doc"];
+				$this->wms_filter = $row2["wms_filter"];
+				$this->wms_supportsld = $row2["wms_supportsld"];
+				$this->wms_userlayer = $row2["wms_userlayer"];
+				$this->wms_userstyle = $row2["wms_userstyle"];
+				$this->wms_remotewfs = $row2["wms_remotewfs"];
+				$this->wms_timestamp_create = $row2["wms_timestamp_create"];
+				$this->fees = $row2["fees"];
+				$this->accessconstraints = $row2["accessconstraints"];
+				$this->contactperson = $row2["contactperson"];
+				$this->contactposition = $row2["contactposition"];
+				$this->contactvoicetelephone = $row2["contactvoicetelephone"];
+				$this->contactfacsimiletelephone = $row2["contactfacsimiletelephone"];
+				$this->contactorganization = $row2["contactorganization"];
+				$this->address = $row2["address"];
+				$this->city = $row2["city"];
+				$this->stateorprovince = $row2["stateorprovince"];
+				$this->postcode = $row2["postcode"];
+				$this->country = $row2["country"];
+				$this->contactelectronicmailaddress = $row2["contactelectronicmailaddress"];
+				
+				$count_wms++;
+			}
+	
+			### srs
+			$srs_sql = "SELECT * FROM wms_srs WHERE fkey_wms_id = $1 ";
+			$srs_v = array($wms_id);
+			$srs_t = array('i'); 
+			$srs_res = db_prep_query($srs_sql, $srs_v, $srs_t);
+			$this->wms_srs = array();
+			while($srs_row = db_fetch_array($srs_res)) {		
+				$this->wms_srs[]= $srs_row["wms_srs"];
+			}
+
+			### formats
+			$sql = "SELECT * FROM wms_format WHERE fkey_wms_id = $1 ";
+			$v = array($wms_id);
+			$t = array('i'); 
+			$res_wms = db_prep_query($sql,$v,$t);
+			$count_format=0;		
+			while($row3 = db_fetch_array($res_wms)){		
+				$this->data_type[$count_format] = $row3["data_type"];
+				$this->data_format[$count_format] = $row3["data_format"];
+				$count_format++;
+			}
+			$count++;
+		}
+		
+		#layer
+		$sql = "Select * from gui_layer JOIN layer ON gui_layer.fkey_layer_id = layer.layer_id where gui_layer_wms_id = $1 AND fkey_gui_id = $2 ";
+		$sql .= " AND gui_layer_status = 1 ORDER BY gui_layer_priority, CAST(layer_pos AS numeric);";
+		$v = array($wms_id,$gui_id);
+		$t = array('i','s');
+		$res = db_prep_query($sql,$v,$t);
+		$count=0;
+		
+		while($row = db_fetch_array($res)){
+			$layer_id = $row["fkey_layer_id"];		
+			$sql = "Select * from layer where layer_id = $1";
+			$v = array($layer_id);
+			$t = array('i');
+			$res_layer = db_prep_query($sql,$v,$t);
+			$count_layer=0;
+			while($row2 = db_fetch_array($res_layer)){
+				$this->addLayer($row2["layer_pos"],$row2["layer_parent"]);
+				$layer_cnt=count($this->objLayer)-1;
+				$this->objLayer[$layer_cnt]->layer_uid = $layer_id;
+				$this->objLayer[$layer_cnt]->layer_name = administration::convertIncomingString($row2["layer_name"]);
+				$this->objLayer[$layer_cnt]->layer_title = administration::convertIncomingString($row2["layer_title"]);			
+				$this->objLayer[$layer_cnt]->layer_dataurl_href =$row2["layer_dataurl"];
+				$this->objLayer[$layer_cnt]->layer_metadataurl =$row2["layer_metadataurl"];
+				$this->objLayer[$layer_cnt]->layer_searchable =$row2["layer_searchable"];
+				$this->objLayer[$layer_cnt]->layer_pos =$row2["layer_pos"];						
+				$this->objLayer[$layer_cnt]->layer_queryable =$row2["layer_pos"];
+				$this->objLayer[$layer_cnt]->layer_queryable =$row2["layer_queryable"];
+				$this->objLayer[$layer_cnt]->layer_minscale =$row2["layer_minscale"];
+				$this->objLayer[$layer_cnt]->layer_maxscale = $row2["layer_maxscale"];
+				$count_layer++;
+			}
+			$this->objLayer[$layer_cnt]->layer_uid = $layer_id;
+			$this->objLayer[$layer_cnt]->gui_layer_wms_id = $row["gui_layer_wms_id"];
+			$this->objLayer[$layer_cnt]->gui_layer_selectable = $row["gui_layer_selectable"];
+			$this->objLayer[$layer_cnt]->gui_layer_title = $row["gui_layer_title"] != "" ? $row["gui_layer_title"] : $this->objLayer[$layer_cnt]->layer_title;
+			$this->objLayer[$layer_cnt]->gui_layer_visible = $row["gui_layer_visible"];
+			$this->objLayer[$layer_cnt]->gui_layer_queryable = $row["gui_layer_queryable"];
+			$this->objLayer[$layer_cnt]->gui_layer_querylayer = $row["gui_layer_querylayer"];
+			$this->objLayer[$layer_cnt]->gui_layer_minscale = $row["gui_layer_minscale"];
+			$this->objLayer[$layer_cnt]->gui_layer_maxscale = $row["gui_layer_maxscale"];
+			$this->objLayer[$layer_cnt]->gui_layer_style = $row["gui_layer_style"];
+			$this->objLayer[$layer_cnt]->gui_layer_wfs_featuretype = $row["gui_layer_wfs_featuretype"];
+
+			$sql = "Select * from layer_epsg where fkey_layer_id = $1 ORDER BY fkey_layer_id";
+			$v = array($layer_id);
+			$t = array('i');
+			$res_layer_epsg = db_prep_query($sql,$v,$t);
+			
+			$count_layer_epsg=0;
+			while($row2 = db_fetch_array($res_layer_epsg)){
+				$this->objLayer[$layer_cnt]->layer_epsg[$count_layer_epsg]["epsg"]=$row2["epsg"];
+				$this->objLayer[$layer_cnt]->layer_epsg[$count_layer_epsg]["minx"]=$row2["minx"];
+				$this->objLayer[$layer_cnt]->layer_epsg[$count_layer_epsg]["miny"]=$row2["miny"];
+				$this->objLayer[$layer_cnt]->layer_epsg[$count_layer_epsg]["maxx"]=$row2["maxx"];
+				$this->objLayer[$layer_cnt]->layer_epsg[$count_layer_epsg]["maxy"]=$row2["maxy"];
+				$count_layer_epsg++;
+			}
+			
+			### handle styles
+			$sql = "SELECT * FROM layer_style WHERE fkey_layer_id = $1 ";
+			$v = array($layer_id);
+			$t = array('i');
+			$res_style = db_prep_query($sql,$v,$t);
+			$count_layer_style = 0;
+			while($row2 = db_fetch_array($res_style)){
+				$this->objLayer[$layer_cnt]->layer_style[$count_layer_style]["name"] = $row2["name"] ? $row2["name"] : "default";
+				$this->objLayer[$layer_cnt]->layer_style[$count_layer_style]["title"]=$row2["title"];
+				if($wmsowsproxy != ""){
+					if($row2["legendurl"]!=''){
+						$this->objLayer[$layer_cnt]->layer_style[$count_layer_style]["legendurl"]=$owsproxyurl.
+						"REQUEST=getlegendgraphic&VERSION=".$this->wms_version."&LAYER=".$this->objLayer[$layer_cnt]->layer_name."&FORMAT=".$row2["legendurlformat"].
+						"&STYLE=".$row2["name"];
+					}
+				}
+				else{
+					if($row2["legendurl"]!=''){
+						$this->objLayer[$layer_cnt]->layer_style[$count_layer_style]["legendurl"]=$row2["legendurl"];
+						#$e = new mb_exception("legendurl = ".$this->objLayer[$layer_cnt]->layer_style[$count_layer_style]["legendurl"]);
+					}
+				}
+				$this->objLayer[$layer_cnt]->layer_style[$count_layer_style]["legendurlformat"]=$row2["legendurlformat"];
+				$count_layer_style++;
+			}
+			$count++;
+		}
+	   }
+	/** end createObjfromDB **/
+	
+	  /**
+	* creatObjfromDBNoGui
+	*
+	*/ 
+	  function createObjFromDBNoGui($wms_id){
+	   	$sql = "Select * from wms where wms_id = $1 ";
+		$v = array($wms_id);
+		$t = array('i');
+		$res_wms = db_prep_query($sql,$v,$t);
+		$count_wms=0;
+		while($row2 = db_fetch_array($res_wms)){
+			$this->wms_id = $row2["wms_id"];
+			$this->wms_version = $row2["wms_version"];
+			$this->wms_title = administration::convertIncomingString($this->stripEndlineAndCarriageReturn($row2["wms_title"]));
+			$this->wms_abstract = administration::convertIncomingString($this->stripEndlineAndCarriageReturn($row2["wms_abstract"]));
+			$wmsowsproxy = $row2["wms_owsproxy"];
+			#$wmsowsproxy = "test";
+			if($wmsowsproxy != ""){
+				$owsproxyurl = OWSPROXY."/".session_id()."/".$wmsowsproxy."?";
+				$this->wms_getmap = $owsproxyurl;
+				$this->wms_getcapabilities =  $owsproxyurl;
+				$this->wms_getfeatureinfo = $owsproxyurl;
+				$this->wms_getlegendurl = $owsproxyurl;
+			}
+			else{
+				$this->wms_getmap =  $row2["wms_getmap"];
+				$this->wms_getcapabilities =  $row2["wms_getcapabilities"];
+				$this->wms_getfeatureinfo = $row2["wms_getfeatureinfo"];
+				$this->wms_getlegendurl = $row2["wms_getlegendurl"];
+			}			
+			// TO DO: Capabilities document needs to 
+			// be encoded to the original encoding
+			// if different from the database encoding
+			$this->wms_getcapabilities_doc = $row2["wms_getcapabilities_doc"];
+			$this->wms_filter = $row2["wms_filter"];
+			$this->wms_supportsld = $row2["wms_supportsld"];
+			$this->wms_userlayer = $row2["wms_userlayer"];
+			$this->wms_userstyle = $row2["wms_userstyle"];
+			$this->wms_remotewfs = $row2["wms_remotewfs"];
+			$this->wms_timestamp = $row2["wms_timestamp"];
+			$this->wms_timestamp_create = $row2["wms_timestamp_create"];
+			$this->fees = $row2["fees"];
+			$this->accessconstraints = $row2["accessconstraints"];
+			$this->contactperson = $row2["contactperson"];
+			$this->contactposition = $row2["contactposition"];
+			$this->contactvoicetelephone = $row2["contactvoicetelephone"];
+			$this->contactfacsimiletelephone = $row2["contactfacsimiletelephone"];
+			$this->contactorganization = $row2["contactorganization"];
+			$this->address = $row2["address"];
+			$this->city = $row2["city"];
+			$this->stateorprovince = $row2["stateorprovince"];
+			$this->postcode = $row2["postcode"];
+			$this->country = $row2["country"];
+			$this->contactelectronicmailaddress = $row2["contactelectronicmailaddress"];
+			
+			#some default
+			$this->gui_wms_visible = 1;
+			$this->gui_wms_opacity = 100;
+			$this->gui_wms_epsg=$row["gui_wms_epsg"];
+			$this->gui_wms_sldurl = $row["gui_wms_sldurl"];
+			
+			if($this->wms_version == "1.0.0"){
+                    $this->gui_wms_mapformat = "PNG";
+                    $this->gui_wms_featureinfoformat = "MIME";
+                    $this->gui_wms_exceptionformat = "INIMAGE";
+            }
+            /*define defaults for wms-version 1.1.0 and 1.1.1*/
+            else{
+                    $this->gui_wms_mapformat = "image/png";
+                    $this->gui_wms_featureinfoformat = "text/html";
+                    $this->gui_wms_exceptionformat = "application/vnd.ogc.se_inimage";
+            }
+			
+			$count_wms++;
+		}
+	
+		### formats
+		$sql = "SELECT * FROM wms_format WHERE fkey_wms_id = $1 ";
+		$v = array($wms_id);
+		$t = array('i'); 
+		$res_wms = db_prep_query($sql,$v,$t);
+		$count_format=0;		
+		while($row3 = db_fetch_array($res_wms)){		
+			$this->data_type[$count_format] = $row3["data_type"];
+			$this->data_format[$count_format] = $row3["data_format"];
+			$count_format++;
+		}
+
+			
+		$sql = "Select * from layer where fkey_wms_id = $1 ORDER BY layer_pos";
+		$v = array($wms_id);
+		$t = array('i');
+		$res_layer = db_prep_query($sql,$v,$t);
+		$count_layer=0;
+		while($row2 = db_fetch_array($res_layer)){
+			$this->addLayer($row2["layer_pos"],$row2["layer_parent"]);
+			$layer_cnt=count($this->objLayer)-1;
+			$this->objLayer[$layer_cnt]->layer_uid = $row2["layer_id"];
+			$this->objLayer[$layer_cnt]->layer_name = administration::convertIncomingString($row2["layer_name"]);
+			$this->objLayer[$layer_cnt]->layer_title = administration::convertIncomingString($row2["layer_title"]);	
+			$this->objLayer[$layer_cnt]->gui_layer_title = $this->objLayer[$layer_cnt]->layer_title;			
+			$this->objLayer[$layer_cnt]->layer_dataurl_href =$row2["layer_dataurl"];
+			$this->objLayer[$layer_cnt]->layer_metadataurl =$row2["layer_metadataurl"];
+			$this->objLayer[$layer_cnt]->layer_searchable =$row2["layer_searchable"];
+			$this->objLayer[$layer_cnt]->layer_pos =$row2["layer_pos"];						
+			$this->objLayer[$layer_cnt]->layer_queryable =$row2["layer_queryable"];
+			$this->objLayer[$layer_cnt]->layer_minscale =$row2["layer_minscale"];
+			$this->objLayer[$layer_cnt]->layer_maxscale = $row2["layer_maxscale"];
+			
+			if($this->objLayer[$layer_cnt]->layer_minscale == ""){
+				$this->objLayer[$layer_cnt]->layer_minscale = 0;
+			}
+			if($this->objLayer[$layer_cnt]->layer_maxscale == ""){
+				$this->objLayer[$layer_cnt]->layer_maxscale = 0;
+			}
+			$this->objLayer[$layer_cnt]->gui_layer_minscale = $this->objLayer[$layer_cnt]->layer_minscale;
+			$this->objLayer[$layer_cnt]->gui_layer_maxscale = $this->objLayer[$layer_cnt]->layer_maxscale;
+			$this->objLayer[$layer_cnt]->gui_layer_queryable = $this->objLayer[$layer_cnt]->layer_queryable;
+			
+			$sql = "Select * from layer_epsg where fkey_layer_id = $1 ORDER BY fkey_layer_id";
+			$v = array($this->objLayer[$layer_cnt]->layer_uid);
+			$t = array('i');
+			$res_layer_epsg = db_prep_query($sql,$v,$t);
+			
+			$count_layer_epsg=0;
+			while($row2 = db_fetch_array($res_layer_epsg)){
+				$this->objLayer[$layer_cnt]->layer_epsg[$count_layer_epsg]["epsg"]=$row2["epsg"];
+				$this->objLayer[$layer_cnt]->layer_epsg[$count_layer_epsg]["minx"]=$row2["minx"];
+				$this->objLayer[$layer_cnt]->layer_epsg[$count_layer_epsg]["miny"]=$row2["miny"];
+				$this->objLayer[$layer_cnt]->layer_epsg[$count_layer_epsg]["maxx"]=$row2["maxx"];
+				$this->objLayer[$layer_cnt]->layer_epsg[$count_layer_epsg]["maxy"]=$row2["maxy"];
+				$count_layer_epsg++;
+			}
+			
+			### handle styles
+			$sql = "SELECT * FROM layer_style WHERE fkey_layer_id = $1 ";
+			$v = array($this->objLayer[$layer_cnt]->layer_uid);
+			$t = array('i');
+			$res_style = db_prep_query($sql,$v,$t);
+			$count_layer_style = 0;
+			while($row2 = db_fetch_array($res_style)){
+				$this->objLayer[$layer_cnt]->layer_style[$count_layer_style]["name"]=$row2["name"];
+				$this->objLayer[$layer_cnt]->layer_style[$count_layer_style]["title"]=$row2["title"];
+				if($wmsowsproxy != ""){
+					if($row2["legendurl"]!=''){
+						$this->objLayer[$layer_cnt]->layer_style[$count_layer_style]["legendurl"]=$owsproxyurl.
+						"REQUEST=getlegendgraphic&VERSION=".$this->wms_version."&LAYER=".$this->objLayer[$layer_cnt]->layer_name."&FORMAT=".$row2["legendurlformat"].
+						"&STYLE=".$row2["name"];
+					}
+				}
+				else{
+					if($row2["legendurl"]!=''){
+						$this->objLayer[$layer_cnt]->layer_style[$count_layer_style]["legendurl"]=$row2["legendurl"];
+						#$e = new mb_exception("legendurl = ".$this->objLayer[$layer_cnt]->layer_style[$count_layer_style]["legendurl"]);
+					}
+				}
+				$this->objLayer[$layer_cnt]->layer_style[$count_layer_style]["legendurlformat"]=$row2["legendurlformat"];
+				$count_layer_style++;
+			}
+						
+			$count_layer++;
+		}
+	
+   }
+	/** end createObjfromDBNoGui **/
+	
+	  /**
+	* function checkObjExistsInDB()
+	*
+	* this function checks wether the onlineresource already exists in the database.
+	*/ 
+	function checkObjExistsInDB(){
+	
+		$sql = "Select * from wms where wms_getcapabilities = $1";
+		$v = array($this->wms_getcapabilities);
+		$t = array('s');
+		$res = db_prep_query($sql,$v,$t);
+		$res_count= db_num_rows($res);	  
+		$wms_id=0;
+		if($res_count>0){
+			$count=0;
+			while($row = db_fetch_array($res)){
+				$wms_id=$row["wms_id"];
+				$count++;
+			}
+		}
+		return $wms_id;
+	}
+	
+	function displayDBInformation(){
+		echo $this->wms_getcapabilities;
+		$sql="Select * from wms where wms_getcapabilities = $1";
+		$v = array($this->wms_getcapabilities);
+		$t = array('s');
+		$res = db_prep_query($sql,$v,$t);
+		$count=0;
+		while($row = db_fetch_array($res)){
+		echo "count: ".$count."<br>";
+			$wms_id=$row["wms_id"];
+			echo "version: " .$wms_id." <br>";
+			echo "title: " .$row["wms_version"]. " <br>";
+			echo "abstract: " . $row["wms_title"] . " <br>";
+			echo "maprequest: " .$row["wms_abstract"] . " <br>";
+			echo "capabilitiesrequest: " . $row["wms_getcapabilities"] . " <br>";
+			echo "featureinforequest: " . $row["wms_getmap"]. " <br>";
+			echo "gui_wms_mapformat: " . $row["wms_getfeatureinfo"] . " <br>---------<br>";
+			$count++;
+		}
+	   echo "----<br> wms_id: ".$wms_id."<br>";
+	   
+	   $sql = "Select * from gui_wms where fkey_wms_id = $1";
+	   $v = array($wms_id);
+	   $t = array('i');
+	   echo "sql: ".$sql." <br>---------<br>";
+	   $res = db_prep_query($sql,$v,$t);
+	   $res_count= db_num_rows($res); 
+	   echo "result count: ".$res_count." <br>---------<br>";
+	   
+	   $count=0;
+	   while($row = db_fetch_array($res)){
+	    	echo "gui_wms_featureinfoformat: " . $row["gui_wms_featureinfoformat"]." <br>";
+	    	echo "gui_wms_exceptionformat: " .  $row["gui_wms_exceptionformat"]. " <br>";
+	    	echo "gui_wms_epsg: " .  $row["gui_wms_epsg"]. " <br>";
+	      $count++;
+	   }
+		
+	   #db_close($connect);
+	}
+
+	function checkObj(){
+		if($this->wms_getcapabilities == '' || $this->wms_getmap == '' ){
+			echo "<br>Missing parameters: <br>";
+			$this->displayWMS();
+			print_r($this);
+			echo "<br> Data not committed<br>";
+			die();
+		}
+	}
+	
+	public static function getWmsIdByLayerId ($id) {
+		$sql = "SELECT DISTINCT fkey_wms_id FROM layer WHERE layer_id = $1";
+		$res = db_prep_query($sql, array($id), array("i"));
+		$row = db_fetch_assoc($res);
+		if ($row) {
+			return $row["fkey_wms_id"];
+		}
+		return null;
+	}
+	
+	/**
+	 * Selects all WMS of the current user from the database.
+	 * Then it creates the corresponding WMS object and returns
+	 * these objects as an array.
+	 * 
+	 * @return wms[]
+	 * @param $appId String
+	 */
+	public static function selectMyWmsByApplication ($appId) {
+		// check if user is permitted to access the application
+		$currentUser = new User(Mapbender::session()->get("mb_user_id"));
+		$appArray = $currentUser->getApplicationsByPermission(false);
+		if (!in_array($appId, $appArray)) {
+			$e = new mb_warning("class_wms.php: selectMyWmsByApplication(): User '" . $currentUser . "' is not allowed to acces application '" . $appId . "'.");
+			return array();
+		}
+		
+		// get WMS of this application
+		$sql = "SELECT fkey_wms_id FROM gui_wms WHERE " . 
+				"fkey_gui_id = $1 ORDER BY gui_wms_position";
+		$v = array($appId);
+		$t = array('s');
+		$res = db_prep_query($sql,$v,$t);
+		
+		// instantiate PHP objects and store in array
+		$wmsArray = array();
+		while ($row = db_fetch_array($res)) {
+			$currentWms = new wms();
+			$currentWms->createObjFromDB($appId, $row["fkey_wms_id"]);
+			array_push($wmsArray, $currentWms);
+		}
+		return $wmsArray;
+	}
+}
+class layer extends wms {	
+	var $layer_id;
+	var $layer_parent;
+	var $layer_name;
+	var $layer_title;
+	var $layer_abstract;
+	var $layer_pos;
+	var $layer_queryable;
+	var $layer_minscale;
+	var $layer_maxscale;	
+    var $layer_dataurl_href;
+    var $layer_metadataurl;
+	var $layer_searchable;
+    var $layer_keyword = array();
+	var $layer_epsg = array();
+	var $layer_style = array();
+	var $layer_md_topic_category_id = array();
+	var $layer_inspire_category_id = array();
+	var $layer_custom_category_id = array();
+	
+	var $gui_layer_wms_id;
+	var $gui_layer_status = 1;
+	var $gui_layer_selectable = 1;
+	var $gui_layer_visible = 0;
+	var $gui_layer_queryable = 0;
+	var $gui_layer_querylayer = 0;
+	var $gui_layer_style = NULL;	
+	
+	function layer($id,$parent){
+		$this->layer_id = $id;
+		$this->layer_parent = $parent;	
+		//var_dump($this);	
+	}
+
+	public function equals ($layer) {
+		if (is_numeric($this->layer_uid) && $this->layer_uid === $layer->layer_uid) {
+			return true;
+		}
+		return false;
+	}
+
+	public static function getLayerMetadataUrl ($layerId) {
+		return preg_replace(
+			"/(.*)frames\/login.php/", 
+			"$1php/mod_layerMetadata.php?id=", 
+			LOGIN
+		) . $layerId;
+	}
+
+	public function __toString () {
+		$e = new mb_exception("TITLE: " . $this->layer_title);
+		return $this->layer_title;
+	}
+	
+	public function getChildren () {
+		$children = array();
+		$wmsId = wms::getWmsIdByLayerId($this->layer_uid);
+		$wmsFactory = new UniversalWmsFactory();
+		$wms = $wmsFactory->createFromDb($wmsId);
+		if (!is_null($wms)) {
+			try {
+				$currentLayer = $wms->getLayerById($this->layer_uid);
+			}
+			catch (Exception $e) {
+				return $children;
+			}
+			for ($i = 0; $i < count($wms->objLayer); $i++) {
+				$l = $wms->objLayer[$i];
+				if ($l->layer_parent === $currentLayer->layer_pos) {
+					// add this layer and add its children recursively
+					$children = array_merge($children, array($l), $l->getChildren());
+				}
+			}
+		}
+		return $children;
+	}
+	
+	public function getParents () {
+		$parents = array();
+		$wmsId = wms::getWmsIdByLayerId($this->layer_uid);
+		$wmsFactory = new UniversalWmsFactory();
+		$wms = $wmsFactory->createFromDb($wmsId);
+		if (!is_null($wms)) {
+			try {
+				$currentLayer = $wms->getLayerById($this->layer_uid);
+			}
+			catch (Exception $e) {
+				return $parents;
+			}
+			while (!is_null($currentLayer)) {
+				$pos = $currentLayer->layer_parent;
+				$currentLayer = $wms->getLayerByPos($pos);
+				if (!is_null($currentLayer)) {
+					$parents[]= $currentLayer;
+				}
+			}
+		}
+		return $parents;
+	}
+}
+?>
\ No newline at end of file

Deleted: branches/mapbender/http/classes/class_wms_1_1_1_factory.php
===================================================================
--- trunk/mapbender/http/classes/class_wms_1_1_1_factory.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/http/classes/class_wms_1_1_1_factory.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,89 +0,0 @@
-<?php
-# License:
-# Copyright (c) 2009, Open Source Geospatial Foundation
-# This program is dual licensed under the GNU General Public License 
-# and Simplified BSD license.  
-# http://svn.osgeo.org/mapbender/trunk/mapbender/license/license.txt
-
-require_once dirname(__FILE__) . "/../../core/globalSettings.php";
-require_once dirname(__FILE__) . "/../classes/class_wms_factory.php";
-require_once dirname(__FILE__) . "/../classes/class_wms.php";
-require_once dirname(__FILE__) . "/../classes/class_connector.php";
-require_once dirname(__FILE__) . "/../classes/class_administration.php";
-
-/**
- * Creates WMS < 1.2 objects from a capabilities documents.
- * 
- * @return Wms
- */
-class Wms_1_1_1_Factory extends WmsFactory {
-
-	/**
-	 * Creates WMS < 1.2 objects from a capabilities documents.
-	 * 
-	 * @return Wms
-	 * @param $xml String
-	 */
-	public function createFromXml ($xml) {
-	}
-	
-	public function createFromDb ($id) {
-		$appId = func_num_args() >= 2 ? 
-			func_get_arg(1) : null;
-
-		$myWms = new wms();
-		if (!is_null($appId)) {
-			return parent::createFromDb($id, $myWms, $appId);
-		}
-		return parent::createFromDb($id, $myWms);
-	}
-	
-	public function createLayerFromDb ($id) {
-		$wmsId = func_num_args() >= 2 ? 
-			func_get_arg(1) : null;
-
-		$appId = func_num_args() >= 3 ? 
-			func_get_arg(2) : null;
-
-		//
-		// get WMS of this layer
-		//
-		if (!is_null($appId)) {
-			$myWms = $this->createFromDb($wmsId, $appId);
-		}
-		else {
-			$myWms = $this->createFromDb($wmsId);
-		}
-		
-		if (is_null($myWms)) {
-			return null;
-		}
-		
-		//
-		// delete all layers apart from the one mentioned (but keep parents and children)
-		//
-		
-		// Find layers that have both parents and children for testing:
-		// SELECT DISTINCT q.layer_id, q.layer_pos, q.layer_parent FROM layer q, layer r WHERE r.layer_parent <> '' AND q.layer_pos = CAST(r.layer_parent AS numeric) and q.layer_parent = '0' and q.fkey_wms_id = r.fkey_wms_id
-		$currentLayer = $myWms->getLayerById($id);
-		$children = $currentLayer->getChildren();
-		$parents = $currentLayer->getParents();
-		$keep = array_merge(array($currentLayer), $children, $parents);
-		
-		//
-		// 2. delete layers not for keeping
-		//
-		$i = 0;
-		while ($i < count($myWms->objLayer)) {
-			$l = $myWms->objLayer[$i];
-			if (in_array($l, $keep)) {
-				$i++;
-				continue;
-			}
-			// delete layer
-			array_splice($myWms->objLayer, $i, 1);
-		}
-		return $myWms;
-	}
-}
-?>
\ No newline at end of file

Copied: branches/mapbender/http/classes/class_wms_1_1_1_factory.php (from rev 6955, trunk/mapbender/http/classes/class_wms_1_1_1_factory.php)
===================================================================
--- branches/mapbender/http/classes/class_wms_1_1_1_factory.php	                        (rev 0)
+++ branches/mapbender/http/classes/class_wms_1_1_1_factory.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -0,0 +1,100 @@
+<?php
+# License:
+# Copyright (c) 2009, Open Source Geospatial Foundation
+# This program is dual licensed under the GNU General Public License 
+# and Simplified BSD license.  
+# http://svn.osgeo.org/mapbender/trunk/mapbender/license/license.txt
+
+require_once dirname(__FILE__) . "/../../core/globalSettings.php";
+require_once dirname(__FILE__) . "/../classes/class_wms_factory.php";
+require_once dirname(__FILE__) . "/../classes/class_wms.php";
+require_once dirname(__FILE__) . "/../classes/class_connector.php";
+require_once dirname(__FILE__) . "/../classes/class_administration.php";
+
+/**
+ * Creates WMS < 1.2 objects from a capabilities documents.
+ * 
+ * @return Wms
+ */
+class Wms_1_1_1_Factory extends WmsFactory {
+
+	/**
+	 * Creates WMS < 1.2 objects from a capabilities documents.
+	 * 
+	 * @return Wms
+	 * @param $xml String
+	 */
+	public function createFromXml ($xml) {
+	}
+	
+	public function createFromDb ($id) {
+		$appId = func_num_args() >= 2 ? 
+			func_get_arg(1) : null;
+
+		$myWms = new wms();
+		if (!is_null($appId)) {
+			return parent::createFromDb($id, $myWms, $appId);
+		}
+		return parent::createFromDb($id, $myWms);
+	}
+	
+	public function createLayerFromDb ($id) {
+		$wmsId = func_num_args() >= 2 ? 
+			func_get_arg(1) : null;
+
+		$appId = func_num_args() >= 3 ? 
+			func_get_arg(2) : null;
+
+		//
+		// get WMS of this layer
+		//
+		if (!is_null($appId)) {
+			$myWms = $this->createFromDb($wmsId, $appId);
+		}
+		else {
+			$myWms = $this->createFromDb($wmsId);
+		}
+		
+		if (is_null($myWms)) {
+			return null;
+		}
+		
+		//
+		// delete all layers apart from the one mentioned (but keep parents and children)
+		//
+		
+		// Find layers that have both parents and children for testing:
+		// SELECT DISTINCT q.layer_id, q.layer_pos, q.layer_parent FROM layer q, layer r WHERE r.layer_parent <> '' AND q.layer_pos = CAST(r.layer_parent AS numeric) and q.layer_parent = '0' and q.fkey_wms_id = r.fkey_wms_id
+		$currentLayer = $myWms->getLayerById($id);
+
+		$keep = array();
+
+		$parents = $currentLayer->getParents();
+		foreach ($parents as $parent) {
+			$keep[]= $parent->layer_uid;
+		}
+
+		$keep[]= $currentLayer->layer_uid;
+
+		$children = $currentLayer->getChildren();
+		foreach ($children as $child) {
+			$keep[]= $child->layer_uid;
+		}
+
+		//
+		// 2. delete layers not for keeping
+		//
+		$i = 0;
+		while ($i < count($myWms->objLayer)) {
+			$l = $myWms->objLayer[$i];
+			if (in_array($l->layer_uid, $keep)) {
+				$i++;
+				continue;
+			}
+			// delete layer
+			array_splice($myWms->objLayer, $i, 1);
+		}
+		return $myWms;
+	}
+}
+?>
\ No newline at end of file

Deleted: branches/mapbender/http/classes/class_wms_factory.php
===================================================================
--- trunk/mapbender/http/classes/class_wms_factory.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/http/classes/class_wms_factory.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,37 +0,0 @@
-<?php
-# License:
-# Copyright (c) 2009, Open Source Geospatial Foundation
-# This program is dual licensed under the GNU General Public License 
-# and Simplified BSD license.  
-# http://svn.osgeo.org/mapbender/trunk/mapbender/license/license.txt
-
-require_once dirname(__FILE__) . "/../../core/globalSettings.php";
-require_once dirname(__FILE__) . "/class_administration.php";
-require_once dirname(__FILE__) . "/class_ows_factory.php";
-
-abstract class WmsFactory extends OwsFactory {
-	/**
-	 * Retrieves the data of a WMS from the database and initiates the object.
-	 * 
-	 * @return 
-	 * @param $id Integer
-	 * @param $aWms Wms is being created by the subclass
-	 * @param $appId id of the application where this WMS is configured
-	 */
-	public function createFromDb ($id) {
-		$myWms = func_num_args() >= 2 ? 
-			func_get_arg(1) : null;
-
-		$appId = func_num_args() >= 3 ? 
-			func_get_arg(2) : null;
-
-		if (!is_null($appId)) {
-			$myWms->createObjFromDB($id, $appId);
-		}
-		else {
-			$myWms->createObjFromDBNoGui($id);
-		}
-		return $myWms;
-	}
-}
-?>

Copied: branches/mapbender/http/classes/class_wms_factory.php (from rev 6928, trunk/mapbender/http/classes/class_wms_factory.php)
===================================================================
--- branches/mapbender/http/classes/class_wms_factory.php	                        (rev 0)
+++ branches/mapbender/http/classes/class_wms_factory.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -0,0 +1,37 @@
+<?php
+# License:
+# Copyright (c) 2009, Open Source Geospatial Foundation
+# This program is dual licensed under the GNU General Public License 
+# and Simplified BSD license.  
+# http://svn.osgeo.org/mapbender/trunk/mapbender/license/license.txt
+
+require_once dirname(__FILE__) . "/../../core/globalSettings.php";
+require_once dirname(__FILE__) . "/class_administration.php";
+require_once dirname(__FILE__) . "/class_ows_factory.php";
+
+abstract class WmsFactory extends OwsFactory {
+	/**
+	 * Retrieves the data of a WMS from the database and initiates the object.
+	 * 
+	 * @return 
+	 * @param $id Integer
+	 * @param $aWms Wms is being created by the subclass
+	 * @param $appId id of the application where this WMS is configured
+	 */
+	public function createFromDb ($id) {
+		$myWms = func_num_args() >= 2 ? 
+			func_get_arg(1) : null;
+
+		$appId = func_num_args() >= 3 ? 
+			func_get_arg(2) : null;
+
+		if (!is_null($appId)) {
+			$myWms->createObjFromDB($appId, $id);
+		}
+		else {
+			$myWms->createObjFromDBNoGui($id);
+		}
+		return $myWms;
+	}
+}
+?>

Modified: branches/mapbender/http/frames/index.php
===================================================================
--- trunk/mapbender/http/frames/index.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/http/frames/index.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -18,11 +18,13 @@
 # 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("../php/mb_validateSession.php");
 require_once(dirname(__FILE__)."/../classes/class_gui.php");
 
 Mapbender::session()->set("mb_user_gui",$gui_id);
 
+print_r($_SESSION);
 //
 // check if user is allowed to access current GUI; 
 // if not, return to login screen
@@ -72,14 +74,14 @@
 	e_id = fkey_e_id 
 	AND e_element <> 'iframe' 
 	AND gui_element.fkey_gui_id = $1 
-	AND gui_element_vars.fkey_gui_id = $1 
+	AND gui_element_vars.fkey_gui_id = $2
 	AND var_type='file/css' 
 ORDER BY var_name
 
 SQL;
 
-	$v = array($gui_id);
-	$t = array('s');
+	$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)){
@@ -96,14 +98,14 @@
 	e_id = fkey_e_id 
 	AND e_element <> 'iframe' 
 	AND gui_element.fkey_gui_id = $1 
-	AND gui_element_vars.fkey_gui_id = $1 
+	AND gui_element_vars.fkey_gui_id = $2
 	AND var_type = 'text/css' 
 ORDER BY var_name
 
 SQL;
 
-	$v = array($gui_id);
-	$t = array('s');
+	$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)){

Deleted: branches/mapbender/http/javascripts/initWmcObj.php
===================================================================
--- trunk/mapbender/http/javascripts/initWmcObj.php	2010-09-21 19:35:52 UTC (rev 6926)
+++ branches/mapbender/http/javascripts/initWmcObj.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,222 +0,0 @@
-<?php
-//
-// Load WMS via WMC
-// 
-require_once dirname(__FILE__)."/../php/mb_validateSession.php";
-require_once dirname(__FILE__)."/../classes/class_wmc.php";
-require_once dirname(__FILE__)."/../classes/class_administration.php";
-require_once dirname(__FILE__)."/../../lib/class_GetApi.php";
-
-$wmc = new wmc();
-
-//check if session contains a wmc, otherwise create a new wmc from application
-if (!Mapbender::session()->get("mb_wmc")) {
-	$e = new mb_notice("wmc not set, generating from app: " .
-			Mapbender::session()->get("mb_user_gui"));
-	$wmc->createFromApplication(Mapbender::session()->get("mb_user_gui"));
-}
-else {
-	if (!$wmc->createFromXml(Mapbender::session()->get("mb_wmc"))) {
-		$e = new mb_notice("error creating initial WMC from session.");
-	}
-}
-
-function getConfiguration ($key) {
-	//check if key param can be found in SESSION, 
-	// otherwise take it from GET
-	if (Mapbender::session()->exists($key)) {
-		return Mapbender::session()->get($key);
-	}
-	return $_GET[$key];
-}
-
-$options = array();
-if (Mapbender::session()->exists("addwms_showWMS")) {
-	$options["show"] = intval(Mapbender::session()->get("addwms_showWMS"));
-}
-if (Mapbender::session()->exists("addwms_zoomToExtent")) {
-	$options["zoom"] = !!Mapbender::session()->get("addwms_zoomToExtent");
-}
-
-$getParams = array(
-	"WMS" => getConfiguration("WMS"),
-	"LAYER" => getConfiguration("LAYER"),
-	"FEATURETYPE" => getConfiguration("FEATURETYPE")
-);
-$getApi = new GetApi($getParams);
-
-if ($getParams['WMS']) {
-	// WMS param given as array
-	if (is_array($getParams['WMS'])) {
-		$inputWmsArray = $getParams['WMS'];
-	}
-	// WMS param given as comma separated list
-	else {
-		$inputWmsArray = split(",",$getParams['WMS']); 
-	}
-	
-	$wmsArray = array();
-	$singleAssocArray = array();
-	$multipleAssocArray = array();
-	
-	foreach ($inputWmsArray as $key=>$val) {
-		if (is_array($val)) {
-			foreach ($val as $attr=>$value) {
-				$multipleAssocArray[$attr] = $value;
-			}
-			//get WMS by ID with settings of given application
-			if (array_key_exists('application', $multipleAssocArray) && 
-				array_key_exists('id', $multipleAssocArray)) {
-				$currentWms = new wms();	
-				$currentWms->createObjFromDB(
-					$multipleAssocArray['application'],
-					$multipleAssocArray['id']
-				);
-			}
-			//get WMS by URL
-			elseif (array_key_exists('url', $multipleAssocArray)) {
-				$currentWms = new wms();
-				$currentWms->createObjFromXML($multipleAssocArray['url']);
-			}
-			else {
-				continue;
-			}
-			array_push($wmsArray, $currentWms);
-			
-			$options['visible'] = $multipleAssocArray['visible'] === "1" ?
-				true : false;
-
-			$options['zoom'] = $multipleAssocArray['zoom'] === "1" ?
-				true : false;
-			
-			$wmc->mergeWmsArray($wmsArray, $options);
-			$wmsArray = array();
-			$multipleAssocArray = array();
-		}
-		else {
-			$currentWms = new wms();
-			if(is_numeric($key)) {
-				//get WMS by URL
-				if (is_string($val)) {
-					$currentWms->createObjFromXML($val);
-				}
-				//get WMS by ID
-				if (is_numeric($val)) {
-					$currentWms->createObjFromDBNoGui($val);
-				}
-				array_push($wmsArray, $currentWms);
-				$wmc->mergeWmsArray($wmsArray);
-				$wmsArray = array();
-			} 
-			else {
-				$singleAssocArray[$key] = $val;
-			}
-		}
-	}
-	
-	//get WMS by ID with settings of given application
-	if (array_key_exists('application', $singleAssocArray) && 
-		array_key_exists('id', $singleAssocArray)) {
-		$currentWms = new wms();	
-		$currentWms->createObjFromDB(
-			$singleAssocArray['application'],
-			$singleAssocArray['id']
-		);
-		array_push($wmsArray, $currentWms);
-		$options['visible'] = $singleAssocArray['visible'] === "1" ?
-			true : false;
-		
-		$options['zoom'] = $singleAssocArray['zoom'] === "1" ? true : false;
-
-		$wmc->mergeWmsArray($wmsArray, $options);
-		$wmsArray = array();
-		$singleAssocArray = array();
-	}
-	//get WMS by URL
-	elseif (array_key_exists('url', $singleAssocArray)) {
-		$currentWms = new wms();
-		$currentWms->createObjFromXML($singleAssocArray['url']);
-		array_push($wmsArray, $currentWms);
-		if($singleAssocArray['visible']) {
-			$options['visible'] = $singleAssocArray['visible'] === "1" ?
-				true : false;
-		}
-		if($singleAssocArray['zoom']) {
-			$options['zoom'] = $singleAssocArray['zoom'] === "1" ?
-				true : false;
-		}
-		$wmc->mergeWmsArray($wmsArray, $options);
-		$wmsArray = array();
-		$singleAssocArray = array();
-	}
-}
-
-$inputLayerArray = $getApi->getLayers();
-if ($inputLayerArray) {
-	foreach ($inputLayerArray as $input) {
-		// just make it work for a single layer id
-		$wmsFactory = new UniversalWmsFactory();
-		$wms = $wmsFactory->createLayerFromDb($input["id"]);
-		$options = array();
-		if ($input["visible"]) {
-			// this is a hack for the time being:
-			// make WMS visible if it has less than 100000 layers
-			$options["show"] = 100000;
-		}
-		$wmc->mergeWmsArray(array($wms), $options);
-	}
-}
-
-$inputFeaturetypeArray = $getApi->getFeaturetypes();
-if ($inputFeaturetypeArray) {
-	$wfsConfIds = array();	
-	foreach ($inputFeaturetypeArray as $input) {
-		array_push($wfsConfIds, $input["id"]);
-	}
-	
-	$wmc->generalExtensionArray['WFSCONFIDSTRING'] = implode(",", array_merge(
-		$wmc->generalExtensionArray['WFSCONFIDSTRING'] ? 
-			explode(",", $wmc->generalExtensionArray['WFSCONFIDSTRING']) :
-			array(),
-		$wfsConfIds
-	));
-}
-
-//workaround to have a fully merged WMC for loading
-
-$xml = $wmc->toXml();
-
-$wmc = new wmc();
-$wmc->createFromXml($xml);
-
-$output = $wmc->wmsToJavaScript();
-
-//workaround for zoom to WMS
-$extent = $wmc->mainMap->getExtent();
-Mapbender::session()->set("mb_myBBOX", $extent->min->x . "," .
-	$extent->min->y . "," . $extent->max->x . "," . $extent->max->y);
-
-$outputString = "";
-for ($i = 0; $i < count($output); $i++) {
-	$outputString .= administration::convertOutgoingString($output[$i]);
-}
-
-$wmcFeaturetypeJson = $wmc->featuretypeConfToJavaScript();
-$wmcFeaturetypeStr = <<<JS
-	Mapbender.events.afterInit.register(function () {
-		$('#body').trigger('addFeaturetypeConfs', [
-			{featuretypeConfObj : $wmcFeaturetypeJson}
-		]);
-	});
-JS;
-
-$outputString .= $wmcFeaturetypeStr;
-
-echo $outputString;
-
-
-Mapbender::session()->delete("addwms_showWMS");
-Mapbender::session()->delete("addwms_zoomToExtent");
-unset($output);
-unset($wmc);
-?>

Copied: branches/mapbender/http/javascripts/initWmcObj.php (from rev 6955, trunk/mapbender/http/javascripts/initWmcObj.php)
===================================================================
--- branches/mapbender/http/javascripts/initWmcObj.php	                        (rev 0)
+++ branches/mapbender/http/javascripts/initWmcObj.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -0,0 +1,276 @@
+<?php
+//
+// Load WMS via WMC
+// 
+require_once dirname(__FILE__)."/../php/mb_validateSession.php";
+require_once dirname(__FILE__)."/../classes/class_wmc.php";
+require_once dirname(__FILE__)."/../classes/class_administration.php";
+require_once dirname(__FILE__)."/../../lib/class_GetApi.php";
+require_once dirname(__FILE__)."/../classes/class_elementVar.php";
+
+function getConfiguration ($key) {
+	//check if key param can be found in SESSION,
+	// otherwise take it from GET
+	if (Mapbender::session()->exists($key)) {
+		return Mapbender::session()->get($key);
+	}
+	return $_GET[$key];
+}
+
+$wmc = new wmc();
+
+$app = Mapbender::session()->get("mb_user_gui");
+$wmcDocSession = Mapbender::session()->get("mb_wmc");
+
+try {
+	$loadFromSession = new ElementVar($app, "loadwmc", "loadFromSession");
+	if ($loadFromSession->value === "1") {
+		//check if session contains a wmc,
+		//otherwise create a new wmc from application
+		$e = new mb_notice("trying to load session WMC...");
+		if (!$wmc->createFromXml($wmcDocSession)) {
+			$e = new mb_notice("loading session WMC failed.");
+			$e = new mb_notice("creating wmc from app: " . $app);
+			$wmc->createFromApplication($app);
+		}
+	}
+	else {
+		$e = new mb_notice("loading from session WMC disabled in loadwmc.");
+		$e = new mb_notice("creating wmc from app: " . $app);
+		$wmc->createFromApplication($app);
+	}
+}
+catch (Exception $e) {
+	$e = new mb_notice("creating wmc from app: " . $app);
+	$wmc->createFromApplication($app);
+}
+
+$options = array();
+if (Mapbender::session()->exists("addwms_showWMS")) {
+	$options["show"] = intval(Mapbender::session()->get("addwms_showWMS"));
+}
+if (Mapbender::session()->exists("addwms_zoomToExtent")) {
+	$options["zoom"] = !!Mapbender::session()->get("addwms_zoomToExtent");
+}
+
+$getParams = array(
+	"WMC" => getConfiguration("WMC"),
+	"WMS" => getConfiguration("WMS"),
+	"LAYER" => getConfiguration("LAYER"),
+	"FEATURETYPE" => getConfiguration("FEATURETYPE")
+);
+$getApi = new GetApi($getParams);
+
+
+$inputWmcArray = $getApi->getWmc();
+if ($inputWmcArray) {
+	foreach ($inputWmcArray as $input) {
+		// just make it work for a single Wmc
+
+	}
+}
+
+if ($getParams['WMS']) {
+	// WMS param given as array
+	if (is_array($getParams['WMS'])) {
+		$inputWmsArray = $getParams['WMS'];
+	}
+	// WMS param given as comma separated list
+	else {
+		$inputWmsArray = split(",",$getParams['WMS']); 
+	}
+	
+	$wmsArray = array();
+	$singleAssocArray = array();
+	$multipleAssocArray = array();
+	
+	foreach ($inputWmsArray as $key=>$val) {
+		if (is_array($val)) {
+			foreach ($val as $attr=>$value) {
+				$multipleAssocArray[$attr] = $value;
+			}
+			//get WMS by ID with settings of given application
+			if (array_key_exists('application', $multipleAssocArray) && 
+				array_key_exists('id', $multipleAssocArray)) {
+				$currentWms = new wms();	
+				$currentWms->createObjFromDB(
+					$multipleAssocArray['application'],
+					$multipleAssocArray['id']
+				);
+			}
+			//get WMS by URL
+			elseif (array_key_exists('url', $multipleAssocArray)) {
+				$currentWms = new wms();
+				$currentWms->createObjFromXML($multipleAssocArray['url']);
+			}
+			else {
+				continue;
+			}
+			array_push($wmsArray, $currentWms);
+			
+			$options['visible'] = $multipleAssocArray['visible'] === "1" ?
+				true : false;
+
+			$options['zoom'] = $multipleAssocArray['zoom'] === "1" ?
+				true : false;
+			
+			$wmc->mergeWmsArray($wmsArray, $options);
+			$wmsArray = array();
+			$multipleAssocArray = array();
+		}
+		else {
+			$currentWms = new wms();
+			if(is_numeric($key)) {
+				//get WMS by URL
+				if (is_string($val)) {
+					$currentWms->createObjFromXML($val);
+				}
+				//get WMS by ID
+				if (is_numeric($val)) {
+					$currentWms->createObjFromDBNoGui($val);
+				}
+				array_push($wmsArray, $currentWms);
+				$wmc->mergeWmsArray($wmsArray);
+				$wmsArray = array();
+			} 
+			else {
+				$singleAssocArray[$key] = $val;
+			}
+		}
+	}
+	
+	//get WMS by ID with settings of given application
+	if (array_key_exists('application', $singleAssocArray) && 
+		array_key_exists('id', $singleAssocArray)) {
+		$currentWms = new wms();	
+		$currentWms->createObjFromDB(
+			$singleAssocArray['application'],
+			$singleAssocArray['id']
+		);
+		array_push($wmsArray, $currentWms);
+		$options['visible'] = $singleAssocArray['visible'] === "1" ?
+			true : false;
+		
+		$options['zoom'] = $singleAssocArray['zoom'] === "1" ? true : false;
+
+		$wmc->mergeWmsArray($wmsArray, $options);
+		$wmsArray = array();
+		$singleAssocArray = array();
+	}
+	//get WMS by URL
+	elseif (array_key_exists('url', $singleAssocArray)) {
+		$currentWms = new wms();
+		$currentWms->createObjFromXML($singleAssocArray['url']);
+		array_push($wmsArray, $currentWms);
+		if($singleAssocArray['visible']) {
+			$options['visible'] = $singleAssocArray['visible'] === "1" ?
+				true : false;
+		}
+		if($singleAssocArray['zoom']) {
+			$options['zoom'] = $singleAssocArray['zoom'] === "1" ?
+				true : false;
+		}
+		$wmc->mergeWmsArray($wmsArray, $options);
+		$wmsArray = array();
+		$singleAssocArray = array();
+	}
+}
+
+$inputLayerArray = $getApi->getLayers();
+if ($inputLayerArray) {
+	foreach ($inputLayerArray as $input) {
+		// just make it work for a single layer id
+		$wmsFactory = new UniversalWmsFactory();
+		if (isset($input["application"])) {
+			$wms = $wmsFactory->createLayerFromDb(
+				$input["id"], $input["application"]
+			);
+		}
+		else {
+			$wms = $wmsFactory->createLayerFromDb($input["id"]);
+		}
+		$options = array();
+		if ($input["visible"]) {
+			// this is a hack for the time being:
+			// make WMS visible if it has less than 100000 layers
+			$options["show"] = 100000;
+		}
+		if (isset($input["querylayer"])) {
+			$options["querylayer"] = $input["querylayer"];
+		}
+		$wmc->mergeWmsArray(array($wms), $options);
+
+		// do not use "zoom" attribute of mergeWmsArray,
+		// as this would zoom to the entre WMS.
+		// Here we set extent to the layer extent only.
+		if ($input["zoom"]) {
+				$bboxArray = array();
+				try {
+					$layer = $wms->getLayerById(intval($input["id"]));
+					for ($i = 0; $i < count($layer->layer_epsg); $i++) {
+						$bboxArray[]= Mapbender_bbox::createFromLayerEpsg(
+							$layer->layer_epsg[$i]
+						);
+					}
+					$wmc->mainMap->mergeExtent($bboxArray);
+				}
+				catch (Exception $e) {
+					
+				}
+		}
+	}
+}
+
+$inputFeaturetypeArray = $getApi->getFeaturetypes();
+if ($inputFeaturetypeArray) {
+	$wfsConfIds = array();	
+	foreach ($inputFeaturetypeArray as $input) {
+		array_push($wfsConfIds, $input["id"]);
+	}
+	
+	$wmc->generalExtensionArray['WFSCONFIDSTRING'] = implode(",", array_merge(
+		$wmc->generalExtensionArray['WFSCONFIDSTRING'] ? 
+			explode(",", $wmc->generalExtensionArray['WFSCONFIDSTRING']) :
+			array(),
+		$wfsConfIds
+	));
+}
+
+//workaround to have a fully merged WMC for loading
+
+$xml = $wmc->toXml();
+
+$wmc = new wmc();
+$wmc->createFromXml($xml);
+
+$output = $wmc->wmsToJavaScript();
+
+//workaround for zoom to WMS
+$extent = $wmc->mainMap->getExtent();
+Mapbender::session()->set("mb_myBBOX", $extent->min->x . "," .
+	$extent->min->y . "," . $extent->max->x . "," . $extent->max->y);
+
+$outputString = "";
+for ($i = 0; $i < count($output); $i++) {
+	$outputString .= administration::convertOutgoingString($output[$i]);
+}
+
+$wmcFeaturetypeJson = $wmc->featuretypeConfToJavaScript();
+$wmcFeaturetypeStr = <<<JS
+	Mapbender.events.afterInit.register(function () {
+		$('#body').trigger('addFeaturetypeConfs', [
+			{featuretypeConfObj : $wmcFeaturetypeJson}
+		]);
+	});
+JS;
+
+$outputString .= $wmcFeaturetypeStr;
+
+echo $outputString;
+
+
+Mapbender::session()->delete("addwms_showWMS");
+Mapbender::session()->delete("addwms_zoomToExtent");
+unset($output);
+unset($wmc);
+?>

Deleted: branches/mapbender/http/javascripts/mod_savewmc.js
===================================================================
--- trunk/mapbender/http/javascripts/mod_savewmc.js	2010-09-21 19:35:52 UTC (rev 6926)
+++ branches/mapbender/http/javascripts/mod_savewmc.js	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,371 +0,0 @@
-/**
- * Package: savewmc
- *
- * Description:
- * save workspace as WMC
- * 
- * Files:
- *  - http/javascripts/mod_savewmc.php
- *  - http/javascripts/mod_savewmc.js
- *  - http/php/mod_savewmc_server.php
- *
- * SQL:
- * > INSERT INTO gui_element(fkey_gui_id, e_id, e_pos, e_public, e_comment, 
- * > e_title, e_element, e_src, e_attributes, e_left, e_top, e_width, 
- * > e_height, e_z_index, e_more_styles, e_content, e_closetag, e_js_file, 
- * > e_mb_mod, e_target, e_requires, e_url) VALUES('<gui_id>','savewmc',2,1,
- * > 'save workspace as WMC','Save workspace as web map context document',
- * > 'img','../img/button_blink_red/wmc_save_off.png','',870,60,24,24,1,'',
- * > '','','mod_savewmc.php','','mapframe1','mapframe1',
- * > 'http://www.mapbender.org/index.php/SaveWMC');
- * >
- * > INSERT INTO gui_element_vars(fkey_gui_id, fkey_e_id, var_name, var_value, 
- * > context, var_type) VALUES('<gui_id>', 'savewmc', 'overwrite', '1', '',
- * > 'var');
- * > 
- * > INSERT INTO gui_element_vars(fkey_gui_id, fkey_e_id, var_name, var_value, 
- * > context, var_type) VALUES('<gui_id>', 'savewmc', 'saveInSession', '1', 
- * > '' ,'var');
- *
- * Help:
- * http://www.mapbender.org/index.php/SaveWMC
- *
- * Maintainer:
- * http://www.mapbender.org/User:Christoph_Baudson
- * 
- * 
- * Parameters:
- * 
- * overwrite     - *[optional]* if set to 1, a WMC document is overwritten
- * 					if a WMC with the given name already exists
- * 
- * saveInSession - *[optional]* if set to 1, the state of the client is 
- * 					stored in the session after each map request in
- * 					the target map
- * 
- *
- * License:
- * Copyright (c) 2009, Open Source Geospatial Foundation
- * This program is dual licensed under the GNU General Public License 
- * and Simplified BSD license.  
- * http://svn.osgeo.org/mapbender/trunk/mapbender/license/license.txt
- */
-
-//
-// init element_vars
-//
-var overwrite = options.overwrite || false;
-var saveInSession = typeof options.saveInSession === "undefined" ? 0 : options.saveInSession;
-if (typeof originalI18nObj !== "object") {
-	var originalI18nObj = {};
-}
-if (typeof translatedI18nObj !== "object") {
-	var translatedI18nObj = {};
-}
-
-//
-// button behaviour
-//
-var $this = $(this);
-
-var SaveWmcApi = function () {
-	var that = this;
-
-	this.extensionData = {};
-	
-	this.overwrite = overwrite;
-	
-	this.events = {
-		saved: new Mapbender.Event()
-	};
-	
-	this.setExtensionData = function (obj) {
-		if (typeof obj === "object") {
-			$.extend(this.extensionData, obj);
-		}
-		return this;
-	};
-	
-	this.save = function (obj) {
-		if (typeof obj !== "object") {
-			new Mapbender.Exception("Invalid parameters.");
-			return this;
-		}
-		if (obj.session === true) {
-			sendMapDataToServer("session", 1, function(result, status) {});
-			return this;
-		}
-		if (typeof obj.attributes === "object" && typeof obj.callback === "function") {
-			sendMapDataToServer(obj.attributes, 0, obj.callback);
-		}
-		return this;
-	};
-
-	var sendMapDataToServer = function (attributes, storeInSession, callbackFunction) {
-		var	extensionDataString = "";
-		if (that.extensionData !== null) {
-			extensionDataString = $.toJSON(that.extensionData);
-		}
-	
-		if (storeInSession) {
-			$.ajaxSetup({async:false}); 
-		}
-	
-		//
-		// WORKAROUND....cannot serialize map object,
-		// as it contains a jQuery collection, which is
-		// cyclic.
-		// Removing the $target from the map object before
-		// serialization, and re-appending it afterwards
-		//
-		var $target = [];
-		for (var i = 0; i < mb_mapObj.length; i++) {
-			$target.push(mb_mapObj[i].$target);
-			delete mb_mapObj[i].$target;
-		}
-	    
-		// actual save request
-		var req = new Mapbender.Ajax.Request({
-	        url: "../php/mod_savewmc_server.php",
-	        method: "saveWMC",
-			parameters : {
-			  saveInSession:storeInSession, 
-			  attributes:attributes,
-			  overwrite: overwrite,
-			  extensionData:extensionDataString, 
-			  mapObject:$.toJSON(mb_mapObj)
-			},
-	        callback: function(result, status, message) {
-				callbackFunction(result, status, message);
-				that.events.saved.trigger();
-			}
-	    }); 
-	    req.send();
-
-		//
-		// reversal of above WORKAROUND
-		//
-		for (var i = 0; i < mb_mapObj.length; i++) {
-			mb_mapObj[i].$target = $target[i];
-		}
-	};
-
-	var localize = function () {
-		//
-		// buttons
-		//
-		$("#" + options.id + "_saveWMCForm").dialog('option', 'buttons', getButtons());
-		
-		// title
-		$("#" + options.id + "_saveWMCForm").dialog('option', 'title', translatedI18nObj.title);
-		
-		//
-		// form
-		//
-		var $form = $("#" + options.id + "_saveWMCForm > form > fieldset");
-		$form.children("label").each(function () {
-			var forId = $(this).attr("for");
-			switch (forId) {
-				case options.id + "_wmctype" : 
-					$(this).text(translatedI18nObj.labelNewOrOverwrite).next()
-						.children().eq(0).text(translatedI18nObj.labelNewWmc);
-					break;
-				case options.id + "_wmcname" : 
-					$(this).text(translatedI18nObj.labelName);
-					break;
-				case options.id + "_wmcabstract" : 
-					$(this).text(translatedI18nObj.labelAbstract);
-					break;
-				case options.id + "_wmckeywords" : 
-					$(this).text(translatedI18nObj.labelKeywords);
-					break;
-				case options.id + "_wmckeywords" : 
-					$(this).text(translatedI18nObj.labelKeywords);
-					break;
-			}
-		});
-		var $legend = $form.next().children("legend");
-		$legend.text(translatedI18nObj.labelCategories);
-	};
-
-	this.getExistingWmcData = function (callback) {
-		// get WMC data from server
-		var req = new Mapbender.Ajax.Request({
-			url: "../php/mod_loadwmc_server.php",
-			method: "getWmc",
-			callback: function(obj, result, message){
-				if (!result) {
-					new Mb_exception(message);
-					return;
-				}
-				if (typeof callback === "function") {
-					callback(obj.wmc);
-				}
-			}
-		});
-		req.send();
-	};
-	
-	var createSelectBoxForExistingWmcs = function (obj) {
-		(function () {
-			$select = $("#" + options.id + "_wmctype").empty();
-			$select.removeAttr("disabled");
-			var select = "<option value=''>" + translatedI18nObj.labelNewWmc + "</option>";
-			if (typeof obj === "object" && obj.length) {
-				for (var i = 0; i < obj.length; i++) {
-					var wmc = obj[i];
-					if (wmc.disabled) {
-						continue;
-					}
-					
-					select += "<option value='" + wmc.id + "'>" + 
-						wmc.title + "</option>";
-				}
-			}
-			
-			$select.html(select).change(function () {
-				//
-				// reset fields if new wmc is saved
-				//		
-				if (this.value === "") {
-					$("#" + options.id + "_wmc_id").val("");
-					$("#" + options.id + "_wmcname").val("");
-					$("#" + options.id + "_wmcabstract").val("");
-					$("#" + options.id + "_wmckeywords").val("");
-					$("input[id^='" + options.id + "_wmcinspire_']").removeAttr("checked");
-					return false;
-				}
-				//
-				// set fields according to wmc
-				//
-				for (var i = 0; i < obj.length; i++) {
-					var wmc = obj[i];
-					if (wmc.id === this.value) {
-						$("#" + options.id + "_wmc_id").val(wmc.id);
-						$("#" + options.id + "_wmcname").val(wmc.title);
-						$("#" + options.id + "_wmcabstract").val(wmc.abstract);
-						$("#" + options.id + "_wmckeywords").val(wmc.keywords.join(","));
-						$("input[id^='" + options.id + "_wmcinspire_']").removeAttr("checked");
-						for (var j = 0; j < wmc.categories.length; j++) {
-							var cat = wmc.categories[j];
-							$("#" + options.id + "_wmcinspire_" + cat).attr("checked", "checked");
-						}
-						return false;
-					}
-				}
-			});
-		})();
-	};
-	
-	var getButtons = function () {
-		var buttonObj = {};
-		buttonObj[translatedI18nObj.labelSave] = function() {
-			var inspire_cat = {};
-			var regExp = new RegExp(options.id + "_");
-			$("#" + options.id + "_wmcinspire:checkbox").each(function(){
-				if(!!$(this).attr('checked')) {
-					inspire_cat[$(this).attr('id').replace(regExp, "")] = true;
-				}
-			});
-			var attributes = {};
-			attributes.wmc_id 	= $("#" + options.id + "_wmc_id").val();
-			attributes.title 	= $("#" + options.id + "_wmcname").val();
-			attributes.abstract = $("#" + options.id + "_wmcabstract").val();
-			attributes.keywords = $("#" + options.id + "_wmckeywords").val();
-			attributes.inspirecat = inspire_cat;
-			if (!!attributes.title) {
-				sendMapDataToServer(attributes, 0, (function(result, status, message) {
-					alert(message);
-					$("#" + options.id + "_saveWMCForm form")[0].reset();
-				}));
-			}
-			else{
-				//perfom validation	
-			}
-			$(this).dialog('close');
-		};
-		buttonObj[translatedI18nObj.labelCancel] = function() {
-			$("#" + options.id + "_saveWMCForm form")[0].reset();
-			$(this).dialog('close');
-		};
-		return buttonObj;
-	};
-	
-	var mod_savewmc = function () {
-		that.getExistingWmcData(function (obj) {
-			createSelectBoxForExistingWmcs(obj);
-			$("#" + options.id + "_saveWMCForm").dialog('open');
-		});
-	};
-	
-	//
-	// constructor
-	//
-
-	$this.click(function () {
-		mod_savewmc();
-	}).mouseover(function () {
-		if (options.src) {
-			this.src = options.src.replace(/_off/, "_over");
-		}
-	}).mouseout(function () {
-		if (options.src) {
-			this.src = options.src;
-		}
-	});
-
-	Mapbender.events.init.register(function () {
-		if (saveInSession === 1) {
-			options.$target.each(function () {
-				$(this).mapbender().events.afterMapRequest.register(function () {
-					that.save({
-						session : true
-					});
-				});
-			});
-		}
-	
-		var t = translatedI18nObj;
-		var savewmcHtml = '<div id="' + options.id + '_saveWMCForm" ' + 
-			'title="' + translatedI18nObj.title + '">' + 
-			'<style> fieldset label { display: block; }</style>' + 
-			wmcSaveFormHtml + 
-			'</div>';
-	
-		var $saveWmcDialog = $(savewmcHtml).dialog({
-			bgiframe: true,
-			autoOpen: false,
-			height: 400,
-			width: 500,
-			modal: true,
-			beforeclose: function (event, ui) {
-				try {
-					$saveWmcDialog.parent().effect("transfer", {
-						to: $this
-					}, 300);
-				}
-				catch (exc) {
-					new Mb_warning("jq_ui_effect is missing.");
-				}
-			},
-			buttons: getButtons()
-		});
-	});
-	
-	Mapbender.events.localize.register(function () {
-		Mapbender.modules.i18n.queue(options.id, originalI18nObj, function (translatedObj) {
-			if (typeof translatedObj !== "object") {
-				return;
-			}
-			translatedI18nObj = translatedObj;
-			try {
-				localize();
-			}
-			catch (exc) {
-				new Mapbender.Warning("Error when translating: " . exc.message);
-			}
-		});
-	});
-};
-
-$this.mapbender(new SaveWmcApi());

Copied: branches/mapbender/http/javascripts/mod_savewmc.js (from rev 6929, trunk/mapbender/http/javascripts/mod_savewmc.js)
===================================================================
--- branches/mapbender/http/javascripts/mod_savewmc.js	                        (rev 0)
+++ branches/mapbender/http/javascripts/mod_savewmc.js	2010-09-29 11:31:10 UTC (rev 6957)
@@ -0,0 +1,372 @@
+/**
+ * Package: savewmc
+ *
+ * Description:
+ * save workspace as WMC
+ * 
+ * Files:
+ *  - http/javascripts/mod_savewmc.php
+ *  - http/javascripts/mod_savewmc.js
+ *  - http/php/mod_savewmc_server.php
+ *
+ * SQL:
+ * > INSERT INTO gui_element(fkey_gui_id, e_id, e_pos, e_public, e_comment, 
+ * > e_title, e_element, e_src, e_attributes, e_left, e_top, e_width, 
+ * > e_height, e_z_index, e_more_styles, e_content, e_closetag, e_js_file, 
+ * > e_mb_mod, e_target, e_requires, e_url) VALUES('<gui_id>','savewmc',2,1,
+ * > 'save workspace as WMC','Save workspace as web map context document',
+ * > 'img','../img/button_blink_red/wmc_save_off.png','',870,60,24,24,1,'',
+ * > '','','mod_savewmc.php','','mapframe1','mapframe1',
+ * > 'http://www.mapbender.org/index.php/SaveWMC');
+ * >
+ * > INSERT INTO gui_element_vars(fkey_gui_id, fkey_e_id, var_name, var_value, 
+ * > context, var_type) VALUES('<gui_id>', 'savewmc', 'overwrite', '1', '',
+ * > 'var');
+ * > 
+ * > INSERT INTO gui_element_vars(fkey_gui_id, fkey_e_id, var_name, var_value, 
+ * > context, var_type) VALUES('<gui_id>', 'savewmc', 'saveInSession', '1', 
+ * > '' ,'var');
+ *
+ * Help:
+ * http://www.mapbender.org/index.php/SaveWMC
+ *
+ * Maintainer:
+ * http://www.mapbender.org/User:Christoph_Baudson
+ * 
+ * 
+ * Parameters:
+ * 
+ * overwrite     - *[optional]* if set to 1, a WMC document is overwritten
+ * 					if a WMC with the given name already exists
+ * 
+ * saveInSession - *[optional]* if set to 1, the state of the client is 
+ * 					stored in the session after each map request in
+ * 					the target map
+ * 
+ *
+ * License:
+ * Copyright (c) 2009, Open Source Geospatial Foundation
+ * This program is dual licensed under the GNU General Public License 
+ * and Simplified BSD license.  
+ * http://svn.osgeo.org/mapbender/trunk/mapbender/license/license.txt
+ */
+
+//
+// init element_vars
+//
+var overwrite = options.overwrite || false;
+var saveInSession = typeof options.saveInSession === "undefined" ?
+	0 : options.saveInSession;
+if (typeof originalI18nObj !== "object") {
+	var originalI18nObj = {};
+}
+if (typeof translatedI18nObj !== "object") {
+	var translatedI18nObj = {};
+}
+
+//
+// button behaviour
+//
+var $this = $(this);
+
+var SaveWmcApi = function () {
+	var that = this;
+
+	this.extensionData = {};
+	
+	this.overwrite = overwrite;
+	
+	this.events = {
+		saved: new Mapbender.Event()
+	};
+	
+	this.setExtensionData = function (obj) {
+		if (typeof obj === "object") {
+			$.extend(this.extensionData, obj);
+		}
+		return this;
+	};
+	
+	this.save = function (obj) {
+		if (typeof obj !== "object") {
+			new Mapbender.Exception("Invalid parameters.");
+			return this;
+		}
+		if (obj.session === true) {
+			sendMapDataToServer("session", 1, function(result, status) {});
+			return this;
+		}
+		if (typeof obj.attributes === "object" && typeof obj.callback === "function") {
+			sendMapDataToServer(obj.attributes, 0, obj.callback);
+		}
+		return this;
+	};
+
+	var sendMapDataToServer = function (attributes, storeInSession, callbackFunction) {
+		var	extensionDataString = "";
+		if (that.extensionData !== null) {
+			extensionDataString = $.toJSON(that.extensionData);
+		}
+	
+		if (storeInSession) {
+			$.ajaxSetup({async:false}); 
+		}
+	
+		//
+		// WORKAROUND....cannot serialize map object,
+		// as it contains a jQuery collection, which is
+		// cyclic.
+		// Removing the $target from the map object before
+		// serialization, and re-appending it afterwards
+		//
+		var $target = [];
+		for (var i = 0; i < mb_mapObj.length; i++) {
+			$target.push(mb_mapObj[i].$target);
+			delete mb_mapObj[i].$target;
+		}
+	    
+		// actual save request
+		var req = new Mapbender.Ajax.Request({
+	        url: "../php/mod_savewmc_server.php",
+	        method: "saveWMC",
+			parameters : {
+			  saveInSession:storeInSession, 
+			  attributes:attributes,
+			  overwrite: overwrite,
+			  extensionData:extensionDataString, 
+			  mapObject:$.toJSON(mb_mapObj)
+			},
+	        callback: function(result, status, message) {
+				callbackFunction(result, status, message);
+				that.events.saved.trigger();
+			}
+	    }); 
+	    req.send();
+
+		//
+		// reversal of above WORKAROUND
+		//
+		for (var i = 0; i < mb_mapObj.length; i++) {
+			mb_mapObj[i].$target = $target[i];
+		}
+	};
+
+	var localize = function () {
+		//
+		// buttons
+		//
+		$("#" + options.id + "_saveWMCForm").dialog('option', 'buttons', getButtons());
+		
+		// title
+		$("#" + options.id + "_saveWMCForm").dialog('option', 'title', translatedI18nObj.title);
+		
+		//
+		// form
+		//
+		var $form = $("#" + options.id + "_saveWMCForm > form > fieldset");
+		$form.children("label").each(function () {
+			var forId = $(this).attr("for");
+			switch (forId) {
+				case options.id + "_wmctype" : 
+					$(this).text(translatedI18nObj.labelNewOrOverwrite).next()
+						.children().eq(0).text(translatedI18nObj.labelNewWmc);
+					break;
+				case options.id + "_wmcname" : 
+					$(this).text(translatedI18nObj.labelName);
+					break;
+				case options.id + "_wmcabstract" : 
+					$(this).text(translatedI18nObj.labelAbstract);
+					break;
+				case options.id + "_wmckeywords" : 
+					$(this).text(translatedI18nObj.labelKeywords);
+					break;
+				case options.id + "_wmckeywords" : 
+					$(this).text(translatedI18nObj.labelKeywords);
+					break;
+			}
+		});
+		var $legend = $form.next().children("legend");
+		$legend.text(translatedI18nObj.labelCategories);
+	};
+
+	this.getExistingWmcData = function (callback) {
+		// get WMC data from server
+		var req = new Mapbender.Ajax.Request({
+			url: "../php/mod_loadwmc_server.php",
+			method: "getWmc",
+			callback: function(obj, result, message){
+				if (!result) {
+					new Mb_exception(message);
+					return;
+				}
+				if (typeof callback === "function") {
+					callback(obj.wmc);
+				}
+			}
+		});
+		req.send();
+	};
+	
+	var createSelectBoxForExistingWmcs = function (obj) {
+		(function () {
+			$select = $("#" + options.id + "_wmctype").empty();
+			$select.removeAttr("disabled");
+			var select = "<option value=''>" + translatedI18nObj.labelNewWmc + "</option>";
+			if (typeof obj === "object" && obj.length) {
+				for (var i = 0; i < obj.length; i++) {
+					var wmc = obj[i];
+					if (wmc.disabled) {
+						continue;
+					}
+					
+					select += "<option value='" + wmc.id + "'>" + 
+						wmc.title + "</option>";
+				}
+			}
+			
+			$select.html(select).change(function () {
+				//
+				// reset fields if new wmc is saved
+				//		
+				if (this.value === "") {
+					$("#" + options.id + "_wmc_id").val("");
+					$("#" + options.id + "_wmcname").val("");
+					$("#" + options.id + "_wmcabstract").val("");
+					$("#" + options.id + "_wmckeywords").val("");
+					$("input[id^='" + options.id + "_wmcinspire_']").removeAttr("checked");
+					return false;
+				}
+				//
+				// set fields according to wmc
+				//
+				for (var i = 0; i < obj.length; i++) {
+					var wmc = obj[i];
+					if (wmc.id === this.value) {
+						$("#" + options.id + "_wmc_id").val(wmc.id);
+						$("#" + options.id + "_wmcname").val(wmc.title);
+						$("#" + options.id + "_wmcabstract").val(wmc.abstract);
+						$("#" + options.id + "_wmckeywords").val(wmc.keywords.join(","));
+						$("input[id^='" + options.id + "_wmcinspire_']").removeAttr("checked");
+						for (var j = 0; j < wmc.categories.length; j++) {
+							var cat = wmc.categories[j];
+							$("#" + options.id + "_wmcinspire_" + cat).attr("checked", "checked");
+						}
+						return false;
+					}
+				}
+			});
+		})();
+	};
+	
+	var getButtons = function () {
+		var buttonObj = {};
+		buttonObj[translatedI18nObj.labelSave] = function() {
+			var inspire_cat = {};
+			var regExp = new RegExp(options.id + "_");
+			$("#" + options.id + "_wmcinspire:checkbox").each(function(){
+				if(!!$(this).attr('checked')) {
+					inspire_cat[$(this).attr('id').replace(regExp, "")] = true;
+				}
+			});
+			var attributes = {};
+			attributes.wmc_id 	= $("#" + options.id + "_wmc_id").val();
+			attributes.title 	= $("#" + options.id + "_wmcname").val();
+			attributes.abstract = $("#" + options.id + "_wmcabstract").val();
+			attributes.keywords = $("#" + options.id + "_wmckeywords").val();
+			attributes.inspirecat = inspire_cat;
+			if (!!attributes.title) {
+				sendMapDataToServer(attributes, 0, (function(result, status, message) {
+					alert(message);
+					$("#" + options.id + "_saveWMCForm form")[0].reset();
+				}));
+			}
+			else{
+				//perfom validation	
+			}
+			$(this).dialog('close');
+		};
+		buttonObj[translatedI18nObj.labelCancel] = function() {
+			$("#" + options.id + "_saveWMCForm form")[0].reset();
+			$(this).dialog('close');
+		};
+		return buttonObj;
+	};
+	
+	var mod_savewmc = function () {
+		that.getExistingWmcData(function (obj) {
+			createSelectBoxForExistingWmcs(obj);
+			$("#" + options.id + "_saveWMCForm").dialog('open');
+		});
+	};
+	
+	//
+	// constructor
+	//
+
+	$this.click(function () {
+		mod_savewmc();
+	}).mouseover(function () {
+		if (options.src) {
+			this.src = options.src.replace(/_off/, "_over");
+		}
+	}).mouseout(function () {
+		if (options.src) {
+			this.src = options.src;
+		}
+	});
+
+	Mapbender.events.init.register(function () {
+		if (saveInSession === 1) {
+			options.$target.each(function () {
+				$(this).mapbender().events.afterMapRequest.register(function () {
+					that.save({
+						session : true
+					});
+				});
+			});
+		}
+	
+		var t = translatedI18nObj;
+		var savewmcHtml = '<div id="' + options.id + '_saveWMCForm" ' + 
+			'title="' + translatedI18nObj.title + '">' + 
+			'<style> fieldset label { display: block; }</style>' + 
+			wmcSaveFormHtml + 
+			'</div>';
+	
+		var $saveWmcDialog = $(savewmcHtml).dialog({
+			bgiframe: true,
+			autoOpen: false,
+			height: 400,
+			width: 500,
+			modal: true,
+			beforeclose: function (event, ui) {
+				try {
+					$saveWmcDialog.parent().effect("transfer", {
+						to: $this
+					}, 300);
+				}
+				catch (exc) {
+					new Mb_warning("jq_ui_effect is missing.");
+				}
+			},
+			buttons: getButtons()
+		});
+	});
+	
+	Mapbender.events.localize.register(function () {
+		Mapbender.modules.i18n.queue(options.id, originalI18nObj, function (translatedObj) {
+			if (typeof translatedObj !== "object") {
+				return;
+			}
+			translatedI18nObj = translatedObj;
+			try {
+				localize();
+			}
+			catch (exc) {
+				new Mapbender.Warning("Error when translating: " . exc.message);
+			}
+		});
+	});
+};
+
+$this.mapbender(new SaveWmcApi());

Deleted: branches/mapbender/http/javascripts/mod_searchCSW_ajax_button.php
===================================================================
--- trunk/mapbender/http/javascripts/mod_searchCSW_ajax_button.php	2010-09-21 19:35:52 UTC (rev 6926)
+++ branches/mapbender/http/javascripts/mod_searchCSW_ajax_button.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,86 +0,0 @@
-<?php
-# $Id: mod_addWmsFromFilteredList_button.php 6834 2010-08-30 08:52:00Z verenadiewald $
-# http://www.mapbender.org/Add_WMS_from_filtered_list_%28AJAX%29
-# 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__)."/../php/mb_validatePermission.php");
-
-echo "var searchCSWId = '" . $e_id . "';";
-?>
-var searchCSW_title;
-var searchCSWPopup;
-
-eventInit.register(function () {
-	var $searchCSWButton = $("#" + searchCSWId);
-	searchCSW_title = $searchCSWButton.get(0).title;
-	$searchCSWButton.click(function () {
-		var $searchCSWButton = $("#" + searchCSWId);
-		searchCSW_title = $searchCSWButton.get(0).title;
-		searchCSW_showPopup();
-	});
-});
-
-var searchCSW_showPopup = function () {
-	if($('.searchCSWIframe').size() > 0) {
-		$('.searchCSWIframe').dialog('destroy');
-	}
-	var $searchCSWPopup = $('<div class="searchCSWIframe"><iframe style="width:100%;height:98%;" src="../javascripts/mod_searchCSW_ajax.php?<?php 
-		
-	echo session_name() . '=' . session_id() . '&';
-	echo "guiID=" . $gui_id . '&';
-	echo "elementID=" . $e_id;
-	
-		?>"></iframe></div>');
-	$searchCSWPopup.dialog({
-		title : searchCSW_title,
-		bgiframe: true,
-		autoOpen: true,
-		modal: false,
-		width: 720,
-		height: 600,
-		pos: [300,100]
-	});
-};
-
-eventLocalize.register(function () {
-	if($('.searchCSWIframe').size() > 0) {
-		$('.searchCSWIframe').dialog('destroy');
-	}
-});
-
-eventInit.register(function () {
-	mod_searchCSW_init();
-});
-
-var mod_searchCSW_img = new Image(); 
-mod_searchCSW_img.src = "<?php  echo $e_src;  ?>";
-var mod_searchCSW_img_over = new Image(); 
-mod_searchCSW_img_over.src = "<?php  echo preg_replace("/_off/","_over",$e_src);  ?>";
-
-function mod_searchCSW_init() {
-	var obj = document.getElementById(searchCSWId);
-	obj.src = mod_searchCSW_img.src;
-	obj.onmouseover = new Function("mod_searchCSW_over()");
-	obj.onmouseout = new Function("mod_searchCSW_out()");
-}
-function mod_searchCSW_over(){
-	document.getElementById(searchCSWId).src = mod_searchCSW_img_over.src;
-}
-
-function mod_searchCSW_out(){
-	document.getElementById(searchCSWId).src = mod_searchCSW_img.src;
-}
\ No newline at end of file

Copied: branches/mapbender/http/javascripts/mod_searchCSW_ajax_button.php (from rev 6953, trunk/mapbender/http/javascripts/mod_searchCSW_ajax_button.php)
===================================================================
--- branches/mapbender/http/javascripts/mod_searchCSW_ajax_button.php	                        (rev 0)
+++ branches/mapbender/http/javascripts/mod_searchCSW_ajax_button.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -0,0 +1,86 @@
+<?php
+# $Id: mod_addWmsFromFilteredList_button.php 6834 2010-08-30 08:52:00Z verenadiewald $
+# http://www.mapbender.org/Add_WMS_from_filtered_list_%28AJAX%29
+# 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__)."/../php/mb_validatePermission.php");
+
+echo "var searchCSWId = '" . $e_id . "';";
+?>
+var searchCSW_title;
+var searchCSWPopup;
+
+eventInit.register(function () {
+	var $searchCSWButton = $("#" + searchCSWId);
+	searchCSW_title = $searchCSWButton.get(0).title;
+	$searchCSWButton.click(function () {
+		var $searchCSWButton = $("#" + searchCSWId);
+		searchCSW_title = $searchCSWButton.get(0).title;
+		searchCSW_showPopup();
+	});
+});
+
+var searchCSW_showPopup = function () {
+	if($('.searchCSWIframe').size() > 0) {
+		$('.searchCSWIframe').dialog('destroy');
+	}
+	var $searchCSWPopup = $('<div class="searchCSWIframe"><iframe style="border-style:none;width:100%;height:98%;" src="../javascripts/mod_searchCSW_ajax.php?<?php 
+		
+	echo session_name() . '=' . session_id() . '&';
+	echo "guiID=" . $gui_id . '&';
+	echo "elementID=" . $e_id;
+	
+		?>"></iframe></div>');
+	$searchCSWPopup.dialog({
+		title : searchCSW_title,
+		bgiframe: true,
+		autoOpen: true,
+		modal: false,
+		width: 720,
+		height: 600,
+		pos: [300,100]
+	});
+};
+
+eventLocalize.register(function () {
+	if($('.searchCSWIframe').size() > 0) {
+		$('.searchCSWIframe').dialog('destroy');
+	}
+});
+
+eventInit.register(function () {
+	mod_searchCSW_init();
+});
+
+var mod_searchCSW_img = new Image(); 
+mod_searchCSW_img.src = "<?php  echo $e_src;  ?>";
+var mod_searchCSW_img_over = new Image(); 
+mod_searchCSW_img_over.src = "<?php  echo preg_replace("/_off/","_over",$e_src);  ?>";
+
+function mod_searchCSW_init() {
+	var obj = document.getElementById(searchCSWId);
+	obj.src = mod_searchCSW_img.src;
+	obj.onmouseover = new Function("mod_searchCSW_over()");
+	obj.onmouseout = new Function("mod_searchCSW_out()");
+}
+function mod_searchCSW_over(){
+	document.getElementById(searchCSWId).src = mod_searchCSW_img_over.src;
+}
+
+function mod_searchCSW_out(){
+	document.getElementById(searchCSWId).src = mod_searchCSW_img.src;
+}
\ No newline at end of file

Deleted: branches/mapbender/http/javascripts/wms.js
===================================================================
--- trunk/mapbender/http/javascripts/wms.js	2010-09-21 19:35:52 UTC (rev 6926)
+++ branches/mapbender/http/javascripts/wms.js	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,890 +0,0 @@
-/* 
- * $Id: map_obj.js 2413 2008-04-23 16:21:04Z christoph $
- * COPYRIGHT: (C) 2001 by ccgis. This program is free software under the GNU General Public
- * License (>=v2). Read the file gpl.txt that comes with Mapbender for details. 
- */
-
-//global variables
-var wms = [];
-var wms_layer_count = 0;
-
-/**
- * global function to add wms to the wms-object
- * 
- * @param {String} wms_id the unique id of the wms 
- * @param {String} wms_version the version assumed from capabilities
- * @param {String} wms_title the title of the wms
- * @param {String} wms_abstract the abstract of the wms
- * @param {String} wms_getmap the url for map requests
- * @param {String} wms_getfeatureinfo the url for featureInof requests
- * @param {String} wms_getlegendurl the url for legend requests
- * @param {String} wms_filter a filter (deprecated)
- * @param {String} gui_wms_mapformat the image-format in the actual gui
- * @param {String} gui_wms_featureinfoformat the current format for featureInfos
- * @param {String} gui_wms_exceptionformat the exceptionformat for map requests
- * @param {String} gui_wms_epsg the current srs
- * @param {Integer} gui_wms_visible the visibility of this service
- * @param {Integer} gui_wms_opacity the initial display opacity in percent
- * @param {String} gui_wms_sldurl url to an actual sld
- */
-function add_wms(
-			wms_id,
-			wms_version,
-			wms_title,
-			wms_abstract,
-			wms_getmap,
-			wms_getfeatureinfo,
-			wms_getlegendurl,
-			wms_filter,
-			gui_wms_mapformat,
-			gui_wms_featureinfoformat,
-			gui_wms_exceptionformat,
-			gui_wms_epsg,
-			gui_wms_visible,
-			gui_wms_opacity,
-			gui_wms_sldurl){
-					wms[wms.length] = new wms_const( 
-					wms_id,
-					wms_version,
-					wms_title,
-					wms_abstract,
-					wms_getmap,
-					wms_getfeatureinfo,
-					wms_getlegendurl,
-					wms_filter,
-					gui_wms_mapformat,
-					gui_wms_featureinfoformat,
-					gui_wms_exceptionformat,
-					gui_wms_epsg,
-					parseInt(gui_wms_visible, 10),
-					parseInt(gui_wms_opacity),
-					gui_wms_sldurl);
-					wms_layer[wms.length - 1] = [];
-}
-/**
- * @class A class representing the wms
- *
- * @constructor
- * @param {String} wms_id the unique id of the wms 
- * @param {String} wms_version the version assumed from capabilities
- * @param {String} wms_title the title of the wms
- * @param {String} wms_abstract the abstract of the wms
- * @param {String} wms_getmap the url for map requests
- * @param {String} wms_getfeatureinfo the url for featureInof requests
- * @param {String} wms_getlegendurl the url for legend requests
- * @param {String} wms_filter a filter (deprecated)
- * @param {String} gui_wms_mapformat the image-format in the actual gui
- * @param {String} gui_wms_featureinfoformat the current format for featureInfos
- * @param {String} gui_wms_exceptionformat the exceptionformat for map requests
- * @param {String} gui_wms_epsg the current srs
- * @param {String} gui_wms_visible the visibility of this service
- * @param {Integer} gui_wms_opacity the initial display opacity in percent
- * @param {String} gui_wms_sldurl url to an actual sld
- * 
- */
-function wms_const(  
-			wms_id,
-			wms_version,
-			wms_title,
-			wms_abstract,
-			wms_getmap,
-			wms_getfeatureinfo,
-		    wms_getlegendurl,
-			wms_filter,
-			gui_wms_mapformat,
-			gui_wms_featureinfoformat,
-			gui_wms_exceptionformat,
-			gui_wms_epsg,
-			gui_wms_visible,
-			gui_wms_opacity,
-			gui_wms_sldurl){
-   
-	if (!wms_id) {
-		var id_ok = false;
-		while (id_ok === false) {
-			wms_id = "a"+Math.round(10000*Math.random());
-			id_ok = true;
-			for (var i=0; i < wms.length && id_ok === true; i++) {
-				if (wms_id == wms[i].wms_id) { 
-					id_ok = false;
-				}
-			}
-		}
-	}
-	
-	this.wms_id = wms_id;
-	this.wms_version = wms_version;
-	this.wms_title = wms_title;
-	this.wms_currentTitle = wms_title;
-	this.wms_abstract = wms_abstract;
-	this.wms_getmap = wms_getmap;
-	this.wms_getfeatureinfo = wms_getfeatureinfo;
-	this.wms_getlegendurl = wms_getlegendurl;
-	this.wms_filter = wms_filter;
-	this.data_type = [];
-	this.data_format = [];
-	this.objLayer = [];
-	this.gui_wms_mapformat = gui_wms_mapformat;
-	this.gui_wms_featureinfoformat = gui_wms_featureinfoformat;
-	this.gui_wms_exceptionformat = gui_wms_exceptionformat;
-	this.gui_wms_epsg = gui_wms_epsg;
-	this.gui_wms_visible = gui_wms_visible;
-	this.gui_epsg = [];
-	this.gui_epsg_supported = [];
-	this.gui_minx = [];
-	this.gui_miny = [];
-	this.gui_maxx = [];
-	this.gui_maxy = [];
-
-	// opacity version 
-	this.gui_wms_mapopacity = gui_wms_opacity/100;
-	// sld version
-	this.gui_wms_sldurl = gui_wms_sldurl;    
-
-	this.setCrs = function (options) {
-		var crsIndex = $.inArray(options.source.srsCode, this.gui_epsg);
-		if (crsIndex !== -1 && 
-			typeof this.gui_minx[crsIndex] === 'number' &&
-			typeof this.gui_miny[crsIndex] === 'number' &&	
-			typeof this.gui_maxx[crsIndex] === 'number' &&
-			typeof this.gui_maxy[crsIndex] === 'number'
-		) {
-			var sw = new Proj4js.Point(
-				this.gui_minx[crsIndex], 
-				this.gui_miny[crsIndex]
-			);
-			var ne = new Proj4js.Point(
-				this.gui_maxx[crsIndex], 
-				this.gui_maxy[crsIndex]
-			);
-			sw = Proj4js.transform(options.source, options.dest, sw);
-			ne = Proj4js.transform(options.source, options.dest, ne);
-			var extent = new Mapbender.Extent(sw.x, sw.y, ne.x, ne.y);
-			this.setBoundingBoxBySrs(options.dest.srsCode, extent);
-		}
-		else {
-			this.setBoundingBoxBySrs(options.dest.srsCode);
-		}
-	};
-	
-	this.setBoundingBoxBySrs = function (srs, ext) {
-		for (var i = 0; i < this.gui_epsg.length && ext !== undefined; i++) {
-			if (srs == this.gui_epsg[i]) {
-				this.gui_minx[i] = parseFloat(ext.minx);
-				this.gui_miny[i] = parseFloat(ext.miny);
-				this.gui_maxx[i] = parseFloat(ext.maxx);
-				this.gui_maxy[i] = parseFloat(ext.maxy);
-				return i;
-			}
-		}
-		this.gui_epsg.push(srs);
-		this.gui_epsg_supported.push(false);
-		
-		if (ext !== undefined) {
-			this.gui_minx.push(ext.minx);
-			this.gui_miny.push(ext.miny);
-			this.gui_maxx.push(ext.maxx);
-			this.gui_maxy.push(ext.maxy);
-		}
-		
-		return this.gui_epsg.length - 1;
-	};
-}
-
-wms_const.prototype.getBoundingBoxBySrs = function (srs) {
-	for (var i = 0; i < this.gui_epsg.length; i++) {
-		if (srs == this.gui_epsg[i]) {
-			var bbox_minx = parseFloat(this.gui_minx[i]);
-			var bbox_miny = parseFloat(this.gui_miny[i]);
-			var bbox_maxx = parseFloat(this.gui_maxx[i]);
-			var bbox_maxy = parseFloat(this.gui_maxy[i]);
-			if (bbox_minx !== null && !isNaN(bbox_minx) &&
-				bbox_miny !== null && !isNaN(bbox_miny) &&
-				bbox_maxx !== null && !isNaN(bbox_maxx) &&
-				bbox_maxy !== null && !isNaN(bbox_maxy)
-			) {
-				return new Extent(bbox_minx, bbox_miny, bbox_maxx, bbox_maxy);
-			}
-		}
-	}
-	return null;
-};
-
-/**
- * rephrases the featureInfoRequest
- *
- * @param {Object} mapObj the mapbender mapObject of the wms  
- * @param {Point} clickPoint map-click position {@link Point}
- * @return featureInfoRequest, onlineresource + params
- * @type string
- */
-wms_const.prototype.getFeatureInfoRequest = function(mapObj, clickPoint){	
-	
-	//check layers and querylayers first 
-	var layers = this.getLayers(mapObj);
-	var querylayers = this.getQuerylayers(mapObj);
-	
-	if(!layers || !querylayers){
-		return false;
-	}
-	
-	var rq = this.wms_getfeatureinfo;
-	rq += mb_getConjunctionCharacter(this.wms_getfeatureinfo);
-	if(this.wms_version === "1.0.0"){
-		rq += "WMTVER=" + this.wms_version + "&REQUEST=feature_info";
-	}
-	else{
-		rq += "VERSION=" + this.wms_version + "&REQUEST=GetFeatureInfo&SERVICE=WMS";
-	}
-	
-	rq += "&LAYERS=" + layers.join(",");
-	rq += "&QUERY_LAYERS=" + querylayers.join(",");
-	rq += "&WIDTH=" + mapObj.getWidth();
-	rq += "&HEIGHT=" + mapObj.getHeight();
-	rq += "&SRS=" + mapObj.getSRS();
-	rq += "&BBOX=" + mapObj.getExtent();
-	rq += "&STYLES=" + this.getLayerstyles(mapObj).join(",");
-	rq += "&FORMAT=" + this.gui_wms_mapformat;
-	rq += "&INFO_FORMAT=" + this.gui_wms_featureinfoformat;
-	rq += "&EXCEPTIONS=application/vnd.ogc.se_xml";
-	rq += "&X=" + clickPoint.x;
-	rq += "&Y=" + clickPoint.y;
-	if(mb_feature_count > 0){             
-		rq += "&FEATURE_COUNT="+mb_feature_count;
-	}
-	rq += "&";
-	// add vendor-specific
-	var currentWms = this;
-	for (var v = 0; v < mb_vendorSpecific.length; v++) {
-		var functionName = 'setFeatureInfoRequest';
-		var currentWms_wms_title = this.wms_title;
-		var vendorSpecificString = eval(mb_vendorSpecific[v]);
-		// if eval doesn't evaluate a function, the result is undefined.
-		// Sometimes it is necessary not to evaluate a function, for
-		// example if you want to change a variable from the current
-		// scope (see mod_addSLD.php) 
-		if (typeof(vendorSpecificString) != "undefined") {
-			rq += vendorSpecificString + "&";
-			try {
-				if (this.wms_title == removeLayerAndStylesAffectedWMSTitle) {
-					rq = url.replace(/LAYERS=[^&]*&/, '');
-					rq = url.replace(/STYLES=[^&]*&/, '');
-				}
-			}
-			catch (exc) {
-				new Mb_warning(exc.message);
-			}
-		}
-	}
-	return rq;
-};
-
-/**
- * sets Opacity of WMS
- * 
- * @param {Integer} new opacity percentage value
- */
-wms_const.prototype.setOpacity = function(opacity){
-	//calc new opacity
-	this.gui_wms_mapopacity = parseInt(opacity)/100;
-	if(this.gui_wms_mapopacity>1||isNaN(this.gui_wms_mapopacity))
-		this.gui_wms_mapopacity=1;
-	if(this.gui_wms_mapopacity<0)
-		this.gui_wms_mapopacity=0;
-		
-	if (this.gui_wms_visible > 0) {
-
-		//get div id
-		var divId = null;
-		for (var i=0; i < wms.length; i++) {
-			if (this.wms_id == wms[i].wms_id) { 
-				var divId = 'div_'+i;
-				break;
-			}
-		}
-		if(!divId)
-			return;	
-		
-		//TODO: check if mapframe1 is the right mapframe
-		var ind = getMapObjIndexByName("mapframe1");
-		var el = mb_mapObj[ind].getDomElement();
-		wmsImage = el.ownerDocument.getElementById(divId);
-		if (wmsImage != null) {
-			wmsImage.style.opacity = this.gui_wms_mapopacity;
-			wmsImage.style.MozOpacity = this.gui_wms_mapopacity;
-			wmsImage.style.KhtmlOpacity = this.gui_wms_mapopacity;
-			wmsImage.style.filter = "alpha(opacity=" + this.gui_wms_mapopacity*100 + ")";
-		}
-	}
-}
-
-/**
- * get all visible layers
- *
- * @return array of layernames 
- * @type string[]
- */
-wms_const.prototype.getLayers = function(mapObj){
-	var scale = null;
-	if (arguments.length === 2) {
-		scale = arguments[1];
-	}
-	try {
-		//visibility of the wms
-		var wmsIsVisible = (this.gui_wms_visible > 0);
-		if(!wmsIsVisible){
-			return [];
-		}
-		visibleLayers = [];
-		for(var i=0; i< this.objLayer.length; i++){
-			var isVisible = (this.objLayer[i].gui_layer_visible === 1);
-			var hasNoChildren = (!this.objLayer[i].has_childs);
-			if (isVisible && hasNoChildren){
-				if(this.objLayer[i].checkScale(mapObj, scale)){
-					visibleLayers.push(this.objLayer[i].layer_name);
-				}
-			}
-		}
-		if(visibleLayers.length === 0){
-			return [];
-		}
-		return visibleLayers;
-	}
-	catch (e) {
-		alert(e);
-	}
-	return [];
-};
-
-/**
- * get the actual style of all visible layers
- *
- * @return commaseparated list of actual layerstyles
- * @type string
- */
-wms_const.prototype.getLayerstyles = function(mapObj){
-	
-	var layers = this.getLayers(mapObj);
-	var layerstyles = '';
-	var styles = [];
-	if(layers){
-		for(i = 0; i < layers.length; i++){
-			var style = this.getCurrentStyleByLayerName(layers[i]);
-			if(!style){
-				style = '';
-			}
-			styles.push(style);
-		}
-		return styles;
-	}
-	return false;
-};
-
-/**
- * check if layer is parentLayer
- *
- * @param layername
- * @return the parent value of the given layer
- * @type integer
- */
-wms_const.prototype.checkLayerParentByLayerName = function(layername){
-	for(var i=0; i< this.objLayer.length; i++){
-		if(this.objLayer[i].layer_name == layername){
-			return this.objLayer[i].layer_parent;
-		}
-	}
-};
-
-/**
- * get the title of the current layer
- *
- * @param layername
- * @return the title of the given layer
- * @type string
- */
-wms_const.prototype.getTitleByLayerName = function(layername){
-	for(var i=0; i< this.objLayer.length; i++){
-		if(this.objLayer[i].layer_name == layername){
-			return this.objLayer[i].layer_title;
-		}
-	}
-};
-
-wms_const.prototype.getLayerByLayerName = function(layername){
-	for(var i=0; i< this.objLayer.length; i++){
-		if(this.objLayer[i].layer_name === layername){
-			return this.objLayer[i];
-		}
-	}
-};
-
-/**
- * get the current style of the layer
- *
- * @param layername
- * @return the stylename of the given layer
- * @type string
- */
-wms_const.prototype.getCurrentStyleByLayerName = function(layername){
-	for(var i=0; i< this.objLayer.length; i++){
-		var currentLayer = this.objLayer[i];
-		if (currentLayer.layer_name === layername) {
-			if (currentLayer.gui_layer_style === '' || currentLayer.gui_layer_style === null){
-				return "default";
-//				return false;
-			}
-			else{
-				return currentLayer.gui_layer_style;	
-			}
-		}
-	}
-	return false;
-};
-
-/**
- * get the legendurl of the gui layer style
- *
- * @param stylename
- * @return the legendurl of the given style
- * @type string
- */
-wms_const.prototype.getLegendUrlByGuiLayerStyle = function(layername,guiLayerStyle){
-	for(var i=0; i< this.objLayer.length; i++){
-		if(this.objLayer[i].layer_name == layername){
-			if(this.objLayer[i].layer_style.length === 0){
-				return false;
-			}
-			for(var k=0; k< this.objLayer[i].layer_style.length; k++){
-				var legendUrl = '';
-				if(guiLayerStyle == '' && k == 0){
-					legendUrl = this.objLayer[i].layer_style[k].legendurl;
-					if (this.gui_wms_sldurl !== "") {
-					 		legendUrl += "&SLD="+escape(this.gui_wms_sldurl);
-					}				
-					if(legendUrl !=='' && legendUrl !== null && typeof(legendUrl) != 'undefined'){
-						return legendUrl;
-					}
-					else {
-						return false;
-					}
-				}else if(this.objLayer[i].layer_style[k].name == guiLayerStyle){
-					legendUrl = this.objLayer[i].layer_style[k].legendurl;
-					if (this.gui_wms_sldurl !== "") {
-					 		legendUrl += "&SLD="+escape(this.gui_wms_sldurl);
-					}				
-					if(legendUrl !=='' && legendUrl !== null && typeof(legendUrl) != 'undefined'){
-						return legendUrl;
-					}
-					else {
-						return false;
-					}
-				}
-			}
-		}
-	}
-	return false;
-};
-
-/**
- * get all querylayers
- *
- * @return array of layernames
- * @type string[]
- */
-wms_const.prototype.getQuerylayers = function(map){
-	var currentScale = map.getScale();
-	queryLayers = [];
-	for(var i=0; i< this.objLayer.length; i++){
-		
-		var isVisible = this.objLayer[i].gui_layer_visible === 1 && 
-			 this.objLayer[i].gui_layer_minscale <= currentScale && 
-			(this.objLayer[i].gui_layer_maxscale >= currentScale ||
-			this.objLayer[i].gui_layer_maxscale === 0);
-		if(this.objLayer[i].gui_layer_querylayer === 1 && !this.objLayer[i].has_childs && isVisible){
-			queryLayers.push(this.objLayer[i].layer_name);
-		}
-	}
-	if(queryLayers.length === 0){
-		return false;
-	}
-	return queryLayers;
-};
-
-/**
- * get a layer Object by layer_pos
- * 
- * @param int payer_pos layer_pos of layer you want to get
- * @return object layer
- */
-
-wms_const.prototype.getLayerByLayerPos = function(layer_pos){
-	for(var i=0;i<this.objLayer.length;i++){
-		if(this.objLayer[i].layer_pos == layer_pos) {
-			return this.objLayer[i];
-		}
-	}
-	return null;
-};
-
-wms_const.prototype.getLayerById = function(id){
-	for(var i=0;i<this.objLayer.length;i++){
-		if(parseInt(this.objLayer[i].layer_uid, 10) === parseInt(id,10)) {
-			return this.objLayer[i];
-		}
-	}
-	return null;
-};
-/**
- * get the state of sublayers from a specified layer
- * 
- * @param int layer_id of the parent layer
- * @param String type "visible" or "querylayer"
- * @return int -1 if state differs else the state
- */
-
-wms_const.prototype.getSublayerState = function(layer_id, type){
-	var i;
-	var state=-1,value;
-	for(i = 0; i < this.objLayer.length; i++){
-		if(this.objLayer[i].layer_id==layer_id) {
-			break;
-		}
-	}
-	
-	//go throught sublayers
-	for(var j = i+1; j < this.objLayer.length; j++){
-		if(this.objLayer[i].parent_layer == this.objLayer[j].parent_layer) {
-			break;
-		}
-		if(type == "visible") {
-			value = this.objLayer[j].gui_layer_visible;
-		}
-		else if(type == "querylayer") {
-			value = this.objLayer[j].gui_layer_querylayer;
-		}
-		if(state == -1) {
-			state = value;
-		}
-		if(state != value) {
-			return -1;
-		}
-	}
-	
-	return state;
-};
-/**
- * handle change of visibility / quaryability of a layer
- * 
- * @param string layer_name of layer to handle
- * @param string type of change ("visible" or "querylayer")
- * @param int value of the change
- */
-wms_const.prototype.handleLayer = function(layer_name, type, value){
-	var i;
-	var found = false;
-	for(i = 0; i < this.objLayer.length; i++){
-		if(this.objLayer[i].layer_name==layer_name) {
-			found = true;
-			break;
-		}
-	}
-	// layer not found
-	if (!found) {
-		return;
-	}
-	
-	//Set visibility/queryability of Layer and Sublayers
-	for(var j = i; j < this.objLayer.length; j++){
-		if (i != j && this.objLayer[i].layer_parent >= this.objLayer[j].layer_parent) {
-			break;
-		}
-		if(type == "visible") {
-			this.objLayer[j].gui_layer_visible = parseInt(value, 10);
-		}
-		else if(type=="querylayer" && this.objLayer[j].gui_layer_queryable) {
-			this.objLayer[j].gui_layer_querylayer = parseInt(value, 10);
-		}
-	}
-
-	//Update visibility/queryability of parent layer
-	var parentLayer = this.getLayerByLayerPos(this.objLayer[i].layer_parent);
-	if(parentLayer){
-		var state = this.getSublayerState(parentLayer.layer_id, type);
-		if(state!=-1){
-			if(type == "visible") {
-				this.objLayer[j].gui_layer_visible = state;
-			}
-			else if(type=="querylayer" && this.objLayer[j].gui_layer_queryable) {
-				this.objLayer[j].gui_layer_querylayer = state;
-			}
-		}
-	}
-};
-
-
-/**
- * move a layer (with his sublayers) up or down
- * 
- * @param int layerId layer_id of layer to move
- * @param boolean moveUp true to move up or false to move down
- * @return boolean success
- */
-
-wms_const.prototype.moveLayer = function(layerId, moveUp){
-	var iLayer=-1;
-	var i;
-	
-	//find layer to move
-	for(i=0;i<this.objLayer.length;i++){
-		if(this.objLayer[i].layer_id==layerId){
-			iLayer=i;
-			break;
-		}
-	}
-	if(iLayer==-1) {
-		return false;
-	}
-	
-	var upperLayer = -1;
-	var lowerLayer = -1;
-	
-	//find layer to swap position with
-	var parentLayer = this.objLayer[iLayer].layer_parent;	
-	if(moveUp){
-		lowerLayer = iLayer;
-		
-		//find previous layer on same level
-		for(i=iLayer-1;i>0;i--){
-			if(parentLayer == this.objLayer[i].layer_parent){
-				upperLayer = i;
-				break;
-			}
-		}
-		if(upperLayer == -1){
-			//alert("The Layer you selected is already on top of parent Layer/WMS");
-			return false;
-		}
-	}
-	else{
-		upperLayer = iLayer;
-		
-		//find next layer on same level
-		for(i=iLayer+1;i<this.objLayer.length;i++){
-			if(parentLayer == this.objLayer[i].layer_parent){
-				lowerLayer = i;
-				break;
-			}
-		}
-		if(lowerLayer == -1){
-			//alert("The Layer you selected is already on bottom of parent Layer/WMS");
-			return false;
-		}
-	}
-	
-	//calc number of layers to move down
-	var layersDown = lowerLayer - upperLayer;
-	
-	//get number of layers to move up
-	for(i=lowerLayer+1; i<this.objLayer.length; i++){
-		if(parentLayer == this.objLayer[i].layer_parent){
-			break;
-		}
-	}
-	var layersUp = i - lowerLayer;
-	
-	//do moving
-	var temp = [];
-	for(i=0;i<layersDown+layersUp;i++){
-		temp[temp.length]=this.objLayer[upperLayer+i];
-	}
-	for(i=0;i<layersUp;i++){
-		this.objLayer[upperLayer+i]=temp[i+layersDown];
-	}
-	for(i=0;i<layersDown;i++){
-		this.objLayer[upperLayer+layersUp+i]=temp[i];
-	}
-
-	return true;
-};
-
-function wms_add_data_type_format(datatype,dataformat){
-	var insertDataFormat = true;
-	for (var i = 0 ; i < wms[wms.length-1].data_type.length ; i ++) {
-		if (wms[wms.length-1].data_type[i] == datatype && wms[wms.length-1].data_format[i] == dataformat) {
-			insertDataFormat = false;
-		}
-	}
-	if (insertDataFormat === true) {
-		wms[wms.length-1].data_type[wms[wms.length-1].data_type.length] = datatype;
-		wms[wms.length-1].data_format[wms[wms.length-1].data_format.length] = dataformat;
-	}
-}
-function wms_addSRS(epsg,minx,miny,maxx,maxy){
-	wms[wms.length-1].gui_epsg[wms[wms.length-1].gui_epsg.length] = epsg;
-	wms[wms.length-1].gui_epsg_supported[wms[wms.length-1].gui_epsg_supported.length] = true;
-	wms[wms.length-1].gui_minx[wms[wms.length-1].gui_minx.length] = minx;
-	wms[wms.length-1].gui_miny[wms[wms.length-1].gui_miny.length] = miny;
-	wms[wms.length-1].gui_maxx[wms[wms.length-1].gui_maxx.length] = maxx;
-	wms[wms.length-1].gui_maxy[wms[wms.length-1].gui_maxy.length] = maxy;
-}
-function wms_addLayerStyle(styleName, styleTitle, count, layerCount, styleLegendUrl, styleLegendUrlFormat){
-	var currentLayer = wms[wms.length-1].objLayer[layerCount]; 
-	if (currentLayer) {
-		currentLayer.layer_style[count] = {};
-		currentLayer.layer_style[count].name = styleName;
-		currentLayer.layer_style[count].title = styleTitle;
-		currentLayer.layer_style[count].legendurl = styleLegendUrl;
-		currentLayer.layer_style[count].legendurlformat = styleLegendUrlFormat;
-	}
-}
-//TODO: add layerstyle handling....
-//layer
-function wms_add_layer(
-			layer_parent,
-			layer_uid,
-			layer_name,
-			layer_title,
-			layer_dataurl_href,
-			layer_pos,
-			layer_queryable,
-			layer_minscale,
-			layer_maxscale,
-			layer_metadataurl,
-			gui_layer_wms_id,
-			gui_layer_status,
-			gui_layer_style,
-			gui_layer_selectable,
-			gui_layer_visible,
-			gui_layer_queryable,
-			gui_layer_querylayer,
-			gui_layer_minscale,
-			gui_layer_maxscale,
-			gui_layer_wfs_featuretype,
-			gui_layer_title){
-                      
-	wms[wms.length-1].objLayer[wms[wms.length-1].objLayer.length] = new wms_layer(
-											layer_parent,
-											layer_uid,
-											layer_name,
-											layer_title,
-											layer_dataurl_href,
-											layer_pos,
-											layer_queryable,
-											layer_minscale,
-											layer_maxscale,
-											layer_metadataurl,
-											gui_layer_wms_id,
-											gui_layer_status,
-											gui_layer_style,
-											parseInt(gui_layer_selectable, 10),
-											parseInt(gui_layer_visible, 10),
-											parseInt(gui_layer_queryable, 10),
-											parseInt(gui_layer_querylayer, 10),
-											parseInt(gui_layer_minscale, 10),
-											parseInt(gui_layer_maxscale, 10),
-											gui_layer_wfs_featuretype,
-											gui_layer_title );
-	var parentLayer = wms[wms.length-1].getLayerByLayerPos(parseInt(layer_parent, 10));
-	if(parentLayer) {
-		parentLayer.has_childs = true;
-	}
-}
-function layer_addEpsg(epsg,minx,miny,maxx,maxy){
-	var j = wms[wms.length-1].objLayer.length-1;
-	var k = wms[wms.length-1].objLayer[j].layer_epsg.length;
-	var currentLayer = wms[wms.length-1].objLayer[j];
-	currentLayer.layer_epsg[k]={};
-	currentLayer.layer_epsg[k].epsg = epsg;
-	currentLayer.layer_epsg[k].minx = minx;
-	currentLayer.layer_epsg[k].miny = miny;
-	currentLayer.layer_epsg[k].maxx = maxx;
-	currentLayer.layer_epsg[k].maxy = maxy;
-}
-function wms_layer(
-			layer_parent,
-			wms_layer_uid,
-			layer_name,
-			layer_title,
-			layer_dataurl_href,
-			layer_pos,
-			layer_queryable,
-			layer_minscale,
-			layer_maxscale,
-			layer_metadataurl,
-			gui_layer_wms_id,
-			gui_layer_status,
-			gui_layer_style,
-			gui_layer_selectable,
-			gui_layer_visible,
-			gui_layer_queryable,
-			gui_layer_querylayer,
-			gui_layer_minscale,
-			gui_layer_maxscale,
-			gui_layer_wfs_featuretype,
-			gui_layer_title){
-	this.layer_id = wms_layer_count;
-	this.layer_uid = wms_layer_uid;
-	this.layer_parent = layer_parent;
-	this.layer_name = layer_name;
-	this.layer_title = layer_title;
-	this.gui_layer_title = gui_layer_title || layer_title;
-	this.layer_currentTitle = this.gui_layer_title;
-	this.layer_dataurl_href = layer_dataurl_href;
-	this.layer_pos = layer_pos;
-	this.layer_queryable = layer_queryable;
-	this.layer_minscale = layer_minscale;
-	this.layer_maxscale = layer_maxscale;
-	this.layer_metadataurl = layer_metadataurl;
-	this.layer_epsg = [];
-	this.gui_layer_wms_id = gui_layer_wms_id;
-	this.gui_layer_status = gui_layer_status;
-	this.gui_layer_selectable = gui_layer_selectable;
-	this.gui_layer_visible = gui_layer_visible;
-	this.gui_layer_queryable = gui_layer_queryable;
-	this.gui_layer_querylayer = gui_layer_querylayer;
-	this.gui_layer_minscale = gui_layer_minscale;
-	this.gui_layer_maxscale = gui_layer_maxscale;
-	this.gui_layer_style = gui_layer_style;
-	this.gui_layer_wfs_featuretype = gui_layer_wfs_featuretype;
-	this.has_childs = false;
-	this.layer_style = [];
-	wms_layer_count++;
-}
-/**
- * check the scale of the layer
- *
- * @param Object mapObj the mapbender mapObject of the layer
- * @return boolean if the layer is in scale or not
- * @type boolean
- */
-wms_layer.prototype.checkScale = function(mapObj){
-	var currentScale = parseInt(mapObj.getScale(), 10);
-	if (arguments.length === 2 && arguments[1] !== null) {
-		currentScale = arguments[1];
-	}
-	var minScale = parseInt(this.gui_layer_minscale, 10);
-	var maxScale = parseInt(this.gui_layer_maxscale, 10);
-	if(minScale === 0 && maxScale === 0){
-		return true;
-	}
-	if(minScale > currentScale || (maxScale !== 0 && maxScale < currentScale)) {
-		return false;
-	}	
-	return true;
-};
-/**
- * set visibility of the layer
- * @param boolean visible visibility on/off
- */
-wms_layer.prototype.setVisible = function(visible){
-	this.gui_layer_visible = parseInt(visible, 10);
-};
-
-/**
- * set queryability of the layer
- * @param boolean queryable queryability on/off
- */
-
-wms_layer.prototype.setQueryable = function(queryable){
-	this.gui_layer_querylayer = parseInt(queryable, 10);
-};

Copied: branches/mapbender/http/javascripts/wms.js (from rev 6938, trunk/mapbender/http/javascripts/wms.js)
===================================================================
--- branches/mapbender/http/javascripts/wms.js	                        (rev 0)
+++ branches/mapbender/http/javascripts/wms.js	2010-09-29 11:31:10 UTC (rev 6957)
@@ -0,0 +1,890 @@
+/* 
+ * $Id: map_obj.js 2413 2008-04-23 16:21:04Z christoph $
+ * COPYRIGHT: (C) 2001 by ccgis. This program is free software under the GNU General Public
+ * License (>=v2). Read the file gpl.txt that comes with Mapbender for details. 
+ */
+
+//global variables
+var wms = [];
+var wms_layer_count = 0;
+
+/**
+ * global function to add wms to the wms-object
+ * 
+ * @param {String} wms_id the unique id of the wms 
+ * @param {String} wms_version the version assumed from capabilities
+ * @param {String} wms_title the title of the wms
+ * @param {String} wms_abstract the abstract of the wms
+ * @param {String} wms_getmap the url for map requests
+ * @param {String} wms_getfeatureinfo the url for featureInof requests
+ * @param {String} wms_getlegendurl the url for legend requests
+ * @param {String} wms_filter a filter (deprecated)
+ * @param {String} gui_wms_mapformat the image-format in the actual gui
+ * @param {String} gui_wms_featureinfoformat the current format for featureInfos
+ * @param {String} gui_wms_exceptionformat the exceptionformat for map requests
+ * @param {String} gui_wms_epsg the current srs
+ * @param {Integer} gui_wms_visible the visibility of this service
+ * @param {Integer} gui_wms_opacity the initial display opacity in percent
+ * @param {String} gui_wms_sldurl url to an actual sld
+ */
+function add_wms(
+	wms_id,
+	wms_version,
+	wms_title,
+	wms_abstract,
+	wms_getmap,
+	wms_getfeatureinfo,
+	wms_getlegendurl,
+	wms_filter,
+	gui_wms_mapformat,
+	gui_wms_featureinfoformat,
+	gui_wms_exceptionformat,
+	gui_wms_epsg,
+	gui_wms_visible,
+	gui_wms_opacity,
+	gui_wms_sldurl){
+	wms[wms.length] = new wms_const(
+		wms_id,
+		wms_version,
+		wms_title,
+		wms_abstract,
+		wms_getmap,
+		wms_getfeatureinfo,
+		wms_getlegendurl,
+		wms_filter,
+		gui_wms_mapformat,
+		gui_wms_featureinfoformat,
+		gui_wms_exceptionformat,
+		gui_wms_epsg,
+		parseInt(gui_wms_visible, 10),
+		parseInt(gui_wms_opacity),
+		gui_wms_sldurl);
+	wms_layer[wms.length - 1] = [];
+}
+/**
+ * @class A class representing the wms
+ *
+ * @constructor
+ * @param {String} wms_id the unique id of the wms 
+ * @param {String} wms_version the version assumed from capabilities
+ * @param {String} wms_title the title of the wms
+ * @param {String} wms_abstract the abstract of the wms
+ * @param {String} wms_getmap the url for map requests
+ * @param {String} wms_getfeatureinfo the url for featureInof requests
+ * @param {String} wms_getlegendurl the url for legend requests
+ * @param {String} wms_filter a filter (deprecated)
+ * @param {String} gui_wms_mapformat the image-format in the actual gui
+ * @param {String} gui_wms_featureinfoformat the current format for featureInfos
+ * @param {String} gui_wms_exceptionformat the exceptionformat for map requests
+ * @param {String} gui_wms_epsg the current srs
+ * @param {String} gui_wms_visible the visibility of this service
+ * @param {Integer} gui_wms_opacity the initial display opacity in percent
+ * @param {String} gui_wms_sldurl url to an actual sld
+ * 
+ */
+function wms_const(  
+	wms_id,
+	wms_version,
+	wms_title,
+	wms_abstract,
+	wms_getmap,
+	wms_getfeatureinfo,
+	wms_getlegendurl,
+	wms_filter,
+	gui_wms_mapformat,
+	gui_wms_featureinfoformat,
+	gui_wms_exceptionformat,
+	gui_wms_epsg,
+	gui_wms_visible,
+	gui_wms_opacity,
+	gui_wms_sldurl){
+   
+	if (!wms_id) {
+		var id_ok = false;
+		while (id_ok === false) {
+			wms_id = "a"+Math.round(10000*Math.random());
+			id_ok = true;
+			for (var i=0; i < wms.length && id_ok === true; i++) {
+				if (wms_id == wms[i].wms_id) { 
+					id_ok = false;
+				}
+			}
+		}
+	}
+	
+	this.wms_id = wms_id;
+	this.wms_version = wms_version;
+	this.wms_title = wms_title;
+	this.wms_currentTitle = wms_title;
+	this.wms_abstract = wms_abstract;
+	this.wms_getmap = wms_getmap;
+	this.wms_getfeatureinfo = wms_getfeatureinfo;
+	this.wms_getlegendurl = wms_getlegendurl;
+	this.wms_filter = wms_filter;
+	this.data_type = [];
+	this.data_format = [];
+	this.objLayer = [];
+	this.gui_wms_mapformat = gui_wms_mapformat;
+	this.gui_wms_featureinfoformat = gui_wms_featureinfoformat;
+	this.gui_wms_exceptionformat = gui_wms_exceptionformat;
+	this.gui_wms_epsg = gui_wms_epsg;
+	this.gui_wms_visible = gui_wms_visible;
+	this.gui_epsg = [];
+	this.gui_epsg_supported = [];
+	this.gui_minx = [];
+	this.gui_miny = [];
+	this.gui_maxx = [];
+	this.gui_maxy = [];
+
+	// opacity version 
+	this.gui_wms_mapopacity = gui_wms_opacity/100;
+	// sld version
+	this.gui_wms_sldurl = gui_wms_sldurl;    
+
+	this.setCrs = function (options) {
+		var crsIndex = $.inArray(options.source.srsCode, this.gui_epsg);
+		if (crsIndex !== -1 && 
+			typeof this.gui_minx[crsIndex] === 'number' &&
+			typeof this.gui_miny[crsIndex] === 'number' &&	
+			typeof this.gui_maxx[crsIndex] === 'number' &&
+			typeof this.gui_maxy[crsIndex] === 'number'
+			) {
+			var sw = new Proj4js.Point(
+				this.gui_minx[crsIndex], 
+				this.gui_miny[crsIndex]
+				);
+			var ne = new Proj4js.Point(
+				this.gui_maxx[crsIndex], 
+				this.gui_maxy[crsIndex]
+				);
+			sw = Proj4js.transform(options.source, options.dest, sw);
+			ne = Proj4js.transform(options.source, options.dest, ne);
+			var extent = new Mapbender.Extent(sw.x, sw.y, ne.x, ne.y);
+			this.setBoundingBoxBySrs(options.dest.srsCode, extent);
+		}
+		else {
+			this.setBoundingBoxBySrs(options.dest.srsCode);
+		}
+	};
+	
+	this.setBoundingBoxBySrs = function (srs, ext) {
+		for (var i = 0; i < this.gui_epsg.length && ext !== undefined; i++) {
+			if (srs == this.gui_epsg[i]) {
+				this.gui_minx[i] = parseFloat(ext.minx);
+				this.gui_miny[i] = parseFloat(ext.miny);
+				this.gui_maxx[i] = parseFloat(ext.maxx);
+				this.gui_maxy[i] = parseFloat(ext.maxy);
+				return i;
+			}
+		}
+		this.gui_epsg.push(srs);
+		this.gui_epsg_supported.push(false);
+		
+		if (ext !== undefined) {
+			this.gui_minx.push(ext.minx);
+			this.gui_miny.push(ext.miny);
+			this.gui_maxx.push(ext.maxx);
+			this.gui_maxy.push(ext.maxy);
+		}
+		
+		return this.gui_epsg.length - 1;
+	};
+}
+
+wms_const.prototype.getBoundingBoxBySrs = function (srs) {
+	for (var i = 0; i < this.gui_epsg.length; i++) {
+		if (srs == this.gui_epsg[i]) {
+			var bbox_minx = parseFloat(this.gui_minx[i]);
+			var bbox_miny = parseFloat(this.gui_miny[i]);
+			var bbox_maxx = parseFloat(this.gui_maxx[i]);
+			var bbox_maxy = parseFloat(this.gui_maxy[i]);
+			if (bbox_minx !== null && !isNaN(bbox_minx) &&
+				bbox_miny !== null && !isNaN(bbox_miny) &&
+				bbox_maxx !== null && !isNaN(bbox_maxx) &&
+				bbox_maxy !== null && !isNaN(bbox_maxy)
+				) {
+				return new Extent(bbox_minx, bbox_miny, bbox_maxx, bbox_maxy);
+			}
+		}
+	}
+	return null;
+};
+
+/**
+ * rephrases the featureInfoRequest
+ *
+ * @param {Object} mapObj the mapbender mapObject of the wms  
+ * @param {Point} clickPoint map-click position {@link Point}
+ * @return featureInfoRequest, onlineresource + params
+ * @type string
+ */
+wms_const.prototype.getFeatureInfoRequest = function(mapObj, clickPoint){	
+	
+	//check layers and querylayers first 
+	var layers = this.getLayers(mapObj);
+	var querylayers = this.getQuerylayers(mapObj);
+	
+	if(!layers || !querylayers){
+		return false;
+	}
+	
+	var rq = this.wms_getfeatureinfo;
+	rq += mb_getConjunctionCharacter(this.wms_getfeatureinfo);
+	if(this.wms_version === "1.0.0"){
+		rq += "WMTVER=" + this.wms_version + "&REQUEST=feature_info";
+	}
+	else{
+		rq += "VERSION=" + this.wms_version + "&REQUEST=GetFeatureInfo&SERVICE=WMS";
+	}
+	
+	rq += "&LAYERS=" + layers.join(",");
+	rq += "&QUERY_LAYERS=" + querylayers.join(",");
+	rq += "&WIDTH=" + mapObj.getWidth();
+	rq += "&HEIGHT=" + mapObj.getHeight();
+	rq += "&SRS=" + mapObj.getSRS();
+	rq += "&BBOX=" + mapObj.getExtent();
+	rq += "&STYLES=" + this.getLayerstyles(mapObj).join(",");
+	rq += "&FORMAT=" + this.gui_wms_mapformat;
+	rq += "&INFO_FORMAT=" + this.gui_wms_featureinfoformat;
+	rq += "&EXCEPTIONS=application/vnd.ogc.se_xml";
+	rq += "&X=" + clickPoint.x;
+	rq += "&Y=" + clickPoint.y;
+	if(mb_feature_count > 0){             
+		rq += "&FEATURE_COUNT="+mb_feature_count;
+	}
+	rq += "&";
+	// add vendor-specific
+	var currentWms = this;
+	for (var v = 0; v < mb_vendorSpecific.length; v++) {
+		var functionName = 'setFeatureInfoRequest';
+		var currentWms_wms_title = this.wms_title;
+		var vendorSpecificString = eval(mb_vendorSpecific[v]);
+		// if eval doesn't evaluate a function, the result is undefined.
+		// Sometimes it is necessary not to evaluate a function, for
+		// example if you want to change a variable from the current
+		// scope (see mod_addSLD.php) 
+		if (typeof(vendorSpecificString) != "undefined") {
+			rq += vendorSpecificString + "&";
+			try {
+				if (this.wms_title == removeLayerAndStylesAffectedWMSTitle) {
+					rq = url.replace(/LAYERS=[^&]*&/, '');
+					rq = url.replace(/STYLES=[^&]*&/, '');
+				}
+			}
+			catch (exc) {
+				new Mb_warning(exc.message);
+			}
+		}
+	}
+	return rq;
+};
+
+/**
+ * sets Opacity of WMS
+ * 
+ * @param {Integer} new opacity percentage value
+ */
+wms_const.prototype.setOpacity = function(opacity){
+	//calc new opacity
+	this.gui_wms_mapopacity = parseInt(opacity)/100;
+	if(this.gui_wms_mapopacity>1||isNaN(this.gui_wms_mapopacity))
+		this.gui_wms_mapopacity=1;
+	if(this.gui_wms_mapopacity<0)
+		this.gui_wms_mapopacity=0;
+		
+	if (this.gui_wms_visible > 0) {
+
+		//get div id
+		var divId = null;
+		for (var i=0; i < wms.length; i++) {
+			if (this.wms_id == wms[i].wms_id) { 
+				var divId = 'div_'+i;
+				break;
+			}
+		}
+		if(!divId)
+			return;	
+		
+		//TODO: check if mapframe1 is the right mapframe
+		var ind = getMapObjIndexByName("mapframe1");
+		var el = mb_mapObj[ind].getDomElement();
+		wmsImage = el.ownerDocument.getElementById(divId);
+		if (wmsImage != null) {
+			wmsImage.style.opacity = this.gui_wms_mapopacity;
+			wmsImage.style.MozOpacity = this.gui_wms_mapopacity;
+			wmsImage.style.KhtmlOpacity = this.gui_wms_mapopacity;
+			wmsImage.style.filter = "alpha(opacity=" + this.gui_wms_mapopacity*100 + ")";
+		}
+	}
+}
+
+/**
+ * get all visible layers
+ *
+ * @return array of layernames 
+ * @type string[]
+ */
+wms_const.prototype.getLayers = function(mapObj){
+	var scale = null;
+	if (arguments.length === 2) {
+		scale = arguments[1];
+	}
+	try {
+		//visibility of the wms
+		var wmsIsVisible = (this.gui_wms_visible > 0);
+		if(!wmsIsVisible){
+			return [];
+		}
+		visibleLayers = [];
+		for(var i=0; i< this.objLayer.length; i++){
+			var isVisible = (this.objLayer[i].gui_layer_visible === 1);
+			var hasNoChildren = (!this.objLayer[i].has_childs);
+			if (isVisible && hasNoChildren){
+				if(this.objLayer[i].checkScale(mapObj, scale)){
+					visibleLayers.push(this.objLayer[i].layer_name);
+				}
+			}
+		}
+		if(visibleLayers.length === 0){
+			return [];
+		}
+		return visibleLayers;
+	}
+	catch (e) {
+		alert(e);
+	}
+	return [];
+};
+
+/**
+ * get the actual style of all visible layers
+ *
+ * @return commaseparated list of actual layerstyles
+ * @type string
+ */
+wms_const.prototype.getLayerstyles = function(mapObj){
+	
+	var layers = this.getLayers(mapObj);
+	var layerstyles = '';
+	var styles = [];
+	if(layers){
+		for(i = 0; i < layers.length; i++){
+			var style = this.getCurrentStyleByLayerName(layers[i]);
+			if(!style){
+				style = '';
+			}
+			styles.push(style);
+		}
+		return styles;
+	}
+	return false;
+};
+
+/**
+ * check if layer is parentLayer
+ *
+ * @param layername
+ * @return the parent value of the given layer
+ * @type integer
+ */
+wms_const.prototype.checkLayerParentByLayerName = function(layername){
+	for(var i=0; i< this.objLayer.length; i++){
+		if(this.objLayer[i].layer_name == layername){
+			return this.objLayer[i].layer_parent;
+		}
+	}
+};
+
+/**
+ * get the title of the current layer
+ *
+ * @param layername
+ * @return the title of the given layer
+ * @type string
+ */
+wms_const.prototype.getTitleByLayerName = function(layername){
+	for(var i=0; i< this.objLayer.length; i++){
+		if(this.objLayer[i].layer_name == layername){
+			return this.objLayer[i].layer_title;
+		}
+	}
+};
+
+wms_const.prototype.getLayerByLayerName = function(layername){
+	for(var i=0; i< this.objLayer.length; i++){
+		if(this.objLayer[i].layer_name === layername){
+			return this.objLayer[i];
+		}
+	}
+};
+
+/**
+ * get the current style of the layer
+ *
+ * @param layername
+ * @return the stylename of the given layer
+ * @type string
+ */
+wms_const.prototype.getCurrentStyleByLayerName = function(layername){
+	for(var i=0; i< this.objLayer.length; i++){
+		var currentLayer = this.objLayer[i];
+		if (currentLayer.layer_name === layername) {
+			if (currentLayer.gui_layer_style === '' || currentLayer.gui_layer_style === null){
+				return "default";
+			//				return false;
+			}
+			else{
+				return currentLayer.gui_layer_style;	
+			}
+		}
+	}
+	return false;
+};
+
+/**
+ * get the legendurl of the gui layer style
+ *
+ * @param stylename
+ * @return the legendurl of the given style
+ * @type string
+ */
+wms_const.prototype.getLegendUrlByGuiLayerStyle = function(layername,guiLayerStyle){
+	for(var i=0; i< this.objLayer.length; i++){
+		if(this.objLayer[i].layer_name == layername){
+			if(this.objLayer[i].layer_style.length === 0){
+				return false;
+			}
+			for(var k=0; k< this.objLayer[i].layer_style.length; k++){
+				var legendUrl = '';
+				if(guiLayerStyle == '' && k == 0){
+					legendUrl = this.objLayer[i].layer_style[k].legendurl;
+					if (this.gui_wms_sldurl !== "") {
+						legendUrl += "&SLD="+escape(this.gui_wms_sldurl);
+					}				
+					if(legendUrl !=='' && legendUrl !== null && typeof(legendUrl) != 'undefined'){
+						return legendUrl;
+					}
+					else {
+						return false;
+					}
+				}else if(this.objLayer[i].layer_style[k].name == guiLayerStyle){
+					legendUrl = this.objLayer[i].layer_style[k].legendurl;
+					if (this.gui_wms_sldurl !== "") {
+						legendUrl += "&SLD="+escape(this.gui_wms_sldurl);
+					}				
+					if(legendUrl !=='' && legendUrl !== null && typeof(legendUrl) != 'undefined'){
+						return legendUrl;
+					}
+					else {
+						return false;
+					}
+				}
+			}
+		}
+	}
+	return false;
+};
+
+/**
+ * get all querylayers
+ *
+ * @return array of layernames
+ * @type string[]
+ */
+wms_const.prototype.getQuerylayers = function(map){
+	var currentScale = map.getScale();
+	queryLayers = [];
+	for(var i=0; i< this.objLayer.length; i++){
+		
+		var isVisible = this.objLayer[i].gui_layer_visible === 1 && 
+		this.objLayer[i].gui_layer_minscale <= currentScale &&
+		(this.objLayer[i].gui_layer_maxscale >= currentScale ||
+			this.objLayer[i].gui_layer_maxscale === 0);
+		if(this.objLayer[i].gui_layer_querylayer === 1 && !this.objLayer[i].has_childs && isVisible){
+			queryLayers.push(this.objLayer[i].layer_name);
+		}
+	}
+	if(queryLayers.length === 0){
+		return false;
+	}
+	return queryLayers;
+};
+
+/**
+ * get a layer Object by layer_pos
+ * 
+ * @param int payer_pos layer_pos of layer you want to get
+ * @return object layer
+ */
+
+wms_const.prototype.getLayerByLayerPos = function(layer_pos){
+	for(var i=0;i<this.objLayer.length;i++){
+		if(this.objLayer[i].layer_pos == layer_pos) {
+			return this.objLayer[i];
+		}
+	}
+	return null;
+};
+
+wms_const.prototype.getLayerById = function(id){
+	for(var i=0;i<this.objLayer.length;i++){
+		if(parseInt(this.objLayer[i].layer_uid, 10) === parseInt(id,10)) {
+			return this.objLayer[i];
+		}
+	}
+	return null;
+};
+/**
+ * get the state of sublayers from a specified layer
+ * 
+ * @param int layer_id of the parent layer
+ * @param String type "visible" or "querylayer"
+ * @return int -1 if state differs else the state
+ */
+
+wms_const.prototype.getSublayerState = function(layer_id, type){
+	var i;
+	var state=-1,value;
+	for(i = 0; i < this.objLayer.length; i++){
+		if(this.objLayer[i].layer_id==layer_id) {
+			break;
+		}
+	}
+	
+	//go throught sublayers
+	for(var j = i+1; j < this.objLayer.length; j++){
+		if(this.objLayer[i].parent_layer == this.objLayer[j].parent_layer) {
+			break;
+		}
+		if(type == "visible") {
+			value = this.objLayer[j].gui_layer_visible;
+		}
+		else if(type == "querylayer") {
+			value = this.objLayer[j].gui_layer_querylayer;
+		}
+		if(state == -1) {
+			state = value;
+		}
+		if(state != value) {
+			return -1;
+		}
+	}
+	
+	return state;
+};
+/**
+ * handle change of visibility / quaryability of a layer
+ * 
+ * @param string layer_name of layer to handle
+ * @param string type of change ("visible" or "querylayer")
+ * @param int value of the change
+ */
+wms_const.prototype.handleLayer = function(layer_name, type, value){
+	var i;
+	var found = false;
+	for(i = 0; i < this.objLayer.length; i++){
+		if(this.objLayer[i].layer_name==layer_name) {
+			found = true;
+			break;
+		}
+	}
+	// layer not found
+	if (!found) {
+		return;
+	}
+	
+	//Set visibility/queryability of Layer and Sublayers
+	for(var j = i; j < this.objLayer.length; j++){
+		if (i != j && this.objLayer[i].layer_parent >= this.objLayer[j].layer_parent) {
+			break;
+		}
+		if(type == "visible") {
+			this.objLayer[j].gui_layer_visible = parseInt(value, 10);
+		}
+		else if(type=="querylayer" && this.objLayer[j].gui_layer_queryable) {
+			this.objLayer[j].gui_layer_querylayer = parseInt(value, 10);
+		}
+	}
+
+	//Update visibility/queryability of parent layer
+	var parentLayer = this.getLayerByLayerPos(this.objLayer[i].layer_parent);
+	if(parentLayer){
+		var state = this.getSublayerState(parentLayer.layer_id, type);
+		if(state!=-1){
+			if(type == "visible") {
+				this.objLayer[j].gui_layer_visible = state;
+			}
+			else if(type=="querylayer" && this.objLayer[j].gui_layer_queryable) {
+				this.objLayer[j].gui_layer_querylayer = state;
+			}
+		}
+	}
+};
+
+
+/**
+ * move a layer (with his sublayers) up or down
+ * 
+ * @param int layerId layer_id of layer to move
+ * @param boolean moveUp true to move up or false to move down
+ * @return boolean success
+ */
+
+wms_const.prototype.moveLayer = function(layerId, moveUp){
+	var iLayer=-1;
+	var i;
+	
+	//find layer to move
+	for(i=0;i<this.objLayer.length;i++){
+		if(this.objLayer[i].layer_id==layerId){
+			iLayer=i;
+			break;
+		}
+	}
+	if(iLayer==-1) {
+		return false;
+	}
+	
+	var upperLayer = -1;
+	var lowerLayer = -1;
+	
+	//find layer to swap position with
+	var parentLayer = this.objLayer[iLayer].layer_parent;	
+	if(moveUp){
+		lowerLayer = iLayer;
+		
+		//find previous layer on same level
+		for(i=iLayer-1;i>0;i--){
+			if(parentLayer == this.objLayer[i].layer_parent){
+				upperLayer = i;
+				break;
+			}
+		}
+		if(upperLayer == -1){
+			//alert("The Layer you selected is already on top of parent Layer/WMS");
+			return false;
+		}
+	}
+	else{
+		upperLayer = iLayer;
+		
+		//find next layer on same level
+		for(i=iLayer+1;i<this.objLayer.length;i++){
+			if(parentLayer == this.objLayer[i].layer_parent){
+				lowerLayer = i;
+				break;
+			}
+		}
+		if(lowerLayer == -1){
+			//alert("The Layer you selected is already on bottom of parent Layer/WMS");
+			return false;
+		}
+	}
+	
+	//calc number of layers to move down
+	var layersDown = lowerLayer - upperLayer;
+	
+	//get number of layers to move up
+	for(i=lowerLayer+1; i<this.objLayer.length; i++){
+		if(parentLayer == this.objLayer[i].layer_parent){
+			break;
+		}
+	}
+	var layersUp = i - lowerLayer;
+	
+	//do moving
+	var temp = [];
+	for(i=0;i<layersDown+layersUp;i++){
+		temp[temp.length]=this.objLayer[upperLayer+i];
+	}
+	for(i=0;i<layersUp;i++){
+		this.objLayer[upperLayer+i]=temp[i+layersDown];
+	}
+	for(i=0;i<layersDown;i++){
+		this.objLayer[upperLayer+layersUp+i]=temp[i];
+	}
+
+	return true;
+};
+
+function wms_add_data_type_format(datatype,dataformat){
+	var insertDataFormat = true;
+	for (var i = 0 ; i < wms[wms.length-1].data_type.length ; i ++) {
+		if (wms[wms.length-1].data_type[i] == datatype && wms[wms.length-1].data_format[i] == dataformat) {
+			insertDataFormat = false;
+		}
+	}
+	if (insertDataFormat === true) {
+		wms[wms.length-1].data_type[wms[wms.length-1].data_type.length] = datatype;
+		wms[wms.length-1].data_format[wms[wms.length-1].data_format.length] = dataformat;
+	}
+}
+function wms_addSRS(epsg,minx,miny,maxx,maxy){
+	wms[wms.length-1].gui_epsg[wms[wms.length-1].gui_epsg.length] = epsg;
+	wms[wms.length-1].gui_epsg_supported[wms[wms.length-1].gui_epsg_supported.length] = true;
+	wms[wms.length-1].gui_minx[wms[wms.length-1].gui_minx.length] = minx;
+	wms[wms.length-1].gui_miny[wms[wms.length-1].gui_miny.length] = miny;
+	wms[wms.length-1].gui_maxx[wms[wms.length-1].gui_maxx.length] = maxx;
+	wms[wms.length-1].gui_maxy[wms[wms.length-1].gui_maxy.length] = maxy;
+}
+function wms_addLayerStyle(styleName, styleTitle, count, layerCount, styleLegendUrl, styleLegendUrlFormat){
+	var currentLayer = wms[wms.length-1].objLayer[layerCount]; 
+	if (currentLayer) {
+		currentLayer.layer_style[count] = {};
+		currentLayer.layer_style[count].name = styleName;
+		currentLayer.layer_style[count].title = styleTitle;
+		currentLayer.layer_style[count].legendurl = styleLegendUrl;
+		currentLayer.layer_style[count].legendurlformat = styleLegendUrlFormat;
+	}
+}
+//TODO: add layerstyle handling....
+//layer
+function wms_add_layer(
+	layer_parent,
+	layer_uid,
+	layer_name,
+	layer_title,
+	layer_dataurl_href,
+	layer_pos,
+	layer_queryable,
+	layer_minscale,
+	layer_maxscale,
+	layer_metadataurl,
+	gui_layer_wms_id,
+	gui_layer_status,
+	gui_layer_style,
+	gui_layer_selectable,
+	gui_layer_visible,
+	gui_layer_queryable,
+	gui_layer_querylayer,
+	gui_layer_minscale,
+	gui_layer_maxscale,
+	gui_layer_wfs_featuretype,
+	gui_layer_title){
+                      
+	wms[wms.length-1].objLayer[wms[wms.length-1].objLayer.length] = new wms_layer(
+		layer_parent,
+		layer_uid,
+		layer_name,
+		layer_title,
+		layer_dataurl_href,
+		layer_pos,
+		layer_queryable,
+		layer_minscale,
+		layer_maxscale,
+		layer_metadataurl,
+		gui_layer_wms_id,
+		gui_layer_status,
+		gui_layer_style,
+		parseInt(gui_layer_selectable, 10),
+		parseInt(gui_layer_visible, 10),
+		parseInt(gui_layer_queryable, 10),
+		parseInt(gui_layer_querylayer, 10),
+		parseInt(gui_layer_minscale, 10),
+		parseInt(gui_layer_maxscale, 10),
+		gui_layer_wfs_featuretype,
+		gui_layer_title );
+	var parentLayer = wms[wms.length-1].getLayerByLayerPos(parseInt(layer_parent, 10));
+	if(parentLayer) {
+		parentLayer.has_childs = true;
+	}
+}
+function layer_addEpsg(epsg,minx,miny,maxx,maxy){
+	var j = wms[wms.length-1].objLayer.length-1;
+	var k = wms[wms.length-1].objLayer[j].layer_epsg.length;
+	var currentLayer = wms[wms.length-1].objLayer[j];
+	currentLayer.layer_epsg[k]={};
+	currentLayer.layer_epsg[k].epsg = epsg;
+	currentLayer.layer_epsg[k].minx = minx;
+	currentLayer.layer_epsg[k].miny = miny;
+	currentLayer.layer_epsg[k].maxx = maxx;
+	currentLayer.layer_epsg[k].maxy = maxy;
+}
+function wms_layer(
+	layer_parent,
+	wms_layer_uid,
+	layer_name,
+	layer_title,
+	layer_dataurl_href,
+	layer_pos,
+	layer_queryable,
+	layer_minscale,
+	layer_maxscale,
+	layer_metadataurl,
+	gui_layer_wms_id,
+	gui_layer_status,
+	gui_layer_style,
+	gui_layer_selectable,
+	gui_layer_visible,
+	gui_layer_queryable,
+	gui_layer_querylayer,
+	gui_layer_minscale,
+	gui_layer_maxscale,
+	gui_layer_wfs_featuretype,
+	gui_layer_title){
+	this.layer_id = wms_layer_count;
+	this.layer_uid = wms_layer_uid;
+	this.layer_parent = layer_parent;
+	this.layer_name = layer_name;
+	this.layer_title = layer_title;
+	this.gui_layer_title = gui_layer_title || layer_title;
+	this.layer_currentTitle = this.gui_layer_title;
+	this.layer_dataurl_href = layer_dataurl_href;
+	this.layer_pos = layer_pos;
+	this.layer_queryable = layer_queryable;
+	this.layer_minscale = layer_minscale;
+	this.layer_maxscale = layer_maxscale;
+	this.layer_metadataurl = layer_metadataurl;
+	this.layer_epsg = [];
+	this.gui_layer_wms_id = gui_layer_wms_id;
+	this.gui_layer_status = gui_layer_status;
+	this.gui_layer_selectable = gui_layer_selectable;
+	this.gui_layer_visible = gui_layer_visible;
+	this.gui_layer_queryable = gui_layer_queryable;
+	this.gui_layer_querylayer = gui_layer_querylayer;
+	this.gui_layer_minscale = gui_layer_minscale;
+	this.gui_layer_maxscale = gui_layer_maxscale;
+	this.gui_layer_style = gui_layer_style;
+	this.gui_layer_wfs_featuretype = gui_layer_wfs_featuretype;
+	this.has_childs = false;
+	this.layer_style = [];
+	wms_layer_count++;
+}
+/**
+ * check the scale of the layer
+ *
+ * @param Object mapObj the mapbender mapObject of the layer
+ * @return boolean if the layer is in scale or not
+ * @type boolean
+ */
+wms_layer.prototype.checkScale = function(mapObj){
+	var currentScale = parseInt(mapObj.getScale(), 10);
+	if (arguments.length === 2 && arguments[1] !== null) {
+		currentScale = arguments[1];
+	}
+	var minScale = parseInt(this.gui_layer_minscale, 10);
+	var maxScale = parseInt(this.gui_layer_maxscale, 10);
+	if(minScale === 0 && maxScale === 0){
+		return true;
+	}
+	if(minScale > currentScale || (maxScale !== 0 && maxScale < currentScale)) {
+		return false;
+	}	
+	return true;
+};
+/**
+ * set visibility of the layer
+ * @param boolean visible visibility on/off
+ */
+wms_layer.prototype.setVisible = function(visible){
+	this.gui_layer_visible = parseInt(visible, 10);
+};
+
+/**
+ * set queryability of the layer
+ * @param boolean queryable queryability on/off
+ */
+
+wms_layer.prototype.setQueryable = function(queryable){
+	this.gui_layer_querylayer = parseInt(queryable, 10);
+};

Deleted: branches/mapbender/http/php/mod_showMetadata.php
===================================================================
--- trunk/mapbender/http/php/mod_showMetadata.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/http/php/mod_showMetadata.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,520 +0,0 @@
-<?php
-# $Id: mod_showMetadata.php 235 2010-09-08 08:34:48Z armin11 $
-# http://www.mapbender.org/index.php/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__) . "/../../core/globalSettings.php";
-require_once dirname(__FILE__) . "/../classes/class_user.php";
-
-//GET:
-//resource: wms, layer, wfs, featuretype, wfs-conf, wmc
-//id: integer
-//outputFormat: html, xml, georss, 
-//languageCode: de, en, fr
-
-//Parse REQUEST Parameters
-if (isset($_REQUEST["resource"]) & $_REQUEST["resource"] != "") {
-	//validate to csv integer list
-	$testMatch = $_REQUEST["resource"];
-	if (!($testMatch == 'wms' or $testMatch == 'layer' or $testMatch == 'wfs' or $testMatch == 'featuretype' or $testMatch == 'wfs-conf')){ 
-		echo 'resource: <b>'.$testMatch.'</b> is not valid.<br/>'; 
-		die(); 		
- 	}
-	$resource = $testMatch;
-	$testMatch = NULL;
-}
-if (isset($_REQUEST["id"]) & $_REQUEST["id"] != "") {
-	//validate to csv integer list
-	$testMatch = $_REQUEST["id"];
-	$pattern = '/^[\d,]*$/';		
- 	if (!preg_match($pattern,$testMatch)){ 
-		echo 'id: <b>'.$testMatch.'</b> is not valid.<br/>'; 
-		die(); 		
- 	}
-	$id = $testMatch;
-	$testMatch = NULL;
-}
-if (isset($_REQUEST["outputFormat"]) & $_REQUEST["outputFormat"] != "") {
-	//validate to csv integer list
-	$testMatch = $_REQUEST["outputFormat"];
-	if (!($testMatch == 'iso19139' or $testMatch == 'html' or $testMatch == 'georss')){ 
-		echo 'outputFormat: <b>'.$testMatch.'</b> is not valid.<br/>'; 
-		die(); 		
- 	}
-	$outputFormat = $testMatch;
-	$testMatch = NULL;
-}
-if (isset($_REQUEST["languageCode"]) & $_REQUEST["languageCode"] != "") {
-	//validate to csv integer list
-	$testMatch = $_REQUEST["languageCode"];
-	if (!($testMatch == 'de' or $testMatch == 'fr' or $testMatch == 'en')){ 
-		echo 'languageCode: <b>'.$testMatch.'</b> is not valid.<br/>'; 
-		die(); 		
- 	}
-	$languageCode = $testMatch;
-	$testMatch = NULL;
-}
-
-$subscribe = intval($_GET["subscribe"]);
-
-//get language parameter out of mapbender session if it is set else set default language to de_DE
-if (isset($_SESSION['mb_lang']) and $_SESSION['mb_lang']!='') {
-	$e = new mb_exception("mod_showMetadata.php: language in session: ".$_SESSION['mb_lang']);
-	$language = $_SESSION["mb_lang"];
-} else {
-	$language = "de_DE";//use locale for compatibility with later mapbender version
-}
-
-//extract language code out of locale
-
-$langCode = explode("_", $language);
-
-$langCode = $langCode[0];
-
-#$langCode="de";
-
-$e = new mb_exception("mod_showMetadata.php: language: ".$langCode);
-
-//Array with translations:
-$translation['overview'] = 'Ãœbersicht';
-$translation['properties'] = 'Eigenschaften';
-$translation['termsOfUse'] = 'Nutzungsbedingungen';
-$translation['contact'] = 'Kontakt';
-$translation['quality'] = 'Qualität';
-$translation['interfaces'] = 'Schnittstellen';
-$translation['metadata'] = 'Metadaten';
-$translation['kindOfResource'] = 'Art der Ressource';
-$translation['wms'] = 'Kartendienst';
-$translation['layer'] = 'Kartenebene';
-$translation['preview'] = 'Voransicht';
-$translation['resourceAbstract'] = 'Zusammenfassung';
-$translation['resourceTitle'] = 'Titel';
-$translation['metadataProvider'] = 'Veröffentlichende Stelle';
-$translation['serviceProvider'] = 'Dienstanbieter';
-$translation['contactPerson'] = 'Ansprechpartner';
-$translation['contactOrganization'] = 'Organisation';
-$translation['contactAddress'] = 'Adresse';
-$translation['email'] = 'Email';
-$translation['city'] = 'Ort';
-$translation['logo'] = 'Logo';
-$translation['status'] = 'Status';
-$translation['availability'] = 'Verfügbarkeit';
-$translation['statusRed'] = 'Probleme beim letzten Monitoring!';
-$translation['statusGreen'] = 'Letztes Monitoring OK';
-$translation['statusYellow'] = 'Dienstebeschreibung hat sich geändert!';
-$translation['queryableFalse'] = 'Ebene nicht abfragbar';
-$translation['queryableTrue'] = 'Ebene abfragbar';
-$translation['queryable'] = 'Abfragbarkeit';
-$translation['restrictedScale'] = 'Sichtbarkeit';
-$translation['minscale'] = 'Minimaler Maßstab';
-$translation['maxscale'] = 'Maximaler Maßstab';
-$translation['crs'] = 'Koordinatenreferenzsysteme (mit BBOX)';
-$translation['wgs84Bbox'] = 'Ausdehnung in geographischen Koordinaten';
-$translation['mapbenderCapabilities'] = 'Geoportal Capabilities';
-$translation['originalCapabilities'] = 'Original Capabilities';
-$translation['kml'] = 'KML';
-$translation['inspireMetadata'] = 'INSPIRE Service Metadaten';
-$translation['securedCapabilities'] = 'Secured Capabilities URL';
-$translation['capabilities'] = 'Link zum Capabilities Dokument';
-$translation['inspireMetadataValidation'] = 'Validierung gegen INSPIRE Geoportal';
-//Array with infos about the different elements which are shown in the tabs
-
-//Check if an id and a resource was given
-if (!isset($_REQUEST["id"]) or !isset($_REQUEST["resource"])) {
-	echo 'Not enough input parameters. resource and id must be given!<br/>'; 
-	die(); 	
-}
-
-//Read out information from mapbender database
-switch ($resource) {
-	case "wms":
-		//get root layer information
-		$sql = "SELECT layer_id FROM layer WHERE fkey_wms_id = $1 AND layer_pos = 0";
-		$v = array($id);
-		$t = array("i");
-		$res = db_prep_query($sql, $v, $t);
-		$row = db_fetch_array($res);
-		$layerId = $row["layer_id"];
-		$sql = "SELECT ";
-		$sql .= "layer.layer_id as contentid, layer.layer_title as contenttitle, layer.layer_abstract as contentabstract, layer.layer_pos as contentpos, layer.layer_parent as contentparent, ";
-		$sql .= "layer.layer_minscale as contentminscale, layer.layer_maxscale as contentmaxscale, layer.layer_queryable,";
-		$sql .= "wms.wms_title as servicetitle, wms.wms_abstract as serviceabstract, wms.wms_id as serviceid, wms.fees, wms.accessconstraints, wms.contactperson, wms.wms_getcapabilities,";
-		$sql .= "wms.contactposition, wms.contactorganization, wms.address, wms.city, wms_timestamp as timestamp, wms_owner as owner, wms.wms_owsproxy as owsproxy, wms.fkey_mb_group_id,";
-		$sql .= "wms.stateorprovince, wms.postcode, wms.contactvoicetelephone, wms.contactfacsimiletelephone, ";
-		$sql .= "wms.contactelectronicmailaddress, wms.country ";
-		$sql .= "FROM layer, wms WHERE layer.layer_id = $1 AND layer.fkey_wms_id = wms.wms_id LIMIT 1";
-		$v = array($layerId);
-		$t = array('i');
-		$serviceType = 'wms';
-		
-		break;
-	case "layer":
-		$layerId = $id;
-		$sql = "SELECT ";
-		$sql .= "layer.layer_id as contentid, layer.layer_title as contenttitle, layer.layer_abstract as contentabstract, layer.layer_pos as contentpos, layer.layer_parent as contentparent, ";
-		$sql .= "layer.layer_minscale as contentminscale, layer.layer_maxscale as contentmaxscale, layer.layer_queryable,";
-		$sql .= "wms.wms_title as servicetitle, wms.wms_abstract as serviceabstract, wms.wms_id as serviceid, wms.fees, wms.accessconstraints, wms.contactperson,  wms.wms_getcapabilities,";
-		$sql .= "wms.contactposition, wms.contactorganization, wms.address, wms.city, wms_timestamp as timestamp, wms_owner as owner, wms.wms_owsproxy as owsproxy, wms.fkey_mb_group_id,";
-		$sql .= "wms.stateorprovince, wms.postcode, wms.contactvoicetelephone, wms.contactfacsimiletelephone, ";
-		$sql .= "wms.contactelectronicmailaddress, wms.country ";
-		$sql .= "FROM layer, wms WHERE layer.layer_id = $1 AND layer.fkey_wms_id = wms.wms_id LIMIT 1";
-		$v = array($layerId);
-		$t = array('i');
-		$serviceType = 'wms';
-		break;
-	case "wfs":
-		echo 'Not yet implemented!'; 
-		$serviceType = 'wfs';
-		die(); 	
-		break;
-	case "featuretype":
-		echo 'Not yet implemented!'; 
-		$serviceType = 'wfs';
-		die(); 	
-		break;
-	case "wfs-conf":
-		echo 'Not yet implemented!'; 
-		$serviceType = 'wfs';
-		die(); 	
-		break;
-	case "wmc":
-		echo 'Not yet implemented!'; 
-		die(); 	
-		break;
-}
-//read resource information from database
-$res = db_prep_query($sql,$v,$t);
-$resourceMetadata = db_fetch_array($res);
-if (!isset($resourceMetadata['contentid']) or ($resourceMetadata['contentid'] == '')) {
-		echo 'No result for the requested id found in the registry!'; 
-		die(); 	
-}
-if($resourceMetadata['owsproxy']!='') {
-	$resourceSecured = true;
-}
-else {
-	$resourceSecured = false;
-}
-$serviceId = $resourceMetadata['serviceid'];
-
-//$e = new mb_exception("mod_showMetadata: fkey_mb_group_id from wms or wfs table: ".$resourceMetadata['fkey_mb_group_id']);
-if (!isset($resourceMetadata['fkey_mb_group_id']) or isnull($resourceMetadata['fkey_mb_group_id'])){
-	$e = new mb_notice("mod_showMetadata: fkey_mb_group_id not found!");
-	//Get information about owning user of the relation mb_user_mb_group - alternativly the defined fkey_mb_group_id from the service must be used!
-	$sqlDep = "SELECT mb_group_name as metdatapointofcontactorgname, mb_group_title as metdatapointofcontactorgtitle, mb_group_id, mb_group_logo_path  as metdatapointofcontactorglogo, mb_group_address as metdatapointofcontactorgaddress, mb_group_email as metdatapointofcontactorgemail, mb_group_postcode as metdatapointofcontactorgpostcode, mb_group_city as metdatapointofcontactorgcity, mb_group_voicetelephone as metdatapointofcontactorgtelephone, mb_group_facsimiletelephone as metdatapointofcontactorgfax FROM mb_group AS a, mb_user AS b, mb_user_mb_group AS c WHERE b.mb_user_id = $1  AND b.mb_user_id = c.fkey_mb_user_id AND c.fkey_mb_group_id = a.mb_group_id AND b.mb_user_department = a.mb_group_description LIMIT 1";
-	$vDep = array($resourceMetadata['owner']);
-	$tDep = array('i');
-	$resDep = db_prep_query($sqlDep, $vDep, $tDep);
-	$metadataContactGroup = db_fetch_array($resDep);
-	$e = new mb_notice("mod_showMetadata: mb_group_id: ".$metadataContactGroup['mb_group_id']);
-	$e = new mb_notice("mod_showMetadata: mb_group_logo_path: ".$metadataContactGroup['metdatapointofcontactorglogo']);
-} else {
-	$e = new mb_notice("mod_showMetadata: fkey_mb_group_id found!");
-	$sqlDep = "SELECT mb_group_name as metdatapointofcontactorgname, mb_group_title as metdatapointofcontactorgtitle, mb_group_id, mb_group_logo_path  as metdatapointofcontactorglogo, mb_group_address as metdatapointofcontactorgaddress, mb_group_email as metdatapointofcontactorgemail, mb_group_postcode as metdatapointofcontactorgpostcode, mb_group_city as metdatapointofcontactorgcity, mb_group_voicetelephone as metdatapointofcontactorgtelephone, mb_group_facsimiletelephone as metdatapointofcontactorgfax FROM mb_group WHERE mb_group_id = $1 LIMIT 1";
-	$vDep = array($resourceMetadata['fkey_mb_group_id']);
-	$tDep = array('i');
-	$resDep = db_prep_query($sqlDep, $vDep, $tDep);
-	$metadataContactGroup = db_fetch_array($resDep);
-}
-
-$e = new mb_exception("mod_showMetadata: mb_group_name: ".$metadataContactGroup['mb_group_name']);
-//db select for layer previews
-if ($resource == 'wms' or $resource == 'layer') {
-	$sqlP = "SELECT * FROM layer_preview WHERE fkey_layer_id = $1 LIMIT 1";
-	$vP = array($layerId);
-	$tP = array('i');
-	$resP = db_prep_query($sqlP, $vP, $tP);
-	$rowP = db_fetch_array($resP);
-	if ($rowP['layer_map_preview_filename'] != "") {
-		$resourceMetadata['preview'] = "<img src = '../x_geoportal/layer_preview/".$rowP['layer_map_preview_filename']."'>";
-	}
-	if ($rowP['layer_legend_preview_filename'] != "") {
-		$resourceMetadata['legend'] .= "<img src = '../x_geoportal/layer_preview/".$rowP['layer_legend_preview_filename']."'>";
-	}
-	
-}
-
-//db select for service quality
-if ($resource == 'wms' or $resource == 'layer') {
-	$sql = "SELECT availability, last_status FROM mb_wms_availability WHERE fkey_wms_id = $1";
-	$v = array($serviceId);
-	$t = array('i');
-	$res = db_prep_query($sql, $v, $t);
-	$serviceQuality = db_fetch_array($res);
-}
-//db select for content properties
-if ($resource == 'wms' or $resource == 'layer') {
-	//get bbox and crs codes for single layer - maybe some entries ;-)
-	$sql = "SELECT * FROM layer_epsg WHERE fkey_layer_id = $1";
-	$contentBboxes = array();
-	$v = array($layerId);
-	$t = array('i');
-	$res = db_prep_query($sql, $v, $t);
-	$j = 0;
-	while ($row = db_fetch_array($res)){
-		$contentBboxes[$j] = array();
-		$contentBboxes[$j]['epsg'] = $row['epsg'];
-		$contentBboxes[$j]['minx'] = $row['minx'];
-		$contentBboxes[$j]['miny'] = $row['miny'];
-		$contentBboxes[$j]['maxx'] = $row['maxx'];
-		$contentBboxes[$j]['maxy'] = $row['maxy'];
-		$j++;
-	}
-	$j = 0;
-}
-
-//generate HTML frame
-
-//Give out page
-
-//Array with structure of metadata
-
-//e.g. tabs and their content
-$html = '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="'.$langCode.'">';
-$html .= '<body>';
-$metadataStr .= '<head>' . 
-		'<title>'.$translation['metadata'].'</title>' . 
-		'<meta name="description" content="'.$translation['metadata'].'" xml:lang="'.$langCode.'" />'.
-		'<meta name="keywords" content="'.$translation['metadata'].'" xml:lang="'.$langCode.'" />'	.	
-		'<meta http-equiv="cache-control" content="no-cache">'.
-		'<meta http-equiv="pragma" content="no-cache">'.
-		'<meta http-equiv="expires" content="0">'.
-		'<meta http-equiv="content-language" content="'.$langCode.'" />'.
-		'<meta http-equiv="content-style-type" content="text/css" />'.
-		'<meta http-equiv="Content-Type" content="text/html; charset='.CHARSET.'">' . 	
-		'</head>';
-$html .= $metadataStr;
-//define the javascripts to include
-$html .= '<link type="text/css" href="../extensions/jquery-ui-1.8.1.custom/css/ui-lightness/jquery-ui-1.8.1.custom.css" rel="Stylesheet" />';	
-$html .= '<script type="text/javascript" src="../extensions/jquery-ui-1.8.1.custom/js/jquery-1.4.2.min.js"></script>';
-$html .= '<script type="text/javascript" src="../extensions/jquery-ui-1.8.1.custom/js/jquery-ui-1.8.1.custom.min.js"></script>';
-
-//define the javascript functions
-$html .= '<script type="text/javascript">';
-$html .= '	$(function() {';
-$html .= '		$("#accordion").accordion();';
-//$html .= '		$("#accordion").accordion({ autoHeight: false});';
-//$html .= '		$("#accordion").accordion({ autoHeight: false , clearStyle: true });';
-$html .= '	});';
-$html .= '	</script>';
-$html .= '<div class="demo">';
-$html .= '<div id="accordion">';
-
-//some placeholders
-$tableBegin =  "<table>\n";
-$t_a = "\t<tr>\n\t\t<th>\n\t\t\t";
-$t_b = "\n\t\t</th>\n\t\t<td>\n\t\t\t";
-$t_c = "\n\t\t</td>\n\t</tr>\n";
-$tableEnd = "</table>\n";
-
-//generate div tags for the content - the divs are defined in the array
-$html .= '<h3><a href="#">'.$translation["overview"].'</a></h3>';
-$html .= '<div style="height:300px">';
-$html .= '<p>';
-$html .= $tableBegin;
-$html .= $t_a.$translation['resourceTitle'].$t_b.displayText($resourceMetadata['contenttitle']).$t_c;
-$html .= $t_a.$translation['kindOfResource'].$t_b.displayText($translation[$resource]).$t_c;
-if (($resource == 'wms' or $resource == 'layer') and isset($resourceMetadata['preview'])) {
-	$html .= $t_a.$translation['preview'].$t_b.$resourceMetadata['preview'];
-	if (isset($resourceMetadata['legend'])) {
-		$html .= $resourceMetadata['legend'];
-	}
-	$html .= $t_c;
-}
-$html .= $t_a.$translation['resourceAbstract'].$t_b.displayText($resourceMetadata['contentabstract']).$t_c;
-
-$user = new User();
-//
-// Monitoring is only available if the user is allowed to access this service
-//
-
-if ($resource == 'wms' or $resource == 'layer'){
-	if ($user->isLayerAccessible($layerId)) {
-		if ($subscribe === 1) {
-			$user->addSubscription($resourceMetadata['serviceid']);
-		}
-		else if ($subscribe === 0) {
-			$user = new User();
-			$user->cancelSubscription($resourceMetadata['serviceid']);
-		}
-		$currentUser = new User();
-		$is_subscribed = $currentUser->hasSubscription($resourceMetadata['serviceid']);
-		$is_public = $currentUser->isPublic();
-		//show abo function to registred and authorized users
-		//if ($is_subscribed && !$is_public) {
-		if ($is_subscribed) {
-			$aboStr = "<tr><th>Abo</th><td><img src = '../img/mail_delete.png'>" . 
-					"<a href = '../php/mod_showMetadata.php?id=" . 
-					$layerId . "&resource=layer&user_id=" . $currentUser->id . "&subscribe=0'>" . 
-					_mb("Monitoring Abo l&ouml;schen") . "</a></td></tr>"; //TODO check wherefor user_id should be given as parameter?
-		}
-		//else if (!$is_subscribed && !$is_public) {
-		else if (!$is_subscribed) {
-			$aboStr = "<tr><th>Abo</th><td><img src = '../img/mail_send.png'>" . 
-					"<a href = '../php/mod_showMetadata.php?id=" . $layerId . 
-					"&resource=layer&user_id=" . $currentUser->id . "&subscribe=1'>" . 
-					_mb("Monitoring abonnieren") . "</a></td></tr>";
-		}
-	}
-	$html .= $aboStr;
-}
-
-$html .= $tableEnd;
-$html .= '</p>';
-$html .= '</div>';
-$html .= '<h3><a href="#">'.$translation["properties"].'</a></h3>';
-$html .= '<div style="height:300px">';
-$html .= '<p>';
-$html .= $tableBegin;
-
-if ($resource == 'wms' or $resource == 'layer'){
-	if ($resourceMetadata['layer_queryable'] == '1') {
-			$html .= $t_a.$translation['queryable'].$t_b.$translation['queryableTrue'].$t_c;	
-	} else {
-			$html .= $t_a.$translation['queryable'].$t_b.$translation['queryableFalse'].$t_c;
-	}
-}
-$epsgString = '';
-for ($j = 0; $j < count($contentBboxes); $j++) {
-		$epsgString .= $contentBboxes[$j]['epsg']." ";
-		if ($contentBboxes[$j]['epsg'] == 'EPSG:4326') {
-			$wgs84Bbox = $contentBboxes[$j]['minx'].",".$contentBboxes[$j]['miny'].",".$contentBboxes[$j]['maxx'].",".$contentBboxes[$j]['maxy'];
-		}
-}
-
-$html .= $t_a.$translation['crs'].$t_b.$epsgString.$t_c;
-if (isset($wgs84Bbox)) {
-	$html .= $t_a.$translation['wgs84Bbox'].$t_b.$wgs84Bbox.$t_c;
-}
-$html .= $tableEnd;
-$html .= $tableBegin;
-//Scales
-if (isset($resourceMetadata['contentminscale']) or isset($resourceMetadata['contentmaxscale'])){
-	$html .= '<h4>'.$translation['restrictedScale'].'</h4>';
-	if (isset($resourceMetadata['contentminscale']) & $resourceMetadata['contentminscale'] != '0' ) {
-		$html .= $t_a.$translation['maxscale'].$t_b. "1 : ".$resourceMetadata['contentminscale'].$t_c;	
-	}
-	if (isset($resourceMetadata['contentmaxscale']) & $resourceMetadata['contentmaxscale'] != '0') {
-		$html .= $t_a.$translation['minscale'].$t_b. "1 : ".$resourceMetadata['contentmaxscale'].$t_c;	
-	}
-}
-
-$html .= $tableEnd;
-$html .= '</p>';
-$html .= '</div>';
-
-$html .= '<h3><a href="#">'.$translation["contact"].'</a></h3>';
-
-$html .= '<div style="height:300px">';
-$html .= '<p>';
-
-$html .= '<h4>'.$translation['metadataProvider'].'</h4>';
-
-$html .= $tableBegin;
-if ($metadataContactGroup['metdatapointofcontactorglogo'] != '') {
-	$html .= $t_a.$translation['logo'].$t_b."<img src='".$metadataContactGroup['metdatapointofcontactorglogo']."'  height='30'>".$t_c;
-}
-$html .= $t_a.$translation['contactOrganization'].$t_b.displayText($metadataContactGroup['metdatapointofcontactorgtitle']).$t_c;
-$html .= $t_a.$translation['contactAddress'].$t_b.displayText($metadataContactGroup['metdatapointofcontactorgaddress']).$t_c;
-$html .= $t_a.$translation['city'].$t_b.displayText($metadataContactGroup['metdatapointofcontactorgpostcode'].' '.$metadataContactGroup['metdatapointofcontactorgcity']).$t_c;
-$html .= $t_a.$translation['email'].$t_b.displayText($metadataContactGroup['metdatapointofcontactorgemail']).$t_c;
-$html .= $tableEnd;
-
-$html .= '<h4>'.$translation['serviceProvider'].'</h4>';
-$html .= $tableBegin;
-$html .= $t_a.$translation['contactOrganization'].$t_b.displayText($resourceMetadata['contactorganization']).$t_c;
-$html .= $t_a.$translation['contactPerson'].$t_b.displayText($resourceMetadata['contactperson']).$t_c;
-$html .= $t_a.$translation['contactAddress'].$t_b.displayText($resourceMetadata['address']).$t_c;
-$html .= $t_a.$translation['contactCity'].$t_b.displayText($resourceMetadata['postcode'].' '.$resourceMetadata['city']).$t_c;
-$html .= $t_a.$translation['email'].$t_b.displayText($resourceMetadata['contactelectronicmailaddress']).$t_c;
-$html .= $tableEnd;
-
-$html .= '</p>';
-
-$html .= '</div>';
-
-$html .= '<h3><a href="#">'.$translation["termsOfUse"].'</a></h3>';
-$html .= '<div style="height:300px">';
-$html .= '<p>';
-$tou = file_get_contents("http://localhost/mapbender/php/mod_getServiceDisclaimer.php?type=".$serviceType."&id=".$serviceId."&languageCode=".$langCode."&asTable=true");
-$html .= $tou;
-$html .= '</p>';
-$html .= '</div>';
-
-$html .= '<h3><a href="#">'.$translation["quality"].'</a></h3>';
-$html .= '<div style="height:300px">';
-$html .= '<p>';
-$html .= $tableBegin;
-switch ($serviceQuality['last_status']) {
-	case '1':
-		$html .= $t_a.$translation['status'].$t_b.'Stable'.$t_c;
-		break;
-	case '0':
-		$html .= $t_a.$translation['status'].$t_b.'Not up to date'.$t_c;
-		break;
-	case '-1':
-		$html .= $t_a.$translation['status'].$t_b.'Service has Problems'.$t_c;
-		break;
-}
-if (isset($serviceQuality['availability'])) {
-	$html .= $t_a.$translation['availability'].$t_b.$serviceQuality['availability']." %".$t_c;
-}
-$html .= $tableEnd;
-$html .= '</p>';
-$html .= '</div>';
-$html .= '<h3><a href="#">'.$translation["interfaces"].'</a></h3>';
-$html .= '<div style="height:300px">';
-$html .= '<p>';
-
-/*$translation['mapbenderCapabilities'] = 'Geoportal Capabilities';
-$translation['originalCapabilities'] = 'Original Capabilities';
-$translation['kml'] = 'KML';
-$translation['inspireMetadata'] = 'INSPIRE Service Metadaten';
-$translation['securedCapabilities'] = 'Secured Capabilities URL';*/
-$html .= $tableBegin;
-$html .= $t_a.$translation['mapbenderCapabilities'].$t_b."<a href = '../php/wms.php?layer_id=".$layerId."&PHPSESSID=".session_id()."&REQUEST=GetCapabilities&VERSION=1.1.1&SERVICE=WMS' target=_blank>".$translation['capabilities']."</a>".$t_c;
-$html .= $t_a.$translation['originalCapabilities'].$t_b."<a href = '".$resourceMetadata['wms_getcapabilities']."&REQUEST=GetCapabilities&VERSION=1.1.1&SERVICE=WMS' target=_blank>".$translation['capabilities']."</a>".$t_c;
-$html .= $t_a.$translation['inspireMetadata'].$t_b."<a href='../php/mod_layerISOMetadata.php?SERVICE=WMS&outputFormat=iso19139&Id=".	$layerId."' target=_blank ><img src='../img/inspire_tr_36.png' title='".$translation['inspireMetadata']."' style='width:34px;height:34px' alt='' /></a>"."<a href='../php/mod_layerISOMetadata.php?SERVICE=WMS&outputFormat=iso19139&Id=".$layerId."&validate=true' target=_blank title='".$translation['inspireMetadataValidation']."'>".$translation['inspireMetadataValidation']."</a>";
-
-//if service is secured and http_auth is adjusted show secured url
-if ($resourceSecured) {
-	$securedLink = HTTP_AUTH_PROXY."/".$layerId."?REQUEST=GetCapabilities&VERSION=1.1.1&SERVICE=WMS";
-	$html .= $t_a.$translation['securedCapabilities'].$t_b."<a href = '".$securedLink."' target=_blank>".$translation['capabilities']."</a>".$t_c;
-}
-//kml
-$html .= $t_a.$translation['kml'].$t_b."<a href='../php/mod_interfaceWms4Kml.php?id=".$layerId.">".$translation['kml']."-Datei</a>".$t_c;
-
-$html .= $tableEnd;
-$html .= '</p>';
-$html .= '</div>';
-
-$html .= '</div>'; //accordion
-$html .= '</div>'; //demo
-
-$html .= '</body>';
-$html .= '</html>';
-
-echo $html;
-
-//functions (from old metadata module):
-function displayText($string) {
-    $string = mb_eregi_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "<a href=\"\\0\" target=_blank>\\0</a>", $string);   
-    $string = mb_eregi_replace("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@([0-9a-z](-?[0-9a-z])*\.)+[a-z]{2}([zmuvtg]|fo|me)?$", "<a href=\"mailto:\\0\" target=_blank>\\0</a>", $string);   
-    $string = mb_eregi_replace("\n", "<br>", $string);
-    return $string;
-} 
-?>

Copied: branches/mapbender/http/php/mod_showMetadata.php (from rev 6953, trunk/mapbender/http/php/mod_showMetadata.php)
===================================================================
--- branches/mapbender/http/php/mod_showMetadata.php	                        (rev 0)
+++ branches/mapbender/http/php/mod_showMetadata.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -0,0 +1,752 @@
+<?php
+# $Id: mod_showMetadata.php 235 2010-09-08 08:34:48Z armin11 $
+# http://www.mapbender.org/index.php/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__) . "/../../core/globalSettings.php";
+require_once dirname(__FILE__) . "/../classes/class_user.php";
+require_once dirname(__FILE__) . "/../../tools/wms_extent/extent_service.conf";
+
+//GET:
+//resource: wms, layer, wfs, featuretype, wfs-conf, wmc
+//id: integer
+//outputFormat: html, xml, georss, 
+//languageCode: de, en, fr
+$layout = 'accordion';
+//Parse REQUEST Parameters
+if (isset($_REQUEST["resource"]) & $_REQUEST["resource"] != "") {
+	//validate to csv integer list
+	$testMatch = $_REQUEST["resource"];
+	if (!($testMatch == 'wms' or $testMatch == 'layer' or $testMatch == 'wfs' or $testMatch == 'featuretype' or $testMatch == 'wfs-conf')){ 
+		echo 'resource: <b>'.$testMatch.'</b> is not valid.<br/>'; 
+		die(); 		
+ 	}
+	$resource = $testMatch;
+	$testMatch = NULL;
+}
+if (isset($_REQUEST["id"]) & $_REQUEST["id"] != "") {
+	//validate to csv integer list
+	$testMatch = $_REQUEST["id"];
+	$pattern = '/^[\d,]*$/';		
+ 	if (!preg_match($pattern,$testMatch)){ 
+		echo 'id: <b>'.$testMatch.'</b> is not valid.<br/>'; 
+		die(); 		
+ 	}
+	$id = $testMatch;
+	$testMatch = NULL;
+}
+if (isset($_REQUEST["outputFormat"]) & $_REQUEST["outputFormat"] != "") {
+	//validate to csv integer list
+	$testMatch = $_REQUEST["outputFormat"];
+	if (!($testMatch == 'iso19139' or $testMatch == 'html' or $testMatch == 'georss')){ 
+		echo 'outputFormat: <b>'.$testMatch.'</b> is not valid.<br/>'; 
+		die(); 		
+ 	}
+	$outputFormat = $testMatch;
+	$testMatch = NULL;
+}
+if (isset($_REQUEST["languageCode"]) & $_REQUEST["languageCode"] != "") {
+	//validate to csv integer list
+	$testMatch = $_REQUEST["languageCode"];
+	if (!($testMatch == 'de' or $testMatch == 'fr' or $testMatch == 'en')){ 
+		echo 'languageCode: <b>'.$testMatch.'</b> is not valid.<br/>'; 
+		die(); 		
+ 	}
+	$languageCode = $testMatch;
+	$testMatch = NULL;
+}
+if (isset($_REQUEST["layout"]) & $_REQUEST["layout"] != "") {
+	//validate to csv integer list
+	$testMatch = $_REQUEST["layout"];
+	if (!($testMatch == 'tabs' or $testMatch == 'accordion' or $testMatch == 'plain')){ 
+		echo 'layout: <b>'.$testMatch.'</b> is not valid.<br/>'; 
+		die(); 		
+ 	}
+	$layout = $testMatch;
+	$testMatch = NULL;
+}
+$subscribe = intval($_GET["subscribe"]);
+
+//get language parameter out of mapbender session if it is set else set default language to de_DE
+if (isset($_SESSION['mb_lang']) and $_SESSION['mb_lang']!='') {
+	$e = new mb_exception("mod_showMetadata.php: language in session: ".$_SESSION['mb_lang']);
+	$language = $_SESSION["mb_lang"];
+} else {
+	$language = "de_DE";//use locale for compatibility with later mapbender version
+}
+
+//extract language code out of locale
+
+$langCode = explode("_", $language);
+
+$langCode = $langCode[0];
+if ($languageCode == 'de' or $languageCode == 'en' or $languageCode == 'fr') {
+	$langCode = $language;
+}
+#$langCode="de";
+
+$e = new mb_exception("mod_showMetadata.php: language: ".$langCode);
+
+//Array with translations:
+$translation['overview'] = 'Ãœbersicht';
+$translation['properties'] = 'Eigenschaften';
+$translation['termsOfUse'] = 'Nutzungsbedingungen';
+$translation['contact'] = 'Kontakt';
+$translation['quality'] = 'Qualität';
+$translation['interfaces'] = 'Schnittstellen';
+$translation['metadata'] = 'Metadaten';
+$translation['kindOfResource'] = 'Art der Ressource';
+$translation['wms'] = 'Kartendienst';
+$translation['layer'] = 'Kartenebene';
+$translation['contentId'] = 'Resourcenidentifikator';
+$translation['serviceId'] = 'Informationen zum Dienst';
+$translation['preview'] = 'Voransicht';
+$translation['extent'] = 'Ausdehnung';
+$translation['resourceAbstract'] = 'Zusammenfassung';
+$translation['resourceTitle'] = 'Titel';
+$translation['metadataProvider'] = 'Inhaltlich verantwortliche Stelle';
+$translation['serviceProvider'] = 'Technisch verantwortliche Stelle';
+$translation['contactPerson'] = 'Ansprechpartner';
+$translation['contactOrganization'] = 'Organisation';
+$translation['contactAddress'] = 'Adresse';
+$translation['email'] = 'Email';
+$translation['city'] = 'Ort';
+$translation['logo'] = 'Logo';
+$translation['status'] = 'Status';
+$translation['availability'] = 'Verfügbarkeit';
+$translation['statusRed'] = 'Probleme beim letzten Monitoring!';
+$translation['statusGreen'] = 'Letztes Monitoring OK';
+$translation['statusYellow'] = 'Dienstebeschreibung hat sich geändert!';
+$translation['queryableFalse'] = 'Ebene nicht abfragbar';
+$translation['queryableTrue'] = 'Ebene abfragbar';
+$translation['queryable'] = 'Abfragbarkeit';
+$translation['restrictedScale'] = 'Sichtbarkeit';
+$translation['minscale'] = 'Minimaler Maßstab';
+$translation['maxscale'] = 'Maximaler Maßstab';
+$translation['crs'] = 'Koordinatenreferenzsysteme (mit BBOX)';
+$translation['wgs84Bbox'] = 'Eckpunkte in geogr. Koordinaten';
+$translation['wgs84BboxGraphic'] = 'Kartenübersicht';
+$translation['mapbenderCapabilities'] = 'Geoportal Capabilities';
+$translation['originalCapabilities'] = 'Original Capabilities';
+$translation['kml'] = 'KML';
+$translation['inspireMetadata'] = 'INSPIRE Service Metadaten';
+$translation['securedCapabilities'] = 'Secured Capabilities URL';
+$translation['capabilities'] = 'Link zum Capabilities Dokument';
+$translation['inspireMetadataValidation'] = 'Validierung gegen INSPIRE Geoportal';
+
+$translation['statusOK'] = 'Stabil';
+$translation['statusChanged'] = 'Beschreibung hat sich geändert - Aktualisierung nötig';
+$translation['statusProblem'] = 'Problem bei letzter Kontrolle';
+
+
+//Array with infos about the different elements which are shown in the tabs
+
+//Check if an id and a resource was given
+if (!isset($_REQUEST["id"]) or !isset($_REQUEST["resource"])) {
+	echo 'Not enough input parameters. resource and id must be given!<br/>'; 
+	die(); 	
+}
+
+//Read out information from mapbender database
+switch ($resource) {
+	case "wms":
+		//get root layer information
+		$sql = "SELECT layer_id FROM layer WHERE fkey_wms_id = $1 AND layer_pos = 0";
+		$v = array($id);
+		$t = array("i");
+		$res = db_prep_query($sql, $v, $t);
+		$row = db_fetch_array($res);
+		$layerId = $row["layer_id"];
+		$sql = "SELECT ";
+		$sql .= "layer.layer_id as contentid, layer.layer_title as contenttitle, layer.layer_abstract as contentabstract, layer.layer_pos as contentpos, layer.layer_parent as contentparent, ";
+		$sql .= "layer.layer_minscale as contentminscale, layer.layer_maxscale as contentmaxscale, layer.layer_queryable,";
+		$sql .= "wms.wms_title as servicetitle, wms.wms_abstract as serviceabstract, wms.wms_id as serviceid, wms.fees, wms.accessconstraints, wms.contactperson, wms.wms_getcapabilities,";
+		$sql .= "wms.contactposition, wms.contactorganization, wms.address, wms.city, wms_timestamp as timestamp, wms_owner as owner, wms.wms_owsproxy as owsproxy, wms.fkey_mb_group_id,";
+		$sql .= "wms.stateorprovince, wms.postcode, wms.contactvoicetelephone, wms.contactfacsimiletelephone, ";
+		$sql .= "wms.contactelectronicmailaddress, wms.country ";
+		$sql .= "FROM layer, wms WHERE layer.layer_id = $1 AND layer.fkey_wms_id = wms.wms_id LIMIT 1";
+		$v = array($layerId);
+		$t = array('i');
+		$serviceType = 'wms';
+		$resourceSymbol = "<img src='../img/osgeo_graphics/geosilk/server_map.png' alt='".$translation['wms']." - Bild' title='".$translation['wms']."'> - ".$translation['wms'];
+		break;
+	case "layer":
+		$layerId = $id;
+		$sql = "SELECT ";
+		$sql .= "layer.layer_id as contentid, layer.layer_title as contenttitle, layer.layer_abstract as contentabstract, layer.layer_pos as contentpos, layer.layer_parent as contentparent, ";
+		$sql .= "layer.layer_minscale as contentminscale, layer.layer_maxscale as contentmaxscale, layer.layer_queryable,";
+		$sql .= "wms.wms_title as servicetitle, wms.wms_abstract as serviceabstract, wms.wms_id as serviceid, wms.fees, wms.accessconstraints, wms.contactperson,  wms.wms_getcapabilities,";
+		$sql .= "wms.contactposition, wms.contactorganization, wms.address, wms.city, wms_timestamp as timestamp, wms_owner as owner, wms.wms_owsproxy as owsproxy, wms.fkey_mb_group_id,";
+		$sql .= "wms.stateorprovince, wms.postcode, wms.contactvoicetelephone, wms.contactfacsimiletelephone, ";
+		$sql .= "wms.contactelectronicmailaddress, wms.country ";
+		$sql .= "FROM layer, wms WHERE layer.layer_id = $1 AND layer.fkey_wms_id = wms.wms_id LIMIT 1";
+		$v = array($layerId);
+		$t = array('i');
+		$serviceType = 'wms';
+		$resourceSymbol = "<img src='../img/osgeo_graphics/Layer.png' alt='".$translation['layer']." - Bild' title='".$translation['layer']."'> - ".$translation['layer'];
+		break;
+	case "wfs":
+		echo 'Not yet implemented!'; 
+		$serviceType = 'wfs';
+		die(); 	
+		break;
+	case "featuretype":
+		echo 'Not yet implemented!'; 
+		$serviceType = 'wfs';
+		die(); 	
+		break;
+	case "wfs-conf":
+		echo 'Not yet implemented!'; 
+		$serviceType = 'wfs';
+		die(); 	
+		break;
+	case "wmc":
+		echo 'Not yet implemented!'; 
+		die(); 	
+		break;
+}
+//read resource information from database
+$res = db_prep_query($sql,$v,$t);
+$resourceMetadata = db_fetch_array($res);
+if (!isset($resourceMetadata['contentid']) or ($resourceMetadata['contentid'] == '')) {
+		echo 'No result for the requested id found in the registry!'; 
+		die(); 	
+}
+if($resourceMetadata['owsproxy']!='') {
+	$resourceSecured = true;
+}
+else {
+	$resourceSecured = false;
+}
+$serviceId = $resourceMetadata['serviceid'];
+
+
+/*switch ($serviceType) {
+	case "wms":
+		#$resourceSymbol = "<img src='../img/osgeo_graphics/geosilk/server_map.png' alt='".."' title='".."'>";
+		die(); 	
+		break;
+	case "wfs":
+		#$resourceSymbol = "<img src='../img/osgeo_graphics/geosilk/server_vector.png' alt='' title=''>";
+		die(); 	
+		break;		
+	case "wmc":
+		$resourceSymbol = "<img src='' alt='' title=''>";
+		die(); 	
+		break;
+	case "kml":
+		die(); 	
+		break;
+	case "georss":
+		die(); 	
+		break;
+}
+
+*/
+
+
+
+
+//$e = new mb_exception("mod_showMetadata: fkey_mb_group_id from wms or wfs table: ".$resourceMetadata['fkey_mb_group_id']);
+if (!isset($resourceMetadata['fkey_mb_group_id']) or isnull($resourceMetadata['fkey_mb_group_id'])){
+	$e = new mb_notice("mod_showMetadata: fkey_mb_group_id not found!");
+	//Get information about owning user of the relation mb_user_mb_group - alternativly the defined fkey_mb_group_id from the service must be used!
+	$sqlDep = "SELECT mb_group_name as metdatapointofcontactorgname, mb_group_title as metdatapointofcontactorgtitle, mb_group_id, mb_group_logo_path  as metdatapointofcontactorglogo, mb_group_address as metdatapointofcontactorgaddress, mb_group_email as metdatapointofcontactorgemail, mb_group_postcode as metdatapointofcontactorgpostcode, mb_group_city as metdatapointofcontactorgcity, mb_group_voicetelephone as metdatapointofcontactorgtelephone, mb_group_facsimiletelephone as metdatapointofcontactorgfax FROM mb_group AS a, mb_user AS b, mb_user_mb_group AS c WHERE b.mb_user_id = $1  AND b.mb_user_id = c.fkey_mb_user_id AND c.fkey_mb_group_id = a.mb_group_id AND b.mb_user_department = a.mb_group_description LIMIT 1";
+	$vDep = array($resourceMetadata['owner']);
+	$tDep = array('i');
+	$resDep = db_prep_query($sqlDep, $vDep, $tDep);
+	$metadataContactGroup = db_fetch_array($resDep);
+	$e = new mb_notice("mod_showMetadata: mb_group_id: ".$metadataContactGroup['mb_group_id']);
+	$e = new mb_notice("mod_showMetadata: mb_group_logo_path: ".$metadataContactGroup['metdatapointofcontactorglogo']);
+} else {
+	$e = new mb_notice("mod_showMetadata: fkey_mb_group_id found!");
+	$sqlDep = "SELECT mb_group_name as metdatapointofcontactorgname, mb_group_title as metdatapointofcontactorgtitle, mb_group_id, mb_group_logo_path  as metdatapointofcontactorglogo, mb_group_address as metdatapointofcontactorgaddress, mb_group_email as metdatapointofcontactorgemail, mb_group_postcode as metdatapointofcontactorgpostcode, mb_group_city as metdatapointofcontactorgcity, mb_group_voicetelephone as metdatapointofcontactorgtelephone, mb_group_facsimiletelephone as metdatapointofcontactorgfax FROM mb_group WHERE mb_group_id = $1 LIMIT 1";
+	$vDep = array($resourceMetadata['fkey_mb_group_id']);
+	$tDep = array('i');
+	$resDep = db_prep_query($sqlDep, $vDep, $tDep);
+	$metadataContactGroup = db_fetch_array($resDep);
+}
+
+$e = new mb_exception("mod_showMetadata: mb_group_name: ".$metadataContactGroup['mb_group_name']);
+//db select for layer previews
+if ($resource == 'wms' or $resource == 'layer') {
+	$sqlP = "SELECT * FROM layer_preview WHERE fkey_layer_id = $1 LIMIT 1";
+	$vP = array($layerId);
+	$tP = array('i');
+	$resP = db_prep_query($sqlP, $vP, $tP);
+	$rowP = db_fetch_array($resP);
+	if ($rowP['layer_map_preview_filename'] != "") {
+		$resourceMetadata['preview'] = "<img src = '../x_geoportal/layer_preview/".$rowP['layer_map_preview_filename']."'>";
+	}
+	if ($rowP['layer_legend_preview_filename'] != "") {
+		$resourceMetadata['legend'] .= "<img src = '../x_geoportal/layer_preview/".$rowP['layer_legend_preview_filename']."'>";
+	}
+	if ($rowP['layer_extent_preview_filename'] != "") {
+		$resourceMetadata['extent'] .= "<img src = '../x_geoportal/layer_preview/".$rowP['layer_extent_preview_filename']."'>";
+	}
+	
+}
+
+//db select for service quality
+if ($resource == 'wms' or $resource == 'layer') {
+	$sql = "SELECT availability, last_status FROM mb_wms_availability WHERE fkey_wms_id = $1";
+	$v = array($serviceId);
+	$t = array('i');
+	$res = db_prep_query($sql, $v, $t);
+	$serviceQuality = db_fetch_array($res);
+}
+//db select for content properties
+if ($resource == 'wms' or $resource == 'layer') {
+	//get bbox and crs codes for single layer - maybe some entries ;-)
+	$sql = "SELECT * FROM layer_epsg WHERE fkey_layer_id = $1";
+	$contentBboxes = array();
+	$v = array($layerId);
+	$t = array('i');
+	$res = db_prep_query($sql, $v, $t);
+	$j = 0;
+	while ($row = db_fetch_array($res)){
+		$contentBboxes[$j] = array();
+		$contentBboxes[$j]['epsg'] = $row['epsg'];
+		$contentBboxes[$j]['minx'] = $row['minx'];
+		$contentBboxes[$j]['miny'] = $row['miny'];
+		$contentBboxes[$j]['maxx'] = $row['maxx'];
+		$contentBboxes[$j]['maxy'] = $row['maxy'];
+		$j++;
+	}
+	$j = 0;
+}
+
+//generate HTML frame
+
+//Give out page
+
+//Array with structure of metadata
+
+//e.g. tabs and their content
+$html = '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="'.$langCode.'">';
+$html .= '<body>';
+$metadataStr .= '<head>' . 
+		'<title>'.$translation['metadata'].'</title>' . 
+		'<meta name="description" content="'.$translation['metadata'].'" xml:lang="'.$langCode.'" />'.
+		'<meta name="keywords" content="'.$translation['metadata'].'" xml:lang="'.$langCode.'" />'	.	
+		'<meta http-equiv="cache-control" content="no-cache">'.
+		'<meta http-equiv="pragma" content="no-cache">'.
+		'<meta http-equiv="expires" content="0">'.
+		'<meta http-equiv="content-language" content="'.$langCode.'" />'.
+		'<meta http-equiv="content-style-type" content="text/css" />'.
+		'<meta http-equiv="Content-Type" content="text/html; charset='.CHARSET.'">' . 	
+		'</head>';
+$html .= $metadataStr;
+//define the javascripts to include
+	$html .= '<link type="text/css" href="../css/metadataNew.css" rel="Stylesheet" />';
+
+if ($layout == 'tabs') {
+	$html .= '<link type="text/css" href="../extensions/jquery-ui-1.8.1.custom/css/custom-theme/jquery-ui-1.8.4.custom.css" rel="Stylesheet" />';	
+	$html .= '<script type="text/javascript" src="../extensions/jquery-ui-1.8.1.custom/js/jquery-1.4.2.min.js"></script>';
+	$html .= '<script type="text/javascript" src="../extensions/jquery-ui-1.8.1.custom/js/jquery-ui-1.8.1.custom.min.js"></script>';
+
+
+/*if ($metadataContactGroup['metdatapointofcontactorglogo'] != '') {
+	$html .= "<img src='".$metadataContactGroup['metdatapointofcontactorglogo']."'  height='30'>";
+}
+//TODO use right name
+$html .= displayText($resourceMetadata['contactorganization']);
+$html .= '<h3>'.displayText($resourceMetadata['contenttitle']).'</h3>';
+*/
+
+
+
+//initialize tabs
+	$html .= '<script type="text/javascript">';
+	$html .= '$(function() {';
+	$html .= '	$("#tabs").tabs();';
+	$html .= '});';
+	$html .= '</script>';
+
+
+
+
+
+
+
+
+
+//independently define the headers of the parts
+	$html .= '<div class="demo">';
+	$html .= '<div id="tabs">';
+	$html .= '<ul>';
+	$html .= 	'<li><a href="#tabs-1">'.$translation["overview"].'</a></li>';
+	$html .= 	'<li><a href="#tabs-2">'.$translation["properties"].'</a></li>';
+	$html .= 	'<li><a href="#tabs-3">'.$translation["contact"].'</a></li>';
+	$html .= 	'<li><a href="#tabs-4">'.$translation["termsOfUse"].'</a></li>';
+	$html .= 	'<li><a href="#tabs-5">'.$translation["quality"].'</a></li>';
+	$html .= 	'<li><a href="#tabs-6">'.$translation["interfaces"].'</a></li>';
+	$html .= '</ul>';
+
+}
+
+if ($layout == 'accordion') {
+	$html .= '<link type="text/css" href="../extensions/jquery-ui-1.8.1.custom/css/custom-theme/jquery-ui-1.8.4.custom.css" rel="Stylesheet" />';	
+	$html .= '<script type="text/javascript" src="../extensions/jquery-ui-1.8.1.custom/js/jquery-1.4.2.min.js"></script>';
+	$html .= '<script type="text/javascript" src="../extensions/jquery-ui-1.8.1.custom/js/jquery-ui-1.8.1.custom.min.js"></script>';
+	//define the javascript functions
+	$html .= '<script type="text/javascript">';
+	$html .= '	$(function() {';
+	$html .= '		$("#accordion").accordion();';
+	//$html .= '		$("#accordion").accordion({ autoHeight: false});';
+	//$html .= '		$("#accordion").accordion({ autoHeight: false , clearStyle: true });';
+	$html .= '	});';
+	$html .= '	</script>';
+	$html .= '<div class="demo">';
+	$html .= '<div id="accordion">';
+}
+if ($layout == 'plain') {
+	$html .= '<div class="demo">';
+	$html .= '<div id="plain">';
+}
+
+//some placeholders
+$tableBegin =  "<table>\n";
+$t_a = "\t<tr>\n\t\t<th>\n\t\t\t";
+$t_b = "\n\t\t</th>\n\t\t<td>\n\t\t\t";
+$t_c = "\n\t\t</td>\n\t</tr>\n";
+$tableEnd = "</table>\n";
+//**************************overview part begin******************************
+//generate div tags for the content - the divs are defined in the array
+if ($layout == 'accordion') {
+	$html .= '<h3><a href="#">'.$translation["overview"].'</a></h3>';
+	$html .= '<div style="height:300px">';
+}
+if ($layout == 'tabs') {
+	$html .= '<div id="tabs-1">';
+}
+if ($layout == 'plain') {
+	$html .= '<h3>'.$translation["overview"].'</h3>';
+	$html .= '<div>';
+}
+$html .= '<p>';
+$html .= $tableBegin;
+$html .= $t_a.$translation['resourceTitle'].$t_b."<em>".displayText($resourceMetadata['contenttitle'])."</em>".$t_c;
+
+//decide if a root layer have been found - then the type will be a server
+#$html .= "<br>".$resourceMetadata['contentpos']."<br>";
+#$html .= "<br>".$resource."<br>";
+if ($resource == 'layer' & $resourceMetadata['contentpos'] == 0) {
+	$resourceSymbol = "<img src='../img/osgeo_graphics/geosilk/server_map.png' alt='".$translation['wms']." - Bild' title='".$translation['wms']."'> - ".$translation['wms'];
+}
+$html .= $t_a.$translation['kindOfResource'].$t_b.$resourceSymbol.$t_c;
+
+//identification information:
+$html .= $t_a.$translation['contentId'].$t_b.$resourceMetadata['contentid'].$t_c;
+$html .= $t_a.$translation['serviceId'].$t_b."<a href='".$self."?resource=".$serviceType."&id=".$serviceId."&layout=".$layout."'>".$serviceId."</a>".$t_c;
+
+if (($resource == 'wms' or $resource == 'layer') and isset($resourceMetadata['preview'])) {
+	$html .= $t_a.$translation['preview'].$t_b.$resourceMetadata['preview'];
+	if (isset($resourceMetadata['legend'])) {
+		$html .= $resourceMetadata['legend'];
+	}
+	$html .= $t_c;
+}
+
+
+
+
+
+if ($metadataContactGroup['metdatapointofcontactorglogo'] != '') {
+	$html .= $t_a.$translation['contactOrganization'].$t_b."<img src='".$metadataContactGroup['metdatapointofcontactorglogo']."'  height='30'>";
+}
+$html .= displayText($metadataContactGroup['metadatacontactorganization']).$t_c;
+$html .= $t_a.$translation['resourceAbstract'].$t_b.displayText($resourceMetadata['contentabstract']).$t_c;
+
+$user = new User();
+//
+// Monitoring is only available if the user is allowed to access this service
+//
+
+if ($resource == 'wms' or $resource == 'layer'){
+	if ($user->isLayerAccessible($layerId)) {
+		if ($subscribe === 1) {
+			$user->addSubscription($resourceMetadata['serviceid']);
+		}
+		else if ($subscribe === 0) {
+			$user = new User();
+			$user->cancelSubscription($resourceMetadata['serviceid']);
+		}
+		$currentUser = new User();
+		$is_subscribed = $currentUser->hasSubscription($resourceMetadata['serviceid']);
+		$is_public = $currentUser->isPublic();
+		//show abo function to registred and authorized users
+		//if ($is_subscribed && !$is_public) {
+		if ($is_subscribed) {
+			$aboStr = "<tr><th>Abo</th><td><img src = '../img/mail_delete.png'>" . 
+					"<a href = '../php/mod_showMetadata.php?id=" . 
+					$layerId . "&resource=layer&user_id=" . $currentUser->id . "&subscribe=0'>" . 
+					_mb("Monitoring Abo l&ouml;schen") . "</a></td></tr>"; //TODO check wherefor user_id should be given as parameter?
+		}
+		//else if (!$is_subscribed && !$is_public) {
+		else if (!$is_subscribed) {
+			$aboStr = "<tr><th>Abo</th><td><img src = '../img/mail_send.png'>" . 
+					"<a href = '../php/mod_showMetadata.php?id=" . $layerId . 
+					"&resource=layer&user_id=" . $currentUser->id . "&subscribe=1'>" . 
+					_mb("Monitoring abonnieren") . "</a></td></tr>";
+		}
+	}
+	$html .= $aboStr;
+}
+
+$html .= $tableEnd;
+$html .= '</p>';
+$html .= '</div>';
+
+//**************************overview part end******************************
+
+//**************************properties part begin******************************
+if ($layout == 'accordion') {
+	$html .= '<h3><a href="#">'.$translation["properties"].'</a></h3>';
+	$html .= '<div style="height:300px">';
+}
+if ($layout == 'tabs') {
+	$html .= '<div id="tabs-2">';
+}
+if ($layout == 'plain') {
+	$html .= '<h3>'.$translation["properties"].'</h3>';
+	$html .= '<div>';
+}
+$html .= '<p>';
+$html .= $tableBegin;
+
+if ($resource == 'wms' or $resource == 'layer'){
+	if ($resourceMetadata['layer_queryable'] == '1') {
+			$html .= $t_a.$translation['queryable'].$t_b."<img src='../img/osgeo_graphics/select.png' title='".$translation['queryableTrue']."' alt='".$translation['queryableTrue']."'>".$t_c;	
+	} else {
+		$html .= $t_a.$translation['queryable'].$t_b."<img src='../img/osgeo_graphics/not_selectable.png' title='".$translation['queryableFalse']."' alt='".$translation['queryableFalse']."'>".$t_c;	
+	}
+}
+$epsgString = '';
+for ($j = 0; $j < count($contentBboxes); $j++) {
+		$epsgString .= $contentBboxes[$j]['epsg']." ";
+		if ($contentBboxes[$j]['epsg'] == 'EPSG:4326') {
+			$wgs84Bbox = $contentBboxes[$j]['minx'].",".$contentBboxes[$j]['miny'].",".$contentBboxes[$j]['maxx'].",".$contentBboxes[$j]['maxy'];
+			
+			$getMapUrl = getExtentGraphic(explode(",", $wgs84Bbox),$layerId);
+		}
+}
+
+$html .= $t_a.$translation['crs'].$t_b.$epsgString.$t_c;
+if (isset($wgs84Bbox)) {
+	$html .= $t_a.$translation['wgs84Bbox'].$t_b.$wgs84Bbox.$t_c;
+	if (defined('EXTENTSERVICEURL')) {
+		$html .= $t_a.$translation['wgs84BboxGraphic'].$t_b."<img src='".$getMapUrl."'>".$t_c;
+	}
+	//show preview map - dynamically
+	
+}
+$html .= $tableEnd;
+$html .= $tableBegin;
+//Scales
+if ((isset($resourceMetadata['contentminscale']) & $resourceMetadata['contentminscale'] != '0') or (isset($resourceMetadata['contentmaxscale']) & $resourceMetadata['contentmaxscale'] != '0')){
+	$html .= '<h4>'.$translation['restrictedScale'].'</h4>';
+	if (isset($resourceMetadata['contentminscale']) & $resourceMetadata['contentminscale'] != '0' ) {
+		$html .= $t_a.$translation['maxscale'].$t_b. "1 : ".$resourceMetadata['contentminscale'].$t_c;	
+	}
+	if (isset($resourceMetadata['contentmaxscale']) & $resourceMetadata['contentmaxscale'] != '0') {
+		$html .= $t_a.$translation['minscale'].$t_b. "1 : ".$resourceMetadata['contentmaxscale'].$t_c;	
+	}
+}
+
+$html .= $tableEnd;
+$html .= '</p>';
+$html .= '</div>';
+//**************************properties  part end******************************
+
+//**************************contact part begin******************************
+if ($layout == 'accordion') {
+	$html .= '<h3><a href="#">'.$translation["contact"].'</a></h3>';
+	$html .= '<div style="height:300px">';
+}
+if ($layout == 'tabs') {
+	$html .= '<div id="tabs-3">';
+}
+if ($layout == 'plain') {
+	$html .= '<h3>'.$translation["contact"].'</h3>';
+	$html .= '<div>';
+}
+$html .= '<p>';
+
+$html .= '<h4>'.$translation['metadataProvider'].'</h4>';
+
+$html .= $tableBegin;
+if ($metadataContactGroup['metdatapointofcontactorglogo'] != '') {
+	$html .= $t_a.$translation['logo'].$t_b."<img src='".$metadataContactGroup['metdatapointofcontactorglogo']."'  height='30'>".$t_c;
+}
+$html .= $t_a.$translation['contactOrganization'].$t_b.displayText($metadataContactGroup['metdatapointofcontactorgtitle']).$t_c;
+$html .= $t_a.$translation['contactAddress'].$t_b.displayText($metadataContactGroup['metdatapointofcontactorgaddress']).$t_c;
+$html .= $t_a.$translation['city'].$t_b.displayText($metadataContactGroup['metdatapointofcontactorgpostcode'].' '.$metadataContactGroup['metdatapointofcontactorgcity']).$t_c;
+$html .= $t_a.$translation['email'].$t_b.displayText($metadataContactGroup['metdatapointofcontactorgemail']).$t_c;
+$html .= $tableEnd;
+
+$html .= '<h4>'.$translation['serviceProvider'].'</h4>';
+$html .= $tableBegin;
+$html .= $t_a.$translation['contactOrganization'].$t_b.displayText($resourceMetadata['contactorganization']).$t_c;
+$html .= $t_a.$translation['contactPerson'].$t_b.displayText($resourceMetadata['contactperson']).$t_c;
+$html .= $t_a.$translation['contactAddress'].$t_b.displayText($resourceMetadata['address']).$t_c;
+$html .= $t_a.$translation['contactCity'].$t_b.displayText($resourceMetadata['postcode'].' '.$resourceMetadata['city']).$t_c;
+$html .= $t_a.$translation['email'].$t_b.displayText($resourceMetadata['contactelectronicmailaddress']).$t_c;
+$html .= $tableEnd;
+
+$html .= '</p>';
+
+$html .= '</div>';
+//**************************contact part end******************************
+
+//**************************termsOfUse part begin******************************
+if ($layout == 'accordion') {
+	$html .= '<h3><a href="#">'.$translation["termsOfUse"].'</a></h3>';
+	$html .= '<div style="height:300px">';
+}
+if ($layout == 'tabs') {
+	$html .= '<div id="tabs-4">';
+}
+if ($layout == 'plain') {
+	$html .= '<h3>'.$translation["termsOfUse"].'</h3>';
+	$html .= '<div>';
+}
+$html .= '<p>';
+$tou = file_get_contents("http://localhost/mapbender/php/mod_getServiceDisclaimer.php?type=".$serviceType."&id=".$serviceId."&languageCode=".$langCode."&asTable=true");
+$html .= $tou;
+$html .= '</p>';
+$html .= '</div>';
+//**************************termsOfUse part end******************************
+
+//**************************quality part begin******************************
+if ($layout == 'accordion') {
+	$html .= '<h3><a href="#">'.$translation["quality"].'</a></h3>';
+	$html .= '<div style="height:300px">';
+}
+if ($layout == 'tabs') {
+	$html .= '<div id="tabs-5">';
+}
+if ($layout == 'plain') {
+	$html .= '<h3>'.$translation["quality"].'</h3>';
+	$html .= '<div>';
+}
+$html .= '<p>';
+$html .= $tableBegin;
+switch ($serviceQuality['last_status']) {
+	case '1':
+		$html .= $t_a.$translation['status'].$t_b."<img src='../img/trafficlights/go.bmp' height='24px' width='24px' alt='".$translation['statusOK']."' title='".$translation['statusOK']."'>".$t_c;
+		break;
+	case '0':
+		$html .= $t_a.$translation['status'].$t_b."<img src='../img/trafficlights/wait.bmp' height='24px' width='24px'  alt='".$translation['statusChanged']."' title='".$translation['statusChanged']."'>".$t_c;
+		break;
+	case '-1':
+		$html .= $t_a.$translation['status'].$t_b."<img src='../img/trafficlights/stop.bmp' height='24px' width='24px'  alt='".$translation['statusProblem']."' title='".$translation['statusChanged']."'>".$t_c;
+		break;
+}
+if (isset($serviceQuality['availability'])) {
+	$html .= $t_a.$translation['availability'].$t_b.$serviceQuality['availability']." %".$t_c;
+}
+$html .= $tableEnd;
+$html .= '</p>';
+$html .= '</div>';
+//**************************quality part end******************************
+
+//**************************interfaces part begin******************************
+if ($layout == 'accordion') {
+	$html .= '<h3><a href="#">'.$translation["interfaces"].'</a></h3>';
+	$html .= '<div style="height:300px">';
+}
+if ($layout == 'tabs') {
+	$html .= '<div id="tabs-6">';
+}
+if ($layout == 'plain') {
+	$html .= '<h3>'.$translation["interfaces"].'</h3>';
+	$html .= '<div>';
+}
+$html .= '<p>';
+
+/*$translation['mapbenderCapabilities'] = 'Geoportal Capabilities';
+$translation['originalCapabilities'] = 'Original Capabilities';
+$translation['kml'] = 'KML';
+$translation['inspireMetadata'] = 'INSPIRE Service Metadaten';
+$translation['securedCapabilities'] = 'Secured Capabilities URL';*/
+$html .= $tableBegin;
+$html .= $t_a.$translation['mapbenderCapabilities'].$t_b."<a href = '../php/wms.php?layer_id=".$layerId."&PHPSESSID=".session_id()."&REQUEST=GetCapabilities&VERSION=1.1.1&SERVICE=WMS' target=_blank>".$translation['capabilities']."</a>".$t_c;
+$html .= $t_a.$translation['originalCapabilities'].$t_b."<a href = '".$resourceMetadata['wms_getcapabilities']."&REQUEST=GetCapabilities&VERSION=1.1.1&SERVICE=WMS' target=_blank>".$translation['capabilities']."</a>".$t_c;
+$html .= $t_a.$translation['inspireMetadata'].$t_b."<a href='../php/mod_layerISOMetadata.php?SERVICE=WMS&outputFormat=iso19139&Id=".	$layerId."' target=_blank ><img src='../img/inspire_tr_36.png' title='".$translation['inspireMetadata']."' style='width:34px;height:34px' alt='' /></a>"."<a href='../php/mod_layerISOMetadata.php?SERVICE=WMS&outputFormat=iso19139&Id=".$layerId."&validate=true' target=_blank title='".$translation['inspireMetadataValidation']."'>".$translation['inspireMetadataValidation']."</a>";
+
+//if service is secured and http_auth is adjusted show secured url
+if ($resourceSecured) {
+	$securedLink = HTTP_AUTH_PROXY."/".$layerId."?REQUEST=GetCapabilities&VERSION=1.1.1&SERVICE=WMS";
+	$html .= $t_a.$translation['securedCapabilities'].$t_b."<a href = '".$securedLink."' target=_blank>".$translation['capabilities']."</a>".$t_c;
+}
+//kml
+$html .= $t_a.$translation['kml'].$t_b."<a href='../php/mod_interfaceWms4Kml.php?id=".$layerId."'>".$translation['kml']."-Datei</a>".$t_c;
+
+$html .= $tableEnd;
+$html .= '</p>';
+$html .= '</div>';
+//**************************interfaces part end******************************
+
+$html .= '</div>'; //accordion
+$html .= '</div>'; //demo
+
+$html .= '</body>';
+$html .= '</html>';
+
+echo $html;
+
+//functions (from old metadata module):
+function displayText($string) {
+    $string = mb_eregi_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "<a href=\"\\0\" target=_blank>\\0</a>", $string);   
+    $string = mb_eregi_replace("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@([0-9a-z](-?[0-9a-z])*\.)+[a-z]{2}([zmuvtg]|fo|me)?$", "<a href=\"mailto:\\0\" target=_blank>\\0</a>", $string);   
+    $string = mb_eregi_replace("\n", "<br>", $string);
+    return $string;
+} 
+function getExtentGraphic($layer_4326_box, $layerId) {
+		$rlp_4326_box = array(6.05,48.9,8.6,50.96);
+		if ($layer_4326_box[0] <= $rlp_4326_box[0] || $layer_4326_box[2] >= $rlp_4326_box[2] || $layer_4326_box[1] <= $rlp_4326_box[1] || $layer_4326_box[3] >= $rlp_4326_box[3]) {
+			if ($layer_4326_box[0] < $rlp_4326_box[0]) {
+				$rlp_4326_box[0] = $layer_4326_box[0]; 
+			}
+			if ($layer_4326_box[2] > $rlp_4326_box[2]) {
+				$rlp_4326_box[2] = $layer_4326_box[2]; 
+			}
+			if ($layer_4326_box[1] < $rlp_4326_box[1]) {
+				$rlp_4326_box[1] = $layer_4326_box[1]; 
+			}
+			if ($layer_4326_box[3] > $rlp_4326_box[3]) {
+				$rlp_4326_box[3] = $layer_4326_box[3]; 
+			}
+
+			$d_x = $rlp_4326_box[2] - $rlp_4326_box[0]; 
+			$d_y = $rlp_4326_box[3] - $rlp_4326_box[1];
+			
+			$new_minx = $rlp_4326_box[0] - 0.05*($d_x);
+			$new_maxx = $rlp_4326_box[2] + 0.05*($d_x);
+			$new_miny = $rlp_4326_box[1] - 0.05*($d_y);
+			$new_maxy = $rlp_4326_box[3] + 0.05*($d_y);
+
+			if ($new_minx < -180) $rlp_4326_box[0] = -180; else $rlp_4326_box[0] = $new_minx;
+			if ($new_maxx > 180) $rlp_4326_box[2] = 180; else $rlp_4326_box[2] = $new_maxx;
+			if ($new_miny < -90) $rlp_4326_box[1] = -90; else $rlp_4326_box[1] = $new_miny;
+			if ($new_maxy > 90) $rlp_4326_box[3] = 90; else $rlp_4326_box[3] = $new_maxy;
+		}
+		$getMapUrl = EXTENTSERVICEURL."VERSION=1.1.1&REQUEST=GetMap&SERVICE=WMS&LAYERS=background,extent&STYLES=&SRS=EPSG:4326&BBOX=".$rlp_4326_box[0].",".$rlp_4326_box[1].",".$rlp_4326_box[2].",".$rlp_4326_box[3]."&WIDTH=120&HEIGHT=120&FORMAT=image/png&BGCOLOR=0xffffff&TRANSPARENT=TRUE&EXCEPTIONS=application/vnd.ogc.se_inimage&minx=".$layer_4326_box[0]."&miny=".$layer_4326_box[1]."&maxx=".$layer_4326_box[2]."&maxy=".$layer_4326_box[3];
+		return $getMapUrl;
+}
+?>

Deleted: branches/mapbender/http/php/wms.php
===================================================================
--- trunk/mapbender/http/php/wms.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/http/php/wms.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,1093 +0,0 @@
-<?php
-# $Id: mb_listGUIs.php 11 2006-07-31 16:22:36Z rothstein $
-# http://www.mapbender.org/index.php/mb_listGUIs.php
-# 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__)."/../../core/globalSettings.php");
-require_once(dirname(__FILE__)."/../classes/class_layer_monitor.php");
-
-//
-// make all parameters available as upper case
-//
-foreach($_GET as $key => $val) {
-	$_GET[strtoupper($key)] = $val;
-}
-
-$requestType = $_GET["REQUEST"];
-$version = $_GET["VERSION"];
-$service = strtoupper($_GET["SERVICE"]);
-$layerId = $_GET["LAYER_ID"];
-$updateSequence = intval($_GET["UPDATESEQUENCE"]);
-$mapbenderMetadataUrl = preg_replace("/(.*)frames\/login.php/", "$1php/mod_layerMetadata.php?id=", LOGIN);
-
-/**
- * Creates an XML Exception according to WMS 1.1.1
- * 
- * @return an XML String
- * @param $errorCode String
- * @param $errorMessage String
- */
-function createExceptionXml ($errorCode, $errorMessage) {
-	// see http://de2.php.net/manual/de/domimplementation.createdocumenttype.php
-	$imp = new DOMImplementation;
-	$dtd = $imp->createDocumentType("ServiceExceptionReport", "", "http://schemas.opengis.net/wms/1.1.1/exception_1_1_1.dtd");
-	
-	$doc = $imp->createDocument("", "", $dtd);
-	$doc->encoding = 'UTF-8';
-	$doc->standalone = false;
-	
-	$el = $doc->createElement("ServiceExceptionReport");
-	$exc = $doc->createElement("ServiceException", $errorMessage);
-	if ($errorCode) {
-		$exc->setAttribute("code", $errorCode);
-	}
-	$el->appendChild($exc);
-	$doc->appendChild($el);
-	
-	return $doc->saveXML();
-}
-
-//
-// check if service param is set
-//
-if (!isset($service) || $service === "" || $service != "WMS") {
-	header("Content-type: application/xhtml+xml; charset=UTF-8");
-	echo createExceptionXml("", "Parameter SERVICE invalid");
-	die;
-}
-
-//
-// check if request param is set
-//
-if (!isset($requestType) || $requestType === "" || 
-	($service == "WMS" && $requestType != "GetCapabilities")) {
-		
-	header("Content-type: application/xhtml+xml; charset=UTF-8");
-	echo createExceptionXml("", "Parameter REQUEST invalid");
-	die;
-}
-
-//
-// check if version param is set
-//
-if (!isset($version) || $version === "" || 
-	($service == "WMS" && $version != "1.1.1")) {
-		
-	// optional parameter, set to 1.1.1 if not set
-	$version = "1.1.1";
-}
-
-//
-// check if layer id is set
-//
-if (!isset($layerId) || !is_numeric($layerId)) {
-	// TO DO: create exception XML
-	header("Content-type: application/xhtml+xml; charset=UTF-8");
-	echo createExceptionXml(
-		"Layer not defined", 
-		"Unknown layer id " . $layerId
-	);
-	die;
-}
-
-//
-// check if layer is stored in database
-//
-$wms_sql = "SELECT * FROM wms AS w, layer AS l " . 
-	"where l.layer_id = $1 AND l.fkey_wms_id = w.wms_id LIMIT 1";
-$v = array($layerId);
-$t = array("i");
-$res_wms_sql = db_prep_query($wms_sql, $v, $t);
-$wms_row = db_fetch_array($res_wms_sql);
-
-if (!$wms_row["wms_id"]) {
-	// TO DO: create exception XML
-	header("Content-type: application/xhtml+xml; charset=UTF-8");
-	echo createExceptionXml(
-		"Layer not defined", 
-		"Unknown layer id " . $layerId
-	);
-	die;
-}
-
-//
-// check if update sequence is valid
-//
-$updateSequenceDb = intval($wms_row["wms_timestamp"]);
-
-if ($updateSequence) {
-	if ($updateSequence > $updateSequenceDb) {
-		// Exception: code=InvalidUpdateSequence
-		header("Content-type: application/xhtml+xml; charset=UTF-8");
-		echo createExceptionXml("InvalidUpdateSequence", "Invalid update sequence");
-		die;
-	}
-	else if ($updateSequence == $updateSequenceDb) {
-		// Exception: code=CurrentUpdateSequence
-		header("Content-type: application/xhtml+xml; charset=UTF-8");
-		echo createExceptionXml("CurrentUpdateSequence", "Current update sequence");
-		die;
-	}
-}
-
-//
-// increment layer count
-//
-$monitor = new Layer_load_count();
-$monitor->increment($layerId);
-
-// ---------------------------------------------------------------------------
-//
-// START TO CREATE CAPABILITIES DOC
-// (return most recent Capabilities XML)
-//
-// ---------------------------------------------------------------------------
-
-$doc = new DOMDocument('1.0');
-$doc->encoding = 'UTF-8';
-$doc->standalone = false;
-
-#Check for existing content in database
-#to be adopted TODO armin 
-function validate ($contactInformation_column) {
-    if ($contactInformation_column <> "" AND $contactInformation_column <> NULL) {
-             $contactinformationcheck = true;
-    }
-    else {
-		$contactinformationcheck = false;
-	}
-	return $contactinformationcheck;
-}
- 
-	
-#Creating the "WMT_MS_Capabilities" node
-$wmt_ms_capabilities = $doc->createElement("WMT_MS_Capabilities");
-$wmt_ms_capabilities->setAttribute("updateSequence", $wms_row["wms_timestamp"]);
-$wmt_ms_capabilities = $doc->appendChild($wmt_ms_capabilities);
-$wmt_ms_capabilities->setAttribute('version', '1.1.1');
-
-#Creatig the "Service" node 
-$service = $doc->createElement("Service");
-$service = $wmt_ms_capabilities->appendChild($service);
-
-#Creating the "Name" Node
-$name = $doc->createElement("Name");
-$name = $service->appendChild($name);
-$nameText = $doc->createTextNode("OGC:WMS");
-$nameText = $name->appendChild($nameText);
-
-#Creating the "Title" node
-if($wms_row['wms_title'] <> "" AND $wms_row['wms_title'] <> NULL) {
-    $title = $doc->createElement("Title");
-	$title = $service->appendChild($title);
-	$titleText = $doc->createTextNode($wms_row['wms_title']);
-	$titleText = $title->appendChild($titleText);
-}
-
-#Creating the "Abstract" node
-if($wms_row['wms_abstract'] <> "" AND $wms_row['wms_abstract'] <> NULL) {
-	$abstract = $doc->createElement("Abstract");
-	$abstract = $service->appendChild($abstract);
-	$abstractText = $doc->createTextNode($wms_row['wms_abstract']);
-	$abstractText = $abstract->appendChild($abstractText);
-}
-	
-# switch URLs for OWSPROXY
-if($wms_row['wms_owsproxy'] <> "" AND $wms_row['wms_owsproxy'] <> NULL) {
-	$tmpOR = "http://".$_SERVER["HTTP_HOST"]."/owsproxy/".session_id()."/".$wms_row["wms_owsproxy"]."?";
-	$tmpOR = str_replace(SERVERIP, SERVERNAME, $tmpOR);
-	$wms_row['wms_getcapabilities'] = $tmpOR;
-	$wms_row['wms_getmap'] = $tmpOR;
-	$wms_row['wms_getfeatureinfo'] = $tmpOR;
-
-}
-#Creating the "OnlineResource" node
-//if($wms_row['wms_getcapabilities'] <> "" AND $wms_row['wms_getcapabilities'] <> NULL) {
-    $onlineResource = $doc->createElement("OnlineResource");
-	$onlineResource = $service->appendChild($onlineResource);
-	$onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink" );
-//	$onlineResource->setAttribute("xlink:href", $wms_row['wms_getcapabilities']);
-	$onlRes = $_SERVER["HTTP_HOST"] . $_SERVER["SCRIPT_NAME"] . "?layer_id=" . $layerId."&".session_name()."=".session_id();
-	if (isset($_SERVER["HTTPS"])) {
-		$onlRes = "https://" . $onlRes;
-	}
-	else {
-		$onlRes = "http://" . $onlRes;
-	}
-	$onlineResource->setAttribute("xlink:href", $onlRes);
-	$onlineResource->setAttribute("xlink:type", "simple");
-//}
-
-#Insert contact information
-
-#Creating "Contact Information" node
-if (validate($wms_row['contactperson']) &&
-	validate($wms_row['contactorganization']) &&
-	validate($wms_row['contactposition']) && 
-	validate($wms_row['address']) && 
-	validate($wms_row['city']) && 
-	validate($wms_row['stateorprovince']) && 
-	validate($wms_row['postcode']) /*AND validate($wms_row['country'])*/ &&
-	validate($wms_row['contactvoicetelephone']) && 
-	validate($wms_row['contactfacsimiletelephone']) &&
-	validate($wms_row['contactelectronicmailaddress']))
-{
-$contactInformation = $doc->createElement("ContactInformation");
-$contactInformation = $service->appendChild($contactInformation);
-
-#Creating "Contact Person Primary" node
-if(validate($wms_row['contactperson']) AND validate($wms_row['contactorganization']))
-{
-$contactPersonPrimary = $doc->createElement("ContactPersonPrimary");
-$contactPersonPrimary = $contactInformation->appendChild($contactPersonPrimary); 
-}
-
-#Creating the "ContactPerson" node
-if(validate($wms_row['contactperson']))
-{
-    $contactPerson = $doc->createElement("ContactPerson");
-    $contactPerson = $contactPersonPrimary->appendChild($contactPerson);
-    $contactPersonText = $doc->createTextNode($wms_row['contactperson']);
-    $contactPersonText = $contactPerson->appendChild($contactPersonText);
-}
-
-#Creating the "ContactOrganization" node
-if(validate($wms_row['contactorganization']))
-{
-    $contactOrganization = $doc->createElement("ContactOrganization");
-    $contactOrganization = $contactPersonPrimary->appendChild($contactOrganization);
-    $contactOrganizationText = $doc->createTextNode($wms_row['contactorganization']);
-    $contactOrganizationText = $contactOrganization->appendChild($contactOrganizationText);
-}
-
-
-#Creating the "ContactPosition" node
-if(validate($wms_row['contactposition']))
-{
-    $contactPosition = $doc->createElement("ContactPosition");
-    $contactPosition = $contactInformation->appendChild($contactPosition);
-    $contactPositionText = $doc->createTextNode($wms_row['contactposition']);
-    $contactPositionText = $contactPosition->appendChild($contactPositionText);    
-}
-
-#Creating "ContactAddress" node
-if(validate($wms_row['address']) AND validate($wms_row['city']) AND validate($wms_row['stateorprovince']) AND               validate($wms_row['postcode']) /*AND validate($wms_row['country'])*/)
-{
-$contactAddress = $doc->createElement("ContactAddress");
-$contactAddress = $contactInformation->appendChild($contactAddress); 
-}
-
-#Creating the "AddressType" and "Address" textnode
-if(validate($wms_row['address']))
-{
-	
-    $addressType = $doc->createElement("AddressType");
-    $addressType = $contactAddress->appendChild($addressType);
-    $addresstypeText = $doc->createTextNode("postal");
-    $addresstypeText = $addressType->appendChild($addresstypeText);
-    
-    $address = $doc->createElement("Address");
-    $address = $contactAddress->appendChild($address);
-    $addressText = $doc->createTextNode($wms_row['address']);
-    $addressText = $address->appendChild($addressText);
-}
-
-#Creatig the "City" node  
-if(validate($wms_row['city']))
-{
-    $city = $doc->createElement("City");
-    $city = $contactAddress->appendChild($city);
-    $cityText = $doc->createTextNode($wms_row['city']);
-    $cityText = $city->appendChild($cityText);
-}
-
-#Creatig the "StateOrProvince" node    
-if(validate($wms_row['stateorprovince']))
-{
-    $stateOrProvince = $doc->createElement("StateOrProvince");
-    $stateOrProvince = $contactAddress->appendChild($stateOrProvince);
-    $stateOrProvinceText = $doc->createTextNode($wms_row['stateorprovince']);
-    $stateOrProvinceText = $stateOrProvince->appendChild($stateOrProvinceText);
-}
-
-#Creatig the "PostCode" node    
-if(validate($wms_row['postcode']))
-{
-    $postCode = $doc->createElement("PostCode");
-    $postCode = $contactAddress->appendChild($postCode);
-    $postCodeText = $doc->createTextNode($wms_row['postcode']);
-    $postCodeText = $postCode->appendChild($postCodeText);
-}
-
- 
-#Creatig the "Country" node   
-if(isset($wms_row['country']) AND validate($wms_row['country']))
-{
-    $country = $doc->createElement("Country");
-    $country = $contactAddress->appendChild($country);
-    $countryText = $doc->createTextNode($wms_row['country']);
-    $countryText = $country->appendChild($countryText);
-}
-
-#Creatig the "ContactVoiceTelephone" node
-if(validate($wms_row['contactvoicetelephone']))
-{
-    $contactVoiceTelephone = $doc->createElement("ContactVoiceTelephone");
-    $contactVoiceTelephone = $contactInformation->appendChild($contactVoiceTelephone);
-    $contactVoiceTelephoneText = $doc->createTextNode($wms_row['contactvoicetelephone']);
-    $contactVoiceTelephoneText = $contactVoiceTelephone->appendChild($contactVoiceTelephoneText);
-}
-
-#Creatig the "ContactFacsimileTelephone" node
-if(validate($wms_row['contactfacsimiletelephone']))
-{
-    $contactFacsimileTelephone = $doc->createElement("ContactFacsimileTelephone");
-    $contactFacsimileTelephone = $contactInformation->appendChild($contactFacsimileTelephone);
-    $contactFacsimileTelephoneText = $doc->createTextNode($wms_row['contactfacsimiletelephone']);
-    $contactFacsimileTelephoneText = $contactFacsimileTelephone->appendChild($contactFacsimileTelephoneText);
-}
-
-#Creatig the "ContactElectronicMailAddress" node
-if(validate($wms_row['contactelectronicmailaddress']))
-{
-    $contactElectronicMailAddress = $doc->createElement("ContactElectronicMailAddress");
-    $contactElectronicMailAddress = $contactInformation->appendChild($contactElectronicMailAddress);
-    $contactElectronicMailAddressText = $doc->createTextNode($wms_row['contactelectronicmailaddress']);
-    $contactElectronicMailAddressText = $contactElectronicMailAddress->appendChild($contactElectronicMailAddressText);
-}
-}
-
-#Creatig the "Fees" node
-if(validate($wms_row['fees']))
-{
-    $fees = $doc->createElement("Fees");
-    $fees = $service->appendChild($fees);
-    $feesText = $doc->createTextNode($wms_row['fees']);
-    $feesText = $fees->appendChild($feesText);
-}
-   
-#Creating the "AccessConstraints" node
-if(validate($wms_row['accessconstraints']))
-{
-	$accessConstraints = $doc->createElement("AccessConstraints");
-    $accessConstraints = $service->appendChild($accessConstraints);
-    $accessConstraintsText = $doc->createTextNode($wms_row['accessconstraints']);
-    $accessConstraintsText = $accessConstraints->appendChild($accessConstraintsText);
-}
-
- 
-#Creatig the "Capability" node 
-$capability = $doc->createElement("Capability");
-$capability = $wmt_ms_capabilities->appendChild($capability);
-
-#Creatig the "Request" node 
-$request = $doc->createElement("Request");
-$request = $capability->appendChild($request);
-
-############################################################
-#GetCapabilities
-#Creatig the "GetCapabilities" node 
-$getCapabilities = $doc->createElement("GetCapabilities");
-$getCapabilities = $request->appendChild($getCapabilities);
-
-#Creatig the "Format" node 
-$wms_format_sql ="SELECT data_format FROM wms_format WHERE fkey_wms_id = $1 AND data_type = 'capability'";
-$v = array($wms_row['wms_id']);
-$t = array("i");
-$res_wms_format_sql = db_prep_query($wms_format_sql, $v, $t);
-while ($wms_format_row = db_fetch_array($res_wms_format_sql)) {
-    $format = $doc->createElement("Format");
-    $format = $getCapabilities->appendChild($format);
-    $formatText = $doc->createTextNode($wms_format_row['data_format']);
-    $formatText = $format->appendChild($formatText);    
-}
-#cause the format for capabilities is not read :
-    $format = $doc->createElement("Format");
-    $format = $getCapabilities->appendChild($format);
-    $formatText = $doc->createTextNode('application/vnd.ogc.wms_xml');
-    $formatText = $format->appendChild($formatText); 
-
-
-
-#Creating the "DCPType" node
-$DCPType = $doc->createElement("DCPType");
-$DCPType = $getCapabilities->appendChild($DCPType);
-
-#Creating the "HTTP" node
-$HTTP = $doc->createElement("HTTP");
-$HTTP = $DCPType->appendChild($HTTP);
-
-#Creating the "Get" node
-$get = $doc->createElement("Get");
-$get = $HTTP->appendChild($get);
-
-#Creating the "OnlineResource" node
-
-//if ($wms_row['wms_getcapabilities'] <> "" AND $wms_row['wms_getcapabilities'] <> NULL) {
-	$onlineResource = $doc->createElement("OnlineResource");
-	$onlineResource = $get->appendChild($onlineResource);
-	$onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
-//	$onlineResource->setAttribute("xlink:href", $wms_row['wms_getcapabilities']);
-	$onlRes = $_SERVER["HTTP_HOST"] . $_SERVER["SCRIPT_NAME"] . "?layer_id=" . $layerId;
-	if (isset($_SERVER["HTTPS"])) {
-		$onlRes = "https://" . $onlRes;
-	}
-	else {
-		$onlRes = "http://" . $onlRes;
-	}
-	$onlineResource->setAttribute("xlink:href", $onlRes);
-	$onlineResource->setAttribute("xlink:type", "simple");		
-//}
-
-#Creating the "Post" node
-$post = $doc->createElement("Post");
-$post = $HTTP->appendChild($post);
-
-#Creating the "OnlineResource" node
-//if ($wms_row['wms_getcapabilities'] <> "" AND $wms_row['wms_getcapabilities'] <> NULL) {
-	$onlineResource = $doc->createElement("OnlineResource");
-	$onlineResource = $post->appendChild($onlineResource);
-	$onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
-//	$onlineResource->setAttribute("xlink:href", $wms_row['wms_getcapabilities']);
-	$onlRes = $_SERVER["HTTP_HOST"] . $_SERVER["SCRIPT_NAME"] . "?layer_id=" . $layerId;
-	if (isset($_SERVER["HTTPS"])) {
-		$onlRes = "https://" . $onlRes;
-	}
-	else {
-		$onlRes = "http://" . $onlRes;
-	}
-	$onlineResource->setAttribute("xlink:href", $onlRes);
-	$onlineResource->setAttribute("xlink:type", "simple");
-//}
-
-##########################################################
-#GetMap	
-#Creatig the "GetMap" node 
-$getMap = $doc->createElement("GetMap");
-$getMap = $request->appendChild($getMap);
-
-#Creatig the "Format" node 
-$wms_format_sql ="SELECT data_format FROM wms_format WHERE fkey_wms_id = $1 AND data_type = 'map'";
-$v = array($wms_row['wms_id']);
-$t = array("i");
-$res_wms_format_sql = db_prep_query($wms_format_sql, $v, $t);
-
-while ($wms_format_row = db_fetch_array($res_wms_format_sql)) {
-    $format = $doc->createElement("Format");
-    $format = $getMap->appendChild($format);
-    $formatText = $doc->createTextNode($wms_format_row['data_format']);
-    $formatText = $format->appendChild($formatText);	
-}
-
-#Creating the "DCPType" node
-$DCPType = $doc->createElement("DCPType");
-$DCPType = $getMap->appendChild($DCPType);
-
-#Creating the "HTTP" node
-$HTTP = $doc->createElement("HTTP");
-$HTTP = $DCPType->appendChild($HTTP);
-
-#Creating the "Get" node
-$get = $doc->createElement("Get");
-$get = $HTTP->appendChild($get);
-
-#Creating the "OnlineResource" node
-if ($wms_row['wms_getmap'] <> "" AND $wms_row['wms_getmap'] <> NULL) {
-	$onlineResource = $doc->createElement("OnlineResource");
-	$onlineResource = $get->appendChild($onlineResource);
-	$onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink" );
-	$onlineResource->setAttribute("xlink:href", $wms_row['wms_getmap']);
-	$onlineResource->setAttribute("xlink:type", "simple");
-}
-
-#Creating the "Post" node
-$post = $doc->createElement("Post");
-$post = $HTTP->appendChild($post);
-
-#Creating the "OnlineResource" node
-if($wms_row['wms_getmap'] <> "" AND $wms_row['wms_getmap'] <> NULL) {
-	$onlineResource = $doc->createElement("OnlineResource");
-	$onlineResource = $post->appendChild($onlineResource);
-	$onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink" );
-	$onlineResource->setAttribute("xlink:href", $wms_row['wms_getmap']);
-	$onlineResource->setAttribute("xlink:type", "simple");
-}
-
-##########################################################
-#GetFeatureInfo	
-#Creatig the "GetFeatureInfo" node 
-$getFeatureInfo = $doc->createElement("GetFeatureInfo");
-$getFeatureInfo = $request->appendChild($getFeatureInfo);
-
-#Creatig the "Format" node 
-$wms_format_sql ="SELECT data_format FROM wms_format WHERE fkey_wms_id = $1 AND data_type = 'featureinfo'";
-$v = array($wms_row['wms_id']);
-$t = array("i");
-$res_wms_format_sql = db_prep_query($wms_format_sql, $v, $t);
-while ($wms_format_row = db_fetch_array($res_wms_format_sql))
-{
-    $format = $doc->createElement("Format");
-    $format = $getFeatureInfo->appendChild($format);
-    $formatText = $doc->createTextNode($wms_format_row['data_format']);
-    $formatText = $format->appendChild($formatText);    
-}
-	
-#Creating the "DCPType" node
-$DCPType = $doc->createElement("DCPType");
-$DCPType = $getFeatureInfo->appendChild($DCPType);
-
-#Creating the "HTTP" node
-$HTTP = $doc->createElement("HTTP");
-$HTTP = $DCPType->appendChild($HTTP);
-
-#Creating the "Get" node
-$get = $doc->createElement("Get");
-$get = $HTTP->appendChild($get);
-
-#Creating the "OnlineResource" node
-if($wms_row['wms_getfeatureinfo'] <> "" AND $wms_row['wms_getfeatureinfo'] <> NULL)
-{
-	$onlineResource = $doc->createElement("OnlineResource");
-	$onlineResource = $get->appendChild($onlineResource);
-	$onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink" );
-	$onlineResource->setAttribute("xlink:href", $wms_row['wms_getfeatureinfo']);
-	$onlineResource->setAttribute("xlink:type", "simple");
-}
-#Creating the "Post" node
-$post = $doc->createElement("Post");
-$post = $HTTP->appendChild($post);
-
-#Creating the "OnlineResource" node
-
-if($wms_row['wms_getfeatureinfo'] <> "" AND $wms_row['wms_getfeatureinfo'] <> NULL) {
-	$onlineResource = $doc->createElement("OnlineResource");
-	$onlineResource = $post->appendChild($onlineResource);
-	$onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink" );
-	$onlineResource->setAttribute("xlink:href", $wms_row['wms_getfeatureinfo']);
-	$onlineResource->setAttribute("xlink:type", "simple");
-}
-	
-#Creating the "Exeption" node
-$exception = $doc->createElement("Exception");
-$exception = $capability->appendChild($exception);	
-
-#Creatig the "Format" node 
-$wms_format_sql ="SELECT data_format FROM wms_format WHERE fkey_wms_id = $1 AND data_type = 'exception'";
-$v = array($wms_row['wms_id']);
-$t = array("i");
-$res_wms_format_sql = db_prep_query($wms_format_sql, $v, $t);
-while ($wms_format_row = db_fetch_array($res_wms_format_sql)) {
-    $format = $doc->createElement("Format");
-    $format = $exception->appendChild($format);
-    $formatText = $doc->createTextNode($wms_format_row['data_format']);
-    $formatText = $format->appendChild($formatText); 
-} 
-
-################################################################
-#Querying layer table
-$layer_sql = "SELECT * FROM layer WHERE layer.fkey_wms_id = $1 AND layer.layer_parent = ''";
-$v = array($wms_row['wms_id']);
-$t = array("i");
-
-$res_layer_sql = db_prep_query($layer_sql, $v, $t);
-$layer_row = db_fetch_array($res_layer_sql);
-			
-#Creating layer node
-$layer = $doc->createElement("Layer");
-$layer = $capability->appendChild($layer);
-
-#Write layer to parent layer array
-$parentLayerArray[$layer_row['layer_pos']] = $layer;
-		
-#Creating Name node
-if ($layer_row['layer_name'] <> "" AND $layer_row['layer_name'] <> NULL) {
-	$name = $doc->createElement("Name");
-	$name = $layer->appendChild($name);
-	$nameText = $doc->createTextNode($layer_row['layer_name']);
-	$nameText = $name->appendChild($nameText);
-}
-
-#Creating Title node
-if ($layer_row['layer_title'] <> "" AND $layer_row['layer_title'] <> NULL) {
-	$title = $doc->createElement("Title");
-	$title = $layer->appendChild($title);
-	$titleText = $doc->createTextNode($layer_row['layer_title']);
-	$titleText = $title->appendChild($titleText);
-}
-
-#Creating the "Abstract" node
-if($layer_row['layer_abstract'] <> "" AND $layer_row['layer_abstract'] <> NULL) {
-    $abstract = $doc->createElement("Abstract");
-    $abstract = $layer->appendChild($abstract);
-    $abstractText = $doc->createTextNode($layer_row['layer_abstract']);
-    $abstractText = $abstract->appendChild($abstractText);	
-}
-
-#Request the specific wms- and layerkeywords
-
-$keyword_sql = "SELECT DISTINCT keyword FROM keyword, layer_keyword, layer " . 
-	"WHERE keyword.keyword_id = layer_keyword.fkey_keyword_id " . 
-	"AND layer_keyword.fkey_layer_id = layer.layer_id " . 
-	"AND layer.fkey_wms_id = $1";
-$v = array($wms_row['wms_id']);
-$t = array("i");
-$res_keyword_sql = db_prep_query($keyword_sql, $v, $t);
-
-#Creating list of keyword nodes
-#Iterating over a List of Keywords
-$keywordlistExist = 0;
-
-while ($keyword_sql = db_fetch_array($res_keyword_sql))
-{
-    #Creating the "KeywordList" node
-    if ($keywordlistExist == 0) {
-        $keywordList = $doc->createElement("KeywordList");
-        $keywordList = $layer->appendChild($keywordList);
-		$keywordlistExist = 1;	
-    }
-    
-    #Creating the "Keyword" node
-    $keyword_dom = $doc->createElement("Keyword");
-    $keyword_dom = $keywordList->appendChild($keyword_dom); 
-    $keyword_domText = $doc->createTextNode($keyword_sql['keyword']);
-    $keyword_domText = $keyword_dom->appendChild($keyword_domText);
-}
-
-
-
-#SQL statement to get additional layer information from layer epsg	
-$epsg_sql = "SELECT layer_epsg.epsg, layer_epsg.minx, layer_epsg.miny, " . 
-	"layer_epsg.maxy, layer_epsg.maxx " . 
-	"FROM layer_epsg WHERE layer_epsg.fkey_layer_id = $1";
-	
-$v = array($layer_row['layer_id']);
-$t = array("i");
-$res_espg_sql = db_prep_query($epsg_sql, $v, $t);
-
-$latLonBoundingBoxCreated = false;
-$BoundingBoxCreated = false;
-
-while ($epsg_row = db_fetch_array($res_espg_sql)) {
-
-	#Creating SRS node
-	$srs = $doc->createElement("SRS");
-	$srs = $layer->appendChild($srs);
-	$srsText = $doc->createTextNode($epsg_row['epsg']);
-	$srsText = $srs->appendChild($srsText);
-	
-
-}
-
-#SQL statement to get additional layer information from layer epsg	
-$epsg_sql = "SELECT layer_epsg.epsg, layer_epsg.minx, layer_epsg.miny, " . 
-	"layer_epsg.maxy, layer_epsg.maxx " . 
-	"FROM layer_epsg WHERE layer_epsg.fkey_layer_id = $1";
-	
-$v = array($layer_row['layer_id']);
-$t = array("i");
-$res_espg_sql = db_prep_query($epsg_sql, $v, $t);
-
-while ($epsg_row = db_fetch_array($res_espg_sql)) {
-	#set only epsg 4326 for latlonbbox
-	if ($epsg_row['epsg'] == "EPSG:4326") {
-		
-		$latlon['minx'] = $epsg_row['minx'];
-		$latlon['miny'] = $epsg_row['miny'];
-		$latlon['maxx'] = $epsg_row['maxx'];
-		$latlon['maxy'] = $epsg_row['maxy'];
-
-		#Creating LatLongBoundingBox node
-		$latLonBoundingBox = $doc->createElement("LatLonBoundingBox");
-		$latLonBoundingBox = $layer->appendChild($latLonBoundingBox);
-		$latLonBoundingBox->setAttribute('minx', $latlon['minx']);
-		$latLonBoundingBox->setAttribute('miny', $latlon['miny']);
-		$latLonBoundingBox->setAttribute('maxx', $latlon['maxx']);
-		$latLonBoundingBox->setAttribute('maxy', $latlon['maxy']);
-	    break;
-    }	
-}
-
-#SQL statement to get additional layer information from layer epsg	
-$epsg_sql = "SELECT layer_epsg.epsg, layer_epsg.minx, layer_epsg.miny, " . 
-	"layer_epsg.maxy, layer_epsg.maxx " . 
-	"FROM layer_epsg WHERE layer_epsg.fkey_layer_id = $1";
-	
-$v = array($layer_row['layer_id']);
-$t = array("i");
-$res_espg_sql = db_prep_query($epsg_sql, $v, $t);
-
-while ($epsg_row = db_fetch_array($res_espg_sql)) {
-	#set only first epsg for bbox
-	$bbox['epsg'] = $epsg_row['epsg'];
-	$bbox['minx'] = $epsg_row['minx'];
-	$bbox['miny'] = $epsg_row['miny'];
-	$bbox['maxx'] = $epsg_row['maxx'];
-	$bbox['maxy'] = $epsg_row['maxy'];
-
-	#Creating BoundingBox node
-	$boundingBox = $doc->createElement("BoundingBox");
-	$boundingBox = $layer->appendChild($boundingBox);
-	$boundingBox->setAttribute('SRS', $bbox['epsg']);
-	$boundingBox->setAttribute('minx', $bbox['minx']);
-	$boundingBox->setAttribute('miny', $bbox['miny']);
-	$boundingBox->setAttribute('maxx', $bbox['maxx']);
-	$boundingBox->setAttribute('maxy', $bbox['maxy']);
-}
-
-
-#Append epsg string to srs node
-$srsText = $doc->createTextNode($epsgText);
-$srsText = $srs->appendChild($srsText);
-
-
-####### duplicate root layer 
-#if layer is root layer itself!
-#<armin>
-##if ($layer_row['layer_pos']=='0'){
-#</armin>
-##$clonedLayer = $layer->cloneNode(true);
-##$clonedLayer->setAttribute("queryable", "0");
-##$clonedLayer->setAttribute("cascaded", "0");
-##$layer->appendChild($clonedLayer);
-#<armin>
-##}
-#</armin>
-
-
-
-############## sublayer 
-	
-#SQL statement to get all layers
-$sub_layer_sql = "SELECT * FROM layer WHERE fkey_wms_id = $1 AND layer_parent <> ''";
-$v = array($wms_row['wms_id']);
-$t = array("i");
-
-if (isset($layerId) && $layerId > 0) {	
-	$sub_layer_sql .= " AND layer_id = $2";
-	array_push($v, $layerId);
-	array_push($t, "i");
-}
-$sub_layer_sql .= " ORDER BY layer_pos";
-$res_sub_layer_sql = db_prep_query($sub_layer_sql, $v, $t);
-
-
-#<armin>
-$res_sub_layer_sql_2 = db_prep_query($sub_layer_sql, $v, $t);   
-$sub_layer_row_2 = db_fetch_array($res_sub_layer_sql_2);
-
-
-if (!isset($sub_layer_row_2['layer_pos'])) {
-	$clonedLayer = $layer->cloneNode(true);
-	$clonedLayer->setAttribute("queryable", "0");
-	$clonedLayer->setAttribute("cascaded", "0");
-	$layer->appendChild($clonedLayer);
-}
-#</armin>
-
-
-
-
-while ($sub_layer_row = db_fetch_array($res_sub_layer_sql)) {
-	
-	#Creating layer node
-
-	$sub_layer = $doc->createElement("Layer");
-	
-	$parent = $parentLayerArray[$sub_layer_row['layer_parent']];
-	$sub_layer = $parent->appendChild($sub_layer);
-    
-    if($sub_layer_row['layer_queryable'] <> "" AND $sub_layer_row['layer_queryable'] <> NULL) {
-		$sub_layer->setAttribute('queryable', $sub_layer_row['layer_queryable']);
-    }
-	#Getting information about the hierarchie of layers
-	$cascadeSQL = "SELECT COUNT(*) FROM layer WHERE fkey_wms_id = ".$wms_row[0] . 
-		" AND layer_parent = ".$sub_layer_row['layer_pos']."";
-	$res_cascadeSQL = db_query($cascadeSQL);
-	$cascade = 0;
-	$cascade_row = db_fetch_row($res_cascadeSQL);
-	if($cascade_row[0] > 0)
-	{
-		$cascade = 1;
-	}
-	$sub_layer->setAttribute('cascaded', $cascade);
-	
-	#Write layer to parent layer array
-	$parentLayerArray[$sub_layer_row['layer_pos']] = $sub_layer;
-	
-	#Creating name node
-    if($sub_layer_row['layer_name'] <> "" AND $sub_layer_row['layer_name'] <> NULL)
-    {
-		$name = $doc->createElement("Name");
-		$name = $sub_layer->appendChild($name);
-		$nameText = $doc->createTextNode($sub_layer_row['layer_name']);
-		$nameText = $name->appendChild($nameText);
-    }
-	
-	#Creating Title node
-    if($sub_layer_row['layer_title'] <> "" AND $sub_layer_row['layer_title'] <> NULL)
-    {
-		$title = $doc->createElement("Title");
-		$title = $sub_layer->appendChild($title);
-		$titleText = $doc->createTextNode($sub_layer_row['layer_title']);
-		$titleText = $title->appendChild($titleText);
-    }
-	
-		#Creating the "Abstract" node
-    if($sub_layer_row['layer_abstract'] <> "" AND $sub_layer_row['layer_abstract'] <> NULL)
-    {
-    	$abstract = $doc->createElement("Abstract");
-    	$abstract = $sub_layer->appendChild($abstract);
-    	$abstractText = $doc->createTextNode($sub_layer_row['layer_abstract']);
-    	$abstractText = $abstract->appendChild($abstractText);
-    }
-	
-    #Request the specific wms- and layerkeywords
-    $keyword_sql = "SELECT DISTINCT keyword FROM layer LEFT JOIN layer_keyword ON layer_keyword.fkey_layer_id = layer.layer_id LEFT JOIN keyword ON  keyword.keyword_id = layer_keyword.fkey_keyword_id WHERE layer.fkey_wms_id = ".$wms_row['wms_id']." AND layer.layer_id = ".$sub_layer_row['layer_id']."";
-    $res_keyword_sql = db_query($keyword_sql);
-    
-    #Creating list of keyword nodes
-    #Iterating over a List of Keywords
-    $keywordlistExist = 0;
-    while ($keyword_sql = db_fetch_array($res_keyword_sql))
-    {
-        #Creating the "KeywordList" node
-        if ($keywordlistExist == 0)
-        {
-            $keywordList = $doc->createElement("KeywordList");
-            $keywordList = $sub_layer->appendChild($keywordList);
-		    $keywordlistExist = 1;			
-        }
-        
-        #Creating the "Keyword" node
-        $keyword_dom = $doc->createElement("Keyword");
-        $keyword_dom = $keywordList->appendChild($keyword_dom); 
-        $keyword_domText = $doc->createTextNode($keyword_sql['keyword']);
-        $keyword_domText = $keyword_dom->appendChild($keyword_domText);
-    }
-
-	// inherit srs from parent layer
-	$layer_srs_sql = "SELECT DISTINCT epsg FROM layer_epsg " . 
-			"WHERE fkey_layer_id = ".$sub_layer_row['layer_id'] . 
-			" OR fkey_layer_id = " . $layer_row['layer_id'];
-	$res_layer_srs_sql = db_query($layer_srs_sql);
-
-	while ($layer_srs_row = db_fetch_array($res_layer_srs_sql)) {
-		#Creating SRS node
-		$srs = $doc->createElement("SRS");
-		$srs = $sub_layer->appendChild($srs);
-		$srsText = $doc->createTextNode($layer_srs_row['epsg']);
-		$srsText = $srs->appendChild($srsText);
-
-	}
-	#SQL statement to get additional layer information from layer epsg	
-	$epsg_sql = "SELECT layer_epsg.epsg, layer_epsg.minx, layer_epsg.miny, " . 
-			"layer_epsg.maxy, layer_epsg.maxx FROM layer_epsg " . 
-			"WHERE layer_epsg.fkey_layer_id = ".$sub_layer_row['layer_id'];
-	$res_espg_sql = db_query($epsg_sql);
-	
-	while ($epsg_row = db_fetch_array($res_espg_sql)) {
-		#set epsg 4326 for latlonbbox
-		if ($epsg_row['epsg'] == "EPSG:4326" AND $latLonBoundingBoxCreated == false) {
-			
-			$latlon['minx'] = $epsg_row['minx'];
-			$latlon['miny'] = $epsg_row['miny'];
-			$latlon['maxx'] = $epsg_row['maxx'];
-			$latlon['maxy'] = $epsg_row['maxy'];
-
-			#Creating LatLongBoundingBox node
-		    $latLonBoundingBox = $doc->createElement("LatLonBoundingBox");
-		    $latLonBoundingBox = $sub_layer->appendChild($latLonBoundingBox);
-		    $latLonBoundingBox->setAttribute('minx', $latlon['minx']);
-		    $latLonBoundingBox->setAttribute('miny', $latlon['miny']);
-		    $latLonBoundingBox->setAttribute('maxx', $latlon['maxx']);
-		    $latLonBoundingBox->setAttribute('maxy', $latlon['maxy']);
-	    }	
-	}
-	
-	#SQL statement to get additional layer information from layer epsg	
-	$epsg_sql = "SELECT layer_epsg.epsg, layer_epsg.minx, layer_epsg.miny, " . 
-			"layer_epsg.maxy, layer_epsg.maxx FROM layer_epsg " . 
-			"WHERE layer_epsg.fkey_layer_id = ".$sub_layer_row['layer_id'];
-	$res_espg_sql = db_query($epsg_sql);
-	
-	while ($epsg_row = db_fetch_array($res_espg_sql)) {
-	
-		
-		#set only first epsg for bbox
-		$bbox['epsg'] = $epsg_row['epsg'];
-		$bbox['minx'] = $epsg_row['minx'];
-		$bbox['miny'] = $epsg_row['miny'];
-		$bbox['maxx'] = $epsg_row['maxx'];
-		$bbox['maxy'] = $epsg_row['maxy'];
-
-		#Creating BoundingBox node
-		$boundingBox = $doc->createElement("BoundingBox");
-		$boundingBox = $sub_layer->appendChild($boundingBox);
-		$boundingBox->setAttribute('SRS', $bbox['epsg']);
-		$boundingBox->setAttribute('minx', $bbox['minx']);
-		$boundingBox->setAttribute('miny', $bbox['miny']);
-		$boundingBox->setAttribute('maxx', $bbox['maxx']);
-		$boundingBox->setAttribute('maxy', $bbox['maxy']);
-	}
-	
-	# Creating Metadata Node
-	
-	$metadataUrl = $doc->createElement("MetadataURL");
-	$metadataUrl = $sub_layer->appendChild($metadataUrl);
-	$metadataUrl->setAttribute('type', "TC211");
-	
-	$format = $doc->createElement("Format");
-    $format = $metadataUrl->appendChild($format);
-    $formatText = $doc->createTextNode('text/html');
-    $formatText = $format->appendChild($formatText); 
-
-	if ($wms_row['wms_owsproxy'] <> "" AND $wms_row['wms_owsproxy'] <> NULL) {
-		$onlineResource = $doc->createElement("OnlineResource");
-	   	$onlineResource = $metadataUrl->appendChild($onlineResource);
-	   	$onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink" );
-		$onlineResource->setAttribute("xlink:href", OWSPROXY."/".session_id()."/".$wms_row["wms_owsproxy"]."?");
-		$onlineResource->setAttribute("xlink:type", "simple");
-	}
-	else {
-		if ($sub_layer_row['layer_metadataurl'] <> "" AND $sub_layer_row['layer_metadataurl'] <> NULL) {
-	    	$onlineResource = $doc->createElement("OnlineResource");
-	    	$onlineResource = $metadataUrl->appendChild($onlineResource);
-			$onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink" );
-			$onlineResource->setAttribute("xlink:href", $sub_layer_row['layer_metadataurl']);
-			$onlineResource->setAttribute("xlink:type", "simple");
-	    }
-else
-{
- $onlineResource = $doc->createElement("OnlineResource");
-                $onlineResource = $metadataUrl->appendChild($onlineResource);
-                        $onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink" );
-                        $onlineResource->setAttribute("xlink:type", "simple");
-
-}
-
-
-	}
-	# Creating DataURL Node
-	$dataUrl = $doc->createElement("DataURL");
-	$dataUrl = $sub_layer->appendChild($dataUrl);
-	
-	
-	
-	$format = $doc->createElement("Format");
-    $format = $dataUrl->appendChild($format);
-    $formatText = $doc->createTextNode('text/html');
-    $formatText = $format->appendChild($formatText); 
-
-
-	if($wms_row['wms_owsproxy'] <> "" AND $wms_row['wms_owsproxy'] <> NULL)
-	{
-		$onlineResource = $doc->createElement("OnlineResource");
-	   	$onlineResource = $dataUrl->appendChild($onlineResource);
-	   	$onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink" );
-		$onlineResource->setAttribute("xlink:href", OWSPROXY."/".session_id()."/".$wms_row["wms_owsproxy"]."?");
-		$onlineResource->setAttribute("xlink:type", "simple");
-	}
-	else
-	{
-		if($sub_layer_row['layer_dataurl'] <> "" AND $sub_layer_row['layer_dataurl'] <> NULL)
-	    {
-	    	$onlineResource = $doc->createElement("OnlineResource");
-	    	$onlineResource = $dataUrl->appendChild($onlineResource);
-			$onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink" );
-			$onlineResource->setAttribute("xlink:href", $sub_layer_row['layer_dataurl']);
-			$onlineResource->setAttribute("xlink:type", "simple");
-	    }
-else
-{
- $onlineResource = $doc->createElement("OnlineResource");
-                $onlineResource = $dataUrl->appendChild($onlineResource);
-                        $onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink" );
-                        $onlineResource->setAttribute("xlink:href", $mapbenderMetadataUrl.$sub_layer_row['layer_id']);
-                        $onlineResource->setAttribute("xlink:type", "simple");
-
-}
-
-
-
-
-
-
-
-	}
-	
-	
-	#Creating Style Node
-	$style = $doc->createElement("Style");
-	$style = $sub_layer->appendChild($style);
-	
-	$name = $doc->createElement("Name");
-    $name = $style->appendChild($name);
-    $nameText = $doc->createTextNode('default');
-    $nameText = $name->appendChild($nameText);
-
-	$title = $doc->createElement("Title");
-    $title = $style->appendChild($title);
-    $titleText = $doc->createTextNode('default');
-    $titleText = $title->appendChild($titleText);
-	
-
-
-    if($wms_row['wms_getlegendurl'] <> "" AND $wms_row['wms_getlegendurl'] <> NULL){	
-	$legendUrl = $doc->createElement("LegendURL");
-	$legendUrl = $style->appendChild($legendUrl);
-	$legendUrl->setAttribute("width", "10" );
-	$legendUrl->setAttribute("height", "8" );
-
-	$format = $doc->createElement("Format");
-    $format = $legendUrl->appendChild($format);
-    $formatText = $doc->createTextNode('image/png');
-    $formatText = $format->appendChild($formatText); 
-
-	if($wms_row['wms_owsproxy'] <> "" AND $wms_row['wms_owsproxy'] <> NULL)
-	{
-		$onlineResource = $doc->createElement("OnlineResource");
-	   	$onlineResource = $legendUrl->appendChild($onlineResource);
-	   	$onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink" );
-		$onlineResource->setAttribute("xlink:href", OWSPROXY."/".session_id()."/".$wms_row["wms_owsproxy"]."?version=1.1.1&service=WMS&request=GetLegendGraphic&layer=".$sub_layer_row['layer_name']."&format=image/png");
-		$onlineResource->setAttribute("xlink:type", "simple");
-	}
-	else
-	{
-		if($wms_row['wms_getlegendurl'] <> "" AND $wms_row['wms_getlegendurl'] <> NULL)
-	    {
-	    	$onlineResource = $doc->createElement("OnlineResource");
-	    	$onlineResource = $legendUrl->appendChild($onlineResource);
-			$onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink" );
-			$onlineResource->setAttribute("xlink:href", $wms_row['wms_getlegendurl']."version=1.1.1&service=WMS&request=GetLegendGraphic&layer=".$sub_layer_row['layer_name']."&format=image/png");
-			$onlineResource->setAttribute("xlink:type", "simple");
-	    }
-	}
-
-
-}
-	#Creating "ScaleHint" node
-    if ($sub_layer_row['layer_minscale'] <> "" AND $sub_layer_row['layer_minscale'] <> NULL) {
-		$scaleHint = $doc->createElement("ScaleHint");
-		$scaleHint = $sub_layer->appendChild($scaleHint);
-		$scaleHint->setAttribute('min', (floatval($sub_layer_row['layer_minscale'])/2004.3976484406788493955738891127));
-		$scaleHint->setAttribute('max', (floatval($sub_layer_row['layer_maxscale'])/2004.3976484406788493955738891127));
-    }
-}	
-
-header("Content-type: application/xhtml+xml; charset=UTF-8");
-echo $doc->saveXml();
-?>

Copied: branches/mapbender/http/php/wms.php (from rev 6938, trunk/mapbender/http/php/wms.php)
===================================================================
--- branches/mapbender/http/php/wms.php	                        (rev 0)
+++ branches/mapbender/http/php/wms.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -0,0 +1,1096 @@
+<?php
+# $Id: mb_listGUIs.php 11 2006-07-31 16:22:36Z rothstein $
+# http://www.mapbender.org/index.php/mb_listGUIs.php
+# 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__)."/../../core/globalSettings.php");
+require_once(dirname(__FILE__)."/../classes/class_layer_monitor.php");
+
+ob_start();
+
+//
+// make all parameters available as upper case
+//
+foreach($_GET as $key => $val) {
+	$_GET[strtoupper($key)] = $val;
+}
+
+$requestType = $_GET["REQUEST"];
+$version = $_GET["VERSION"];
+$service = strtoupper($_GET["SERVICE"]);
+$layerId = $_GET["LAYER_ID"];
+$updateSequence = intval($_GET["UPDATESEQUENCE"]);
+$mapbenderMetadataUrl = preg_replace("/(.*)frames\/login.php/", "$1php/mod_layerMetadata.php?id=", LOGIN);
+
+/**
+ * Creates an XML Exception according to WMS 1.1.1
+ * 
+ * @return an XML String
+ * @param $errorCode String
+ * @param $errorMessage String
+ */
+function createExceptionXml ($errorCode, $errorMessage) {
+	// see http://de2.php.net/manual/de/domimplementation.createdocumenttype.php
+	$imp = new DOMImplementation;
+	$dtd = $imp->createDocumentType("ServiceExceptionReport", "", "http://schemas.opengis.net/wms/1.1.1/exception_1_1_1.dtd");
+	
+	$doc = $imp->createDocument("", "", $dtd);
+	$doc->encoding = 'UTF-8';
+	$doc->standalone = false;
+	
+	$el = $doc->createElement("ServiceExceptionReport");
+	$exc = $doc->createElement("ServiceException", $errorMessage);
+	if ($errorCode) {
+		$exc->setAttribute("code", $errorCode);
+	}
+	$el->appendChild($exc);
+	$doc->appendChild($el);
+	
+	return $doc->saveXML();
+}
+
+//
+// check if service param is set
+//
+if (!isset($service) || $service === "" || $service != "WMS") {
+	header("Content-type: application/xhtml+xml; charset=UTF-8");
+	echo createExceptionXml("", "Parameter SERVICE invalid");
+	die;
+}
+
+//
+// check if request param is set
+//
+if (!isset($requestType) || $requestType === "" || 
+	($service == "WMS" && $requestType != "GetCapabilities")) {
+		
+	header("Content-type: application/xhtml+xml; charset=UTF-8");
+	echo createExceptionXml("", "Parameter REQUEST invalid");
+	die;
+}
+
+//
+// check if version param is set
+//
+if (!isset($version) || $version === "" || 
+	($service == "WMS" && $version != "1.1.1")) {
+		
+	// optional parameter, set to 1.1.1 if not set
+	$version = "1.1.1";
+}
+
+//
+// check if layer id is set
+//
+if (!isset($layerId) || !is_numeric($layerId)) {
+	// TO DO: create exception XML
+	header("Content-type: application/xhtml+xml; charset=UTF-8");
+	echo createExceptionXml(
+		"Layer not defined", 
+		"Unknown layer id " . $layerId
+	);
+	die;
+}
+
+//
+// check if layer is stored in database
+//
+$wms_sql = "SELECT * FROM wms AS w, layer AS l " . 
+	"where l.layer_id = $1 AND l.fkey_wms_id = w.wms_id LIMIT 1";
+$v = array($layerId);
+$t = array("i");
+$res_wms_sql = db_prep_query($wms_sql, $v, $t);
+$wms_row = db_fetch_array($res_wms_sql);
+
+if (!$wms_row["wms_id"]) {
+	// TO DO: create exception XML
+	header("Content-type: application/xhtml+xml; charset=UTF-8");
+	echo createExceptionXml(
+		"Layer not defined", 
+		"Unknown layer id " . $layerId
+	);
+	die;
+}
+
+//
+// check if update sequence is valid
+//
+$updateSequenceDb = intval($wms_row["wms_timestamp"]);
+
+if ($updateSequence) {
+	if ($updateSequence > $updateSequenceDb) {
+		// Exception: code=InvalidUpdateSequence
+		header("Content-type: application/xhtml+xml; charset=UTF-8");
+		echo createExceptionXml("InvalidUpdateSequence", "Invalid update sequence");
+		die;
+	}
+	else if ($updateSequence == $updateSequenceDb) {
+		// Exception: code=CurrentUpdateSequence
+		header("Content-type: application/xhtml+xml; charset=UTF-8");
+		echo createExceptionXml("CurrentUpdateSequence", "Current update sequence");
+		die;
+	}
+}
+
+//
+// increment layer count
+//
+$monitor = new Layer_load_count();
+$monitor->increment($layerId);
+
+// ---------------------------------------------------------------------------
+//
+// START TO CREATE CAPABILITIES DOC
+// (return most recent Capabilities XML)
+//
+// ---------------------------------------------------------------------------
+
+$doc = new DOMDocument('1.0');
+$doc->encoding = 'UTF-8';
+$doc->standalone = false;
+
+#Check for existing content in database
+#to be adopted TODO armin 
+function validate ($contactInformation_column) {
+    if ($contactInformation_column <> "" AND $contactInformation_column <> NULL) {
+             $contactinformationcheck = true;
+    }
+    else {
+		$contactinformationcheck = false;
+	}
+	return $contactinformationcheck;
+}
+ 
+	
+#Creating the "WMT_MS_Capabilities" node
+$wmt_ms_capabilities = $doc->createElement("WMT_MS_Capabilities");
+$wmt_ms_capabilities->setAttribute("updateSequence", $wms_row["wms_timestamp"]);
+$wmt_ms_capabilities = $doc->appendChild($wmt_ms_capabilities);
+$wmt_ms_capabilities->setAttribute('version', '1.1.1');
+
+#Creatig the "Service" node 
+$service = $doc->createElement("Service");
+$service = $wmt_ms_capabilities->appendChild($service);
+
+#Creating the "Name" Node
+$name = $doc->createElement("Name");
+$name = $service->appendChild($name);
+$nameText = $doc->createTextNode("OGC:WMS");
+$nameText = $name->appendChild($nameText);
+
+#Creating the "Title" node
+if($wms_row['wms_title'] <> "" AND $wms_row['wms_title'] <> NULL) {
+    $title = $doc->createElement("Title");
+	$title = $service->appendChild($title);
+	$titleText = $doc->createTextNode($wms_row['wms_title']);
+	$titleText = $title->appendChild($titleText);
+}
+
+#Creating the "Abstract" node
+if($wms_row['wms_abstract'] <> "" AND $wms_row['wms_abstract'] <> NULL) {
+	$abstract = $doc->createElement("Abstract");
+	$abstract = $service->appendChild($abstract);
+	$abstractText = $doc->createTextNode($wms_row['wms_abstract']);
+	$abstractText = $abstract->appendChild($abstractText);
+}
+	
+# switch URLs for OWSPROXY
+if($wms_row['wms_owsproxy'] <> "" AND $wms_row['wms_owsproxy'] <> NULL) {
+	$tmpOR = "http://".$_SERVER["HTTP_HOST"]."/owsproxy/".session_id()."/".$wms_row["wms_owsproxy"]."?";
+	$tmpOR = str_replace(SERVERIP, SERVERNAME, $tmpOR);
+	$wms_row['wms_getcapabilities'] = $tmpOR;
+	$wms_row['wms_getmap'] = $tmpOR;
+	$wms_row['wms_getfeatureinfo'] = $tmpOR;
+
+}
+#Creating the "OnlineResource" node
+//if($wms_row['wms_getcapabilities'] <> "" AND $wms_row['wms_getcapabilities'] <> NULL) {
+    $onlineResource = $doc->createElement("OnlineResource");
+	$onlineResource = $service->appendChild($onlineResource);
+	$onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink" );
+//	$onlineResource->setAttribute("xlink:href", $wms_row['wms_getcapabilities']);
+	$onlRes = $_SERVER["HTTP_HOST"] . $_SERVER["SCRIPT_NAME"] . "?layer_id=" . $layerId."&".session_name()."=".session_id();
+	if (isset($_SERVER["HTTPS"])) {
+		$onlRes = "https://" . $onlRes;
+	}
+	else {
+		$onlRes = "http://" . $onlRes;
+	}
+	$onlineResource->setAttribute("xlink:href", $onlRes);
+	$onlineResource->setAttribute("xlink:type", "simple");
+//}
+
+#Insert contact information
+
+#Creating "Contact Information" node
+if (validate($wms_row['contactperson']) &&
+	validate($wms_row['contactorganization']) &&
+	validate($wms_row['contactposition']) && 
+	validate($wms_row['address']) && 
+	validate($wms_row['city']) && 
+	validate($wms_row['stateorprovince']) && 
+	validate($wms_row['postcode']) /*AND validate($wms_row['country'])*/ &&
+	validate($wms_row['contactvoicetelephone']) && 
+	validate($wms_row['contactfacsimiletelephone']) &&
+	validate($wms_row['contactelectronicmailaddress']))
+{
+$contactInformation = $doc->createElement("ContactInformation");
+$contactInformation = $service->appendChild($contactInformation);
+
+#Creating "Contact Person Primary" node
+if(validate($wms_row['contactperson']) AND validate($wms_row['contactorganization']))
+{
+$contactPersonPrimary = $doc->createElement("ContactPersonPrimary");
+$contactPersonPrimary = $contactInformation->appendChild($contactPersonPrimary); 
+}
+
+#Creating the "ContactPerson" node
+if(validate($wms_row['contactperson']))
+{
+    $contactPerson = $doc->createElement("ContactPerson");
+    $contactPerson = $contactPersonPrimary->appendChild($contactPerson);
+    $contactPersonText = $doc->createTextNode($wms_row['contactperson']);
+    $contactPersonText = $contactPerson->appendChild($contactPersonText);
+}
+
+#Creating the "ContactOrganization" node
+if(validate($wms_row['contactorganization']))
+{
+    $contactOrganization = $doc->createElement("ContactOrganization");
+    $contactOrganization = $contactPersonPrimary->appendChild($contactOrganization);
+    $contactOrganizationText = $doc->createTextNode($wms_row['contactorganization']);
+    $contactOrganizationText = $contactOrganization->appendChild($contactOrganizationText);
+}
+
+
+#Creating the "ContactPosition" node
+if(validate($wms_row['contactposition']))
+{
+    $contactPosition = $doc->createElement("ContactPosition");
+    $contactPosition = $contactInformation->appendChild($contactPosition);
+    $contactPositionText = $doc->createTextNode($wms_row['contactposition']);
+    $contactPositionText = $contactPosition->appendChild($contactPositionText);    
+}
+
+#Creating "ContactAddress" node
+if(validate($wms_row['address']) AND validate($wms_row['city']) AND validate($wms_row['stateorprovince']) AND               validate($wms_row['postcode']) /*AND validate($wms_row['country'])*/)
+{
+$contactAddress = $doc->createElement("ContactAddress");
+$contactAddress = $contactInformation->appendChild($contactAddress); 
+}
+
+#Creating the "AddressType" and "Address" textnode
+if(validate($wms_row['address']))
+{
+	
+    $addressType = $doc->createElement("AddressType");
+    $addressType = $contactAddress->appendChild($addressType);
+    $addresstypeText = $doc->createTextNode("postal");
+    $addresstypeText = $addressType->appendChild($addresstypeText);
+    
+    $address = $doc->createElement("Address");
+    $address = $contactAddress->appendChild($address);
+    $addressText = $doc->createTextNode($wms_row['address']);
+    $addressText = $address->appendChild($addressText);
+}
+
+#Creatig the "City" node  
+if(validate($wms_row['city']))
+{
+    $city = $doc->createElement("City");
+    $city = $contactAddress->appendChild($city);
+    $cityText = $doc->createTextNode($wms_row['city']);
+    $cityText = $city->appendChild($cityText);
+}
+
+#Creatig the "StateOrProvince" node    
+if(validate($wms_row['stateorprovince']))
+{
+    $stateOrProvince = $doc->createElement("StateOrProvince");
+    $stateOrProvince = $contactAddress->appendChild($stateOrProvince);
+    $stateOrProvinceText = $doc->createTextNode($wms_row['stateorprovince']);
+    $stateOrProvinceText = $stateOrProvince->appendChild($stateOrProvinceText);
+}
+
+#Creatig the "PostCode" node    
+if(validate($wms_row['postcode']))
+{
+    $postCode = $doc->createElement("PostCode");
+    $postCode = $contactAddress->appendChild($postCode);
+    $postCodeText = $doc->createTextNode($wms_row['postcode']);
+    $postCodeText = $postCode->appendChild($postCodeText);
+}
+
+ 
+#Creatig the "Country" node   
+if(isset($wms_row['country']) AND validate($wms_row['country']))
+{
+    $country = $doc->createElement("Country");
+    $country = $contactAddress->appendChild($country);
+    $countryText = $doc->createTextNode($wms_row['country']);
+    $countryText = $country->appendChild($countryText);
+}
+
+#Creatig the "ContactVoiceTelephone" node
+if(validate($wms_row['contactvoicetelephone']))
+{
+    $contactVoiceTelephone = $doc->createElement("ContactVoiceTelephone");
+    $contactVoiceTelephone = $contactInformation->appendChild($contactVoiceTelephone);
+    $contactVoiceTelephoneText = $doc->createTextNode($wms_row['contactvoicetelephone']);
+    $contactVoiceTelephoneText = $contactVoiceTelephone->appendChild($contactVoiceTelephoneText);
+}
+
+#Creatig the "ContactFacsimileTelephone" node
+if(validate($wms_row['contactfacsimiletelephone']))
+{
+    $contactFacsimileTelephone = $doc->createElement("ContactFacsimileTelephone");
+    $contactFacsimileTelephone = $contactInformation->appendChild($contactFacsimileTelephone);
+    $contactFacsimileTelephoneText = $doc->createTextNode($wms_row['contactfacsimiletelephone']);
+    $contactFacsimileTelephoneText = $contactFacsimileTelephone->appendChild($contactFacsimileTelephoneText);
+}
+
+#Creatig the "ContactElectronicMailAddress" node
+if(validate($wms_row['contactelectronicmailaddress']))
+{
+    $contactElectronicMailAddress = $doc->createElement("ContactElectronicMailAddress");
+    $contactElectronicMailAddress = $contactInformation->appendChild($contactElectronicMailAddress);
+    $contactElectronicMailAddressText = $doc->createTextNode($wms_row['contactelectronicmailaddress']);
+    $contactElectronicMailAddressText = $contactElectronicMailAddress->appendChild($contactElectronicMailAddressText);
+}
+}
+
+#Creatig the "Fees" node
+if(validate($wms_row['fees']))
+{
+    $fees = $doc->createElement("Fees");
+    $fees = $service->appendChild($fees);
+    $feesText = $doc->createTextNode($wms_row['fees']);
+    $feesText = $fees->appendChild($feesText);
+}
+   
+#Creating the "AccessConstraints" node
+if(validate($wms_row['accessconstraints']))
+{
+	$accessConstraints = $doc->createElement("AccessConstraints");
+    $accessConstraints = $service->appendChild($accessConstraints);
+    $accessConstraintsText = $doc->createTextNode($wms_row['accessconstraints']);
+    $accessConstraintsText = $accessConstraints->appendChild($accessConstraintsText);
+}
+
+ 
+#Creatig the "Capability" node 
+$capability = $doc->createElement("Capability");
+$capability = $wmt_ms_capabilities->appendChild($capability);
+
+#Creatig the "Request" node 
+$request = $doc->createElement("Request");
+$request = $capability->appendChild($request);
+
+############################################################
+#GetCapabilities
+#Creatig the "GetCapabilities" node 
+$getCapabilities = $doc->createElement("GetCapabilities");
+$getCapabilities = $request->appendChild($getCapabilities);
+
+#Creatig the "Format" node 
+$wms_format_sql ="SELECT data_format FROM wms_format WHERE fkey_wms_id = $1 AND data_type = 'capability'";
+$v = array($wms_row['wms_id']);
+$t = array("i");
+$res_wms_format_sql = db_prep_query($wms_format_sql, $v, $t);
+while ($wms_format_row = db_fetch_array($res_wms_format_sql)) {
+    $format = $doc->createElement("Format");
+    $format = $getCapabilities->appendChild($format);
+    $formatText = $doc->createTextNode($wms_format_row['data_format']);
+    $formatText = $format->appendChild($formatText);    
+}
+#cause the format for capabilities is not read :
+    $format = $doc->createElement("Format");
+    $format = $getCapabilities->appendChild($format);
+    $formatText = $doc->createTextNode('application/vnd.ogc.wms_xml');
+    $formatText = $format->appendChild($formatText); 
+
+
+
+#Creating the "DCPType" node
+$DCPType = $doc->createElement("DCPType");
+$DCPType = $getCapabilities->appendChild($DCPType);
+
+#Creating the "HTTP" node
+$HTTP = $doc->createElement("HTTP");
+$HTTP = $DCPType->appendChild($HTTP);
+
+#Creating the "Get" node
+$get = $doc->createElement("Get");
+$get = $HTTP->appendChild($get);
+
+#Creating the "OnlineResource" node
+
+//if ($wms_row['wms_getcapabilities'] <> "" AND $wms_row['wms_getcapabilities'] <> NULL) {
+	$onlineResource = $doc->createElement("OnlineResource");
+	$onlineResource = $get->appendChild($onlineResource);
+	$onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
+//	$onlineResource->setAttribute("xlink:href", $wms_row['wms_getcapabilities']);
+	$onlRes = $_SERVER["HTTP_HOST"] . $_SERVER["SCRIPT_NAME"] . "?layer_id=" . $layerId;
+	if (isset($_SERVER["HTTPS"])) {
+		$onlRes = "https://" . $onlRes;
+	}
+	else {
+		$onlRes = "http://" . $onlRes;
+	}
+	$onlineResource->setAttribute("xlink:href", $onlRes);
+	$onlineResource->setAttribute("xlink:type", "simple");		
+//}
+
+#Creating the "Post" node
+$post = $doc->createElement("Post");
+$post = $HTTP->appendChild($post);
+
+#Creating the "OnlineResource" node
+//if ($wms_row['wms_getcapabilities'] <> "" AND $wms_row['wms_getcapabilities'] <> NULL) {
+	$onlineResource = $doc->createElement("OnlineResource");
+	$onlineResource = $post->appendChild($onlineResource);
+	$onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
+//	$onlineResource->setAttribute("xlink:href", $wms_row['wms_getcapabilities']);
+	$onlRes = $_SERVER["HTTP_HOST"] . $_SERVER["SCRIPT_NAME"] . "?layer_id=" . $layerId;
+	if (isset($_SERVER["HTTPS"])) {
+		$onlRes = "https://" . $onlRes;
+	}
+	else {
+		$onlRes = "http://" . $onlRes;
+	}
+	$onlineResource->setAttribute("xlink:href", $onlRes);
+	$onlineResource->setAttribute("xlink:type", "simple");
+//}
+
+##########################################################
+#GetMap	
+#Creatig the "GetMap" node 
+$getMap = $doc->createElement("GetMap");
+$getMap = $request->appendChild($getMap);
+
+#Creatig the "Format" node 
+$wms_format_sql ="SELECT data_format FROM wms_format WHERE fkey_wms_id = $1 AND data_type = 'map'";
+$v = array($wms_row['wms_id']);
+$t = array("i");
+$res_wms_format_sql = db_prep_query($wms_format_sql, $v, $t);
+
+while ($wms_format_row = db_fetch_array($res_wms_format_sql)) {
+    $format = $doc->createElement("Format");
+    $format = $getMap->appendChild($format);
+    $formatText = $doc->createTextNode($wms_format_row['data_format']);
+    $formatText = $format->appendChild($formatText);	
+}
+
+#Creating the "DCPType" node
+$DCPType = $doc->createElement("DCPType");
+$DCPType = $getMap->appendChild($DCPType);
+
+#Creating the "HTTP" node
+$HTTP = $doc->createElement("HTTP");
+$HTTP = $DCPType->appendChild($HTTP);
+
+#Creating the "Get" node
+$get = $doc->createElement("Get");
+$get = $HTTP->appendChild($get);
+
+#Creating the "OnlineResource" node
+if ($wms_row['wms_getmap'] <> "" AND $wms_row['wms_getmap'] <> NULL) {
+	$onlineResource = $doc->createElement("OnlineResource");
+	$onlineResource = $get->appendChild($onlineResource);
+	$onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink" );
+	$onlineResource->setAttribute("xlink:href", $wms_row['wms_getmap']);
+	$onlineResource->setAttribute("xlink:type", "simple");
+}
+
+#Creating the "Post" node
+$post = $doc->createElement("Post");
+$post = $HTTP->appendChild($post);
+
+#Creating the "OnlineResource" node
+if($wms_row['wms_getmap'] <> "" AND $wms_row['wms_getmap'] <> NULL) {
+	$onlineResource = $doc->createElement("OnlineResource");
+	$onlineResource = $post->appendChild($onlineResource);
+	$onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink" );
+	$onlineResource->setAttribute("xlink:href", $wms_row['wms_getmap']);
+	$onlineResource->setAttribute("xlink:type", "simple");
+}
+
+##########################################################
+#GetFeatureInfo	
+#Creatig the "GetFeatureInfo" node 
+$getFeatureInfo = $doc->createElement("GetFeatureInfo");
+$getFeatureInfo = $request->appendChild($getFeatureInfo);
+
+#Creatig the "Format" node 
+$wms_format_sql ="SELECT data_format FROM wms_format WHERE fkey_wms_id = $1 AND data_type = 'featureinfo'";
+$v = array($wms_row['wms_id']);
+$t = array("i");
+$res_wms_format_sql = db_prep_query($wms_format_sql, $v, $t);
+while ($wms_format_row = db_fetch_array($res_wms_format_sql))
+{
+    $format = $doc->createElement("Format");
+    $format = $getFeatureInfo->appendChild($format);
+    $formatText = $doc->createTextNode($wms_format_row['data_format']);
+    $formatText = $format->appendChild($formatText);    
+}
+	
+#Creating the "DCPType" node
+$DCPType = $doc->createElement("DCPType");
+$DCPType = $getFeatureInfo->appendChild($DCPType);
+
+#Creating the "HTTP" node
+$HTTP = $doc->createElement("HTTP");
+$HTTP = $DCPType->appendChild($HTTP);
+
+#Creating the "Get" node
+$get = $doc->createElement("Get");
+$get = $HTTP->appendChild($get);
+
+#Creating the "OnlineResource" node
+if($wms_row['wms_getfeatureinfo'] <> "" AND $wms_row['wms_getfeatureinfo'] <> NULL)
+{
+	$onlineResource = $doc->createElement("OnlineResource");
+	$onlineResource = $get->appendChild($onlineResource);
+	$onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink" );
+	$onlineResource->setAttribute("xlink:href", $wms_row['wms_getfeatureinfo']);
+	$onlineResource->setAttribute("xlink:type", "simple");
+}
+#Creating the "Post" node
+$post = $doc->createElement("Post");
+$post = $HTTP->appendChild($post);
+
+#Creating the "OnlineResource" node
+
+if($wms_row['wms_getfeatureinfo'] <> "" AND $wms_row['wms_getfeatureinfo'] <> NULL) {
+	$onlineResource = $doc->createElement("OnlineResource");
+	$onlineResource = $post->appendChild($onlineResource);
+	$onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink" );
+	$onlineResource->setAttribute("xlink:href", $wms_row['wms_getfeatureinfo']);
+	$onlineResource->setAttribute("xlink:type", "simple");
+}
+	
+#Creating the "Exeption" node
+$exception = $doc->createElement("Exception");
+$exception = $capability->appendChild($exception);	
+
+#Creatig the "Format" node 
+$wms_format_sql ="SELECT data_format FROM wms_format WHERE fkey_wms_id = $1 AND data_type = 'exception'";
+$v = array($wms_row['wms_id']);
+$t = array("i");
+$res_wms_format_sql = db_prep_query($wms_format_sql, $v, $t);
+while ($wms_format_row = db_fetch_array($res_wms_format_sql)) {
+    $format = $doc->createElement("Format");
+    $format = $exception->appendChild($format);
+    $formatText = $doc->createTextNode($wms_format_row['data_format']);
+    $formatText = $format->appendChild($formatText); 
+} 
+
+################################################################
+#Querying layer table
+$layer_sql = "SELECT * FROM layer WHERE layer.fkey_wms_id = $1 AND layer.layer_parent = ''";
+$v = array($wms_row['wms_id']);
+$t = array("i");
+
+$res_layer_sql = db_prep_query($layer_sql, $v, $t);
+$layer_row = db_fetch_array($res_layer_sql);
+			
+#Creating layer node
+$layer = $doc->createElement("Layer");
+$layer = $capability->appendChild($layer);
+
+#Write layer to parent layer array
+$parentLayerArray[$layer_row['layer_pos']] = $layer;
+		
+#Creating Name node
+if ($layer_row['layer_name'] <> "" AND $layer_row['layer_name'] <> NULL) {
+	$name = $doc->createElement("Name");
+	$name = $layer->appendChild($name);
+	$nameText = $doc->createTextNode($layer_row['layer_name']);
+	$nameText = $name->appendChild($nameText);
+}
+
+#Creating Title node
+if ($layer_row['layer_title'] <> "" AND $layer_row['layer_title'] <> NULL) {
+	$title = $doc->createElement("Title");
+	$title = $layer->appendChild($title);
+	$titleText = $doc->createTextNode($layer_row['layer_title']);
+	$titleText = $title->appendChild($titleText);
+}
+
+#Creating the "Abstract" node
+if($layer_row['layer_abstract'] <> "" AND $layer_row['layer_abstract'] <> NULL) {
+    $abstract = $doc->createElement("Abstract");
+    $abstract = $layer->appendChild($abstract);
+    $abstractText = $doc->createTextNode($layer_row['layer_abstract']);
+    $abstractText = $abstract->appendChild($abstractText);	
+}
+
+#Request the specific wms- and layerkeywords
+
+$keyword_sql = "SELECT DISTINCT keyword FROM keyword, layer_keyword, layer " . 
+	"WHERE keyword.keyword_id = layer_keyword.fkey_keyword_id " . 
+	"AND layer_keyword.fkey_layer_id = layer.layer_id " . 
+	"AND layer.fkey_wms_id = $1";
+$v = array($wms_row['wms_id']);
+$t = array("i");
+$res_keyword_sql = db_prep_query($keyword_sql, $v, $t);
+
+#Creating list of keyword nodes
+#Iterating over a List of Keywords
+$keywordlistExist = 0;
+
+while ($keyword_sql = db_fetch_array($res_keyword_sql))
+{
+    #Creating the "KeywordList" node
+    if ($keywordlistExist == 0) {
+        $keywordList = $doc->createElement("KeywordList");
+        $keywordList = $layer->appendChild($keywordList);
+		$keywordlistExist = 1;	
+    }
+    
+    #Creating the "Keyword" node
+    $keyword_dom = $doc->createElement("Keyword");
+    $keyword_dom = $keywordList->appendChild($keyword_dom); 
+    $keyword_domText = $doc->createTextNode($keyword_sql['keyword']);
+    $keyword_domText = $keyword_dom->appendChild($keyword_domText);
+}
+
+
+
+#SQL statement to get additional layer information from layer epsg	
+$epsg_sql = "SELECT layer_epsg.epsg, layer_epsg.minx, layer_epsg.miny, " . 
+	"layer_epsg.maxy, layer_epsg.maxx " . 
+	"FROM layer_epsg WHERE layer_epsg.fkey_layer_id = $1";
+	
+$v = array($layer_row['layer_id']);
+$t = array("i");
+$res_espg_sql = db_prep_query($epsg_sql, $v, $t);
+
+$latLonBoundingBoxCreated = false;
+$BoundingBoxCreated = false;
+
+while ($epsg_row = db_fetch_array($res_espg_sql)) {
+
+	#Creating SRS node
+	$srs = $doc->createElement("SRS");
+	$srs = $layer->appendChild($srs);
+	$srsText = $doc->createTextNode($epsg_row['epsg']);
+	$srsText = $srs->appendChild($srsText);
+	
+
+}
+
+#SQL statement to get additional layer information from layer epsg	
+$epsg_sql = "SELECT layer_epsg.epsg, layer_epsg.minx, layer_epsg.miny, " . 
+	"layer_epsg.maxy, layer_epsg.maxx " . 
+	"FROM layer_epsg WHERE layer_epsg.fkey_layer_id = $1";
+	
+$v = array($layer_row['layer_id']);
+$t = array("i");
+$res_espg_sql = db_prep_query($epsg_sql, $v, $t);
+
+while ($epsg_row = db_fetch_array($res_espg_sql)) {
+	#set only epsg 4326 for latlonbbox
+	if ($epsg_row['epsg'] == "EPSG:4326") {
+		
+		$latlon['minx'] = $epsg_row['minx'];
+		$latlon['miny'] = $epsg_row['miny'];
+		$latlon['maxx'] = $epsg_row['maxx'];
+		$latlon['maxy'] = $epsg_row['maxy'];
+
+		#Creating LatLongBoundingBox node
+		$latLonBoundingBox = $doc->createElement("LatLonBoundingBox");
+		$latLonBoundingBox = $layer->appendChild($latLonBoundingBox);
+		$latLonBoundingBox->setAttribute('minx', $latlon['minx']);
+		$latLonBoundingBox->setAttribute('miny', $latlon['miny']);
+		$latLonBoundingBox->setAttribute('maxx', $latlon['maxx']);
+		$latLonBoundingBox->setAttribute('maxy', $latlon['maxy']);
+	    break;
+    }	
+}
+
+#SQL statement to get additional layer information from layer epsg	
+$epsg_sql = "SELECT layer_epsg.epsg, layer_epsg.minx, layer_epsg.miny, " . 
+	"layer_epsg.maxy, layer_epsg.maxx " . 
+	"FROM layer_epsg WHERE layer_epsg.fkey_layer_id = $1";
+	
+$v = array($layer_row['layer_id']);
+$t = array("i");
+$res_espg_sql = db_prep_query($epsg_sql, $v, $t);
+
+while ($epsg_row = db_fetch_array($res_espg_sql)) {
+	#set only first epsg for bbox
+	$bbox['epsg'] = $epsg_row['epsg'];
+	$bbox['minx'] = $epsg_row['minx'];
+	$bbox['miny'] = $epsg_row['miny'];
+	$bbox['maxx'] = $epsg_row['maxx'];
+	$bbox['maxy'] = $epsg_row['maxy'];
+
+	#Creating BoundingBox node
+	$boundingBox = $doc->createElement("BoundingBox");
+	$boundingBox = $layer->appendChild($boundingBox);
+	$boundingBox->setAttribute('SRS', $bbox['epsg']);
+	$boundingBox->setAttribute('minx', $bbox['minx']);
+	$boundingBox->setAttribute('miny', $bbox['miny']);
+	$boundingBox->setAttribute('maxx', $bbox['maxx']);
+	$boundingBox->setAttribute('maxy', $bbox['maxy']);
+}
+
+
+#Append epsg string to srs node
+$srsText = $doc->createTextNode($epsgText);
+$srsText = $srs->appendChild($srsText);
+
+
+####### duplicate root layer 
+#if layer is root layer itself!
+#<armin>
+##if ($layer_row['layer_pos']=='0'){
+#</armin>
+##$clonedLayer = $layer->cloneNode(true);
+##$clonedLayer->setAttribute("queryable", "0");
+##$clonedLayer->setAttribute("cascaded", "0");
+##$layer->appendChild($clonedLayer);
+#<armin>
+##}
+#</armin>
+
+
+
+############## sublayer 
+	
+#SQL statement to get all layers
+$sub_layer_sql = "SELECT * FROM layer WHERE fkey_wms_id = $1 AND layer_parent <> ''";
+$v = array($wms_row['wms_id']);
+$t = array("i");
+
+if (isset($layerId) && $layerId > 0) {	
+	$sub_layer_sql .= " AND layer_id = $2";
+	array_push($v, $layerId);
+	array_push($t, "i");
+}
+$sub_layer_sql .= " ORDER BY layer_pos";
+$res_sub_layer_sql = db_prep_query($sub_layer_sql, $v, $t);
+
+
+#<armin>
+$res_sub_layer_sql_2 = db_prep_query($sub_layer_sql, $v, $t);   
+$sub_layer_row_2 = db_fetch_array($res_sub_layer_sql_2);
+
+
+if (!isset($sub_layer_row_2['layer_pos'])) {
+	$clonedLayer = $layer->cloneNode(true);
+	$clonedLayer->setAttribute("queryable", "0");
+	$clonedLayer->setAttribute("cascaded", "0");
+	$layer->appendChild($clonedLayer);
+}
+#</armin>
+
+
+
+
+while ($sub_layer_row = db_fetch_array($res_sub_layer_sql)) {
+	
+	#Creating layer node
+
+	$sub_layer = $doc->createElement("Layer");
+	
+	$parent = $parentLayerArray[$sub_layer_row['layer_parent']];
+	$sub_layer = $parent->appendChild($sub_layer);
+    
+    if($sub_layer_row['layer_queryable'] <> "" AND $sub_layer_row['layer_queryable'] <> NULL) {
+		$sub_layer->setAttribute('queryable', $sub_layer_row['layer_queryable']);
+    }
+	#Getting information about the hierarchie of layers
+	$cascadeSQL = "SELECT COUNT(*) FROM layer WHERE fkey_wms_id = $1 AND layer_parent = $2";
+	
+	$v = array($wms_row[0], $sub_layer_row['layer_pos']);
+	$t = array("i", "i");
+	$res_cascadeSQL = db_prep_query($cascadeSQL, $v, $t);
+	$cascade = 0;
+	$cascade_row = db_fetch_row($res_cascadeSQL);
+	if($cascade_row[0] > 0)	{
+		$cascade = 1;
+	}
+	$sub_layer->setAttribute('cascaded', $cascade);
+	
+	#Write layer to parent layer array
+	$parentLayerArray[$sub_layer_row['layer_pos']] = $sub_layer;
+	
+	#Creating name node
+    if($sub_layer_row['layer_name'] <> "" AND $sub_layer_row['layer_name'] <> NULL)
+    {
+		$name = $doc->createElement("Name");
+		$name = $sub_layer->appendChild($name);
+		$nameText = $doc->createTextNode($sub_layer_row['layer_name']);
+		$nameText = $name->appendChild($nameText);
+    }
+	
+	#Creating Title node
+    if($sub_layer_row['layer_title'] <> "" AND $sub_layer_row['layer_title'] <> NULL)
+    {
+		$title = $doc->createElement("Title");
+		$title = $sub_layer->appendChild($title);
+		$titleText = $doc->createTextNode($sub_layer_row['layer_title']);
+		$titleText = $title->appendChild($titleText);
+    }
+	
+		#Creating the "Abstract" node
+    if($sub_layer_row['layer_abstract'] <> "" AND $sub_layer_row['layer_abstract'] <> NULL)
+    {
+    	$abstract = $doc->createElement("Abstract");
+    	$abstract = $sub_layer->appendChild($abstract);
+    	$abstractText = $doc->createTextNode($sub_layer_row['layer_abstract']);
+    	$abstractText = $abstract->appendChild($abstractText);
+    }
+	
+    #Request the specific wms- and layerkeywords
+    $keyword_sql = "SELECT DISTINCT keyword FROM layer LEFT JOIN layer_keyword ON layer_keyword.fkey_layer_id = layer.layer_id LEFT JOIN keyword ON  keyword.keyword_id = layer_keyword.fkey_keyword_id WHERE layer.fkey_wms_id = ".$wms_row['wms_id']." AND layer.layer_id = ".$sub_layer_row['layer_id']."";
+    $res_keyword_sql = db_query($keyword_sql);
+    
+    #Creating list of keyword nodes
+    #Iterating over a List of Keywords
+    $keywordlistExist = 0;
+    while ($keyword_sql = db_fetch_array($res_keyword_sql))
+    {
+        #Creating the "KeywordList" node
+        if ($keywordlistExist == 0)
+        {
+            $keywordList = $doc->createElement("KeywordList");
+            $keywordList = $sub_layer->appendChild($keywordList);
+		    $keywordlistExist = 1;			
+        }
+        
+        #Creating the "Keyword" node
+        $keyword_dom = $doc->createElement("Keyword");
+        $keyword_dom = $keywordList->appendChild($keyword_dom); 
+        $keyword_domText = $doc->createTextNode($keyword_sql['keyword']);
+        $keyword_domText = $keyword_dom->appendChild($keyword_domText);
+    }
+
+	// inherit srs from parent layer
+	$layer_srs_sql = "SELECT DISTINCT epsg FROM layer_epsg " . 
+			"WHERE fkey_layer_id = ".$sub_layer_row['layer_id'] . 
+			" OR fkey_layer_id = " . $layer_row['layer_id'];
+	$res_layer_srs_sql = db_query($layer_srs_sql);
+
+	while ($layer_srs_row = db_fetch_array($res_layer_srs_sql)) {
+		#Creating SRS node
+		$srs = $doc->createElement("SRS");
+		$srs = $sub_layer->appendChild($srs);
+		$srsText = $doc->createTextNode($layer_srs_row['epsg']);
+		$srsText = $srs->appendChild($srsText);
+
+	}
+	#SQL statement to get additional layer information from layer epsg	
+	$epsg_sql = "SELECT layer_epsg.epsg, layer_epsg.minx, layer_epsg.miny, " . 
+			"layer_epsg.maxy, layer_epsg.maxx FROM layer_epsg " . 
+			"WHERE layer_epsg.fkey_layer_id = ".$sub_layer_row['layer_id'];
+	$res_espg_sql = db_query($epsg_sql);
+	
+	while ($epsg_row = db_fetch_array($res_espg_sql)) {
+		#set epsg 4326 for latlonbbox
+		if ($epsg_row['epsg'] == "EPSG:4326" AND $latLonBoundingBoxCreated == false) {
+			
+			$latlon['minx'] = $epsg_row['minx'];
+			$latlon['miny'] = $epsg_row['miny'];
+			$latlon['maxx'] = $epsg_row['maxx'];
+			$latlon['maxy'] = $epsg_row['maxy'];
+
+			#Creating LatLongBoundingBox node
+		    $latLonBoundingBox = $doc->createElement("LatLonBoundingBox");
+		    $latLonBoundingBox = $sub_layer->appendChild($latLonBoundingBox);
+		    $latLonBoundingBox->setAttribute('minx', $latlon['minx']);
+		    $latLonBoundingBox->setAttribute('miny', $latlon['miny']);
+		    $latLonBoundingBox->setAttribute('maxx', $latlon['maxx']);
+		    $latLonBoundingBox->setAttribute('maxy', $latlon['maxy']);
+	    }	
+	}
+	
+	#SQL statement to get additional layer information from layer epsg	
+	$epsg_sql = "SELECT layer_epsg.epsg, layer_epsg.minx, layer_epsg.miny, " . 
+			"layer_epsg.maxy, layer_epsg.maxx FROM layer_epsg " . 
+			"WHERE layer_epsg.fkey_layer_id = ".$sub_layer_row['layer_id'];
+	$res_espg_sql = db_query($epsg_sql);
+	
+	while ($epsg_row = db_fetch_array($res_espg_sql)) {
+	
+		
+		#set only first epsg for bbox
+		$bbox['epsg'] = $epsg_row['epsg'];
+		$bbox['minx'] = $epsg_row['minx'];
+		$bbox['miny'] = $epsg_row['miny'];
+		$bbox['maxx'] = $epsg_row['maxx'];
+		$bbox['maxy'] = $epsg_row['maxy'];
+
+		#Creating BoundingBox node
+		$boundingBox = $doc->createElement("BoundingBox");
+		$boundingBox = $sub_layer->appendChild($boundingBox);
+		$boundingBox->setAttribute('SRS', $bbox['epsg']);
+		$boundingBox->setAttribute('minx', $bbox['minx']);
+		$boundingBox->setAttribute('miny', $bbox['miny']);
+		$boundingBox->setAttribute('maxx', $bbox['maxx']);
+		$boundingBox->setAttribute('maxy', $bbox['maxy']);
+	}
+	
+	# Creating Metadata Node
+	
+	$metadataUrl = $doc->createElement("MetadataURL");
+	$metadataUrl = $sub_layer->appendChild($metadataUrl);
+	$metadataUrl->setAttribute('type', "TC211");
+	
+	$format = $doc->createElement("Format");
+    $format = $metadataUrl->appendChild($format);
+    $formatText = $doc->createTextNode('text/html');
+    $formatText = $format->appendChild($formatText); 
+
+	if ($wms_row['wms_owsproxy'] <> "" AND $wms_row['wms_owsproxy'] <> NULL) {
+		$onlineResource = $doc->createElement("OnlineResource");
+	   	$onlineResource = $metadataUrl->appendChild($onlineResource);
+	   	$onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink" );
+		$onlineResource->setAttribute("xlink:href", OWSPROXY."/".session_id()."/".$wms_row["wms_owsproxy"]."?");
+		$onlineResource->setAttribute("xlink:type", "simple");
+	}
+	else {
+		if ($sub_layer_row['layer_metadataurl'] <> "" AND $sub_layer_row['layer_metadataurl'] <> NULL) {
+	    	$onlineResource = $doc->createElement("OnlineResource");
+	    	$onlineResource = $metadataUrl->appendChild($onlineResource);
+			$onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink" );
+			$onlineResource->setAttribute("xlink:href", $sub_layer_row['layer_metadataurl']);
+			$onlineResource->setAttribute("xlink:type", "simple");
+	    }
+else
+{
+ $onlineResource = $doc->createElement("OnlineResource");
+                $onlineResource = $metadataUrl->appendChild($onlineResource);
+                        $onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink" );
+                        $onlineResource->setAttribute("xlink:type", "simple");
+
+}
+
+
+	}
+	# Creating DataURL Node
+	$dataUrl = $doc->createElement("DataURL");
+	$dataUrl = $sub_layer->appendChild($dataUrl);
+	
+	
+	
+	$format = $doc->createElement("Format");
+    $format = $dataUrl->appendChild($format);
+    $formatText = $doc->createTextNode('text/html');
+    $formatText = $format->appendChild($formatText); 
+
+
+	if($wms_row['wms_owsproxy'] <> "" AND $wms_row['wms_owsproxy'] <> NULL)
+	{
+		$onlineResource = $doc->createElement("OnlineResource");
+	   	$onlineResource = $dataUrl->appendChild($onlineResource);
+	   	$onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink" );
+		$onlineResource->setAttribute("xlink:href", OWSPROXY."/".session_id()."/".$wms_row["wms_owsproxy"]."?");
+		$onlineResource->setAttribute("xlink:type", "simple");
+	}
+	else
+	{
+		if($sub_layer_row['layer_dataurl'] <> "" AND $sub_layer_row['layer_dataurl'] <> NULL)
+	    {
+	    	$onlineResource = $doc->createElement("OnlineResource");
+	    	$onlineResource = $dataUrl->appendChild($onlineResource);
+			$onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink" );
+			$onlineResource->setAttribute("xlink:href", $sub_layer_row['layer_dataurl']);
+			$onlineResource->setAttribute("xlink:type", "simple");
+	    }
+else
+{
+ $onlineResource = $doc->createElement("OnlineResource");
+                $onlineResource = $dataUrl->appendChild($onlineResource);
+                        $onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink" );
+                        $onlineResource->setAttribute("xlink:href", $mapbenderMetadataUrl.$sub_layer_row['layer_id']);
+                        $onlineResource->setAttribute("xlink:type", "simple");
+
+}
+
+
+
+
+
+
+
+	}
+	
+	
+	#Creating Style Node
+	$style = $doc->createElement("Style");
+	$style = $sub_layer->appendChild($style);
+	
+	$name = $doc->createElement("Name");
+    $name = $style->appendChild($name);
+    $nameText = $doc->createTextNode('default');
+    $nameText = $name->appendChild($nameText);
+
+	$title = $doc->createElement("Title");
+    $title = $style->appendChild($title);
+    $titleText = $doc->createTextNode('default');
+    $titleText = $title->appendChild($titleText);
+	
+
+
+    if($wms_row['wms_getlegendurl'] <> "" AND $wms_row['wms_getlegendurl'] <> NULL){	
+	$legendUrl = $doc->createElement("LegendURL");
+	$legendUrl = $style->appendChild($legendUrl);
+	$legendUrl->setAttribute("width", "10" );
+	$legendUrl->setAttribute("height", "8" );
+
+	$format = $doc->createElement("Format");
+    $format = $legendUrl->appendChild($format);
+    $formatText = $doc->createTextNode('image/png');
+    $formatText = $format->appendChild($formatText); 
+
+	if($wms_row['wms_owsproxy'] <> "" AND $wms_row['wms_owsproxy'] <> NULL)
+	{
+		$onlineResource = $doc->createElement("OnlineResource");
+	   	$onlineResource = $legendUrl->appendChild($onlineResource);
+	   	$onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink" );
+		$onlineResource->setAttribute("xlink:href", OWSPROXY."/".session_id()."/".$wms_row["wms_owsproxy"]."?version=1.1.1&service=WMS&request=GetLegendGraphic&layer=".$sub_layer_row['layer_name']."&format=image/png");
+		$onlineResource->setAttribute("xlink:type", "simple");
+	}
+	else
+	{
+		if($wms_row['wms_getlegendurl'] <> "" AND $wms_row['wms_getlegendurl'] <> NULL)
+	    {
+	    	$onlineResource = $doc->createElement("OnlineResource");
+	    	$onlineResource = $legendUrl->appendChild($onlineResource);
+			$onlineResource->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink" );
+			$onlineResource->setAttribute("xlink:href", $wms_row['wms_getlegendurl']."version=1.1.1&service=WMS&request=GetLegendGraphic&layer=".$sub_layer_row['layer_name']."&format=image/png");
+			$onlineResource->setAttribute("xlink:type", "simple");
+	    }
+	}
+
+
+}
+	#Creating "ScaleHint" node
+    if ($sub_layer_row['layer_minscale'] <> "" AND $sub_layer_row['layer_minscale'] <> NULL) {
+		$scaleHint = $doc->createElement("ScaleHint");
+		$scaleHint = $sub_layer->appendChild($scaleHint);
+		$scaleHint->setAttribute('min', (floatval($sub_layer_row['layer_minscale'])/2004.3976484406788493955738891127));
+		$scaleHint->setAttribute('max', (floatval($sub_layer_row['layer_maxscale'])/2004.3976484406788493955738891127));
+    }
+}	
+
+header("Content-type: application/xml; charset=UTF-8");
+echo $doc->saveXml();
+?>

Deleted: branches/mapbender/http/plugins/mb_extendedSearch.js
===================================================================
--- trunk/mapbender/http/plugins/mb_extendedSearch.js	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/http/plugins/mb_extendedSearch.js	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,359 +0,0 @@
-/**
- * Package: mb_extendedSearch.js
- *
- * Description:
- *
- * Module for the extended search form. The form itself a mapbender gui.
- * Corresponding server file plugins/mb_extendedSearch_server.php
- * 
- *  
- * Files:
- * - http/plugins/mb_extendedSearch.js
- *
- * SQL:
- * >see ../../db/extentedSearchGui.sql
- * >
- * >
- * >
- * >
- * >
- * >
- * >
- * >
- * 
- * Help:
- *
- * Maintainer:
- * http://www.mapbender.org/User:Armin_Retterath
- *
- * License:
- * Copyright (c) 2009, Open Source Geospatial Foundation
- * This program is dual licensed under the GNU General Public License
- * and Simplified BSD license.
- * http://svn.osgeo.org/mapbender/trunk/mapbender/license/license.txt
- */
-
-
-
-
-var empty = 'false';
-var obj = {};
-//define variables for the 2 different forms:
-var form1 = document.getElementsByName('form1')[0];
-var form2 = document.getElementsByName('form2')[0];
-
-/**
- * get list of all information by ajax call when intializing the client
- */
-function requestList(){
-	obj['action'] = 'getList';
-	var obj2json = $.toJSON(obj);
-	getList(obj2json);
-}
-
-Mapbender.events.init.register(function () {
-	$('.hasdatepicker').datepicker({dateFormat:'yy-mm-dd',showOn: 
-'button', buttonImage: '../img/calendar.png', buttonImageOnly: true, 
-constraintInput: true});
-	$("button, input:submit, a", ".button").button();
-
-    requestList();
-});
-
-/**Mapbender.events.init.register(
-	function() {
-		$("#tabs").tabs();
-	}
-);*/
-
-
-/**
- * Ajax-JSON function to get list of all departments from server
- */
-function getList(obj){
-	mb_ajax_post("../x_geoportal/suche/mod_extendedSearch_serverNew.php",{"obj":obj}, function (json,status){
-		if(status == 'success'){
-			appendList(json);
-			$("form[name='form1']").find('.help-dialog').helpDialog();
-		}		
-		else{
-			alert("An error occured!");
-		}
-	});
-}
-
-/**
- * Function to fill department list selectbox 
- */
-function appendList(json){
-	var djson = json;
-	//new options for department list
-	for(var i=0; i<djson.entries.group_name.length; i++){
-		var newOption = new Option(djson.entries.group_name[i],djson.entries.user_department[i],false,false);
-		var list = form1.registratingDepartments;
-		newOption.newAttribute = "title";
-		newOption.title = djson.entries.group_title[i];
-		list.options[list.length] = newOption;
-	}
-	
-	//new options for inspire list
-	for(var i=0; i<djson.entries.inspire_cat_name.length; i++){
-		var newOption = new Option(djson.entries.inspire_cat_name[i],djson.entries.inspire_cat_id[i],false,false);
-		var list = form1.inspireThemes;
-		newOption.newAttribute = "title";
-		newOption.title = djson.entries.inspire_cat_title[i];
-		list.options[list.length] = newOption;
-	}
-
-	//new options for iso list
-	for(var i=0; i<djson.entries.iso_cat_name.length; i++){
-		var newOption = new Option(djson.entries.iso_cat_name[i],djson.entries.iso_cat_id[i],false,false);
-		var list = form1.isoCategories;
-		newOption.newAttribute = "title";
-		newOption.title = djson.entries.iso_cat_title[i];
-		list.options[list.length] = newOption;
-	}
-
-	//new options for custom list
-	for(var i=0; i<djson.entries.custom_cat_name.length; i++){
-		var newOption = new Option(djson.entries.custom_cat_name[i],djson.entries.custom_cat_id[i],false,false);
-		var list = form1.customCategories;
-		newOption.newAttribute = "title";
-		newOption.title = djson.entries.custom_cat_title[i];
-		list.options[list.length] = newOption;
-	}
-
-	//push translations to form (text fields)
-	//for (var key in djson.entries.translations) {
-	for (var key in djson.entries.translations) {
-		if (key != 'search') { //search is the text for the search button
-			if (key.substring(0,4) != 'help') {
-       				$("#" + key).text(djson.entries.translations[key]);
-			}
-			else {
-				//alert("help found: "+djson.entries.translations[key]);
-				$("#" + key).attr("help","{text:'"+djson.entries.translations[key]+"'}");
-			}
-		}
-		else {
-			$("#" + key).val(djson.entries.translations[key]);
-			$("#" + key).text(djson.entries.translations[key]);
-		}
-	}
-}
-
-function removeListSelections(listname){
-	eval("var list = document.getElementById('"+listname+"');");
-	list.selectedIndex = -1;
-} 
-
-function getValueSearchTypeBbox()
-{
-for (var i=0; i < document.form2.searchTypeBbox.length; i++)
-   {
-   if (document.form2.searchTypeBbox[i].checked)
-      {
-      return document.form2.searchTypeBbox[i].value;
-      }
-   }
-}
-
-function getValueSortBy()
-{
-for (var i=0; i < document.form2.sortBy.length; i++)
-   {
-   if (document.form2.sortBy[i].checked)
-      {
-      return document.form2.sortBy[i].value;
-      }
-   }
-}
-
-/**
-* Function to get map extent of current mapframe1 
-*
-*/
-function getMapExtent(obj){
-	if(obj.checked == true){
-		var mapObj = getMapObjByName("mapframe1");
-		document.form2.searchBbox.value = mapObj.extent;
-	}
-	else{
-		document.form2.searchBbox.value = null;
-	}
-}
-
-/**
-* Function to get values of form1 and fill hidden fields of form2
-*
-*/
-function validate(){
-	var send = true;
-
-	//departments
-	var departments = [];
-	var cnt=0;
-	for(var i=0; i<form1.registratingDepartments.length; i++){
-		if(form1.registratingDepartments.options[i].selected == true){
-			departments[cnt] = form1.registratingDepartments.options[i].value;
-			cnt++;
-		}	
-	}
-	if(cnt>0){
-		form2.registratingDepartments.value = departments.join(",");
-	}
-	else{
-		form2.registratingDepartments.value = empty;
-	}
-
-	//isocategories
-	var categories=[];
-	var cnt=0;
-	for(var i=0; i<form1.isoCategories.length; i++){
-		if(form1.isoCategories.options[i].selected == true){
-			categories[cnt] = form1.isoCategories.options[i].value;
-			cnt++;
-		}	
-	}
-	if(cnt>0){
-		form2.isoCategories.value = categories.join(",");
-	}
-	else{
-		form2.isoCategories.value = empty;
-	}
-
-	//customcategories
-	var categories=[];
-	var cnt=0;
-	for(var i=0; i<form1.customCategories.length; i++){
-		if(form1.customCategories.options[i].selected == true){
-			categories[cnt] = form1.customCategories.options[i].value;
-			cnt++;
-		}	
-	}
-	if(cnt>0){
-		form2.customCategories.value = categories.join(",");
-	}
-	else{
-		form2.customCategories.value = empty;
-	}
-
-	//inspirethemes
-	var categories=[];
-	var cnt=0;
-	for(var i=0; i<form1.inspireThemes.length; i++){
-		if(form1.inspireThemes.options[i].selected == true){
-			categories[cnt] = form1.inspireThemes.options[i].value;
-			cnt++;
-		}	
-	}
-	if(cnt>0){
-		form2.inspireThemes.value = categories.join(",");
-	}
-	else{
-		form2.inspireThemes.value = empty;
-	}
-
-	//searchText
-	if(form1.searchText.value != ""){
-		form2.searchText.value = form1.searchText.value;
-	}
-	else{
-		form2.searchText.value = empty;
-	}
-
-	//validFrom
-	var regTimeBegin = form1.regTimeBegin.value;
-	if(regTimeBegin != ""){
-		//var ds = regTimeBegin.split(".");
-		// var d = new Date(parseInt(ds[2]),(parseInt(ds[1] - 1)),parseInt(ds[0]));
-		 form2.regTimeBegin.value = regTimeBegin;
-	}else{
-		form2.regTimeBegin.value = empty;
-	}
-
-	//validTo
-	var regTimeEnd = form1.regTimeEnd.value;
-	if(regTimeEnd != ""){
-		//var ds = regTimeEnd.split(".");
-		//var d = new Date(parseInt(ds[2]),(parseInt(ds[1] - 1)),parseInt(ds[0]));
-		form2.regTimeEnd.value = regTimeEnd;
-	}
-	else{
-		form2.regTimeEnd.value = empty;
-	}
-
-	//dataFrom
-	var timeBegin = form1.timeBegin.value;
-	if(timeBegin != ""){
-		//var ds = timeBegin.split(".");
-		 //var d = new Date(parseInt(ds[2]),(parseInt(ds[1] - 1)),parseInt(ds[0]));
-		 form2.timeBegin.value = timeBegin;
-	}else{
-		form2.timeBegin.value = empty;
-	}
-	//dataTo
-	var timeEnd = form1.timeEnd.value;
-	if(timeEnd != ""){
-		//var ds = timeEnd.split(".");
-		//var d = new Date(parseInt(ds[2]),(parseInt(ds[1] - 1)),parseInt(ds[0]));
-		form2.timeEnd.value = timeEnd;
-	}
-	else{
-		form2.timeEnd.value = empty;
-	}
-
-	//searchTypeBbox
-	var searchTypeBbox = empty;
-	
-	for (var i=0; i < form1.searchTypeBbox.length; i++){
-		
-  		if (form1.searchTypeBbox[i].checked){
-			
-     			searchTypeBbox = form1.searchTypeBbox[i].value;
-			
-      		}
-  	}
-	form2.searchTypeBbox.value = searchTypeBbox;	
-	
-	//searchBbox
-	getMapExtent(form1.searchBbox);
-	
-	//sortBy
-	var orderBy = empty;
-	
-	for (var i=0; i < form1.orderBy.length; i++){
-		
-  		if (form1.orderBy[i].checked){
-			
-     			orderBy = form1.orderBy[i].value;
-			
-      		}
-  	}
-	form2.orderBy.value = orderBy;
-
-	//searchResources
-	var searchResources = [];
-	var cnt=0;
-	var inputElements = document.getElementsByTagName("input");
-	for(var i=0; i<inputElements.length; i++){
-    		if(inputElements[i].name.indexOf("checkResources") != -1){
-    			if(inputElements[i].checked==true){
-    				searchResources[cnt] = inputElements[i].value;
-    				cnt++;	
-    			}		
-    		}
-   	}
-   	if(cnt>0){
-		form2.searchResources.value = searchResources.join(",");
-	}
-	else{
-		form2.searchResources.value = empty;
-	}	
-
-	if(send == true){
-		form2.submit();
-	}
-	return false;
-}
-

Copied: branches/mapbender/http/plugins/mb_extendedSearch.js (from rev 6953, trunk/mapbender/http/plugins/mb_extendedSearch.js)
===================================================================
--- branches/mapbender/http/plugins/mb_extendedSearch.js	                        (rev 0)
+++ branches/mapbender/http/plugins/mb_extendedSearch.js	2010-09-29 11:31:10 UTC (rev 6957)
@@ -0,0 +1,359 @@
+/**
+ * Package: mb_extendedSearch.js
+ *
+ * Description:
+ *
+ * Module for the extended search form. The form itself a mapbender gui.
+ * Corresponding server file plugins/mb_extendedSearch_server.php
+ * 
+ *  
+ * Files:
+ * - http/plugins/mb_extendedSearch.js
+ *
+ * SQL:
+ * >see ../../db/extentedSearchGui.sql
+ * >
+ * >
+ * >
+ * >
+ * >
+ * >
+ * >
+ * >
+ * 
+ * Help:
+ *
+ * Maintainer:
+ * http://www.mapbender.org/User:Armin_Retterath
+ *
+ * License:
+ * Copyright (c) 2009, Open Source Geospatial Foundation
+ * This program is dual licensed under the GNU General Public License
+ * and Simplified BSD license.
+ * http://svn.osgeo.org/mapbender/trunk/mapbender/license/license.txt
+ */
+
+
+
+
+var empty = 'false';
+var obj = {};
+//define variables for the 2 different forms:
+var form1 = document.getElementsByName('form1')[0];
+var form2 = document.getElementsByName('form2')[0];
+
+/**
+ * get list of all information by ajax call when intializing the client
+ */
+function requestList(){
+	obj['action'] = 'getList';
+	var obj2json = $.toJSON(obj);
+	getList(obj2json);
+}
+
+Mapbender.events.init.register(function () {
+	$('.hasdatepicker').datepicker({dateFormat:'yy-mm-dd',showOn: 
+'button', buttonImage: '../img/calendar.png', buttonImageOnly: true, 
+constraintInput: true});
+	$("button, input:submit, a", ".button").button();
+
+    requestList();
+});
+
+/**Mapbender.events.init.register(
+	function() {
+		$("#tabs").tabs();
+	}
+);*/
+
+
+/**
+ * Ajax-JSON function to get list of all departments from server
+ */
+function getList(obj){
+	mb_ajax_post("../plugins/mb_extendedSearch_server.php",{"obj":obj}, function (json,status){
+		if(status == 'success'){
+			appendList(json);
+			$("form[name='form1']").find('.help-dialog').helpDialog();
+		}		
+		else{
+			alert("An error occured!");
+		}
+	});
+}
+
+/**
+ * Function to fill department list selectbox 
+ */
+function appendList(json){
+	var djson = json;
+	//new options for department list
+	for(var i=0; i<djson.entries.group_name.length; i++){
+		var newOption = new Option(djson.entries.group_name[i],djson.entries.user_department[i],false,false);
+		var list = form1.registratingDepartments;
+		newOption.newAttribute = "title";
+		newOption.title = djson.entries.group_title[i];
+		list.options[list.length] = newOption;
+	}
+	
+	//new options for inspire list
+	for(var i=0; i<djson.entries.inspire_cat_name.length; i++){
+		var newOption = new Option(djson.entries.inspire_cat_name[i],djson.entries.inspire_cat_id[i],false,false);
+		var list = form1.inspireThemes;
+		newOption.newAttribute = "title";
+		newOption.title = djson.entries.inspire_cat_title[i];
+		list.options[list.length] = newOption;
+	}
+
+	//new options for iso list
+	for(var i=0; i<djson.entries.iso_cat_name.length; i++){
+		var newOption = new Option(djson.entries.iso_cat_name[i],djson.entries.iso_cat_id[i],false,false);
+		var list = form1.isoCategories;
+		newOption.newAttribute = "title";
+		newOption.title = djson.entries.iso_cat_title[i];
+		list.options[list.length] = newOption;
+	}
+
+	//new options for custom list
+	for(var i=0; i<djson.entries.custom_cat_name.length; i++){
+		var newOption = new Option(djson.entries.custom_cat_name[i],djson.entries.custom_cat_id[i],false,false);
+		var list = form1.customCategories;
+		newOption.newAttribute = "title";
+		newOption.title = djson.entries.custom_cat_title[i];
+		list.options[list.length] = newOption;
+	}
+
+	//push translations to form (text fields)
+	//for (var key in djson.entries.translations) {
+	for (var key in djson.entries.translations) {
+		if (key != 'search') { //search is the text for the search button
+			if (key.substring(0,4) != 'help') {
+       				$("#" + key).text(djson.entries.translations[key]);
+			}
+			else {
+				//alert("help found: "+djson.entries.translations[key]);
+				$("#" + key).attr("help","{text:'"+djson.entries.translations[key]+"'}");
+			}
+		}
+		else {
+			$("#" + key).val(djson.entries.translations[key]);
+			$("#" + key).text(djson.entries.translations[key]);
+		}
+	}
+}
+
+function removeListSelections(listname){
+	eval("var list = document.getElementById('"+listname+"');");
+	list.selectedIndex = -1;
+} 
+
+function getValueSearchTypeBbox()
+{
+for (var i=0; i < document.form2.searchTypeBbox.length; i++)
+   {
+   if (document.form2.searchTypeBbox[i].checked)
+      {
+      return document.form2.searchTypeBbox[i].value;
+      }
+   }
+}
+
+function getValueSortBy()
+{
+for (var i=0; i < document.form2.sortBy.length; i++)
+   {
+   if (document.form2.sortBy[i].checked)
+      {
+      return document.form2.sortBy[i].value;
+      }
+   }
+}
+
+/**
+* Function to get map extent of current mapframe1 
+*
+*/
+function getMapExtent(obj){
+	if(obj.checked == true){
+		var mapObj = getMapObjByName("mapframe1");
+		document.form2.searchBbox.value = mapObj.extent;
+	}
+	else{
+		document.form2.searchBbox.value = null;
+	}
+}
+
+/**
+* Function to get values of form1 and fill hidden fields of form2
+*
+*/
+function validate(){
+	var send = true;
+
+	//departments
+	var departments = [];
+	var cnt=0;
+	for(var i=0; i<form1.registratingDepartments.length; i++){
+		if(form1.registratingDepartments.options[i].selected == true){
+			departments[cnt] = form1.registratingDepartments.options[i].value;
+			cnt++;
+		}	
+	}
+	if(cnt>0){
+		form2.registratingDepartments.value = departments.join(",");
+	}
+	else{
+		form2.registratingDepartments.value = empty;
+	}
+
+	//isocategories
+	var categories=[];
+	var cnt=0;
+	for(var i=0; i<form1.isoCategories.length; i++){
+		if(form1.isoCategories.options[i].selected == true){
+			categories[cnt] = form1.isoCategories.options[i].value;
+			cnt++;
+		}	
+	}
+	if(cnt>0){
+		form2.isoCategories.value = categories.join(",");
+	}
+	else{
+		form2.isoCategories.value = empty;
+	}
+
+	//customcategories
+	var categories=[];
+	var cnt=0;
+	for(var i=0; i<form1.customCategories.length; i++){
+		if(form1.customCategories.options[i].selected == true){
+			categories[cnt] = form1.customCategories.options[i].value;
+			cnt++;
+		}	
+	}
+	if(cnt>0){
+		form2.customCategories.value = categories.join(",");
+	}
+	else{
+		form2.customCategories.value = empty;
+	}
+
+	//inspirethemes
+	var categories=[];
+	var cnt=0;
+	for(var i=0; i<form1.inspireThemes.length; i++){
+		if(form1.inspireThemes.options[i].selected == true){
+			categories[cnt] = form1.inspireThemes.options[i].value;
+			cnt++;
+		}	
+	}
+	if(cnt>0){
+		form2.inspireThemes.value = categories.join(",");
+	}
+	else{
+		form2.inspireThemes.value = empty;
+	}
+
+	//searchText
+	if(form1.searchText.value != ""){
+		form2.searchText.value = form1.searchText.value;
+	}
+	else{
+		form2.searchText.value = empty;
+	}
+
+	//validFrom
+	var regTimeBegin = form1.regTimeBegin.value;
+	if(regTimeBegin != ""){
+		//var ds = regTimeBegin.split(".");
+		// var d = new Date(parseInt(ds[2]),(parseInt(ds[1] - 1)),parseInt(ds[0]));
+		 form2.regTimeBegin.value = regTimeBegin;
+	}else{
+		form2.regTimeBegin.value = empty;
+	}
+
+	//validTo
+	var regTimeEnd = form1.regTimeEnd.value;
+	if(regTimeEnd != ""){
+		//var ds = regTimeEnd.split(".");
+		//var d = new Date(parseInt(ds[2]),(parseInt(ds[1] - 1)),parseInt(ds[0]));
+		form2.regTimeEnd.value = regTimeEnd;
+	}
+	else{
+		form2.regTimeEnd.value = empty;
+	}
+
+	//dataFrom
+	var timeBegin = form1.timeBegin.value;
+	if(timeBegin != ""){
+		//var ds = timeBegin.split(".");
+		 //var d = new Date(parseInt(ds[2]),(parseInt(ds[1] - 1)),parseInt(ds[0]));
+		 form2.timeBegin.value = timeBegin;
+	}else{
+		form2.timeBegin.value = empty;
+	}
+	//dataTo
+	var timeEnd = form1.timeEnd.value;
+	if(timeEnd != ""){
+		//var ds = timeEnd.split(".");
+		//var d = new Date(parseInt(ds[2]),(parseInt(ds[1] - 1)),parseInt(ds[0]));
+		form2.timeEnd.value = timeEnd;
+	}
+	else{
+		form2.timeEnd.value = empty;
+	}
+
+	//searchTypeBbox
+	var searchTypeBbox = empty;
+	
+	for (var i=0; i < form1.searchTypeBbox.length; i++){
+		
+  		if (form1.searchTypeBbox[i].checked){
+			
+     			searchTypeBbox = form1.searchTypeBbox[i].value;
+			
+      		}
+  	}
+	form2.searchTypeBbox.value = searchTypeBbox;	
+	
+	//searchBbox
+	getMapExtent(form1.searchBbox);
+	
+	//sortBy
+	var orderBy = empty;
+	
+	for (var i=0; i < form1.orderBy.length; i++){
+		
+  		if (form1.orderBy[i].checked){
+			
+     			orderBy = form1.orderBy[i].value;
+			
+      		}
+  	}
+	form2.orderBy.value = orderBy;
+
+	//searchResources
+	var searchResources = [];
+	var cnt=0;
+	var inputElements = document.getElementsByTagName("input");
+	for(var i=0; i<inputElements.length; i++){
+    		if(inputElements[i].name.indexOf("checkResources") != -1){
+    			if(inputElements[i].checked==true){
+    				searchResources[cnt] = inputElements[i].value;
+    				cnt++;	
+    			}		
+    		}
+   	}
+   	if(cnt>0){
+		form2.searchResources.value = searchResources.join(",");
+	}
+	else{
+		form2.searchResources.value = empty;
+	}	
+
+	if(send == true){
+		form2.submit();
+	}
+	return false;
+}
+

Deleted: branches/mapbender/http/plugins/mb_extendedSearch_server.php
===================================================================
--- trunk/mapbender/http/plugins/mb_extendedSearch_server.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/http/plugins/mb_extendedSearch_server.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,244 +0,0 @@
-<?php 
-session_start();
-require_once(dirname(__FILE__)."/../../../core/globalSettings.php");
-include_once(dirname(__FILE__)."/../../extensions/JSON.php");
-
-//db connection
-$con = db_connect($DBSERVER,$OWNER,$PW) or die ("Error while connecting database $dbname");
-db_select_db(DB,$con);
-
-//Define JSON object
-$json = new Services_JSON();
-$obj = $json->decode(stripslashes($_REQUEST['obj']));
-
-//get language parameter out of mapbender session if it is set else set default language to de_DE
-if (isset($_SESSION['mb_lang']) and $_SESSION['mb_lang']!='') {
-	$e = new mb_exception("mb_extentedSearch_server.php: language in session: ".$_SESSION['mb_lang']);
-	$language = $_SESSION["mb_lang"];
-} else {
-	$language = "de_DE";//use locale for compatibility with later mapbender version
-}
-
-//extract language code out of locale
-
-$langCode = explode("_", $language);
-
-$langCode = $langCode[0];
-
-#$langCode="de";
-
-$e = new mb_exception("mb_extendendSearch_server.php: language: ".$langCode);
-
-//workflow:
-switch($obj->action){
-	case 'getList':
-		$obj->entries = getList($langCode);
-		sendOutput($obj);
-	break;
-	default:
-		sendOutput("no action specified...");
-}
-
-/**
- * Get all departments (user_ids and department names), categories
- * 
- * @return mixed[] the user_ids and names of the departments, category names and ids 
- */
-  
-function getList($langCode){
-	global $con;
-	$entries = array();
-	$entries['translations'] = array();
-	switch ($langCode) {
-		case 'de':
-			$entries['translations']['extendedSearchTitle'] = 'Erweiterte Suche';
-			$entries['translations']['extendedSearchTitleBc'] = 'Erweiterte Suche';
-			$entries['translations']['legendSearchTextTitle'] = 'Suchbegriff(e)';
-			$entries['translations']['legendSpatialFilterTitle'] = 'Räumliche Eingrenzung';
-			$entries['translations']['labelSpatialFilter'] = 'räumliche Eingrenzung aktivieren';
-			$entries['translations']['labelSpatialFilterType'] = 'wie?';
-			$entries['translations']['searchTypeBboxIntersects'] = 'angeschnitten';
-			$entries['translations']['searchTypeBboxOutside'] = 'ganz außerhalb';
-			$entries['translations']['searchTypeBboxInside'] = 'innerhalb';
-			$entries['translations']['orderByRelevance'] = 'Relevanz';
-			$entries['translations']['orderByTitle'] = 'Titel';
-			$entries['translations']['orderById'] = 'ID';
-			$entries['translations']['orderByDate'] = 'Datum';
-			$entries['translations']['legendOrderBy'] = 'Sortieren nach:';
-			$entries['translations']['legendDepartment'] = 'Anbieter:';
-			$entries['translations']['legendInspireThemes'] = 'Inspire Themen';
-			$entries['translations']['legendIsoCategories'] = 'ISO19115 Themen';
-			$entries['translations']['legendCustomCategories'] = 'Andere Themen';
-			$entries['translations']['legendDateOfPublication'] = 'Veröffentlichungsdatum';
-			$entries['translations']['legendDateOfLastRevision'] = 'Datenaktualität';
-			$entries['translations']['labelDateOfPublicationStart'] = 'Datum von:';
-			$entries['translations']['labelDateOfPublicationEnd'] = 'Datum bis:';
-			$entries['translations']['labelDateOfLastRevisionStart'] = 'Datum von:';
-			$entries['translations']['labelDateOfLastRevisionEnd'] = 'Datum bis:';
-			$entries['translations']['legendSearchResources'] = 'Ressourcentypen';
-			$entries['translations']['labelIntersects'] = 'angeschnitten';
-			$entries['translations']['labelOutside'] = 'außerhalb';
-			$entries['translations']['labelInside'] = 'komplett innerhalb';
-			$entries['translations']['labelOrderByRank'] = 'Nachfrage';
-			$entries['translations']['labelOrderByTitle'] = 'Titel';
-			$entries['translations']['labelOrderById'] = 'Identifikation';
-			$entries['translations']['labelOrderByDate'] = 'Datum';
-			$entries['translations']['labelCheckResourcesWms'] = 'Interaktive Karten';
-			$entries['translations']['labelCheckResourcesWfs'] = 'Such/Download/Erfassungsmodule';
-			$entries['translations']['labelCheckResourcesWmc'] = 'Kartensammlungen';
-			$entries['translations']['labelCheckResourcesGeorss'] = 'GeoRSS Newsfeeds';
-			$entries['translations']['checkResourcesWms'] = 'Kartendienste';
-			$entries['translations']['checkResourcesWfs'] = 'Such- und Downloaddienste';
-			$entries['translations']['checkResourcesWmc'] = 'Kartenzusammenstellungen';
-			$entries['translations']['checkResourcesGeorss'] = 'GeoRSS Feeds';
-			$entries['translations']['search'] = 'Suche starten';
-			$entries['translations']['deleteSelection1'] = 'Auswahl löschen';
-			$entries['translations']['deleteSelection2'] = 'Auswahl löschen';
-			$entries['translations']['deleteSelection3'] = 'Auswahl löschen';
-			$entries['translations']['deleteSelection4'] = 'Auswahl löschen';
-			$entries['translations']['classificationsLegend'] = 'Klassifikationen';
-			$entries['translations']['legendActuality'] = 'Zeitliche Einschränkung';
-			$entries['translations']['helpInspireThemes'] = 'Hilfe zu den Inspire Themenbereichen';
-			$entries['translations']['helpSearchText'] = 'Hilfe zur Textsuche. Bitte geben Sie hier kommasepariert eine Liste von Suchbegriffen ein. Die Begriffe werden für eine Volltextsuche über Titel, Beschreibung und Keywords verwendet. Die Verknüpfung der Suchbegriffe geschieht über ein UND. Je mehr Begriffe eingegeben werden, desto weniger Treffer werden gefunden. <a href="http://www.geoportal.rlp.de">testlink</a>';
-			$entries['translations']['helpIsoCategories'] = 'Hilfe zu den ISO Kategorien';
-			$entries['translations']['helpCustomCategories'] = 'Hilfe zu eigenen Themenkategorien';
-			$entries['translations']['helpOrderBy'] = 'Hilfe zu Sortierung der Liste';
-			$entries['translations']['helpSpatialFilter'] = 'Hilfe zum räumlichen Filter';
-			$entries['translations']['helpProvider'] = 'Hilfe zu den Providern';
-			$entries['translations']['helpDateOfPublication'] = 'Hilfe zum Veröffentlichungsdatum';
-			$entries['translations']['helpDateOfLastRevision'] = 'Hilfe zum Datum der letzten Änderung';
-			$entries['translations']['helpSearchResources'] = 'Hilfe zu den Resourcentypen';
-
-			$exceptionGroupTitle = "Es wurde noch kein Titel für die Gruppe eingestellt!";
-			break;
-		case 'en':
-			$entries['translations']['extendedSearchTitle'] = 'Extended Search';
-			$entries['translations']['extendedSearchTitleBc'] = 'Extended Search';
-			$entries['translations']['legendSearchTextTitle'] = 'Searchterm(s)';
-			$entries['translations']['legendSpatialFilterTitle'] = 'Spatial Filter';
-			$entries['translations']['labelSpatialFilter'] = 'activate spatial filter';
-			$entries['translations']['labelSpatialFilterType'] = 'how?';
-			$entries['translations']['searchTypeBboxIntersects'] = 'intersects';
-			$entries['translations']['searchTypeBboxOutside'] = 'outside';
-			$entries['translations']['searchTypeBboxInside'] = 'fully inside';
-			$entries['translations']['orderByRelevance'] = 'relevance';
-			$entries['translations']['orderByTitle'] = 'title';
-			$entries['translations']['orderById'] = 'identification';
-			$entries['translations']['orderByDate'] = 'date';
-			$entries['translations']['legendOrderBy'] = 'Sort by:';
-			$entries['translations']['legendDepartment'] = 'Provider:';
-			$entries['translations']['legendInspireThemes'] = 'Inspire themes';
-			$entries['translations']['legendIsoCategories'] = 'ISO19115 themes';
-			$entries['translations']['legendCustomCategories'] = 'Other themes';
-			$entries['translations']['legendDateOfPublication'] = 'Date of publication/last revision';
-			$entries['translations']['legendDateOfLastRevision'] = 'Data Actuality';
-			$entries['translations']['labelDateOfPublicationStart'] = 'Date from:';
-			$entries['translations']['labelDateOfPublicationEnd'] = 'Date to:';
-			$entries['translations']['labelDateOfLastRevisionStart'] = 'Date from:';
-			$entries['translations']['labelDateOfLastRevisionEnd'] = 'Date to:';
-			$entries['translations']['legendSearchResources'] = 'Types of resources';
-			$entries['translations']['labelIntersects'] = 'intersects';
-			$entries['translations']['labelOutside'] = 'outside';
-			$entries['translations']['labelInside'] = 'completely inside';
-			$entries['translations']['labelOrderByRank'] = 'relevance';
-			$entries['translations']['labelOrderByTitle'] = 'title';
-			$entries['translations']['labelOrderById'] = 'identification';
-			$entries['translations']['labelOrderByDate'] = 'date';
-			$entries['translations']['labelCheckResourcesWms'] = 'Viewing Services';
-			$entries['translations']['labelCheckResourcesWfs'] = 'Search/Download/Digitize modules';
-			$entries['translations']['labelCheckResourcesWmc'] = 'Map Collections';
-			$entries['translations']['labelCheckResourcesGeorss'] = 'GeoRSS Newsfeeds';
-			$entries['translations']['search'] = 'Start Search';
-			$entries['translations']['deleteSelection1'] = 'Delete current selection';
-			$entries['translations']['deleteSelection2'] = 'Delete current selection';
-			$entries['translations']['deleteSelection3'] = 'Delete current selection';
-			$entries['translations']['deleteSelection4'] = 'Delete current selection';
-			$entries['translations']['classificationsLegend'] = 'Classifications';
-			$entries['translations']['legendActuality'] = 'Temporal Filter';
-			$entries['translations']['helpInspireThemes'] = 'Help for the Inspire Themes';
-			$entries['translations']['helpSearchText'] = 'Help for Fulltextsearch';
-			$entries['translations']['helpIsoCategories'] = 'Help for ISO19115 classification';
-			$entries['translations']['helpCustomCategories'] = 'Help for own classification';
-			$entries['translations']['helpOrderBy'] = 'Help for ordering filter';
-			$entries['translations']['helpSpatialFilter'] = 'Help for spatial Filter';
-			$entries['translations']['helpProvider'] = 'Help for registrating departments';
-			$entries['translations']['helpDateOfPublication'] = 'Help for date of publication';
-			$entries['translations']['helpDateOfLastRevision'] = 'Help for date of last revision';
-			$entries['translations']['helpSearchResources'] = 'Help for types of resources';
-
-			$exceptionGroupTitle = "The title for this group have not been defined till now!";
-
-			break;
-		case 'fr':
-			break;
-		case 'es':
-
-		
-			break;
-		default:
-	}
-	$entries['user_department'] = array();
-	$entries['group_name'] = array();
-	$entries['group_title'] = array();
-
-	$sql= "SELECT mb_group_id, mb_group_name, mb_group_title from registrating_groups LEFT OUTER JOIN mb_group ON (mb_group_id=fkey_mb_group_id)  GROUP BY mb_group_id, mb_group_name, mb_group_title ORDER BY mb_group_name";
-	$res = pg_query($sql);
-	while($row = db_fetch_array($res)){
-		array_push($entries['user_department'], $row['mb_group_id']);
-		array_push($entries['group_name'], $row['mb_group_name']);
-		if (isset($row['mb_group_title']) and $row['mb_group_title'] != ''){
-			array_push($entries['group_title'], $row['mb_group_title']);
-		} else {
-			array_push($entries['group_title'], $exceptionGroupTitle);
-		}
-	}
-	$maxStrLength = 200;
-	//get list of iso categories
-	$entries['iso_cat_id'] = array();
-	$entries['iso_cat_name'] = array();
-	$entries['iso_cat_title'] = array();
-	$sql_cat= "SELECT * FROM md_topic_category order by md_topic_category_code_".$langCode;
-	$res_cat = pg_query($sql_cat);
-	while($row_cat = db_fetch_array($res_cat)){
-		array_push($entries['iso_cat_id'], $row_cat['md_topic_category_id']);
-		array_push($entries['iso_cat_name'], substr($row_cat["md_topic_category_code_".$langCode], 0,$maxStrLength));
-		array_push($entries['iso_cat_title'], $row_cat["md_topic_category_code_".$langCode]);
-	}
-	//get list of inspire themes
-	$entries['inspire_cat_id'] = array();
-	$entries['inspire_cat_name'] = array();
-	$entries['inspire_cat_title'] = array();
-	$sql_cat= "SELECT * FROM inspire_category order by inspire_category_code_".$langCode;
-	$res_cat = pg_query($sql_cat);
-	while($row_cat = db_fetch_array($res_cat)){
-		array_push($entries['inspire_cat_id'], $row_cat['inspire_category_id']);
-		array_push($entries['inspire_cat_name'], substr($row_cat["inspire_category_code_".$langCode], 0,$maxStrLength));
-		array_push($entries['inspire_cat_title'], $row_cat["inspire_category_key"]." ".$row_cat["inspire_category_code_".$langCode]);
-	}
-	//get list of custom categories
-	$entries['custom_cat_id'] = array();
-	$entries['custom_cat_name'] = array();
-	$entries['custom_cat_title'] = array();
-	$sql_cat= "SELECT * FROM custom_category order by custom_category_code_".$langCode;
-	$res_cat = pg_query($sql_cat);
-	while($row_cat = db_fetch_array($res_cat)){
-		array_push($entries['custom_cat_id'], $row_cat['custom_category_id']);
-		array_push($entries['custom_cat_name'], substr($row_cat["custom_category_code_".$langCode], 0,$maxStrLength));
-		array_push($entries['custom_cat_title'], $row_cat["custom_category_code_".$langCode]);
-	}
-	return $entries;
-}
-
-/**
- * sends output of function back to client
- * 
- * @param mixed[] the output to send
- * @return 
- */
-function sendOutput($out){
-	global $json;
-	$output = $json->encode($out);
-	header("Content-Type: text/x-json");
-	echo $output;
-}
-?>

Copied: branches/mapbender/http/plugins/mb_extendedSearch_server.php (from rev 6953, trunk/mapbender/http/plugins/mb_extendedSearch_server.php)
===================================================================
--- branches/mapbender/http/plugins/mb_extendedSearch_server.php	                        (rev 0)
+++ branches/mapbender/http/plugins/mb_extendedSearch_server.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -0,0 +1,244 @@
+<?php 
+session_start();
+require_once(dirname(__FILE__)."/../../core/globalSettings.php");
+include_once(dirname(__FILE__)."/../extensions/JSON.php");
+
+//db connection
+$con = db_connect($DBSERVER,$OWNER,$PW) or die ("Error while connecting database $dbname");
+db_select_db(DB,$con);
+
+//Define JSON object
+$json = new Services_JSON();
+$obj = $json->decode(stripslashes($_REQUEST['obj']));
+
+//get language parameter out of mapbender session if it is set else set default language to de_DE
+if (isset($_SESSION['mb_lang']) and $_SESSION['mb_lang']!='') {
+	$e = new mb_exception("mb_extentedSearch_server.php: language in session: ".$_SESSION['mb_lang']);
+	$language = $_SESSION["mb_lang"];
+} else {
+	$language = "de_DE";//use locale for compatibility with later mapbender version
+}
+
+//extract language code out of locale
+
+$langCode = explode("_", $language);
+
+$langCode = $langCode[0];
+
+#$langCode="de";
+
+$e = new mb_exception("mb_extendendSearch_server.php: language: ".$langCode);
+
+//workflow:
+switch($obj->action){
+	case 'getList':
+		$obj->entries = getList($langCode);
+		sendOutput($obj);
+	break;
+	default:
+		sendOutput("no action specified...");
+}
+
+/**
+ * Get all departments (user_ids and department names), categories
+ * 
+ * @return mixed[] the user_ids and names of the departments, category names and ids 
+ */
+  
+function getList($langCode){
+	global $con;
+	$entries = array();
+	$entries['translations'] = array();
+	switch ($langCode) {
+		case 'de':
+			$entries['translations']['extendedSearchTitle'] = 'Erweiterte Suche';
+			$entries['translations']['extendedSearchTitleBc'] = 'Erweiterte Suche';
+			$entries['translations']['legendSearchTextTitle'] = 'Suchbegriff(e)';
+			$entries['translations']['legendSpatialFilterTitle'] = 'Räumliche Eingrenzung';
+			$entries['translations']['labelSpatialFilter'] = 'räumliche Eingrenzung aktivieren';
+			$entries['translations']['labelSpatialFilterType'] = 'wie?';
+			$entries['translations']['searchTypeBboxIntersects'] = 'angeschnitten';
+			$entries['translations']['searchTypeBboxOutside'] = 'ganz außerhalb';
+			$entries['translations']['searchTypeBboxInside'] = 'innerhalb';
+			$entries['translations']['orderByRelevance'] = 'Relevanz';
+			$entries['translations']['orderByTitle'] = 'Titel';
+			$entries['translations']['orderById'] = 'ID';
+			$entries['translations']['orderByDate'] = 'Datum';
+			$entries['translations']['legendOrderBy'] = 'Sortieren nach:';
+			$entries['translations']['legendDepartment'] = 'Anbieter:';
+			$entries['translations']['legendInspireThemes'] = 'Inspire Themen';
+			$entries['translations']['legendIsoCategories'] = 'ISO19115 Themen';
+			$entries['translations']['legendCustomCategories'] = 'Andere Themen';
+			$entries['translations']['legendDateOfPublication'] = 'Veröffentlichungsdatum';
+			$entries['translations']['legendDateOfLastRevision'] = 'Datenaktualität';
+			$entries['translations']['labelDateOfPublicationStart'] = 'Datum von:';
+			$entries['translations']['labelDateOfPublicationEnd'] = 'Datum bis:';
+			$entries['translations']['labelDateOfLastRevisionStart'] = 'Datum von:';
+			$entries['translations']['labelDateOfLastRevisionEnd'] = 'Datum bis:';
+			$entries['translations']['legendSearchResources'] = 'Ressourcentypen';
+			$entries['translations']['labelIntersects'] = 'angeschnitten';
+			$entries['translations']['labelOutside'] = 'außerhalb';
+			$entries['translations']['labelInside'] = 'komplett innerhalb';
+			$entries['translations']['labelOrderByRank'] = 'Nachfrage';
+			$entries['translations']['labelOrderByTitle'] = 'Titel';
+			$entries['translations']['labelOrderById'] = 'Identifikation';
+			$entries['translations']['labelOrderByDate'] = 'Datum';
+			$entries['translations']['labelCheckResourcesWms'] = 'Interaktive Karten';
+			$entries['translations']['labelCheckResourcesWfs'] = 'Such/Download/Erfassungsmodule';
+			$entries['translations']['labelCheckResourcesWmc'] = 'Kartensammlungen';
+			$entries['translations']['labelCheckResourcesGeorss'] = 'GeoRSS Newsfeeds';
+			$entries['translations']['checkResourcesWms'] = 'Kartendienste';
+			$entries['translations']['checkResourcesWfs'] = 'Such- und Downloaddienste';
+			$entries['translations']['checkResourcesWmc'] = 'Kartenzusammenstellungen';
+			$entries['translations']['checkResourcesGeorss'] = 'GeoRSS Feeds';
+			$entries['translations']['search'] = 'Suche starten';
+			$entries['translations']['deleteSelection1'] = 'Auswahl löschen';
+			$entries['translations']['deleteSelection2'] = 'Auswahl löschen';
+			$entries['translations']['deleteSelection3'] = 'Auswahl löschen';
+			$entries['translations']['deleteSelection4'] = 'Auswahl löschen';
+			$entries['translations']['classificationsLegend'] = 'Klassifikationen';
+			$entries['translations']['legendActuality'] = 'Zeitliche Einschränkung';
+			$entries['translations']['helpInspireThemes'] = 'Hilfe zu den Inspire Themenbereichen';
+			$entries['translations']['helpSearchText'] = 'Hilfe zur Textsuche. Bitte geben Sie hier kommasepariert eine Liste von Suchbegriffen ein. Die Begriffe werden für eine Volltextsuche über Titel, Beschreibung und Keywords verwendet. Die Verknüpfung der Suchbegriffe geschieht über ein UND. Je mehr Begriffe eingegeben werden, desto weniger Treffer werden gefunden. <a href="http://www.geoportal.rlp.de">testlink</a>';
+			$entries['translations']['helpIsoCategories'] = 'Hilfe zu den ISO Kategorien';
+			$entries['translations']['helpCustomCategories'] = 'Hilfe zu eigenen Themenkategorien';
+			$entries['translations']['helpOrderBy'] = 'Hilfe zu Sortierung der Liste';
+			$entries['translations']['helpSpatialFilter'] = 'Hilfe zum räumlichen Filter';
+			$entries['translations']['helpProvider'] = 'Hilfe zu den Providern';
+			$entries['translations']['helpDateOfPublication'] = 'Hilfe zum Veröffentlichungsdatum';
+			$entries['translations']['helpDateOfLastRevision'] = 'Hilfe zum Datum der letzten Änderung';
+			$entries['translations']['helpSearchResources'] = 'Hilfe zu den Resourcentypen';
+
+			$exceptionGroupTitle = "Es wurde noch kein Titel für die Gruppe eingestellt!";
+			break;
+		case 'en':
+			$entries['translations']['extendedSearchTitle'] = 'Extended Search';
+			$entries['translations']['extendedSearchTitleBc'] = 'Extended Search';
+			$entries['translations']['legendSearchTextTitle'] = 'Searchterm(s)';
+			$entries['translations']['legendSpatialFilterTitle'] = 'Spatial Filter';
+			$entries['translations']['labelSpatialFilter'] = 'activate spatial filter';
+			$entries['translations']['labelSpatialFilterType'] = 'how?';
+			$entries['translations']['searchTypeBboxIntersects'] = 'intersects';
+			$entries['translations']['searchTypeBboxOutside'] = 'outside';
+			$entries['translations']['searchTypeBboxInside'] = 'fully inside';
+			$entries['translations']['orderByRelevance'] = 'relevance';
+			$entries['translations']['orderByTitle'] = 'title';
+			$entries['translations']['orderById'] = 'identification';
+			$entries['translations']['orderByDate'] = 'date';
+			$entries['translations']['legendOrderBy'] = 'Sort by:';
+			$entries['translations']['legendDepartment'] = 'Provider:';
+			$entries['translations']['legendInspireThemes'] = 'Inspire themes';
+			$entries['translations']['legendIsoCategories'] = 'ISO19115 themes';
+			$entries['translations']['legendCustomCategories'] = 'Other themes';
+			$entries['translations']['legendDateOfPublication'] = 'Date of publication/last revision';
+			$entries['translations']['legendDateOfLastRevision'] = 'Data Actuality';
+			$entries['translations']['labelDateOfPublicationStart'] = 'Date from:';
+			$entries['translations']['labelDateOfPublicationEnd'] = 'Date to:';
+			$entries['translations']['labelDateOfLastRevisionStart'] = 'Date from:';
+			$entries['translations']['labelDateOfLastRevisionEnd'] = 'Date to:';
+			$entries['translations']['legendSearchResources'] = 'Types of resources';
+			$entries['translations']['labelIntersects'] = 'intersects';
+			$entries['translations']['labelOutside'] = 'outside';
+			$entries['translations']['labelInside'] = 'completely inside';
+			$entries['translations']['labelOrderByRank'] = 'relevance';
+			$entries['translations']['labelOrderByTitle'] = 'title';
+			$entries['translations']['labelOrderById'] = 'identification';
+			$entries['translations']['labelOrderByDate'] = 'date';
+			$entries['translations']['labelCheckResourcesWms'] = 'Viewing Services';
+			$entries['translations']['labelCheckResourcesWfs'] = 'Search/Download/Digitize modules';
+			$entries['translations']['labelCheckResourcesWmc'] = 'Map Collections';
+			$entries['translations']['labelCheckResourcesGeorss'] = 'GeoRSS Newsfeeds';
+			$entries['translations']['search'] = 'Start Search';
+			$entries['translations']['deleteSelection1'] = 'Delete current selection';
+			$entries['translations']['deleteSelection2'] = 'Delete current selection';
+			$entries['translations']['deleteSelection3'] = 'Delete current selection';
+			$entries['translations']['deleteSelection4'] = 'Delete current selection';
+			$entries['translations']['classificationsLegend'] = 'Classifications';
+			$entries['translations']['legendActuality'] = 'Temporal Filter';
+			$entries['translations']['helpInspireThemes'] = 'Help for the Inspire Themes';
+			$entries['translations']['helpSearchText'] = 'Help for Fulltextsearch';
+			$entries['translations']['helpIsoCategories'] = 'Help for ISO19115 classification';
+			$entries['translations']['helpCustomCategories'] = 'Help for own classification';
+			$entries['translations']['helpOrderBy'] = 'Help for ordering filter';
+			$entries['translations']['helpSpatialFilter'] = 'Help for spatial Filter';
+			$entries['translations']['helpProvider'] = 'Help for registrating departments';
+			$entries['translations']['helpDateOfPublication'] = 'Help for date of publication';
+			$entries['translations']['helpDateOfLastRevision'] = 'Help for date of last revision';
+			$entries['translations']['helpSearchResources'] = 'Help for types of resources';
+
+			$exceptionGroupTitle = "The title for this group have not been defined till now!";
+
+			break;
+		case 'fr':
+			break;
+		case 'es':
+
+		
+			break;
+		default:
+	}
+	$entries['user_department'] = array();
+	$entries['group_name'] = array();
+	$entries['group_title'] = array();
+
+	$sql= "SELECT mb_group_id, mb_group_name, mb_group_title from registrating_groups LEFT OUTER JOIN mb_group ON (mb_group_id=fkey_mb_group_id)  GROUP BY mb_group_id, mb_group_name, mb_group_title ORDER BY mb_group_name";
+	$res = pg_query($sql);
+	while($row = db_fetch_array($res)){
+		array_push($entries['user_department'], $row['mb_group_id']);
+		array_push($entries['group_name'], $row['mb_group_name']);
+		if (isset($row['mb_group_title']) and $row['mb_group_title'] != ''){
+			array_push($entries['group_title'], $row['mb_group_title']);
+		} else {
+			array_push($entries['group_title'], $exceptionGroupTitle);
+		}
+	}
+	$maxStrLength = 200;
+	//get list of iso categories
+	$entries['iso_cat_id'] = array();
+	$entries['iso_cat_name'] = array();
+	$entries['iso_cat_title'] = array();
+	$sql_cat= "SELECT * FROM md_topic_category order by md_topic_category_code_".$langCode;
+	$res_cat = pg_query($sql_cat);
+	while($row_cat = db_fetch_array($res_cat)){
+		array_push($entries['iso_cat_id'], $row_cat['md_topic_category_id']);
+		array_push($entries['iso_cat_name'], substr($row_cat["md_topic_category_code_".$langCode], 0,$maxStrLength));
+		array_push($entries['iso_cat_title'], $row_cat["md_topic_category_code_".$langCode]);
+	}
+	//get list of inspire themes
+	$entries['inspire_cat_id'] = array();
+	$entries['inspire_cat_name'] = array();
+	$entries['inspire_cat_title'] = array();
+	$sql_cat= "SELECT * FROM inspire_category order by inspire_category_code_".$langCode;
+	$res_cat = pg_query($sql_cat);
+	while($row_cat = db_fetch_array($res_cat)){
+		array_push($entries['inspire_cat_id'], $row_cat['inspire_category_id']);
+		array_push($entries['inspire_cat_name'], substr($row_cat["inspire_category_code_".$langCode], 0,$maxStrLength));
+		array_push($entries['inspire_cat_title'], $row_cat["inspire_category_key"]." ".$row_cat["inspire_category_code_".$langCode]);
+	}
+	//get list of custom categories
+	$entries['custom_cat_id'] = array();
+	$entries['custom_cat_name'] = array();
+	$entries['custom_cat_title'] = array();
+	$sql_cat= "SELECT * FROM custom_category order by custom_category_code_".$langCode;
+	$res_cat = pg_query($sql_cat);
+	while($row_cat = db_fetch_array($res_cat)){
+		array_push($entries['custom_cat_id'], $row_cat['custom_category_id']);
+		array_push($entries['custom_cat_name'], substr($row_cat["custom_category_code_".$langCode], 0,$maxStrLength));
+		array_push($entries['custom_cat_title'], $row_cat["custom_category_code_".$langCode]);
+	}
+	return $entries;
+}
+
+/**
+ * sends output of function back to client
+ * 
+ * @param mixed[] the output to send
+ * @return 
+ */
+function sendOutput($out){
+	global $json;
+	$output = $json->encode($out);
+	header("Content-Type: text/x-json");
+	echo $output;
+}
+?>

Deleted: branches/mapbender/http/plugins/mb_metadata_server.php
===================================================================
--- trunk/mapbender/http/plugins/mb_metadata_server.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/http/plugins/mb_metadata_server.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,427 +0,0 @@
-<?php
-require_once dirname(__FILE__) . "/../../core/globalSettings.php";
-require_once dirname(__FILE__) . "/../classes/class_user.php";
-require_once dirname(__FILE__) . "/../classes/class_wms.php";
-
-$ajaxResponse = new AjaxResponse($_POST);
-
-function abort ($message) {
-	global $ajaxResponse;
-	$ajaxResponse->setSuccess(false);
-	$ajaxResponse->setMessage($message);
-	$ajaxResponse->send();
-	die;
-};
-
-function getWms ($wmsId = null) {
-	$user = new User(Mapbender::session()->get("mb_user_id"));
-	$wmsIdArray = $user->getOwnedWms();
-	if (!is_array($wmsIdArray) || count($wmsIdArray) === 0) {
-		abort(_mb("No metadata sets available."));
-	}
-	if (!is_null($wmsId) && !in_array($wmsId, $wmsIdArray)) {
-		abort(_mb("You are not allowed to access this WMS."));
-	}
-	return $wmsIdArray;
-}
-
-function getLayer ($layerId = null) {
-	$user = new User(Mapbender::session()->get("mb_user_id"));
-	$wmsIdArray = $user->getOwnedWms();
-	if (!is_array($wmsIdArray) || count($wmsIdArray) === 0) {
-		abort(_mb("No metadata sets available."));
-	}
-	$wmsId = wms::getWmsIdByLayerId($layerId);
-	if (is_null($wmsId) || !in_array($wmsId, $wmsIdArray)) {
-		abort(_mb("You are not allowed to access WMS " . $wmsId));
-	}
-	return;
-}
-
-switch ($ajaxResponse->getMethod()) {
-	case "getWms" :
-		$wmsIdArray = getWms();
-		
-		$wmsList = implode(",", $wmsIdArray);
-		$sql = <<<SQL
-	
-SELECT wms.wms_id, wms.wms_title, wms.wms_timestamp, wms_version, m.status_comment
-FROM wms LEFT JOIN mb_monitor AS m
-ON wms.wms_id = m.fkey_wms_id 
-WHERE wms_id IN ($wmsList);
-
-SQL;
-		$res = db_query($sql);
-		$resultObj = array(
-			"header" => array(
-				"WMS ID",
-				"Titel",
-				"Timestamp",
-				"Version",
-				"Status"
-			), 
-			"data" => array()
-		);
-
-		while ($row = db_fetch_row($res)) {
-			// convert NULL to '', NULL values cause datatables to crash
-			$walk = array_walk($row, create_function('&$s', '$s=strval($s);'));
-			$resultObj["data"][]= $row;
-		}
-		$ajaxResponse->setResult($resultObj);
-		$ajaxResponse->setSuccess(true);
-		break;
-
-	case "getWmsMetadata" :
-		$wmsId = $ajaxResponse->getParameter("id");
-		getWms($wmsId);
-
-		$wms = new wms();
-		$wms->createObjFromDBNoGui($wmsId);
-
-		$fields = array(
-			"wms_id", 
-			"wms_abstract", 
-			"wms_title", 
-			"fees", 
-			"accessconstraints", 
-			"contactperson", 
-			"contactposition", 
-			"contactvoicetelephone", 
-			"contactfacsimiletelephone", 
-			"contactorganization", 
-			"address", 
-			"city", 
-			"stateorprovince", 
-			"postcode", 
-			"country", 
-			"contactelectronicmailaddress",
-			"wms_timestamp", 
-			"wms_timestamp_create"
-		);
-
-		$resultObj = array();
-		foreach ($fields as $field) {
-			if ($field == "wms_timestamp" || $field == "wms_timestamp_create") {
-				if ($wms->$field != "") {
-					$resultObj[$field] = date('d.m.Y', $wms->$field);
-					
-				}
-			}
-			else {
-				$resultObj[$field] = $wms->$field;	
-			}
-		}
-		
-		// layer searchable
-		$resultObj["layer_searchable"] = array();
-		foreach ($wms->objLayer as $layer) {
-			if (intval($layer->layer_searchable) === 1) {
-				$resultObj["layer_searchable"][] = intval($layer->layer_uid);
-			}
-		}
-		
-		$keywordSql = <<<SQL
-	
-SELECT DISTINCT keyword FROM keyword, layer_keyword 
-WHERE keyword_id = fkey_keyword_id AND fkey_layer_id IN (
-	SELECT layer_id from layer, wms 
-	WHERE fkey_wms_id = wms_id AND wms_id = $wmsId
-) ORDER BY keyword
-
-SQL;
-
-		$keywordRes = db_query($keywordSql);
-		$keywords = array();
-		while ($keywordRow = db_fetch_assoc($keywordRes)) {
-			$keywords[]= $keywordRow["keyword"];
-		}
-
-		$resultObj["wms_keywords"] = implode(", ", $keywords);
-
-		$termsofuseSql = <<<SQL
-SELECT fkey_termsofuse_id FROM wms_termsofuse WHERE fkey_wms_id = $wmsId
-SQL;
-
-		$termsofuseRes = db_query($termsofuseSql);
-		if ($termsofuseRes) {
-			$termsofuseRow = db_fetch_assoc($termsofuseRes);
-			$resultObj["wms_termsofuse"] = $termsofuseRow["fkey_termsofuse_id"];
-		}
-		else {
-			$resultObj["wms_termsofuse"] = null;
-		}
-		
-
-		$ajaxResponse->setResult($resultObj);
-		$ajaxResponse->setSuccess(true);
-
-		break;
-	
-	case "getLayerMetadata" :
-		$layerId = $ajaxResponse->getParameter("id");
-		getLayer($layerId);
-
-		$sql = <<<SQL
-	
-SELECT layer_id, layer_name, layer_title, layer_abstract, layer_searchable 
-FROM layer WHERE layer_id = $layerId;
-
-SQL;
-		$res = db_query($sql);
-
-		$resultObj = array();
-		while ($row = db_fetch_assoc($res)) {
-			foreach ($row as $key => $value) {
-				$resultObj[$key] = $value;
-			}
-		}
-
-		$sql = <<<SQL
-SELECT fkey_md_topic_category_id 
-FROM layer_md_topic_category 
-WHERE fkey_layer_id = $layerId
-SQL;
-		$res = db_query($sql);
-		while ($row = db_fetch_assoc($res)) {
-			$resultObj["layer_md_topic_category_id"][]= $row["fkey_md_topic_category_id"];
-		}
-
-		$sql = <<<SQL
-SELECT fkey_inspire_category_id 
-FROM layer_inspire_category 
-WHERE fkey_layer_id = $layerId
-SQL;
-		$res = db_query($sql);
-		while ($row = db_fetch_assoc($res)) {
-			$resultObj["layer_inspire_category_id"][]= $row["fkey_inspire_category_id"];
-		}
-
-		$sql = <<<SQL
-SELECT fkey_custom_category_id 
-FROM layer_custom_category 
-WHERE fkey_layer_id = $layerId
-SQL;
-		$res = db_query($sql);
-		while ($row = db_fetch_assoc($res)) {
-			$resultObj["layer_custom_category_id"][]= $row["fkey_custom_category_id"];
-		}
-
-		$sql = <<<SQL
-SELECT keyword FROM keyword, layer_keyword 
-WHERE keyword_id = fkey_keyword_id AND fkey_layer_id = $layerId
-SQL;
-		$res = db_query($sql);
-
-		$resultObj["layer_keyword"] = array();
-		while ($row = db_fetch_assoc($res)) {
-			$resultObj["layer_keyword"][]= $row["keyword"];
-		}
-
-		$ajaxResponse->setResult($resultObj);
-		$ajaxResponse->setSuccess(true);
-		break;
-	case "getLayerByWms" :
-		$wmsId = $ajaxResponse->getParameter("id");
-//		getWms($wmsId);
-
-		$sql = <<<SQL
-	
-SELECT layer_id, layer_pos, layer_parent, layer_name, layer_title, layer_abstract, layer_searchable 
-FROM layer WHERE fkey_wms_id = $wmsId ORDER BY layer_pos;
-
-SQL;
-		$res = db_query($sql);
-
-		$rows = array();
-		while ($row = db_fetch_assoc($res)) {
-			$rows[] = $row;
-		}
-		$left = 1;
-
-		function createNode ($left, $right, $row) {
-			return array(
-				"left" => $left,
-				"right" => $right,
-				"parent" => $row["layer_parent"] !== "" ? intval($row["layer_parent"]) : null,
-				"pos" => intval($row["layer_pos"]),
-				"attr" => array (
-					"layer_id" => intval($row["layer_id"]),
-					"layer_name" => $row["layer_name"],
-					"layer_title" => $row["layer_title"],
-					"layer_abstract" => $row["layer_abstract"],
-					"layer_searchable" => intval($row["layer_searchable"])
-				)
-			);
-		}
-
-		function addSubTree ($rows, $i, $left) {
-			$nodeArray = array();
-			$addNewNode = true;
-			for ($j = $i; $j < count($rows); $j++) {
-				$row = $rows[$j];
-				$pos = intval($row["layer_pos"]);
-				$parent = $row["layer_parent"] !== "" ? intval($row["layer_parent"]) : null;
-				
-				// first node of subtree
-				if ($addNewNode) {
-					$nodeArray[]= createNode($left, null, $row);
-					$addNewNode = false;
-				}
-				else {
-					// new sub tree
-					if ($parent === $nodeArray[count($nodeArray)-1]["pos"]) {
-						$addedNodeArray = addSubTree($rows, $j, ++$left);
-						
-						$nodeArray[count($nodeArray)-1]["right"] = 
-							$nodeArray[count($nodeArray)-1]["left"] + 
-							2 * count($addedNodeArray) + 1;
-						
-						$left = $nodeArray[count($nodeArray)-1]["right"] + 1;
-
-						$nodeArray = array_merge($nodeArray, $addedNodeArray);
-						$j += count($addedNodeArray) - 1;
-						$addNewNode = true;
-						
-					}
-					// siblings
-					elseif ($parent === $nodeArray[count($nodeArray)-1]["parent"]) {
-						$nodeArray[count($nodeArray)-1]["right"] = ++$left;
-						$nodeArray[]= createNode(++$left, null, $row);
-					}
-				}
-			}
-			if (is_null($nodeArray[count($nodeArray)-1]["right"])) {
-				$nodeArray[count($nodeArray)-1]["right"] = ++$left;
-			}
-			return $nodeArray;
-		}
-		
-
-		$nodeArray = addSubTree($rows, 0, 1);
-		$resultObj = array(
-			"nestedSets" => $nodeArray
-		);
-		
-		$ajaxResponse->setResult($resultObj);
-		$ajaxResponse->setSuccess(true);
-		
-
-		break;
-	case "save":
-		$data = $ajaxResponse->getParameter("data");
-		
-		try {
-			$wmsId = intval($data->wms->wms_id);
-		}
-		catch (Exception $e) {
-			$ajaxResponse->setSuccess(false);
-			$ajaxResponse->setMessage(_mb("Invalid WMS ID."));
-			$ajaxResponse->send();						
-		}
-		getWms($wmsId);
-		
-		$wms = new wms();
-		$wms->createObjFromDBNoGui($wmsId);
-		
-		$columns = array(
-			"wms_abstract", 
-			"wms_title", 
-			"fees", 
-			"accessconstraints", 
-			"contactperson", 
-			"contactposition", 
-			"contactvoicetelephone", 
-			"contactfacsimiletelephone", 
-			"contactorganization", 
-			"address", 
-			"city", 
-			"stateorprovince", 
-			"postcode", 
-			"country", 
-			"contactelectronicmailaddress",
-			"wms_termsofuse"
-		);
-		foreach ($columns as $c) {
-			$value = $data->wms->$c;
-			if (!is_null($value)) {
-				$wms->$c = $value;
-			}
-		}
-
-		if (is_array($data->wms->layer_searchable)) {
-			foreach ($wms->objLayer as &$layer) {
-				$layer->layer_searchable = 0;
-				for ($i = 0; $i < count($data->wms->layer_searchable); $i++) {
-					$id = $data->wms->layer_searchable[$i];
-					if ($id !== intval($layer->layer_uid)) {
-						continue;						
-					}
-					$layer->layer_searchable = 1;
-					break;
-				}
-				unset($id);
-			}
-		}
-
-		try {
-			$layerId = intval($data->layer->layer_id);
-		}
-		catch (Exception $e) {
-		}
-		
-		if ($layerId) {
-			$layer = $wms->getLayerById($layerId);
-			if (!is_null($layer)) {
-				$columns = array(
-					"layer_abstract", 
-					"layer_title",
-					"layer_keyword",
-					"layer_md_topic_category_id",
-					"layer_inspire_category_id",
-					"layer_custom_category_id"
-				);			
-	
-				foreach ($columns as $c) {
-					$value = $data->layer->$c;
-					if ($c === "layer_keyword") {
-						$layer->$c = explode(",", $value);
-						foreach ($layer->$c as &$val) {
-							$val = trim($val);
-						}
-					}
-					elseif ($c === "layer_md_topic_category_id" 
-						|| $c === "layer_inspire_category_id"
-						|| $c === "layer_custom_category_id"
-					) {
-						if (!is_array($value)) {
-							$layer->$c = array($value);
-						}
-						else {
-							$layer->$c = $value;
-						}
-					}
-					else {
-						if (!is_null($value)) {
-							$layer->$c = $value;
-						}
-					}
-				}
-			}
-		}
-
-		$wms->updateObjInDB($wmsId);
-
-		
-		$ajaxResponse->setMessage("Updated WMS metadata for ID " . $wmsId);
-		$ajaxResponse->setSuccess(true);		
-		
-		break;
-	default: 
-		$ajaxResponse->setSuccess(false);
-		$ajaxResponse->setMessage(_mb("An unknown error occured."));
-		break;
-}
-
-$ajaxResponse->send();
-?>
\ No newline at end of file

Copied: branches/mapbender/http/plugins/mb_metadata_server.php (from rev 6938, trunk/mapbender/http/plugins/mb_metadata_server.php)
===================================================================
--- branches/mapbender/http/plugins/mb_metadata_server.php	                        (rev 0)
+++ branches/mapbender/http/plugins/mb_metadata_server.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -0,0 +1,429 @@
+<?php
+require_once dirname(__FILE__) . "/../../core/globalSettings.php";
+require_once dirname(__FILE__) . "/../classes/class_user.php";
+require_once dirname(__FILE__) . "/../classes/class_wms.php";
+
+$ajaxResponse = new AjaxResponse($_POST);
+
+function abort ($message) {
+	global $ajaxResponse;
+	$ajaxResponse->setSuccess(false);
+	$ajaxResponse->setMessage($message);
+	$ajaxResponse->send();
+	die;
+};
+
+function getWms ($wmsId = null) {
+	$user = new User(Mapbender::session()->get("mb_user_id"));
+	$wmsIdArray = $user->getOwnedWms();
+	if (!is_array($wmsIdArray) || count($wmsIdArray) === 0) {
+		abort(_mb("No metadata sets available."));
+	}
+	if (!is_null($wmsId) && !in_array($wmsId, $wmsIdArray)) {
+		abort(_mb("You are not allowed to access this WMS."));
+	}
+	return $wmsIdArray;
+}
+
+function getLayer ($layerId = null) {
+	$user = new User(Mapbender::session()->get("mb_user_id"));
+	$wmsIdArray = $user->getOwnedWms();
+	if (!is_array($wmsIdArray) || count($wmsIdArray) === 0) {
+		abort(_mb("No metadata sets available."));
+	}
+	$wmsId = wms::getWmsIdByLayerId($layerId);
+	if (is_null($wmsId) || !in_array($wmsId, $wmsIdArray)) {
+		abort(_mb("You are not allowed to access WMS " . $wmsId));
+	}
+	return;
+}
+
+switch ($ajaxResponse->getMethod()) {
+	case "getWms" :
+		$wmsIdArray = getWms();
+		
+		$wmsList = implode(",", $wmsIdArray);
+		$sql = <<<SQL
+	
+SELECT wms.wms_id, wms.wms_title, wms.wms_timestamp, wms_version, m.status_comment
+FROM wms LEFT JOIN mb_monitor AS m
+ON wms.wms_id = m.fkey_wms_id 
+WHERE wms_id IN ($wmsList);
+
+SQL;
+		$res = db_query($sql);
+		$resultObj = array(
+			"header" => array(
+				"WMS ID",
+				"Titel",
+				"Timestamp",
+				"Version",
+				"Status"
+			), 
+			"data" => array()
+		);
+
+		while ($row = db_fetch_row($res)) {
+			// convert NULL to '', NULL values cause datatables to crash
+			$walk = array_walk($row, create_function('&$s', '$s=strval($s);'));
+			$resultObj["data"][]= $row;
+		}
+		$ajaxResponse->setResult($resultObj);
+		$ajaxResponse->setSuccess(true);
+		break;
+
+	case "getWmsMetadata" :
+		$wmsId = $ajaxResponse->getParameter("id");
+		getWms($wmsId);
+
+		$wms = new wms();
+		$wms->createObjFromDBNoGui($wmsId);
+
+		$fields = array(
+			"wms_id", 
+			"wms_abstract", 
+			"wms_title", 
+			"fees", 
+			"accessconstraints", 
+			"contactperson", 
+			"contactposition", 
+			"contactvoicetelephone", 
+			"contactfacsimiletelephone", 
+			"contactorganization", 
+			"address", 
+			"city", 
+			"stateorprovince", 
+			"postcode", 
+			"country", 
+			"contactelectronicmailaddress",
+			"wms_timestamp", 
+			"wms_timestamp_create"
+		);
+
+		$resultObj = array();
+		foreach ($fields as $field) {
+			if ($field == "wms_timestamp" || $field == "wms_timestamp_create") {
+				if ($wms->$field != "") {
+					$resultObj[$field] = date('d.m.Y', $wms->$field);
+					
+				}
+			}
+			else {
+				$resultObj[$field] = $wms->$field;	
+			}
+		}
+		
+		// layer searchable
+		$resultObj["layer_searchable"] = array();
+		foreach ($wms->objLayer as $layer) {
+			if (intval($layer->layer_searchable) === 1) {
+				$resultObj["layer_searchable"][] = intval($layer->layer_uid);
+			}
+		}
+		
+		$keywordSql = <<<SQL
+	
+SELECT DISTINCT keyword FROM keyword, layer_keyword 
+WHERE keyword_id = fkey_keyword_id AND fkey_layer_id IN (
+	SELECT layer_id from layer, wms 
+	WHERE fkey_wms_id = wms_id AND wms_id = $wmsId
+) ORDER BY keyword
+
+SQL;
+
+		$keywordRes = db_query($keywordSql);
+		$keywords = array();
+		while ($keywordRow = db_fetch_assoc($keywordRes)) {
+			$keywords[]= $keywordRow["keyword"];
+		}
+
+		$resultObj["wms_keywords"] = implode(", ", $keywords);
+
+		$termsofuseSql = <<<SQL
+SELECT fkey_termsofuse_id FROM wms_termsofuse WHERE fkey_wms_id = $wmsId
+SQL;
+
+		$termsofuseRes = db_query($termsofuseSql);
+		if ($termsofuseRes) {
+			$termsofuseRow = db_fetch_assoc($termsofuseRes);
+			$resultObj["wms_termsofuse"] = $termsofuseRow["fkey_termsofuse_id"];
+		}
+		else {
+			$resultObj["wms_termsofuse"] = null;
+		}
+		
+
+		$ajaxResponse->setResult($resultObj);
+		$ajaxResponse->setSuccess(true);
+
+		break;
+	
+	case "getLayerMetadata" :
+		$layerId = $ajaxResponse->getParameter("id");
+		getLayer($layerId);
+
+		$sql = <<<SQL
+	
+SELECT layer_id, layer_name, layer_title, layer_abstract, layer_searchable 
+FROM layer WHERE layer_id = $layerId;
+
+SQL;
+		$res = db_query($sql);
+
+		$resultObj = array();
+		while ($row = db_fetch_assoc($res)) {
+			foreach ($row as $key => $value) {
+				$resultObj[$key] = $value;
+			}
+		}
+
+		$sql = <<<SQL
+SELECT fkey_md_topic_category_id 
+FROM layer_md_topic_category 
+WHERE fkey_layer_id = $layerId
+SQL;
+		$res = db_query($sql);
+		while ($row = db_fetch_assoc($res)) {
+			$resultObj["layer_md_topic_category_id"][]= $row["fkey_md_topic_category_id"];
+		}
+
+		$sql = <<<SQL
+SELECT fkey_inspire_category_id 
+FROM layer_inspire_category 
+WHERE fkey_layer_id = $layerId
+SQL;
+		$res = db_query($sql);
+		while ($row = db_fetch_assoc($res)) {
+			$resultObj["layer_inspire_category_id"][]= $row["fkey_inspire_category_id"];
+		}
+
+		$sql = <<<SQL
+SELECT fkey_custom_category_id 
+FROM layer_custom_category 
+WHERE fkey_layer_id = $layerId
+SQL;
+		$res = db_query($sql);
+		while ($row = db_fetch_assoc($res)) {
+			$resultObj["layer_custom_category_id"][]= $row["fkey_custom_category_id"];
+		}
+
+		$sql = <<<SQL
+SELECT keyword FROM keyword, layer_keyword 
+WHERE keyword_id = fkey_keyword_id AND fkey_layer_id = $layerId
+SQL;
+		$res = db_query($sql);
+
+		$resultObj["layer_keyword"] = array();
+		while ($row = db_fetch_assoc($res)) {
+			$resultObj["layer_keyword"][]= $row["keyword"];
+		}
+
+		$ajaxResponse->setResult($resultObj);
+		$ajaxResponse->setSuccess(true);
+		break;
+	case "getLayerByWms" :
+		$wmsId = $ajaxResponse->getParameter("id");
+//		getWms($wmsId);
+
+		$sql = <<<SQL
+	
+SELECT layer_id, layer_pos, layer_parent, layer_name, layer_title, layer_abstract, layer_searchable 
+FROM layer WHERE fkey_wms_id = $wmsId ORDER BY layer_pos;
+
+SQL;
+		$res = db_query($sql);
+
+		$rows = array();
+		while ($row = db_fetch_assoc($res)) {
+			$rows[] = $row;
+		}
+		$left = 1;
+
+		function createNode ($left, $right, $row) {
+			return array(
+				"left" => $left,
+				"right" => $right,
+				"parent" => $row["layer_parent"] !== "" ? intval($row["layer_parent"]) : null,
+				"pos" => intval($row["layer_pos"]),
+				"attr" => array (
+					"layer_id" => intval($row["layer_id"]),
+					"layer_name" => $row["layer_name"],
+					"layer_title" => $row["layer_title"],
+					"layer_abstract" => $row["layer_abstract"],
+					"layer_searchable" => intval($row["layer_searchable"])
+				)
+			);
+		}
+
+		function addSubTree ($rows, $i, $left) {
+			$nodeArray = array();
+			$addNewNode = true;
+			for ($j = $i; $j < count($rows); $j++) {
+				$row = $rows[$j];
+				$pos = intval($row["layer_pos"]);
+				$parent = $row["layer_parent"] !== "" ? intval($row["layer_parent"]) : null;
+				
+				// first node of subtree
+				if ($addNewNode) {
+					$nodeArray[]= createNode($left, null, $row);
+					$addNewNode = false;
+				}
+				else {
+					// new sub tree
+					if ($parent === $nodeArray[count($nodeArray)-1]["pos"]) {
+						$addedNodeArray = addSubTree($rows, $j, ++$left);
+						
+						$nodeArray[count($nodeArray)-1]["right"] = 
+							$nodeArray[count($nodeArray)-1]["left"] + 
+							2 * count($addedNodeArray) + 1;
+						
+						$left = $nodeArray[count($nodeArray)-1]["right"] + 1;
+
+						$nodeArray = array_merge($nodeArray, $addedNodeArray);
+						$j += count($addedNodeArray) - 1;
+						$addNewNode = true;
+						
+					}
+					// siblings
+					elseif ($parent === $nodeArray[count($nodeArray)-1]["parent"]) {
+						$nodeArray[count($nodeArray)-1]["right"] = ++$left;
+						$nodeArray[]= createNode(++$left, null, $row);
+					}
+				}
+			}
+			if (is_null($nodeArray[count($nodeArray)-1]["right"])) {
+				$nodeArray[count($nodeArray)-1]["right"] = ++$left;
+			}
+			return $nodeArray;
+		}
+		
+
+		$nodeArray = addSubTree($rows, 0, 1);
+		$resultObj = array(
+			"nestedSets" => $nodeArray
+		);
+		
+		$ajaxResponse->setResult($resultObj);
+		$ajaxResponse->setSuccess(true);
+		
+
+		break;
+	case "save":
+		$data = $ajaxResponse->getParameter("data");
+		
+		try {
+			$wmsId = intval($data->wms->wms_id);
+		}
+		catch (Exception $e) {
+			$ajaxResponse->setSuccess(false);
+			$ajaxResponse->setMessage(_mb("Invalid WMS ID."));
+			$ajaxResponse->send();						
+		}
+		getWms($wmsId);
+		
+		$wms = new wms();
+		$wms->createObjFromDBNoGui($wmsId);
+		
+		$columns = array(
+			"wms_abstract", 
+			"wms_title", 
+			"fees", 
+			"accessconstraints", 
+			"contactperson", 
+			"contactposition", 
+			"contactvoicetelephone", 
+			"contactfacsimiletelephone", 
+			"contactorganization", 
+			"address", 
+			"city", 
+			"stateorprovince", 
+			"postcode", 
+			"country", 
+			"contactelectronicmailaddress",
+			"wms_termsofuse"
+		);
+		foreach ($columns as $c) {
+			$value = $data->wms->$c;
+			if (!is_null($value)) {
+				$wms->$c = $value;
+			}
+		}
+
+		if (is_array($data->wms->layer_searchable)) {
+			foreach ($wms->objLayer as &$layer) {
+				$layer->layer_searchable = 0;
+				for ($i = 0; $i < count($data->wms->layer_searchable); $i++) {
+					$id = $data->wms->layer_searchable[$i];
+					if ($id !== intval($layer->layer_uid)) {
+						continue;						
+					}
+					$layer->layer_searchable = 1;
+					break;
+				}
+				unset($id);
+			}
+		}
+
+		try {
+			$layerId = intval($data->layer->layer_id);
+		}
+		catch (Exception $e) {
+		}
+		
+		if ($layerId) {
+			try {
+				$layer = $wms->getLayerById($layerId);
+			}
+			catch (Exception $e) {
+			}
+			$columns = array(
+				"layer_abstract",
+				"layer_title",
+				"layer_keyword",
+				"layer_md_topic_category_id",
+				"layer_inspire_category_id",
+				"layer_custom_category_id"
+			);
+
+			foreach ($columns as $c) {
+				$value = $data->layer->$c;
+				if ($c === "layer_keyword") {
+					$layer->$c = explode(",", $value);
+					foreach ($layer->$c as &$val) {
+						$val = trim($val);
+					}
+				}
+				elseif ($c === "layer_md_topic_category_id"
+					|| $c === "layer_inspire_category_id"
+					|| $c === "layer_custom_category_id"
+				) {
+					if (!is_array($value)) {
+						$layer->$c = array($value);
+					}
+					else {
+						$layer->$c = $value;
+					}
+				}
+				else {
+					if (!is_null($value)) {
+						$layer->$c = $value;
+					}
+				}
+			}
+		}
+
+		$wms->updateObjInDB($wmsId);
+
+		
+		$ajaxResponse->setMessage("Updated WMS metadata for ID " . $wmsId);
+		$ajaxResponse->setSuccess(true);		
+		
+		break;
+	default: 
+		$ajaxResponse->setSuccess(false);
+		$ajaxResponse->setMessage(_mb("An unknown error occured."));
+		break;
+}
+
+$ajaxResponse->send();
+?>
\ No newline at end of file

Deleted: branches/mapbender/http/plugins/mb_print.js
===================================================================
--- trunk/mapbender/http/plugins/mb_print.js	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/http/plugins/mb_print.js	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,495 +0,0 @@
-/**
- * Package: printPDF
- *
- * Description:
- * Mapbender print PDF with PDF templates module.
- * 
- * Files:
- *  - http/plugins/mb_print.js
- *  - http/print/classes
- *  - http/print/printFactory.php
- *  - http/print/printPDF_download.php
- *  - lib/printbox.js
- *
- * SQL:
- * > INSERT INTO gui_element(fkey_gui_id, e_id, e_pos, e_public, e_comment, 
- * > e_title, e_element, e_src, e_attributes, e_left, e_top, e_width, 
- * > e_height, e_z_index, e_more_styles, e_content, e_closetag, e_js_file, 
- * > e_mb_mod, e_target, e_requires, e_url) VALUES('<appId>','printPDF',
- * > 2,1,'pdf print','Print','div','','',1,1,2,2,5,'',
- * > '<div id="printPDF_working_bg"></div><div id="printPDF_working"><img src="../img/indicator_wheel.gif" style="padding:10px 0 0 10px">Generating PDF</div><div id="printPDF_input"><form id="printPDF_form" action="../print/printFactory.php"><div id="printPDF_selector"></div><div class="print_option"><input type="hidden" id="map_url" name="map_url" value=""/><input type="hidden" id="legend_url" name="legend_url" value=""/><input type="hidden" id="overview_url" name="overview_url" value=""/><input type="hidden" id="map_scale" name="map_scale" value=""/><input type="hidden" name="measured_x_values" /><input type="hidden" name="measured_y_values" /><br /></div><div class="print_option" id="printPDF_formsubmit"><input id="submit" type="submit" value="Print"><br /></div></form><div id="printPDF_result"></div></div>',
- * > 'div','../plugins/mb_print.js',
- * > '../../lib/printbox.js,../extensions/jquery-ui-1.7.2.custom/development-bundle/external/bgiframe/jquery.bgiframe.min.js,../extensions/jquery.form.min.js',
- * > 'mapframe1','','http://www.mapbender.org/index.php/Print');
- * >
- * > INSERT INTO gui_element_vars(fkey_gui_id, fkey_e_id, var_name, 
- * > var_value, context, var_type) VALUES('<appId>', 'printPDF', 
- * > 'mbPrintConfig', '{"Standard": "mapbender_template.json"}', '' ,'var');
- * >
- * > INSERT INTO gui_element_vars(fkey_gui_id, fkey_e_id, var_name, 
- * > var_value, context, var_type) VALUES('<appId>', 'body', 
- * > 'print_css', '../css/print_div.css', '' ,'file/css');
- * 
- * Help:
- * http://www.mapbender.org/PrintPDF_with_template
- *
- * Maintainer:
- * http://www.mapbender.org/User:Michael_Schulz
- * http://www.mapbender.org/User:Christoph_Baudson
- * 
- * Parameters:
- * mbPrintConfig      - *[optional]* object with name and filename of template,
- * 							like 	{
- * 										"Standard": "a_template.json",
- * 										"Different": "another_template.json"
- * 									}
- *
- * License:
- * Copyright (c) 2009, Open Source Geospatial Foundation
- * This program is dual licensed under the GNU General Public License 
- * and Simplified BSD license.  
- * http://svn.osgeo.org/mapbender/trunk/mapbender/license/license.txt
- */
-
-var myTarget = options.target ? options.target[0] : "mapframe1";
-var myId = options ? options.id : "printPDF";
-
-var mbPrintConfig = options.mbPrintConfig;
-
-/* the array of json print config files */
-
-if (typeof mbPrintConfig === "object") {
-	mbPrintConfigFilenames = [];
-	mbPrintConfigTitles = [];
-	for (var i in mbPrintConfig) {
-		mbPrintConfigFilenames.push(mbPrintConfig[i]);
-		mbPrintConfigTitles.push(i);
-	}
-}
-if (typeof mbPrintConfigFilenames === "undefined") {
-	mbPrintConfigFilenames = ["mapbender_template.json"];
-}
-
-if (typeof mbPrintConfigTitles === "undefined") {
-	mbPrintConfigTitles = ["Default"];
-}
-
-
-var mbPrintConfigPath = "../print/";
-
-
-/* ------------- printbox addition ------------- */
-
-var PrintPDF = function (options) {
-
-	var that = this;
-	
-	/**
- 	 * Property: actualConfig
-	 * 
-	 * object, holds the actual configuration after loading the json file
-	 */
-	var actualConfig;
-
-	/**
- 	 * constructor
-	 */
-	eventInit.register(function () {
-		mod_printPDF_init();
-	});
-	
-	/**
- 	 * Property: printBox
-	 * 
-	 * the movable printframe
-	 */	
-	var printBox = null;
-	
-	eventAfterMapRequest.register(function () {
-		if (printBox !== null) {
-			printBox.repaint();
-		}
-	});
-	/**
- 	 * Method: createPrintBox
-	 * 
-	 * creates a printBox in the current view, calculates the scale 
-	 * (tbd. if not set from the config) so that the printbox fits in the mapframe.
-	 * Width and height are taken from the configuration.
-	 */
-	this.createPrintBox = function () {
-		size = "A4";
-		//document.form1.size.value = size;
-		format = "portrait";
-		var w, h;
-		//validate();
-		var map = getMapObjByName(myTarget);
-		var map_el = map.getDomElement();
-		var jqForm = $("#"+myId+"_form");
-		var $scaleInput = $("#scale");
-
-		if (printBox !== null) {
-			printBox.destroy();
-			printBox = null;
-			jqForm[0].scale.value = "";
-			jqForm[0].coordinates.value = "";
-			jqForm[0].angle.value = "";
-		}
-		else {
-			printBox = new Mapbender.PrintBox({
-				target : myTarget,
-				printWidth : getPDFMapSize("width")/10,
-				printHeight : getPDFMapSize("height")/10,
-				scale : $scaleInput.size() > 0 && !isNaN(parseInt($scaleInput.val(), 10)) ? 
-					parseInt($scaleInput.val(), 10) : 
-					Math.pow(10, Math.floor(Math.log(map.getScale())/Math.LN10)),
-				afterChangeAngle : function (obj) {
-					if (typeof(obj) == "object") {
-						if (typeof(obj.angle) == "number") {
-							jqForm[0].angle.value = obj.angle;
-						}
-						if (obj.coordinates) {
-							jqForm[0].coordinates.value = String(obj.coordinates);
-						}
-					}
-				},
-				afterChangeSize : function (obj) {
-					if (typeof(obj) == "object") {
-						if (obj.scale) {
-							jqForm[0].scale.value = parseInt(obj.scale / 10, 10) * 10;
-						}
-						if (obj.coordinates) {
-							jqForm[0].coordinates.value = String(obj.coordinates);
-						}
-					}
-				}
-			});
-			printBox.paintPoints();
-			printBox.paintBox();
-
-		}
-	};
-
-	/**
- 	 * Method: getPDFMapSize
-	 * 
-	 * checks the actual config for the size w/h values.
-	 *
-	 * Parameters:
-	 * key      - string, the key which value to retrieve (currently width or height)
-	 */	
-	var getPDFMapSize = function (key) {
-		for (var page in actualConfig.pages) {
-			for (var pageElement in actualConfig.pages[page].elements) {
-				if (actualConfig.pages[page].elements[pageElement].type == "map") {
-					return actualConfig.pages[page].elements[pageElement][key];
-				}
-			}
-		} 
-	};
-
-	/**
- 	 * Method: destroyPrintBox
-	 * 
-	 * removes an existing printBox.
-	 */	
-	var destroyPrintBox = function () {
-		if (printBox) {
-			printBox.destroy();
-		}
-	};
-	
-	/**
- 	 * Method: mod_printPDF_init
-	 * 
-	 * initializes the print modules, generates template chooser and loads first configuration.
-	 */	
-	var mod_printPDF_init = function () {
-		/* first we'd need to build the configuration selection */
-		buildConfigSelector();	
-		/* second we'd need to read the json configuration */
-		that.loadConfig(mbPrintConfigFilenames[0]);
-	};
-
-	/**
- 	 * Method: loadConfig
-	 * 
-	 * GETs the config, build corresponding form, remove an existing printBox
-	 */		
-	this.loadConfig = function (configFilename, callback) {
-		$.get(mbPrintConfigPath + configFilename, function(json, status){
-		    actualConfig = $.parseJSON(json);
-		    buildForm(); 
-		    hookForm();
-			if (typeof callback === "function") {
-				printBox = null;
-				callback();
-			}
-		});
-		destroyPrintBox();
-	};
-
-	/**
- 	 * Method: hookForm
-	 * 
-	 * utility method to connect the form plugin to the print form.
-	 */	
-	var hookForm = function () {
-		var options = { 
-	   		url:			'../print/printFactory.php', 
-	   		type:			'post',
-	   		dataType:		'json',
-	   		beforeSubmit: 	validate,
-	   		success:    	showResult
-		};
-		$("#"+myId+"_form").ajaxForm(options);	
-	};
-	
-	/**
-	 * Change status of the working elements. These should begin with "$myId_working" 
-	 *
-	 * @param {String} newStatus either "hide or "show"
-	 */
-	var showHideWorking = function (newStatus) {
-		if (newStatus=="hide") {
-	    	$("[id^='"+myId+"_working']").hide();
-		}
-	    else {
-	    	$("[id^='"+myId+"_working']").show();	
-		}
-	};
-	
-	/**
-	 * update form values helper function
-	 *
-	 */
-	var updateFormField = function (formData, key, value) {
-		for(var j=0; j < formData.length; j++){
-			if (formData[j].name == key) {
-				formData[j].value = value;
-				break;
-			}
-		}	
-	};
-	
-	
-	/**
-	 * Validates and updates form data values.
-	 * Adds the elements before the submit button.
-	 *
-	 * @see jquery.forms#beforeSubmitHandler
-	 */
-	var validate = function (formData, jqForm, options) {
-		showHideWorking("show");
-		
-		// map urls
-		var ind = getMapObjIndexByName(myTarget);
-		var f = jqForm[0];
-		f.map_url.value = '';
-		
-		var scale = f.scale.value || mb_mapObj[ind].getScale();
-		scale = parseInt(scale, 10);
-		
-		var legendUrlArray = [];
-		f.overview_url.value = '';
-		for(var i=0; i < mb_mapObj[ind].wms.length; i++){
-			var currentWms = mb_mapObj[ind].wms[i];
-			if(mb_mapObj[ind].wms[i].gui_wms_visible > 0){
-				if (mb_mapObj[ind].wms[i].mapURL != false && mb_mapObj[ind].wms[i].mapURL != 'false' && mb_mapObj[ind].wms[i].mapURL != ''){   
-					if(f.map_url.value != ""){
-						f.map_url.value += '___';
-					}      
-					f.map_url.value += mb_mapObj[ind].getMapUrl(i, mb_mapObj[ind].getExtentInfos(), scale);
-
-					var wmsLegendObj = [];
-					
-					var layers = currentWms.getLayers(mb_mapObj[ind], scale);
-					for (var j = 0; j < layers.length; j++) {
-						var currentLayer = currentWms.getLayerByLayerName(layers[j]);
-						// TODO: add only visible layers
-						var isVisible = (currentLayer.gui_layer_visible === 1);
-						var hasNoChildren = (!currentLayer.has_childs);
-						if (isVisible && hasNoChildren){
-							var layerLegendObj = {};
-							layerLegendObj.name = currentLayer.layer_name;
-							layerLegendObj.title = currentWms.getTitleByLayerName(currentLayer.layer_name);
-							var layerStyle = currentWms.getCurrentStyleByLayerName(currentLayer.layer_name);
-							if (layerStyle === false) {
-								layerStyle = "default";
-							}
-							layerLegendObj.legendUrl = currentWms.getLegendUrlByGuiLayerStyle(currentLayer.layer_name, layerStyle);
-							if (layerLegendObj.legendUrl !== false) {
-								wmsLegendObj.push(layerLegendObj);
-							}
-						}
-					}
-					if (wmsLegendObj.length > 0) {
-						var tmpObj = {};
-						tmpObj[currentWms.wms_currentTitle] = wmsLegendObj;
-						legendUrlArray.push(tmpObj);
-					}
-				}
-			}
-		}
-		updateFormField(formData, "legend_url", $.toJSON(legendUrlArray));
-		updateFormField(formData, "map_url", f.map_url.value);
-		updateFormField(formData, "scale", scale);
-		
-		//overview_url
-		var ind_overview = getMapObjIndexByName('overview');
-		if(mb_mapObj[ind_overview].mapURL != false ){
-		    f.overview_url.value = mb_mapObj[ind_overview].mapURL;
-			updateFormField(formData, "overview_url", f.overview_url.value);
-		}
-		
-		updateFormField(formData, "map_scale", mb_getScale(myTarget));
-		// write the measured coordinates
-		if (typeof(mod_measure_RX) !== "undefined") {
-			var tmp_x = '';
-			var tmp_y = '';
-			for(i = 0; i < mod_measure_RX.length; i++) {
-				if(tmp_x != '') {
-					tmp_x += ',';
-				}
-				tmp_x += mod_measure_RX[i];
-			}
-			for(i = 0; i < mod_measure_RY.length; i++) {
-				if(tmp_y != '') {
-					tmp_y += ',';
-				}
-				tmp_y += mod_measure_RY[i];
-			}
-			updateFormField(formData, "measured_x_values", tmp_x);
-			updateFormField(formData, "measured_y_values", tmp_y);
-		}	
-		
-		
-		if (f.map_url.value!="") {
-			//return true;
-		} else {
-		    showHideWorking("hide");
-			return false;
-		}
-	};
-
-	/**
- 	 * Method: showResult
-	 * 
-	 * load the generated PDF from the returned URL as an attachment, 
-	 * that triggers a download popup or is displayed in PDF plugin.
-	 */		
-	var showResult = function (res, text) {
-		if (text == 'success') {
-			var $downloadFrame = $("#" + myId + "_frame");
-			if ($downloadFrame.size() === 0) {
-				$downloadFrame = $(
-					"<iframe id='" + myId + "_frame' name='" + 
-					myId + "_frame' width='0' height='0' style='display:none'></iframe>"
-				).appendTo("body");
-			}
-			if ($.browser.msie && $.browser.version === "6.0") {
-				var newWin = window.open(stripslashes(res.outputFileName), "Druckausgabe", "width=200,height=200,left=700,top=200,resizable=yes");
-			}
-			else {
-				window.frames[myId + "_frame"].location.href = 
-					stripslashes(res.outputFileName);
-			}
-			showHideWorking("hide");	
-		}
-		else {
-			/* something went wrong */
-			$("#"+myId+"_result").html(text);
-		}
-	};
-	
-	/**
-	 * Generates form elements as specified in the config controls object.
-	 * Adds the elements before the submit button.
-	 * 
-	 * @param {Object} json the config object in json
-	 */
-	var buildForm = function () {
-		$(".print_option_dyn").remove();
-		var str = "";
-		for (var item in actualConfig.controls) {
-			var element = actualConfig.controls[item];
-			var element_id = myId + "_" + element.id;
-			if (element.type != "hidden") {
-				str += '<div class="print_option_dyn">\n';	
-				str += '<label class="print_label" for="'+element.id+'">'+element.label+'</label>\n';
-			} else {
-				str += '<div class="print_option_dyn" style="display:none;">\n';	
-			}
-			switch (element.type) {
-				case "text":
-					str += '<input type="'+element.type+'" name="'+element.id+'" id="'+element.id+'" size="'+element.size+'"><br>\n';
-					break;
-				case "hidden":
-					str += '<input type="'+element.type+'" name="'+element.id+'" id="'+element.id+'">\n';
-					break;				
-				case "textarea":
-					str += '<textarea id="'+element.id+'" name="'+element.id+'" size="'+element.size+'"></textarea><br>\n';
-					break;				
-				case "select":
-					str += '<select id="'+element.id+'" name="'+element.id+'" size="1">\n';
-					for (var option_index in element.options) {
-						option = element.options[option_index];
-						str += '<option value="'+option.value+'">'+option.label+'</option>\n';
-					}
-					str += '</select><br>\n';
-					break;
-			}
-			str += '</div>\n';
-		}
-		if (str) {
-			$("#" + myId + "_formsubmit").before(str);
-			$("#scale").keydown(function (e) {
-				if (e.keyCode !== 13) {
-					return;
-				}
-				var scale = parseInt(this.value, 10);
-				if (isNaN(scale) || typeof printBox === "undefined") {
-					return false;
-				}
-				printBox.setScale(scale);
-				return false;
-			});
-		}
-	};
-	
-	/**
-	 * Generates the configuration select element from the gui element vars
-	 * mbPrintConfigFilenames and mbPrintConfigTitles
-	 */
-	var buildConfigSelector = function () {
-		var str = "";
-		str += '<label class="print_label" for="printPDF_template">Vorlage</label>\n';
-		str += '<select id="printPDF_template" name="printPDF_template" size="1">\n';
-		for (var i = 0; i < mbPrintConfigFilenames.length; i++) {
-			str += '<option value="'+mbPrintConfigFilenames[i]+'">'+mbPrintConfigTitles[i]+'</option>\n';
-		}
-		str += '</select><img id="printPDF_handle" src="../print/img/shape_handles.png" title="Use printbox">\n';
-		if (str) {
-			$("#printPDF_selector").append(str).find("#printPDF_template").change(function () {
-				printObj.loadConfig(mbPrintConfigFilenames[this.selectedIndex], function () {
-					printObj.createPrintBox()
-				});			
-			});
-			$("#printPDF_handle").click(function () {
-				printObj.createPrintBox();
-			});
-			$("#printPDF_working").bgiframe({ 
-				src: "BLOCKED SCRIPT'&lt;html&gt;&lt;/html&gt;';",
-				width: 200,
-				height: 200
-			});
-		}
-	};
-	
-	var stripslashes = function ( str ) {
-	    return (str+'').replace(/\0/g, '0').replace(/\\([\\'"])/g, '$1');
-	};
-
-};
-
-var printObj = new PrintPDF();

Copied: branches/mapbender/http/plugins/mb_print.js (from rev 6948, trunk/mapbender/http/plugins/mb_print.js)
===================================================================
--- branches/mapbender/http/plugins/mb_print.js	                        (rev 0)
+++ branches/mapbender/http/plugins/mb_print.js	2010-09-29 11:31:10 UTC (rev 6957)
@@ -0,0 +1,565 @@
+/**
+ * Package: printPDF
+ *
+ * Description:
+ * Mapbender print PDF with PDF templates module.
+ * 
+ * Files:
+ *  - http/plugins/mb_print.js
+ *  - http/print/classes
+ *  - http/print/printFactory.php
+ *  - http/print/printPDF_download.php
+ *  - lib/printbox.js
+ *
+ * SQL:
+ * > INSERT INTO gui_element(fkey_gui_id, e_id, e_pos, e_public, e_comment, 
+ * > e_title, e_element, e_src, e_attributes, e_left, e_top, e_width, 
+ * > e_height, e_z_index, e_more_styles, e_content, e_closetag, e_js_file, 
+ * > e_mb_mod, e_target, e_requires, e_url) VALUES('<appId>','printPDF',
+ * > 2,1,'pdf print','Print','div','','',1,1,2,2,5,'',
+ * > '<div id="printPDF_working_bg"></div><div id="printPDF_working"><img src="../img/indicator_wheel.gif" style="padding:10px 0 0 10px">Generating PDF</div><div id="printPDF_input"><form id="printPDF_form" action="../print/printFactory.php"><div id="printPDF_selector"></div><div class="print_option"><input type="hidden" id="map_url" name="map_url" value=""/><input type="hidden" id="legend_url" name="legend_url" value=""/><input type="hidden" id="overview_url" name="overview_url" value=""/><input type="hidden" id="map_scale" name="map_scale" value=""/><input type="hidden" name="measured_x_values" /><input type="hidden" name="measured_y_values" /><br /></div><div class="print_option" id="printPDF_formsubmit"><input id="submit" type="submit" value="Print"><br /></div></form><div id="printPDF_result"></div></div>',
+ * > 'div','../plugins/mb_print.js',
+ * > '../../lib/printbox.js,../extensions/jquery-ui-1.7.2.custom/development-bundle/external/bgiframe/jquery.bgiframe.min.js,../extensions/jquery.form.min.js',
+ * > 'mapframe1','','http://www.mapbender.org/index.php/Print');
+ * >
+ * > INSERT INTO gui_element_vars(fkey_gui_id, fkey_e_id, var_name, 
+ * > var_value, context, var_type) VALUES('<appId>', 'printPDF', 
+ * > 'mbPrintConfig', '{"Standard": "mapbender_template.json"}', '' ,'var');
+ * >
+ * > INSERT INTO gui_element_vars(fkey_gui_id, fkey_e_id, var_name, 
+ * > var_value, context, var_type) VALUES('<appId>', 'body', 
+ * > 'print_css', '../css/print_div.css', '' ,'file/css');
+ * 
+ * Help:
+ * http://www.mapbender.org/PrintPDF_with_template
+ *
+ * Maintainer:
+ * http://www.mapbender.org/User:Michael_Schulz
+ * http://www.mapbender.org/User:Christoph_Baudson
+ * 
+ * Parameters:
+ * mbPrintConfig      - *[optional]* object with name and filename of template,
+ * 							like 	{
+ * 										"Standard": "a_template.json",
+ * 										"Different": "another_template.json"
+ * 									}
+ *
+ * License:
+ * Copyright (c) 2009, Open Source Geospatial Foundation
+ * This program is dual licensed under the GNU General Public License 
+ * and Simplified BSD license.  
+ * http://svn.osgeo.org/mapbender/trunk/mapbender/license/license.txt
+ */
+
+var myTarget = options.target ? options.target[0] : "mapframe1";
+var myId = options ? options.id : "printPDF";
+
+var mbPrintConfig = options.mbPrintConfig;
+
+/* the array of json print config files */
+
+if (typeof mbPrintConfig === "object") {
+	mbPrintConfigFilenames = [];
+	mbPrintConfigTitles = [];
+	for (var i in mbPrintConfig) {
+		mbPrintConfigFilenames.push(mbPrintConfig[i]);
+		mbPrintConfigTitles.push(i);
+	}
+}
+if (typeof mbPrintConfigFilenames === "undefined") {
+	mbPrintConfigFilenames = ["mapbender_template.json"];
+}
+
+if (typeof mbPrintConfigTitles === "undefined") {
+	mbPrintConfigTitles = ["Default"];
+}
+
+
+var mbPrintConfigPath = "../print/";
+
+
+/* ------------- printbox addition ------------- */
+
+var PrintPDF = function (options) {
+
+	var that = this;
+	
+	/**
+ 	 * Property: actualConfig
+	 * 
+	 * object, holds the actual configuration after loading the json file
+	 */
+	var actualConfig;
+
+	/**
+ 	 * constructor
+	 */
+	eventInit.register(function () {
+		mod_printPDF_init();
+	});
+	
+	/**
+ 	 * Property: printBox
+	 * 
+	 * the movable printframe
+	 */	
+	var printBox = null;
+	
+	eventAfterMapRequest.register(function () {
+		if (printBox !== null) {
+			printBox.repaint();
+		}
+	});
+	/**
+ 	 * Method: createPrintBox
+	 * 
+	 * creates a printBox in the current view, calculates the scale 
+	 * (tbd. if not set from the config) so that the printbox fits in the mapframe.
+	 * Width and height are taken from the configuration.
+	 */
+	this.createPrintBox = function () {
+		size = "A4";
+		//document.form1.size.value = size;
+		format = "portrait";
+		var w, h;
+		//validate();
+		var map = getMapObjByName(myTarget);
+		var map_el = map.getDomElement();
+		var jqForm = $("#"+myId+"_form");
+		var $scaleInput = $("#scale");
+
+		if (printBox !== null) {
+			printBox.destroy();
+			printBox = null;
+			jqForm[0].scale.value = "";
+			jqForm[0].coordinates.value = "";
+			jqForm[0].angle.value = "";
+		}
+		else {
+			printBox = new Mapbender.PrintBox({
+				target : myTarget,
+				printWidth : getPDFMapSize("width")/10,
+				printHeight : getPDFMapSize("height")/10,
+				scale : $scaleInput.size() > 0 && !isNaN(parseInt($scaleInput.val(), 10)) ? 
+					parseInt($scaleInput.val(), 10) : 
+					Math.pow(10, Math.floor(Math.log(map.getScale())/Math.LN10)),
+				afterChangeAngle : function (obj) {
+					if (typeof(obj) == "object") {
+						if (typeof(obj.angle) == "number") {
+							jqForm[0].angle.value = obj.angle;
+						}
+						if (obj.coordinates) {
+							jqForm[0].coordinates.value = String(obj.coordinates);
+						}
+					}
+				},
+				afterChangeSize : function (obj) {
+					if (typeof(obj) == "object") {
+						if (obj.scale) {
+							jqForm[0].scale.value = parseInt(obj.scale / 10, 10) * 10;
+						}
+						if (obj.coordinates) {
+							jqForm[0].coordinates.value = String(obj.coordinates);
+						}
+					}
+				}
+			});
+			printBox.paintPoints();
+			printBox.paintBox();
+
+		}
+	};
+
+	/**
+ 	 * Method: getPDFMapSize
+	 * 
+	 * checks the actual config for the size w/h values.
+	 *
+	 * Parameters:
+	 * key      - string, the key which value to retrieve (currently width or height)
+	 */	
+	var getPDFMapSize = function (key) {
+		for (var page in actualConfig.pages) {
+			for (var pageElement in actualConfig.pages[page].elements) {
+				if (actualConfig.pages[page].elements[pageElement].type == "map") {
+					return actualConfig.pages[page].elements[pageElement][key];
+				}
+			}
+		} 
+	};
+
+	/**
+ 	 * Method: destroyPrintBox
+	 * 
+	 * removes an existing printBox.
+	 */	
+	var destroyPrintBox = function () {
+		if (printBox) {
+			printBox.destroy();
+		}
+	};
+	
+	/**
+ 	 * Method: mod_printPDF_init
+	 * 
+	 * initializes the print modules, generates template chooser and loads first configuration.
+	 */	
+	var mod_printPDF_init = function () {
+		/* first we'd need to build the configuration selection */
+		buildConfigSelector();	
+		/* second we'd need to read the json configuration */
+		that.loadConfig(mbPrintConfigFilenames[0]);
+	};
+
+	/**
+ 	 * Method: loadConfig
+	 * 
+	 * GETs the config, build corresponding form, remove an existing printBox
+	 */		
+	this.loadConfig = function (configFilename, callback) {
+		$.get(mbPrintConfigPath + configFilename, function(json, status){
+		    actualConfig = $.parseJSON(json);
+		    buildForm(); 
+		    hookForm();
+			if (typeof callback === "function") {
+				printBox = null;
+				callback();
+			}
+		});
+		destroyPrintBox();
+	};
+
+	/**
+ 	 * Method: hookForm
+	 * 
+	 * utility method to connect the form plugin to the print form.
+	 */	
+	var hookForm = function () {
+		var o = {
+	   		url:			'../print/printFactory.php', 
+	   		type:			'post',
+	   		dataType:		'json',
+	   		beforeSubmit: 	validate,
+	   		success:    	showResult
+		};
+		$("#"+myId+"_form").ajaxForm(o);
+	};
+	
+	/**
+	 * Change status of the working elements. These should begin with "$myId_working" 
+	 *
+	 * @param {String} newStatus either "hide or "show"
+	 */
+	var showHideWorking = function (newStatus) {
+		if (newStatus=="hide") {
+	    	$("[id^='"+myId+"_working']").hide();
+		}
+	    else {
+	    	$("[id^='"+myId+"_working']").show();	
+		}
+	};
+	
+	/**
+	 * update form values helper function
+	 *
+	 */
+	var updateFormField = function (formData, key, value) {
+		for(var j=0; j < formData.length; j++){
+			if (formData[j].name == key) {
+				formData[j].value = value;
+				break;
+			}
+		}	
+	};
+
+	var getCurrentResolution = function (type) {
+
+		// default resolution is 72 dpi
+		var dpi = 72;
+
+		// set resolution according to map configuration in template
+		for (var i in actualConfig.pages) {
+			var page = actualConfig.pages[i];
+			for (var j in page.elements) {
+				var el = page.elements[j];
+				if (type === el.type && typeof el.res_dpi === "number") {
+					dpi = el.res_dpi;
+				}
+			}
+		}
+		// set resolution according to resolution select box (if present)
+
+		// check if hq print is requested
+		var resolutionControl = null;
+		for (var i in actualConfig.controls) {
+			var c = actualConfig.controls[i];
+			try {
+				for (var j in c.pageElementsLink) {
+					if (c.pageElementsLink[j] === "res_dpi") {
+						resolutionControl = typeof c.id === "string" &&
+							c.id.length > 0 ? $("#" + c.id) : null;
+					}
+				}
+			}
+			catch (e) {
+			}
+		}
+		if (resolutionControl !== null && resolutionControl.size() === 1) {
+			dpi = resolutionControl.val();
+		}
+		return parseInt(dpi, 10);
+	};
+
+	var replaceMapFileForHighQualityPrint = function (currentMapUrl, type) {
+		var dpi = getCurrentResolution(type);
+		// replace map file with hq map file (if configured)
+		var hqmapfiles = $.isArray(options.highqualitymapfiles) ?
+			options.highqualitymapfiles : [];
+		for (var i = 0; i < hqmapfiles.length; i++) {
+			var exp = new RegExp(hqmapfiles[i].pattern);
+			if (hqmapfiles[i].pattern && typeof currentMapUrl === "string" && currentMapUrl.match(exp)) {
+				// check if mapping in current resolution exists
+				var resolutions = hqmapfiles[i].replacement;
+				var resolutionExists = false;
+				for (var r in resolutions) {
+					if (parseInt(r, 10) === dpi) {
+						resolutionExists = true;
+					}
+				}
+				if (resolutionExists) {
+					// replace with hqmapfile
+					var hqmapfile = resolutions[dpi];
+					currentMapUrl = currentMapUrl.replace(exp, hqmapfile);
+				}
+			}
+		}
+		return currentMapUrl;
+	};
+
+	/**
+	 * Validates and updates form data values.
+	 * Adds the elements before the submit button.
+	 *
+	 * @see jquery.forms#beforeSubmitHandler
+	 */
+	var validate = function (formData, jqForm, params) {
+		showHideWorking("show");
+		
+		// map urls
+		var ind = getMapObjIndexByName(myTarget);
+		var f = jqForm[0];
+		f.map_url.value = '';
+		
+		var scale = f.scale.value || mb_mapObj[ind].getScale();
+		scale = parseInt(scale, 10);
+		
+		var legendUrlArray = [];
+		f.overview_url.value = '';
+		for(var i=0; i < mb_mapObj[ind].wms.length; i++){
+			var currentWms = mb_mapObj[ind].wms[i];
+			if(mb_mapObj[ind].wms[i].gui_wms_visible > 0){
+				if (mb_mapObj[ind].wms[i].mapURL != false && mb_mapObj[ind].wms[i].mapURL != 'false' && mb_mapObj[ind].wms[i].mapURL != ''){   
+					if(f.map_url.value != ""){
+						f.map_url.value += '___';
+					}      
+					var currentMapUrl = mb_mapObj[ind].getMapUrl(i, mb_mapObj[ind].getExtentInfos(), scale);
+					
+					currentMapUrl = replaceMapFileForHighQualityPrint(currentMapUrl, "map");
+					f.map_url.value += currentMapUrl
+
+					var wmsLegendObj = [];
+					
+					var layers = currentWms.getLayers(mb_mapObj[ind], scale);
+					for (var j = 0; j < layers.length; j++) {
+						var currentLayer = currentWms.getLayerByLayerName(layers[j]);
+						// TODO: add only visible layers
+						var isVisible = (currentLayer.gui_layer_visible === 1);
+						var hasNoChildren = (!currentLayer.has_childs);
+						if (isVisible && hasNoChildren){
+							var layerLegendObj = {};
+							layerLegendObj.name = currentLayer.layer_name;
+							layerLegendObj.title = currentWms.getTitleByLayerName(currentLayer.layer_name);
+							var layerStyle = currentWms.getCurrentStyleByLayerName(currentLayer.layer_name);
+							if (layerStyle === false) {
+								layerStyle = "default";
+							}
+							layerLegendObj.legendUrl = currentWms.getLegendUrlByGuiLayerStyle(currentLayer.layer_name, layerStyle);
+							if (layerLegendObj.legendUrl !== false) {
+								wmsLegendObj.push(layerLegendObj);
+							}
+						}
+					}
+					if (wmsLegendObj.length > 0) {
+						var tmpObj = {};
+						tmpObj[currentWms.wms_currentTitle] = wmsLegendObj;
+						legendUrlArray.push(tmpObj);
+					}
+				}
+			}
+		}
+		updateFormField(formData, "legend_url", $.toJSON(legendUrlArray));
+		updateFormField(formData, "map_url", f.map_url.value);
+		updateFormField(formData, "scale", scale);
+		
+		//overview_url
+		var ind_overview = getMapObjIndexByName('overview');
+		if(mb_mapObj[ind_overview].mapURL != false ){
+		    var overviewUrl = mb_mapObj[ind_overview].mapURL;
+			overviewUrl = $.isArray(overviewUrl) ? overviewUrl[0] : overviewUrl;
+
+		    f.overview_url.value = replaceMapFileForHighQualityPrint(overviewUrl, "overview");
+
+			updateFormField(formData, "overview_url", f.overview_url.value);
+		}
+		
+		updateFormField(formData, "map_scale", mb_getScale(myTarget));
+		// write the measured coordinates
+		if (typeof(mod_measure_RX) !== "undefined") {
+			var tmp_x = '';
+			var tmp_y = '';
+			for(i = 0; i < mod_measure_RX.length; i++) {
+				if(tmp_x != '') {
+					tmp_x += ',';
+				}
+				tmp_x += mod_measure_RX[i];
+			}
+			for(i = 0; i < mod_measure_RY.length; i++) {
+				if(tmp_y != '') {
+					tmp_y += ',';
+				}
+				tmp_y += mod_measure_RY[i];
+			}
+			updateFormField(formData, "measured_x_values", tmp_x);
+			updateFormField(formData, "measured_y_values", tmp_y);
+		}	
+		
+		
+		if (f.map_url.value!="") {
+			//return true;
+		} else {
+		    showHideWorking("hide");
+			return false;
+		}
+	};
+
+	/**
+ 	 * Method: showResult
+	 * 
+	 * load the generated PDF from the returned URL as an attachment, 
+	 * that triggers a download popup or is displayed in PDF plugin.
+	 */		
+	var showResult = function (res, text) {
+		if (text == 'success') {
+			var $downloadFrame = $("#" + myId + "_frame");
+			if ($downloadFrame.size() === 0) {
+				$downloadFrame = $(
+					"<iframe id='" + myId + "_frame' name='" + 
+					myId + "_frame' width='0' height='0' style='display:none'></iframe>"
+				).appendTo("body");
+			}
+			if ($.browser.msie && $.browser.version === "6.0") {
+				var newWin = window.open(stripslashes(res.outputFileName), "Druckausgabe", "width=200,height=200,left=700,top=200,resizable=yes");
+			}
+			else {
+				window.frames[myId + "_frame"].location.href = 
+					stripslashes(res.outputFileName);
+			}
+			showHideWorking("hide");	
+		}
+		else {
+			/* something went wrong */
+			$("#"+myId+"_result").html(text);
+		}
+	};
+	
+	/**
+	 * Generates form elements as specified in the config controls object.
+	 * Adds the elements before the submit button.
+	 * 
+	 * @param {Object} json the config object in json
+	 */
+	var buildForm = function () {
+		$(".print_option_dyn").remove();
+		var str = "";
+		for (var item in actualConfig.controls) {
+			var element = actualConfig.controls[item];
+			var element_id = myId + "_" + element.id;
+			if (element.type != "hidden") {
+				str += '<div class="print_option_dyn">\n';	
+				str += '<label class="print_label" for="'+element.id+'">'+element.label+'</label>\n';
+			} else {
+				str += '<div class="print_option_dyn" style="display:none;">\n';	
+			}
+			switch (element.type) {
+				case "text":
+					str += '<input type="'+element.type+'" name="'+element.id+'" id="'+element.id+'" size="'+element.size+'"><br>\n';
+					break;
+				case "hidden":
+					str += '<input type="'+element.type+'" name="'+element.id+'" id="'+element.id+'">\n';
+					break;				
+				case "textarea":
+					str += '<textarea id="'+element.id+'" name="'+element.id+'" size="'+element.size+'"></textarea><br>\n';
+					break;				
+				case "select":
+					str += '<select id="'+element.id+'" name="'+element.id+'" size="1">\n';
+					for (var option_index in element.options) {
+						option = element.options[option_index];
+						str += '<option value="'+option.value+'">'+option.label+'</option>\n';
+					}
+					str += '</select><br>\n';
+					break;
+			}
+			str += '</div>\n';
+		}
+		if (str) {
+			$("#" + myId + "_formsubmit").before(str);
+			$("#scale").keydown(function (e) {
+				if (e.keyCode !== 13) {
+					return;
+				}
+				var scale = parseInt(this.value, 10);
+				if (isNaN(scale) || typeof printBox === "undefined") {
+					return false;
+				}
+				printBox.setScale(scale);
+				return false;
+			});
+		}
+	};
+	
+	/**
+	 * Generates the configuration select element from the gui element vars
+	 * mbPrintConfigFilenames and mbPrintConfigTitles
+	 */
+	var buildConfigSelector = function () {
+		var str = "";
+		str += '<label class="print_label" for="printPDF_template">Vorlage</label>\n';
+		str += '<select id="printPDF_template" name="printPDF_template" size="1">\n';
+		for (var i = 0; i < mbPrintConfigFilenames.length; i++) {
+			str += '<option value="'+mbPrintConfigFilenames[i]+'">'+mbPrintConfigTitles[i]+'</option>\n';
+		}
+		str += '</select><img id="printPDF_handle" src="../print/img/shape_handles.png" title="Use printbox">\n';
+		if (str) {
+			$("#printPDF_selector").append(str).find("#printPDF_template").change(function () {
+				printObj.loadConfig(mbPrintConfigFilenames[this.selectedIndex], function () {
+					printObj.createPrintBox()
+				});			
+			});
+			$("#printPDF_handle").click(function () {
+				printObj.createPrintBox();
+			});
+			$("#printPDF_working").bgiframe({ 
+				src: "BLOCKED SCRIPT'&lt;html&gt;&lt;/html&gt;';",
+				width: 200,
+				height: 200
+			});
+		}
+	};
+	
+	var stripslashes = function ( str ) {
+	    return (str+'').replace(/\0/g, '0').replace(/\\([\\'"])/g, '$1');
+	};
+
+};
+
+var printObj = new PrintPDF(options);

Modified: branches/mapbender/http/print/mapbender_template.json
===================================================================
--- trunk/mapbender/http/print/mapbender_template.json	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/http/print/mapbender_template.json	2010-09-29 11:31:10 UTC (rev 6957)
@@ -29,7 +29,7 @@
     			"value" : "72",
     			"label" : "normal (72)"
     			},{
-    			"value" : "144",
+    			"value" : "288",
     			"label" : "hoch (dpi)"
     			}
     		]

Deleted: branches/mapbender/http/print/printFactory.php
===================================================================
--- trunk/mapbender/http/print/printFactory.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/http/print/printFactory.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,25 +0,0 @@
-<?php
-
-require_once dirname(__FILE__) . "/../php/mb_validateSession.php";
-require_once dirname(__FILE__) . "/classes/factoryClasses.php";
-
-$pf = new mbPdfFactory();
-
-
-$confFile = basename($_REQUEST["printPDF_template"]);
-if (!preg_match("/^[a-zA-Z0-9_-]+(\.[a-zA-Z0-9]+)$/", $confFile) || 
-	!file_exists($_REQUEST["printPDF_template"])) {
-
-	$errorMessage = _mb("Invalid configuration file");
-	echo htmlentities($errorMessage, ENT_QUOTES, CHARSET);
-	$e = new mb_exception($errorMessage);
-	die;
-}
-
-$pdf = $pf->create($_REQUEST["printPDF_template"]);
-
-$pdf->render();
-$pdf->save();
-
-print $pdf->returnAbsoluteUrl();
-?>
\ No newline at end of file

Copied: branches/mapbender/http/print/printFactory.php (from rev 6946, trunk/mapbender/http/print/printFactory.php)
===================================================================
--- branches/mapbender/http/print/printFactory.php	                        (rev 0)
+++ branches/mapbender/http/print/printFactory.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -0,0 +1,31 @@
+<?php
+
+require_once dirname(__FILE__) . "/../php/mb_validateSession.php";
+require_once dirname(__FILE__) . "/classes/factoryClasses.php";
+
+$pf = new mbPdfFactory();
+
+
+$confFile = basename($_REQUEST["printPDF_template"]);
+if (!preg_match("/^[a-zA-Z0-9_-]+(\.[a-zA-Z0-9]+)$/", $confFile) || 
+	!file_exists($_REQUEST["printPDF_template"])) {
+
+	$errorMessage = _mb("Invalid configuration file");
+	echo htmlentities($errorMessage, ENT_QUOTES, CHARSET);
+	$e = new mb_exception($errorMessage);
+	die;
+}
+
+$pdf = $pf->create($_REQUEST["printPDF_template"]);
+
+$pdf->render();
+try {
+	$pdf->save();
+}
+catch (Exception $e) {
+	new mb_exception($e->message);
+	die;
+}
+
+print $pdf->returnAbsoluteUrl();
+?>
\ No newline at end of file

Deleted: branches/mapbender/http/tmp/ReadMe.txt
===================================================================
--- trunk/mapbender/http/tmp/ReadMe.txt	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/http/tmp/ReadMe.txt	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1 +0,0 @@
-this is a directory for temporary files
\ No newline at end of file

Modified: branches/mapbender/lib/class_GetApi.php
===================================================================
--- trunk/mapbender/lib/class_GetApi.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/lib/class_GetApi.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -13,6 +13,7 @@
 class GetApi {
 	private $layers = array();
 	private $featuretypes = array();
+	private $wmc = array();
 	
 	/**
 	 * @param array $input
@@ -23,11 +24,15 @@
 		}
 		foreach ($input as $key => $value) {
 			switch ($key) {
+				case "WMC":
+					$this->wmc = $this->normalizeWmcInput($value);
+					break;
 				case "LAYER":
 					$this->layers = $this->normalizeLayerInput($value);
 					break;
 				case "FEATURETYPE":
 					$this->featuretypes = $this->normalizeFeaturetypeInput($value);
+					break;
 			}
 		}
 	}
@@ -45,9 +50,42 @@
 	 * @return array
 	 */
 	public function getFeaturetypes () {
-		return $this->featuretypes;	
+		return $this->featuretypes;
 	}
 
+	/**
+	 * Returns an array of wmc
+	 * @return array
+	 */
+	public function getWmc () {
+		return $this->wmc;
+	}
+
+	// for possible inputs see http://www.mapbender.org/GET-Parameter#WMC
+	private function normalizeWmcInput ($input) {
+		// assume WMC=12,13,14
+		$inputArray = split(",", $input);
+		$input = array();
+		$i = 0;
+		foreach ($inputArray as $id) {
+			if (is_numeric($id)) {
+				$input[$i++]["id"] = $id;
+			}
+		}
+
+// check if each layer has at least an id, if not, delete
+		$i = 0;
+		while ($i < count($input)) {
+			if (!is_array($input[$i]) || !isset($input[$i]["id"]) || !is_numeric($input[$i]["id"])) {
+				array_splice($input, $i, 1);
+				continue;
+			}
+			$input[$i]["id"] = intval($input[$i]["id"]);
+			$i++;
+		}
+		return $input;
+	}
+
 	// for possible inputs see http://www.mapbender.org/GET-Parameter#LAYER
 	// for test cases, see http://www.mapbender.org/Talk:GET-Parameter#LAYER
 	private function normalizeLayerInput ($input) {
@@ -83,7 +121,7 @@
 		}
 		else {
 			// assume LAYER=12,13,14
-			$inputArray = split(",", $input); 
+			$inputArray = split(",", $input);
 			$input = array();
 			$i = 0;
 			foreach ($inputArray as $id) {

Modified: branches/mapbender/lib/class_Mapbender.php
===================================================================
--- trunk/mapbender/lib/class_Mapbender.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/lib/class_Mapbender.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -6,21 +6,21 @@
  * Window - Preferences - PHPeclipse - PHP - Code Templates
  */
 require_once(dirname(__FILE__)."/class_Mapbender_session.php");
-require_once(dirname(__FILE__)."/class_Singleton.php");
+require_once(dirname(__FILE__)."/class_Mapbender_database.php");
  
- class Mapbender extends Singleton{
+ class Mapbender {
  	
- 	protected function __construct() {
+	protected function __construct() {
  	}
  
  	public static function session() {	
  		return Mapbender_session::singleton();
  	}
- 	
- 	public static function singleton() {
-        return parent::singleton(__CLASS__);
-    }
-	
+
+	public static function db() {
+		return Mapbender_database::singleton()->db();
+	}
+
 	public static function postgisAvailable () {
 		$sql = "Select postgis_full_version()";
 		$res = db_query($sql);

Modified: branches/mapbender/lib/class_Mapbender_session.php
===================================================================
--- trunk/mapbender/lib/class_Mapbender_session.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/lib/class_Mapbender_session.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -7,11 +7,11 @@
  require_once(dirname(__FILE__)."/../http/classes/class_mb_exception.php");
  require_once(dirname(__FILE__)."/../http/classes/class_mb_warning.php");
  require_once(dirname(__FILE__)."/../http/classes/class_mb_notice.php");
- require_once(dirname(__FILE__)."/class_Singleton.php");
 
- class Mapbender_session extends Singleton{
+ class Mapbender_session {
  	
- 	private $id ;
+ 	private $id;
+	private static $instance;
  	
  	/**
 	 * @constructor
@@ -21,9 +21,11 @@
  		new mb_notice("session.mapbender_session.instantiated ... ");
  	}
 
- 	public static function singleton()
-    {
-        return parent::singleton(__CLASS__);
+ 	public static function singleton() {
+		if (!isset(self::$instance)) {
+			self::$instance = new Mapbender_session();
+		}
+		return self::$instance;
     }
  	
  	/**

Deleted: branches/mapbender/lib/class_Singleton.php
===================================================================
--- trunk/mapbender/lib/class_Singleton.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/lib/class_Singleton.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,23 +0,0 @@
-<?php
-class Singleton
-{
-   // Hold an instance of the class
-   private static $instance;
- 
-   // A private constructor; prevents direct creation of object
-   private function __construct()
-   {
-       echo 'I am constructed';
-   }
-
-   // The singleton method
-   public static function singleton($classname)
-   {
-       if (!isset(self::$instance)) {
-           self::$instance = new $classname;
-       }
-
-       return self::$instance;
-   }
-}
-?>
\ No newline at end of file

Deleted: branches/mapbender/lib/database-mysql.php
===================================================================
--- trunk/mapbender/lib/database-mysql.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/lib/database-mysql.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,426 +0,0 @@
-<?php
-# $Id$
-# http://www.mapbender.org/index.php/database-mysql.php
-# 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.
-
-/**
- * \file
- * \brief MySQL database connection/querying layer
- * 
- * MySQL database connection/querying layer
- *
- * example:
- * \code
- * include_once(dirname(__FILE__)."/afwphp/database-mysql.php");  
- * $sys_dbhost=...                            
- * $sys_dbuser=...                            
- * $sys_dbpasswd=...                           
- * $sys_dbname=...                            
- *                                             
- * db_connect();                               
- * ...                                         
- * $rs = db_query("select * from table");      
- * while($row = db_fetch_array($rs));
- *  ...
- * \endcode
- */
-
-/**
- * System-wide database type
- *
- * @var	constant		$sys_database_type
- */
-$sys_database_type='mysql';
-
-/**
- *  Connect to the database
- *
- *  Notice the global vars that must be set up
- *  Notice the global vars $sys_dbhost,$sys_dbuser,$sys_dbpasswd,$sys_dbname that must be set up 
- *  in other functions in this library
- */
-include_once(dirname(__FILE__)."/../http/classes/class_mb_exception.php");
-include_once(dirname(__FILE__)."/../http/classes/class_checkInput.php");
-function db_escapestring($unescaped_string){
-	return @mysql_escape_string($unescaped_string);
-}
-function db_escape_string($unescaped_string){
-	return @mysql_escape_string($unescaped_string);
-}
-
-
-function db_connect($DBSERVER="",$OWNER="",$PW="") {
-	global $sys_dbhost,$sys_dbuser,$sys_dbpasswd,$sys_dbname,
-		$conn,$conn_update,$sys_db_use_replication,$sys_dbreadhost;
-
-	
-	if ($DBSERVER)
-		$sys_dbhost = $DBSERVER; 
-	if ($OWNER)
-		$sys_dbuser = $OWNER; 
-	if ($PW)
-		$sys_dbpasswd = $PW; 
-	if (PORT!=''){
-		$sys_dbport = ':'.PORT;
-	}
-	else{
-		$sys_dbport = '';
-	} 
-		
-	if ($sys_db_use_replication) {
-		//
-		//  if configured for replication, $conn is the read-only host
-		//  we do not connect to update server until needed
-		//
-		$conn = mysql_connect($sys_dbreadhost,$sys_dbuser,$sys_dbpasswd);
-		$conn_update= mysql_connect($sys_dbhost,$sys_dbuser,$sys_dbpasswd);
-	} 
-	else {
-		# Create a new connection...
-		if( version_compare( PHP_VERSION, '4.2.0', 'ge' ) ) {
-			$conn = mysql_connect( $sys_dbhost,$sys_dbuser,$sys_dbpasswd, true );
-		} 
-		else {
-			# On PHP 4.1 the new_link parameter is not available. We cannot
-			# guarantee that we'll actually get a new connection, and this
-			# may cause some operations to fail possibly.
-			$conn = mysql_connect( $sys_dbhost,$sys_dbuser,$sys_dbpasswd );
-		}
-	
-	}
-
-	if ($sys_dbname)
-		@mysql_select_db($sys_dbname);
-	return $conn;
-}
-
-function db_select_db($DB,$con="") {
-	global $conn,$sys_dbname; 
-	$sys_dbname = $DB;	
-	$_con = $con ? $con : $conn;
-	$ret = @mysql_select_db($sys_dbname,$_con);
-	if ($ret){
-		return true;
-	}
-	else {
-		return false;
-	}
-//	echo "$ret=@mysql_select_db($sys_dbname,$_con);";
-}
-
-/**
- *  Query the database
- *
- *  @param		$qstring (string)	SQL statement
- *  @param		$limit (int)		How many rows do you want returned
- *  @param		$offset (int)		Of matching rows, return only rows starting here
- */
-function db_query($qstring,$limit='-1',$offset=0) {
-	global $QUERY_COUNT,$sys_db_use_replication,$sys_db_is_dirty,$DB,
-		$sys_dbname,$conn,$conn_update,$sys_dbhost,$sys_dbuser,$sys_dbpasswd;
-
-	$QUERY_COUNT++;
-	if(!$sys_dbname && $DB)
-	$sys_dbname = $DB;
-	db_select_db($sys_dbname,$conn);
-	
-	if ($limit > 0) {
-		if (!$offset || $offset < 0) {
-			$offset=0;
-		}
-		$qstring=$qstring." LIMIT $offset,$limit";
-	}
-//	if ($GLOBALS['IS_DEBUG'])
-		$GLOBALS['G_DEBUGQUERY'] .= $qstring . "<P><BR>\n";
-
-	//
-	//are we configured to try to use replication?
-	//
-	if ($sys_db_use_replication) {
-		//
-		//if we haven't yet done an insert/update, 
-		//read from the read-only db
-		//
-		if (!$sys_db_is_dirty && mb_eregi("^( )*(select)",$qstring)) {
-			if ($QUERY_COUNT%3==0) {
-				// 1/3rd of read queries go to master for now
-				return @mysql_db_query($sys_dbname,$qstring,$conn_update);
-			} else {
-				return @mysql_db_query($sys_dbname,$qstring,$conn);
-			}
-		} else {
-			//must be an update/insert/delete query - go to master server
-			$sys_db_is_dirty=true;
-			return @mysql_db_query($sys_dbname,$qstring,$conn_update);
-		}
-	} else {
-		$ret = @mysql_db_query($sys_dbname,$qstring,$conn);
-//		echo "@mysql_db_query($sys_dbname,$qstring,$conn); ret=$ret<br>";
-		if(!$ret){
-			$e = new mb_exception("db_query($qstring)=$ret db_error=".db_error());
-		}
-		return $ret;
-	}
-	//echo "SQL__".$qstring;
-}
-/**
- *  prepare and query the database
- *
- *  @param		$qstring (string)	SQL statement
- *  @param		$params (array string params)		
- *  @param		$types (array string types)		
- */
-function db_prep_query($qstring, $params, $types){
-	$orig_qstring = $qstring;
-	$ci = new checkInput($qstring,$params,$types);
-	$params = $ci->v; 
-	for ($i=0; $i<count($params); $i++){
-		$needle = "$".strval($i+1);
-		$tmp = '';
-		if($params[$i] !== NULL){
-			if($types[$i] == 's'){ $tmp .= "'"; }
-			$tmp .= $params[$i];
-			if($types[$i] == 's'){ $tmp .= "'"; }
-		}
-		else{
-			$tmp .= "NULL";
-		}
-		$posa = mb_strpos($qstring, $needle);
-		if(!$posa) { 
- 			$e = new mb_exception("Error while preparing statement in ".$_SERVER['SCRIPT_FILENAME']. ": Sql :". $orig_qstring .",Error: parameter '$needle' not found ");
- 		}
-		$posb = mb_strlen($needle);
-		$qstring = mb_substr($qstring,0,$posa).$tmp.mb_substr($qstring,($posa + $posb));	
-	}
-	$r = db_query($qstring);
-	return $r;
-}
-/**
- *	Begin a transaction
- *
- *	Begin a transaction for databases that support them
- *	may cause unexpected behavior in databases that don't
- */
-function db_begin() {
-	return db_query("BEGIN WORK");
-}
-
-/**
- * Commit a transaction
- *
- * Commit a transaction for databases that support them
- * may cause unexpected behavior in databases that don't
- */
-function db_commit() {
-	return db_query("COMMIT");
-}
-
-/**
- * Roll back a transaction
- *
- * Rollback a transaction for databases that support them
- * may cause unexpected behavior in databases that don't
- */
-function db_rollback() {
-	$str = db_error();
-	db_query("ROLLBACK");
-	die('sql error: ' . $str . " ROLLBACK performed....");
-}
-
-/**
- * Returns the number of rows in this result set
- *
- *  @param		$qhandle (string)	Query result set handle
- * (!!! Deprecated? Changed the MySQL-Command to match the current syntax)
- */
-function db_numrows($qhandle) {
-	// return only if qhandle exists, otherwise 0
-	if ($qhandle) {
-		return @mysql_num_rows($qhandle);
-	} else {
-		return 0;
-	}
-}
-/**
- * Returns the number of rows in this result set
- *
- *  @param		$qhandle (string)	Query result set handle
- * php 3,4,5
- */
-function db_num_rows($qhandle) {
-	// return only if qhandle exists, otherwise 0
-	if ($qhandle) {
-		return @mysql_num_rows($qhandle);
-	} else {
-		return 0;
-	}
-}
-
-/**
- *  Frees a database result properly 
- *
- *  @param	$qhandle (string)	Query result set handle
- */
-function db_free_result($qhandle) {
-	return @mysql_free_result($qhandle);
-}
-
-/**
- *  Reset a result set.
- *
- *  Reset is useful for db_fetch_array sometimes you need to start over
- *
- *  @param		$qhandle (string)	Query result set handle
- *  @param		$row (int)		Row number
- */
-function db_reset_result($qhandle,$row=0) {
-	return mysql_data_seek($qhandle,$row);
-}
-
-/**
- *  Returns a field from a result set
- *
- *  @param		$qhandle (string)	Query result set handle
- *  @param		$row (int)		Row number
- *  @param		$field (string)	Field name
- */
-function db_result($qhandle,$row,$field) {
-	return @mysql_result($qhandle,$row,$field);
-}
-
-/**
- *  Returns the number of fields in this result set
- *
- *  @param		$lhandle (string)	Query result set handle
- *  (!!! Deprecated? Changed the MySQL-Command to match the current syntax)
- */
-function db_numfields($lhandle) {
-	return @mysql_num_fields($lhandle);
-}
-
-/**
- *  Returns the number of fields in this result set
- *
- *  @param		$lhandle (string)	Query result set handle
- * php 3,4,5
- */
-function db_num_fields($lhandle) {
-	return @mysql_num_fields($lhandle);
-}
-
-/**
- *  Returns the number of rows changed in the last query
- *
- *  @param		$lhandle	(string) Query result set handle
- *  @param		$fnumber (int)	Column number
- */
-function db_fieldname($lhandle,$fnumber) {
-	   return @mysql_fieldname($lhandle,$fnumber);
-}
-
-/**
- *  Returns the number of rows changed in the last query
- *
- *  @param		$qhandle (string)	Query result set handle
- */
-function db_affected_rows($qhandle) {
-	return @mysql_affected_rows();
-}
-
-/**
- *  Fetch an array
- *
- *  Returns an associative array from 
- *  the current row of this database result
- *  Use db_reset_result to seek a particular row
- *
- *  @param		$qhandle (string)	Query result set handle
- */
-function db_fetch_array($qhandle) {
-	return @mysql_fetch_array($qhandle);
-}
-
-/**                                                       
- * fetch a row into an array 
- * 
- *  @param		$qhandle (string)	Query result set handle
- *  @param		$fnumber (int)	Column number
- */
-function db_fetch_row($qhandle,$fnumber=0) {
-	  return @mysql_fetch_row($qhandle);
-}
-
-/**
- *  Returns the last primary key from an insert
- *
- *  @param		$qhandle (string)	Query result set handle
- *  @param		$table_name (string)	Is the name of the table you inserted into
- *  @param		$pkey_field_name (string)	Is the field name of the primary key
- */
-function db_insertid($qhandle="",$table_name="",$pkey_field_name="") {
-	return @mysql_insert_id();
-}
-
-function db_insert_id($qhandle="",$table_name="",$pkey_field_name="") {
-	return @mysql_insert_id();
-}
-
-/**
- * Returns the last error from the database
- */
-function db_error() {
-	return @mysql_error();
-}
-
-/**
- * Get the flags associated with the specified field in a result 
- *
- *  @param		$lhandle	(string) Query result set handle
- *  @param		$fnumber (int)	Column number
- *
- * 					Examples: "not_null", "primary_key", "unique_key", "multiple_key",					 
- *                    "blob", "unsigned", "zerofill","binary", "enum",                  
- *                    "auto_increment", "timestamp"                                     
- */
-
-function db_field_flags($lhandle,$fnumber) {
-	   return @mysql_field_flags($lhandle,$fnumber);
-}
-
-/**                                                       
- * Get the type of the specified field  
- *
- *  @param		$lhandle	(string) Query result set handle
- *  @param		$fnumber (int)	Column number
- */                                                       
-                                                          
-function db_field_type($lhandle,$fnumber) {               
-	   return @mysql_field_type($lhandle,$fnumber);         
-}                                                         
-
-/**                                                       
- * Get the length of the specified field                                                            
- *
- *  @param		$lhandle	(string) Query result set handle
- *  @param		$fnumber (int)	Column number
- */                                                       
-                                                          
-function db_field_len($lhandle,$fnumber) {               
-	   return @mysql_field_len($lhandle,$fnumber);         
-} 
-
-?>

Deleted: branches/mapbender/lib/database-mysqli.php
===================================================================
--- trunk/mapbender/lib/database-mysqli.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/lib/database-mysqli.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,485 +0,0 @@
-<?php
-/**
- * System-wide database type
- *
- * @var	constant		$sys_database_type
- */
-$sys_database_type='mysqli';
-
-/**
- *  Connect to the database
- *
- *  Notice the global vars that must be set up
- *  Notice the global vars $sys_dbhost,$sys_dbuser,$sys_dbpasswd,$sys_dbname that must be set up 
- *  in other functions in this library
- */
-include_once(dirname(__FILE__)."/../../http/classes/class_mb_exception.php");
-include_once(dirname(__FILE__)."/../../http/classes/class_checkInput.php");
-function db_escapestring($unescaped_string){
-	global $conn;
-	return mysqli_escape_string($conn, $unescaped_string);
-}
-function db_escape_string($unescaped_string){
-	global $conn;
-	return mysqli_escape_string($conn, $unescaped_string);
-}
-
-function db_connect($DBSERVER="",$OWNER="",$PW="") {
-	global $sys_dbhost,$sys_dbuser,$sys_dbpasswd,$sys_dbname,
-		$conn,$conn_update,$sys_db_use_replication,$sys_dbreadhost;
-
-	
-	if ($DBSERVER)
-		$sys_dbhost = $DBSERVER; 
-	if ($OWNER)
-		$sys_dbuser = $OWNER; 
-	if ($PW)
-		$sys_dbpasswd = $PW; 
-	if (PORT!=''){
-		$sys_dbport = ':'.PORT;
-	}
-	else{
-		$sys_dbport = '';
-	} 
-		
-	if ($sys_db_use_replication) {
-		//
-		//  if configured for replication, $conn is the read-only host
-		//  we do not connect to update server until needed
-		//
-		$conn = mysqli_connect($sys_dbreadhost,$sys_dbuser,$sys_dbpasswd);
-		$conn_update=mysqli_connect($sys_dbhost,$sys_dbuser,$sys_dbpasswd);
-	} else {
-		$conn = mysqli_connect($sys_dbhost,$sys_dbuser,$sys_dbpasswd,$sys_dbname,intval($sys_dbport));
-		#echo "@mysql_pconnect($sys_dbhost.$sys_dbport,$sys_dbuser,$sys_dbpasswd)";
-	}
-	if ($sys_dbname)
-		mysqli_select_db($conn, $sys_dbname);
-	return $conn;
-}
-
-function db_select_db($DB,$con="") {
-	global $conn,$sys_dbname; 
-	$sys_dbname = $DB;	
-	$_con = $con ? $con : $conn;
-	$ret = mysqli_select_db($_con, $sys_dbname);
-	if ($ret){
-		return true;
-	}
-	else {
-		return false;
-	}
-//	echo "$ret=@mysql_select_db($sys_dbname,$_con);";
-}
-
-/**
- *  Query the database
- *
- *  @param		$qstring (string)	SQL statement
- *  @param		$limit (int)		How many rows do you want returned
- *  @param		$offset (int)		Of matching rows, return only rows starting here
- */
-function db_query($qstring,$limit='-1',$offset=0) {
-	/* Ausmisten! Der Code ist unübersichtlich, und bei manchen Zweigen ist nicht klar,
-	 * ob sie überhaupt ausgeführt werden...
-	 */
-	global $QUERY_COUNT,$sys_db_use_replication,$sys_db_is_dirty,$DB,
-		$sys_dbname,$conn,$conn_update,$sys_dbhost,$sys_dbuser,$sys_dbpasswd;
-
-	$QUERY_COUNT++;
-	if(!$sys_dbname && $DB)
-	$sys_dbname = $DB;
-	db_select_db($sys_dbname,$conn);
-	
-	if ($limit > 0) {
-		if (!$offset || $offset < 0) {
-			$offset=0;
-		}
-		$qstring=$qstring." LIMIT $offset,$limit";
-	}
-//	if ($GLOBALS['IS_DEBUG'])
-		$GLOBALS['G_DEBUGQUERY'] .= $qstring . "<P><BR>\n";
-
-	//
-	//are we configured to try to use replication?
-	//
-	if ($sys_db_use_replication) {
-		//
-		//if we haven't yet done an insert/update, 
-		//read from the read-only db
-		//
-		if (!$sys_db_is_dirty && mb_eregi("^( )*(select)",$qstring)) {
-			if ($QUERY_COUNT%3==0) {
-				// 1/3rd of read queries go to master for now
-				return mysqli_query($sys_dbname,$qstring,$conn_update);
-			} else {
-				return mysqli_query($sys_dbname,$qstring,$conn);
-			}
-		} else {
-			//must be an update/insert/delete query - go to master server
-			$sys_db_is_dirty=true;
-			return mysqli_query($sys_dbname,$qstring,$conn_update);
-		}
-	} else {
-		$ret = mysqli_query($conn, $qstring);
-//		echo "@mysql_db_query($sys_dbname,$qstring,$conn); ret=$ret<br>";
-		if(!$ret){
-			$e = new mb_exception("db_query($qstring)=$ret db_error=".db_error());
-		}
-		return $ret;
-	}
-	//echo "SQL__".$qstring;
-}
-
-function db_prepare_typestr($types) {
-	$result = '';
-	foreach ($types as $current_type) {
-		$result .= $current_type;
-	}
-	return $result;
-}
-	
-/**
- *  prepare and query the database
- *
- *  @param		$qstring (string)	SQL statement
- *  @param		$params (array string params)		
- *  @param		$types (array string types)		
- */
-function db_prep_query($qstring, $params, $types){
-	$orig_qstring = $qstring;
-	// Beim Umschreiben an der PostGreSQL-Bibliothek orientieren
-	global $conn, $stmt;
-
-	@mysqli_stmt_close($stmt);
-
-	$ci = new checkInput($qstring,$params,$types);
-	$params = $ci->v; 
-	if(PREPAREDSTATEMENTS == false){
-		for ($i=0; $i<count($params); $i++){
-			$needle = "$".strval($i+1);
-			$tmp = '';
-			if($params[$i] !== NULL){
-				if($types[$i] == 's'){ $tmp .= "'"; }
-				$tmp .= $params[$i];
-				if($types[$i] == 's'){ $tmp .= "'"; }
-			}
-			else{
-				$tmp .= "NULL";
-			}
-			$posa = mb_strpos($qstring, $needle);
-			if(!$posa) { 
- 				$e = new mb_exception("Error while preparing statement in ".$_SERVER['SCRIPT_FILENAME']. ": Sql :". $orig_qstring .",Error: parameter '$needle' not found ");
- 			}
-			$posb = mb_strlen($needle);
-			$qstring = mb_substr($qstring,0,$posa).$tmp.mb_substr($qstring,($posa + $posb));	
-		}
-		$r = db_query($qstring);
-		if(!$r){
-			$e = new mb_exception("Error while executing sql statement in ".$_SERVER['SCRIPT_FILENAME'].": Sql: ".$qstring.", Error: ".db_error());
-		}
-	}
-	else{
-		if (!$conn) {
-			$e = new mb_exception("Error while connecting to the database in ".$_SERVER['SCRIPT_FILENAME'].", Error: ".db_error());
-		}
-		echo $qstring;
-		$qstring = preg_replace('/\$[0-9]+/', '?', $qstring);
-		echo $qstring;
-		$stmt = mysqli_prepare($conn, $qstring);
-		//echo $result;
-		if(!$stmt){
-			echo "Error while preparing statement in ".$_SERVER['SCRIPT_FILENAME'].": Sql: ".$qstring.", Error: ".db_error();
-			$e = new mb_exception("Error while preparing statement in ".$_SERVER['SCRIPT_FILENAME'].": Sql: ".$qstring.", Error: ".db_error());
-		}
-		$type_string = '"';
-		$param_string = '';
-		$val_def_string = '';
-		$val_string = '';
-		/*for ($i = 0; $i < count($params); $i++) {
-			if ($params[$i] !== NULL) {
-				$type_string .= $types[$i];
-				if ($i > 0) {
-					$param_string .= ', ';
-					$val_string .= ', ';
-				}
-				
-				$param_string .= '"'.$params[$i].'"';
-				if ($types[$i] == 's')
-					$val_def_string .= '$val'.$i.'="'.$params[$i].'";';
-				else
-					$val_def_string .= '$val'.$i.'='.$params[$i].';';
-				$val_string .= '$val'.$i;
-				
-				//mysqli_stmt_bind_param($result, $types[$i], $params[$i]);
-			}
-		}*/
-		
-
-		for( $i = 0; $i < count($params); ++$i ) {
-			$thisVar = "v$i";
-			$variadicParams .= '$' . $thisVar;
-			if( $i != count($params) - 1 ) // don't append a comma on the last variable
-				$variadicParams .= ', ';
-			
-			$variadicExtVars[ $thisVar ] = $params[ $i ];
-		}
-		echo $variadicParams;
-		
-		$bindParamFunc = create_function( '$vars, &$stmt','extract( $vars ); $stmt->bind_param( \'' . implode($types) . '\', ' . $variadicParams . ' );' );
-		$bindParamFunc( $variadicExtVars, $stmt );
-		
-		/* $typeStr = call_user_func_array( 'db_prepare_typestr', $types );
-      	array_unshift( $params, $typeStr );
-      	call_user_func_array( array( 'mysqli_bind_param', $qstring  ), $params ); */		
-		
-		/*$type_string .= '"';
-		$eval_string = $val_def_string.'mysqli_stmt_bind_param($result,'.$type_string.','.$val_string.');';
-		$xyz=1;
-		//$eval_string = 'eead results, this function cancelcho $result;';
-		//$eval_string = 'return mysqli_stmt_bind_param($result,'.$type_string.',$xyz);';
-		echo $eval_string;
-		//echo "mysqli_stmt_bind_param($result,$type_string,$param_string)";
-		eval($eval_string);*/
-		$r = mysqli_stmt_execute($stmt);
-		if(!$r){
-			$e = new mb_exception("Error while executing prepared statement in ".$_SERVER['SCRIPT_FILENAME'].": Sql: ".$qstring.", Error: ".db_error());
-		}
-		$result2 = $stmt;
-	}	
-		
-	return $stmt;
-}
-/**
- *	Begin a transaction
- *
- *	Begin a transaction for databases that support them
- *	may cause unexpected behavior in databases that don't
- */
-function db_begin() {
-	return db_query("BEGIN WORK");
-}
-
-/**
- * Commit a transaction
- *
- * Commit a transaction for databases that support them
- * may cause unexpected behavior in databases that don't
- */
-function db_commit() {
-	return db_query("COMMIT");
-}
-
-/**
- * Roll back a transaction
- *
- * Rollback a transaction for databases that support them
- * may cause unexpected behavior in databases that don't
- */
-function db_rollback() {
-	$str = db_error();
-	db_query("ROLLBACK");
-	die('sql error: ' . $str . " ROLLBACK performed....");
-}
-
-/**
- * Returns the number of rows in this result set
- *
- *  @param		$qhandle (string)	Query result set handle
- */
-function db_num_rows($qhandle) {
-	// return only if qhandle exists, otherwise 0
-	if ($qhandle) {
-		return mysqli_num_rows($qhandle);
-	} else {
-		return 0;
-	}
-}
-
-/**
- *  Frees a database result properly 
- *
- *  @param	$qhandle (string)	Query result set handle
- */
-function db_free_result($qhandle) {
-	return mysqli_free_result($qhandle);
-}
-
-/**
- *  Reset a result set.
- *
- *  Reset is useful for db_fetch_array sometimes you need to start over
- *
- *  @param		$qhandle (string)	Query result set handle
- *  @param		$row (int)		Row number
- */
-function db_reset_result($qhandle,$row=0) {
-	return mysqli_data_seek($qhandle,$row);
-}
-
-/**
- *  Returns a field from a result set
- *
- *  @param		$qhandle (string)	Query result set handle
- *  @param		$row (int)		Row number
- *  @param		$field (string)	Field name
- */
-function db_result($qhandle,$row,$field) {
-	//return mysqli_result($qhandle,$row,$field);
-	if( mysqli_num_rows( $qhandle ) ) {
-		$x = 0;
-		while( $array = mysqli_fetch_array( $qhandle, MYSQLI_NUM ) ) {
-			if( $row == $x++ ) {
-				return isset( $array[ $field ] ) ? $array[ $field ] : '';
-			}
-		}
-	}	
-}
-
-/**
- *  Returns the number of fields in this result set
- *
- *  @param		$lhandle (string)	Query result set handle
- *  (!!! Deprecated? Changed the MySQL-Command to match the current syntax)
- */
-function db_numfields($lhandle) {
-	return mysqli_num_fields($lhandle);
-}
-
-/**
- *  Returns the number of fields in this result set
- *
- *  @param		$lhandle (string)	Query result set handle
- * php 3,4,5
- */
-function db_num_fields($lhandle) {
-	return mysqli_num_fields($lhandle);
-}
-
-/**
- *  Returns the number of rows changed in the last query
- *
- *  @param		$lhandle	(string) Query result set handle
- *  @param		$fnumber (int)	Column number
- */
-function db_fieldname($lhandle,$fnumber) {
-	   return mysql_field_name($lhandle,$fnumber);
-}
-
-/**
- *  Returns the number of rows changed in the last query
- *
- *  @param		$qhandle (string)	Query result set handle
- */
-function db_affected_rows($qhandle) {
-	return mysqli_affected_rows($qhandle);
-}
-
-/**
- *  Fetch an array
- *
- *  Returns an associative array from 
- *  the current row of this database result
- *  Use db_reset_result to seek a particular row
- *
- *  @param		$qhandle (string)	Query result set handle
- */
-function db_fetch_array($qhandle) {
-	global $conn;
-
-	$data = mysqli_stmt_result_metadata($qhandle);
-        $fields = array();
-        $out = array();
-
-        $fields[0] = &$qhandle;
-        $count = 1;
-
-        while($field = mysqli_fetch_field($data)) {
-            $fields[$count] = &$out[$field->name];
-            $count++;
-        }
-       
-        call_user_func_array(mysqli_stmt_bind_result, $fields);
-        mysqli_stmt_fetch($qhandle);
-        return (count($out) == 0) ? false : $out;
-        
-	/*if (!$qhandle)
-		return NULL;
-	else
-		return mysqli_fetch_array($conn); */
-}
-
-/**                                                       
- * fetch a row into an array 
- * 
- *  @param		$qhandle (string)	Query result set handle
- *  @param		$fnumber (int)	Column number
- */
-function db_fetch_row($qhandle,$fnumber=0) {
-	  global $stmt;
-	  if ($qhandle)
-	  	return mysqli_fetch_row($stmt);
-	  else
-	  	return NULL;
-}
-
-/**
- *  Returns the last primary key from an insert
- *
- *  @param		$qhandle (string)	Query result set handle
- *  @param		$table_name (string)	Is the name of the table you inserted into
- *  @param		$pkey_field_name (string)	Is the field name of the primary key
- */
-function db_insertid($qhandle="",$table_name="",$pkey_field_name="") {
-	return mysqli_insert_id();
-}
-
-function db_insert_id($qhandle="",$table_name="",$pkey_field_name="") {
-	return mysqli_insert_id();
-}
-
-/**
- * Returns the last error from the database
- */
-function db_error() {
-	global $conn;
-	return mysqli_error($conn);
-}
-
-/**
- * Get the flags associated with the specified field in a result 
- *
- *  @param		$lhandle	(string) Query result set handle
- *  @param		$fnumber (int)	Column number
- *
- * 					Examples: "not_null", "primary_key", "unique_key", "multiple_key",					 
- *                    "blob", "unsigned", "zerofill","binary", "enum",                  
- *                    "auto_increment", "timestamp"                                     
- */
-
-function db_field_flags($lhandle,$fnumber) {
-	   return mysqli_field_flags($lhandle,$fnumber);
-}
-
-/**                                                       
- * Get the type of the specified field  
- *
- *  @param		$lhandle	(string) Query result set handle
- *  @param		$fnumber (int)	Column number
- */                                                       
-                                                          
-function db_field_type($lhandle,$fnumber) {               
-	   return mysqli_field_type($lhandle,$fnumber);         
-}                                                         
-
-/**                                                       
- * Get the length of the specified field                                                            
- *
- *  @param		$lhandle	(string) Query result set handle
- *  @param		$fnumber (int)	Column number
- */                                                       
-                                                          
-function db_field_len($lhandle,$fnumber) {               
-	   return mysqli_field_len($lhandle,$fnumber);         
-} 
-?>
\ No newline at end of file

Modified: branches/mapbender/lib/database-pgsql.php
===================================================================
--- trunk/mapbender/lib/database-pgsql.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/lib/database-pgsql.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -62,6 +62,8 @@
 
 
 function db_connect($DBSERVER="",$OWNER="",$PW="") {
+	return Mapbender::db();
+/*
 	global $sys_dbhost,$sys_dbuser,$sys_dbpasswd,$sys_dbname,$db_debug;
 	global $conn,$conn_update,$DB;	
 
@@ -109,10 +111,12 @@
 #pg_error($conn);}	
 	
 	return $conn;
+ 
+ */
 }
 
 function db_select_db($DB,$con="") {
-	global $conn,$sys_dbname; 
+//	global $conn,$sys_dbname;
 #	$sys_dbname = DB;	
 #	$_con = $con ? $con : $conn;
 #	$ret = @mysql_select_db($sys_dbname,$_con);
@@ -127,6 +131,8 @@
  *  @param		$offset (int)		Of matching rows, return only rows starting here
  */
 function db_query($qstring) {
+	return Mapbender::db()->query($qstring);
+/*
 	global $sys_dbhost,$sys_dbuser,$sys_dbpasswd,$sys_dbname,$db_debug,
 		$conn,$conn_update,$QUERY_COUNT,$DBSERVER,$OWNER,$PW,$DB;
 	$QUERY_COUNT++;
@@ -135,7 +141,9 @@
 	if(!$ret){
 		$e = new mb_exception("db_query($qstring)=$ret db_error=".db_error());
 	}
-	return $ret;	
+	return $ret;
+
+ */
 }
 /**
  *  prepare and query the database
@@ -145,6 +153,34 @@
  *  @param		$types (array types as strings)		
  */
 function db_prep_query($qstring, $params, $types){
+	for ($i = 1; $i <= count($params); $i++) {
+		$needle = "$".strval($i);
+		$posa = mb_strpos($qstring, $needle);
+		if(!$posa) {
+			$e = new mb_exception("Error while preparing statement in ".$_SERVER['SCRIPT_FILENAME']. ": Sql :". $orig_qstring .",Error: parameter '$needle' not found ");
+		}
+		$posb = mb_strlen($needle);
+		$tmp = ":name$i";
+		$qstring = mb_substr($qstring,0,$posa).$tmp.mb_substr($qstring,($posa + $posb));
+	}
+	$statement = Mapbender::db()->prepare($qstring);
+	if (!$statement) {
+		$e = new mb_exception("Error while preparing statement in ".$_SERVER['SCRIPT_FILENAME']. ": Sql :". $orig_qstring .",Error: parameter '$needle' not found ");
+		return false;
+	}
+	for ($i = 1; $i <= count($params); $i++) {
+		$statement->bindValue(":name$i", $params[$i-1]);
+	}
+
+	if(!$statement->execute()){
+		$errorMsg = $statement->errorInfo();
+		$errorMsg = $errorMsg[2];
+		$e = new mb_exception("Error while preparing statement in ".$_SERVER['SCRIPT_FILENAME']. ": Sql :". $orig_qstring .",Error: parameter '$needle' not found ");
+		return false;
+	}
+	return $statement;
+
+/*
 	$orig_qstring = $qstring;
 	$ci = new checkInput($qstring,$params,$types);
 	$params = $ci->v; 
@@ -183,6 +219,7 @@
 		}
 	}	
 	return $r;
+*/
 }
 /**
  *	Begin a transaction
@@ -191,7 +228,8 @@
  *	may cause unexpected behavior in databases that don't
  */
 function db_begin() {
-	return db_query("BEGIN WORK");
+	return Mapbender::db()->beginTransaction();
+//	return db_query("BEGIN WORK");
 }
 
 /**
@@ -201,7 +239,8 @@
  * may cause unexpected behavior in databases that don't
  */
 function db_commit() {
-	return db_query("COMMIT");
+	return Mapbender::db()->commit();
+//	return db_query("COMMIT");
 }
 
 /**
@@ -211,9 +250,13 @@
  * may cause unexpected behavior in databases that don't
  */
 function db_rollback() {
+	return Mapbender::db()->rollback();
+/*
 	$str = db_error();
 	db_query("ROLLBACK");
 	die('sql error: ' . $str . " ROLLBACK performed....");
+
+ */
 }
 
 /**
@@ -222,12 +265,16 @@
  *  @param		$qhandle (string)	Query result set handle
  */
 function db_numrows($qhandle) {
+	return $qhandle->rowCount;
+/*
 	// return only if qhandle exists, otherwise 0
 	if ($qhandle) {
 		return @pg_numrows($qhandle);
 	} else {
 		return 0;
 	}
+ *
+ */
 }
 /**
  * Returns the number of rows in this result set
@@ -236,12 +283,15 @@
  *	php > 4.2
  */ 
 function db_num_rows($qhandle) {
+	return $qhandle->rowCount;
+/*
 	// return only if qhandle exists, otherwise 0
 	if ($qhandle) {
 		return @pg_num_rows($qhandle);
 	} else {
 		return 0;
 	}
+ */
 }
 
 /**
@@ -250,7 +300,7 @@
  *  @param	$qhandle (string)	Query result set handle
  */
 function db_free_result($qhandle) {
-	return @pg_freeresult($qhandle);
+//	return @pg_freeresult($qhandle);
 }
 
 /**
@@ -263,7 +313,7 @@
  */
 function db_reset_result($qhandle,$row=0) {
 #dummy
-	return 0;#mysql_data_seek($qhandle,$row);
+//	return 0;#mysql_data_seek($qhandle,$row);
 	
 }
 
@@ -275,7 +325,9 @@
  *  @param		$field (string)	Field name
  */
 function db_result($qhandle,$row,$field) {
-	return @pg_result($qhandle,$row,$field);
+	$arr = $qhandle->fetchAll();
+	return $arr[$row][$field];
+//	return @pg_result($qhandle,$row,$field);
 }
 
 /**
@@ -284,7 +336,7 @@
  *  @param		$lhandle (string)	Query result set handle
  */
 function db_numfields($lhandle) {
-	return @pg_numfields($lhandle);
+//	return @pg_numfields($lhandle);
 }
 
 /**
@@ -294,7 +346,8 @@
  *	php >4.2
  */
 function db_num_fields($lhandle) {
-	return @pg_num_fields($lhandle);
+	return $lhandle->columnCount();
+//	return @pg_num_fields($lhandle);
 }
 
 /**
@@ -304,7 +357,7 @@
  *  @param		$fnumber (int)	Column number
  */
 function db_fieldname($lhandle,$fnumber) {
-	   return @pg_fieldname($lhandle,$fnumber);
+//	   return @pg_fieldname($lhandle,$fnumber);
 }
 
 /**
@@ -314,7 +367,7 @@
  */
 function db_affected_rows($qhandle) {
 	
-	return @pg_cmdtuples($qhandle);
+//	return @pg_cmdtuples($qhandle);
 }
 
 /**
@@ -327,7 +380,8 @@
  *  @param		$qhandle (string)	Query result set handle
  */
 function db_fetch_array($qhandle) {
-	return @pg_fetch_array($qhandle);
+	return $qhandle->fetch(PDO::FETCH_BOTH);
+//	return @pg_fetch_array($qhandle);
 }
 /**                                                       
  * fetch a row into an associative array 
@@ -336,11 +390,13 @@
  *  @param		$fnumber (int)	Column number
  */
 function db_fetch_assoc($qhandle) {
-	return @pg_fetch_assoc($qhandle);
+	return $qhandle->fetch(PDO::FETCH_ASSOC);
+//	return @pg_fetch_assoc($qhandle);
 
 }
 function db_fetch_all($qhandle){
-		return @pg_fetch_all($qhandle);
+	return $qhandle->fetchAll();
+//	return @pg_fetch_all($qhandle);
 }
 /**                                                       
  * fetch a row into an array 
@@ -349,7 +405,8 @@
  *  @param		$fnumber (int)	Column number
  */
 function db_fetch_row($qhandle,$fnumber=0) {
-	  return pg_fetch_row($qhandle);
+	return $qhandle->fetch(PDO::FETCH_NUM);
+//	return pg_fetch_row($qhandle);
 }
 
 /**
@@ -360,38 +417,40 @@
  *  @param		$pkey_field_name (string)	Is the field name of the primary key
  */
 function db_insertid($qhandle="",$table_name="",$pkey_field_name="") {
+	$res = Mapbender::db()->query("SELECT max($pkey_field_name) AS id FROM $table_name");
+    if ($res && db_numrows($res) > 0) {
+        return @db_result($res,0,'id');
+    } else {
+        return 0;
+    }
+/*
 	$res=db_query("SELECT max($pkey_field_name) AS id FROM $table_name");
     if ($res && db_numrows($res) > 0) {
         return @db_result($res,0,'id');
     } else {
         return 0;
     }
+ */
 }
 
 
 
 
 function db_insert_id($qhandle="",$table_name="",$pkey_field_name="") {
-		global $sys_dbhost,$sys_dbuser,$sys_dbpasswd,$sys_dbname,$db_debug,
+	return db_insertid($qhandle, $table_name, $pkey_field_name);
+/*
+	global $sys_dbhost,$sys_dbuser,$sys_dbpasswd,$sys_dbname,$db_debug,
 		$conn,$conn_update,$QUERY_COUNT,$DBSERVER,$OWNER,$PW,$DB;
-	/*	
-	$oid =pg_last_oid($qhandle);
-	echo $oid;
-	
-	$res=db_query("SELECT ".$pkey_field_name." FROM ".$table_name." WHERE oid =".$oid );
+  $res=db_query("SELECT max($pkey_field_name) AS id FROM $table_name");
     if ($res && db_numrows($res) > 0) {
-        return @db_result($res,0,0);
-    } else {
-        return 0;
-    }*/
-    $res=db_query("SELECT max($pkey_field_name) AS id FROM $table_name");
-    if ($res && db_numrows($res) > 0) {
         return db_result($res,0,'id');
     } else {
         return 0;
     }
+ *
+ */
 }
-
+/*
 function db_last_oid()
       {
       	global $sys_dbhost,$sys_dbuser,$sys_dbpasswd,$sys_dbname,$db_debug,
@@ -399,13 +458,14 @@
         global $DBSERVER,$OWNER,$PW,$DB	;
              return pg_getlastoid($conn);
       }
+*/
 
-
 /**
  * Returns the last error from the database
  */
 function db_error() {
-	return @pg_last_error();
+	return implode(", ", Mapbender::db()->errorInfo());
+//	return @pg_last_error();
 }
 
 /**
@@ -418,32 +478,32 @@
  *                    "blob", "unsigned", "zerofill","binary", "enum",                  
  *                    "auto_increment", "timestamp"                                     
  */
-
+/*
 function db_field_flags($lhandle,$fnumber) {
 	   print "db_field_flags()	isn't implemented";
 	   
 }
-
+*/
 /**                                                       
  * Get the type of the specified field  
  *
  *  @param		$lhandle	(string) Query result set handle
  *  @param		$fnumber (int)	Column number
  */                                                       
-                                                          
+/*
 function db_field_type($lhandle,$fnumber) {               
 	   return @pg_fieldtype($lhandle,$fnumber);         
 }                                                         
-
+*/
 /**                                                       
  * Get the length of the specified field                                                            
  *
  *  @param		$lhandle	(string) Query result set handle
  *  @param		$fnumber (int)	Column number
  */                                                       
-                                                          
+/*
 function db_field_len($lhandle,$fnumber) {               
 	   return @pg_fieldlen($lhandle,$fnumber);         
 } 
-
+*/
 ?>
\ No newline at end of file

Deleted: branches/mapbender/test/http/classes/GetApiTest.php
===================================================================
--- trunk/mapbender/test/http/classes/GetApiTest.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/test/http/classes/GetApiTest.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,124 +0,0 @@
-<?php
-require_once 'PHPUnit/Framework.php';
-require_once dirname(__FILE__) . "/../../../lib/class_GetApi.php";
-
-class GetApiTest extends PHPUnit_Framework_TestCase {
-
-	public function testSingleLayer () {
-		parse_str("LAYER=12", $getArray);
-
-		$apiObject = new GetApi($getArray);
-		
-		$expected = array(
-			array(
-				"id" => 12
-			)
-		);
-		$this->assertEquals($expected, $apiObject->getLayers());
-	}
-
-	public function testSingleLayerFromApplication () {
-		parse_str("LAYER[application]=gui1&LAYER[id]=12", $getArray);
-		$apiObject = new GetApi($getArray);
-		
-		$expected = array(
-			array(
-				"id" => 12,
-				"application" => "gui1"
-			)
-		);
-		$this->assertEquals($expected, $apiObject->getLayers());
-	}
-
-	public function testMultipleLayer () {
-		parse_str("LAYER[0][application]=gui1&LAYER[0][id]=12&LAYER[1]=13", $getArray);
-		$apiObject = new GetApi($getArray);
-		
-		$expected = array(
-			array(
-				"id" => 12,
-				"application" => "gui1"
-			),
-			array(
-				"id" => 13
-			)
-		);
-		$this->assertEquals($expected, $apiObject->getLayers());
-	}
-
-	public function testMultipleLayerComplex () {
-		parse_str("LAYER[visible]=false&LAYER[zoom]=true&LAYER[application]=gui1&LAYER[id]=12", $getArray);
-		$apiObject = new GetApi($getArray);
-		
-		$expected = array(
-			array(
-				"id" => 12,
-				"application" => "gui1",
-				"visible" => false,
-				"zoom" => true
-			)
-		);
-		$this->assertEquals($expected, $apiObject->getLayers());
-	}
-	
-	public function testSingleFeaturetype () {
-		parse_str("FEATURETYPE=12", $getArray);
-		$apiObject = new GetApi($getArray);
-		
-		$expected = array(
-			array(
-				"id" => 12
-			)
-		);
-		$this->assertEquals($expected, $apiObject->getFeaturetypes());
-	}
-	
-	public function testMultipleFeaturetypes () {
-		parse_str("FEATURETYPE=12,13", $getArray);
-		$apiObject = new GetApi($getArray);
-		
-		$expected = array(
-			array(
-				"id" => 12
-			),
-			array(
-				"id" => 13
-			)
-		);
-		$this->assertEquals($expected, $apiObject->getFeaturetypes());
-	}
-
-	public function testMultipleFeaturetypesArray () {
-		parse_str("FEATURETYPE[]=12&FEATURETYPE[]=13", $getArray);
-		$apiObject = new GetApi($getArray);
-		
-		$expected = array(
-			array(
-				"id" => 12
-			),
-			array(
-				"id" => 13
-			)
-		);
-		$this->assertEquals($expected, $apiObject->getFeaturetypes());
-	}
-
-	public function testMultipleFeaturetypesArrayComplex () {
-		parse_str("FEATURETYPE[active]=false&FEATURETYPE[search][firstname]=a&FEATURETYPE[search][lastname]=b&FEATURETYPE[id]=12", $getArray);
-		$apiObject = new GetApi($getArray);
-		
-		$expected = array(
-			array(
-				"id" => 12,
-				"active" => false,
-				"search" => array(
-					"firstname" => "a",
-					"lastname" => "b"
-				)
-			)
-		);
-		$this->assertEquals($expected, $apiObject->getFeaturetypes());
-	}
-
-}
-?>
\ No newline at end of file

Copied: branches/mapbender/test/http/classes/GetApiTest.php (from rev 6919, trunk/mapbender/test/http/classes/GetApiTest.php)
===================================================================
--- branches/mapbender/test/http/classes/GetApiTest.php	                        (rev 0)
+++ branches/mapbender/test/http/classes/GetApiTest.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -0,0 +1,154 @@
+<?php
+require_once 'PHPUnit/Framework.php';
+require_once dirname(__FILE__) . "/../../../lib/class_GetApi.php";
+
+class GetApiTest extends PHPUnit_Framework_TestCase {
+
+	public function testSingleLayer () {
+		parse_str("LAYER=12", $getArray);
+
+		$apiObject = new GetApi($getArray);
+		
+		$expected = array(
+			array(
+				"id" => 12
+			)
+		);
+		$this->assertEquals($expected, $apiObject->getLayers());
+	}
+
+	public function testSingleLayerFromApplication () {
+		parse_str("LAYER[application]=gui1&LAYER[id]=12", $getArray);
+		$apiObject = new GetApi($getArray);
+		
+		$expected = array(
+			array(
+				"id" => 12,
+				"application" => "gui1"
+			)
+		);
+		$this->assertEquals($expected, $apiObject->getLayers());
+	}
+
+	public function testMultipleLayer () {
+		parse_str("LAYER[0][application]=gui1&LAYER[0][id]=12&LAYER[1]=13", $getArray);
+		$apiObject = new GetApi($getArray);
+		
+		$expected = array(
+			array(
+				"id" => 12,
+				"application" => "gui1"
+			),
+			array(
+				"id" => 13
+			)
+		);
+		$this->assertEquals($expected, $apiObject->getLayers());
+	}
+
+	public function testMultipleLayerComplex () {
+		parse_str("LAYER[visible]=0&LAYER[zoom]=1&LAYER[application]=gui1&LAYER[id]=12", $getArray);
+		$apiObject = new GetApi($getArray);
+		
+		$expected = array(
+			array(
+				"id" => 12,
+				"application" => "gui1",
+				"visible" => 0,
+				"zoom" => 1
+			)
+		);
+		$this->assertEquals($expected, $apiObject->getLayers());
+	}
+	
+	public function testSingleFeaturetype () {
+		parse_str("FEATURETYPE=12", $getArray);
+		$apiObject = new GetApi($getArray);
+		
+		$expected = array(
+			array(
+				"id" => 12
+			)
+		);
+		$this->assertEquals($expected, $apiObject->getFeaturetypes());
+	}
+	
+	public function testMultipleFeaturetypes () {
+		parse_str("FEATURETYPE=12,13", $getArray);
+		$apiObject = new GetApi($getArray);
+		
+		$expected = array(
+			array(
+				"id" => 12
+			),
+			array(
+				"id" => 13
+			)
+		);
+		$this->assertEquals($expected, $apiObject->getFeaturetypes());
+	}
+
+	public function testMultipleFeaturetypesArray () {
+		parse_str("FEATURETYPE[]=12&FEATURETYPE[]=13", $getArray);
+		$apiObject = new GetApi($getArray);
+		
+		$expected = array(
+			array(
+				"id" => 12
+			),
+			array(
+				"id" => 13
+			)
+		);
+		$this->assertEquals($expected, $apiObject->getFeaturetypes());
+	}
+
+	public function testMultipleFeaturetypesArrayComplex () {
+		parse_str("FEATURETYPE[active]=0&FEATURETYPE[search][firstname]=a&FEATURETYPE[search][lastname]=b&FEATURETYPE[id]=12", $getArray);
+		$apiObject = new GetApi($getArray);
+
+		$expected = array(
+			array(
+				"id" => 12,
+				"active" => 0,
+				"search" => array(
+					"firstname" => "a",
+					"lastname" => "b"
+				)
+			)
+		);
+		$this->assertEquals($expected, $apiObject->getFeaturetypes());
+	}
+
+	public function testWmcSimple () {
+		parse_str("WMC=12", $getArray);
+		$apiObject = new GetApi($getArray);
+
+		$expected = array(
+			array(
+				"id" => 12
+			)
+		);
+		$this->assertEquals($expected, $apiObject->getWmc());
+	}
+
+	public function testWmcSimpleMultiple () {
+		parse_str("WMC=12,13,14", $getArray);
+		$apiObject = new GetApi($getArray);
+
+		$expected = array(
+			array(
+				"id" => 12
+			),
+			array(
+				"id" => 13
+			),
+			array(
+				"id" => 14
+			)
+		);
+		$this->assertEquals($expected, $apiObject->getWmc());
+	}
+
+}
+?>
\ No newline at end of file

Deleted: branches/mapbender/test/http/classes/GroupTest.php
===================================================================
--- trunk/mapbender/test/http/classes/GroupTest.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/test/http/classes/GroupTest.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,61 +0,0 @@
-<?php
-require_once 'PHPUnit/Framework.php';
-require_once dirname(__FILE__) . "/../../../http/classes/class_group.php";
-
-class GroupTest extends PHPUnit_Framework_TestCase
-{
-    var $someGroup_name = "demo";
-    var $someGroup_description = "Demo Group zum Test";
-
-	public function testCreate()
-    {
-      $group = new Group(null);
-      $group->name = $this->someGroup_name;
-      $group->description = $this->someGroup_description;
-
- 
-      $this->assertNotNull($group);
-
-      try{
-        $create_result = $group->create();
-      }
-      catch(Exception $E)
-      {
-        $this->assertEquals($E->getMessage(), 'Could not insert new group');
-      }
-      $this->assertNotNull($create_result);
-
-
-      $change_result = $group->change(null);
-      $this->assertTrue($change_result);
-
-
-      try{
-        $commit_result =  $group->commit();
-      }
-      catch(Exception $E)
-      {
-        $this->assertEquals($E->getMessage(), 'Database error updating Group');
-      }
-      
-      $this->assertTrue($commit_result);
-    }
-
-    /*
-    * @depends testCreate
-    */
-    public function testDelete()
-    {
-      $group = Group::byName($this->someGroup_name);
-      $this->assertNotNull($group);
-
-      $remove_result = $group->remove();
-      $this->assertTrue($remove_result);
-
-      $group = null;
-      $group = Group::byName($this->someGroup_name);
-      $this->assertNull($group);
-    } 
-
-}
-?>

Deleted: branches/mapbender/test/http/classes/MbNoticeTest.php
===================================================================
--- trunk/mapbender/test/http/classes/MbNoticeTest.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/test/http/classes/MbNoticeTest.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,35 +0,0 @@
-<?php
-require_once 'PHPUnit/Framework.php';
-require_once dirname(__FILE__) . "/../../../http/classes/class_mb_log.php";
-
-class MbNoticeTest extends PHPUnit_Framework_TestCase
-{
-	var $someNotice;
-	
-	public function setUp () {
-		$this->someNotice = new mb_notice("unit test");		
-	}
-
-	public function tearDown () {
-		unset($this->someNotice);	
-	}
-	
-
-	/**
-	 * Notice was created
-	*/
-	public function testNoticeCreated()
-	{
-	//TODO: check if logfile is really created
-		$this->assertNotNull($this->someNotice);
-	}
-
-	/**
-	 * Notice was Successful
-	*/
-	public function testNoticeSuccessful()
-	{
-		$this->assertEquals("Successful.", $this->someNotice->message);
-	}
-}
-?>

Deleted: branches/mapbender/test/http/classes/MbWarningTest.php
===================================================================
--- trunk/mapbender/test/http/classes/MbWarningTest.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/test/http/classes/MbWarningTest.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,35 +0,0 @@
-<?php
-require_once 'PHPUnit/Framework.php';
-require_once dirname(__FILE__) . "/../../../http/classes/class_mb_log.php";
-
-class MbWarningTest extends PHPUnit_Framework_TestCase
-{
-	var $someNotice;
-	
-	public function setUp () {
-		$this->someWarning = new mb_warning("unit test");		
-	}
-
-	public function tearDown () {
-		unset($this->someWarning);	
-	}
-	
-
-	/**
-	 * Notice was created
-	*/
-	public function testWarningCreated()
-	{
-	//TODO: check if logfile is really created
-		$this->assertNotNull($this->someWarning);
-	}
-
-	/**
-	 * Notice was Successful
-	*/
-	public function testWarningSuccessful()
-	{
-		$this->assertEquals("Successful.", $this->someWarning->message);
-	}
-}
-?>

Deleted: branches/mapbender/test/http/classes/UserTest.php
===================================================================
--- trunk/mapbender/test/http/classes/UserTest.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/test/http/classes/UserTest.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,61 +0,0 @@
-<?php
-require_once 'PHPUnit/Framework.php';
-require_once dirname(__FILE__) . '/../../../http/classes/class_user.php';
-
-class UserTest extends PHPUnit_Framework_TestCase
-{
-    var $someUser_name = "demo";
-    var $someUser_description = "Demo User zum Testen";
-
-    public function testCreate()
-    {
-      $user = new User(null);
-      $user->name = $this->someUser_name;
-      $user->description = $this->someUser_description;
-      $user->public = 1;
-
-
-      $this->assertNotNull($user);
-
-      try{
-        $create_result = $user->create();
-      }
-      catch(Exception $E)
-      {
-        $this->assertEquals($E->getMessage(), 'Could not set initial values of new User');
-      }
-      $this->assertNotNull($create_result);
-
-
-      $change_result = $user->change(null);
-      $this->assertTrue($change_result);
- 
-      try{
-        $commit_result =  $user->commit();
-      }
-      catch(Exception $E)
-      {
-        $this->assertEquals($E->getMessage(), 'Database error updating User');
-      }
-      
-      $this->assertTrue($commit_result);
-
-    }
-
-    /*
-    * @depends testCreate
-    */
-    public function testDelete()
-    {
-      $user = User::byName($this->someUser_name);
-      $this->assertNotNull($user);
-
-      $remove_result = $user->remove();
-      $this->assertTrue($remove_result);
-
-      $user = null;
-      $user = User::byName($this->someUser_name);
-      $this->assertNull($user);
-    }
-}
-?>

Deleted: branches/mapbender/tools/mapFiler.php
===================================================================
--- trunk/mapbender/tools/mapFiler.php	2010-09-15 14:59:57 UTC (rev 6918)
+++ branches/mapbender/tools/mapFiler.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -1,162 +0,0 @@
-<html>
-  <head>
-    <title>MapFiler Version 0.2 for UMN MapServer 5.x</title>
-    <style></style>
-  <script type='text/javascript' >
-  function validate(){
-  	/*eventuell den Inhalt (Pfad) noch aufbereiten?
-	* Slash und Backslash -> win, linux usw.
-	*/
-	document.form1.location.type = 'text';
-	document.form1.myLocation.value = document.form1.location.value;
-	document.form1.submit();
-  }
-  </script>
-  </head>
-  <body>
-  <form name='form1' action='<?php echo $_SERVER["SCRIPT_NAME"]; ?>' method='POST'>
-	<b>MapFiler Version 0.2 for UMN MapServer 5.x </b>
-	<br><br>changes in Version 0.2
-	<li>multiplicate MAXSIZE with factor</li>
-	<li>division SYMBOLSCALE by factor</li>
-	<li>multiplicate WIDTH with factor</li>
-	<li>division MINSCALEDENOM and MAXSCALEDENOM by factor  </li>
-	<br>
-  
-  <table>
-	<tr>
-		<td>Location:</td>
-		<td>
-			<input type='file' name='location' >
-			<input type='hidden' name='myLocation'>
-		</td>
-	</tr>
-	<tr>
-		<td>all files with the same extension:</td>
-		<td>
-		<input type='checkbox' name='dir'>
-		</td>
-	</tr>
-	<tr>
-		<td>Factor:</td>
-		<td><input type='text' name='factor' value='4'></td>
-	</tr>		
-	<tr>
-		<td><input type='button' value="let's go" onclick='validate()'></td>
-		<td></td>
-	</tr>
-  </table>
-  <?php
-  
-import_request_variables('PG');
-
-/*********PARAMS***************/
-$countSymbolsFiles = 0;
-$arraySymbolsFiles;
-/********************************/
-function modify($myDir, $myFile){
-	global $factor;
-	$myContent = fopen($myDir."/".$myFile, "r") or die("Datei " . $myDir . " / ". $myFile ." konnte nicht zum Lesen ge�ffnet werden!");
-	$myNewContent = fopen($myDir."/".str_replace(".","_".$factor.".",$myFile), "w") or die("Datei " . $myDir . " / ". str_replace(".","_".$factor.".",$myFile) ." konnte nicht zum Schreiben ge�ffnet werden!");
-	fputs($myNewContent, "#Modified by MapbenderTools" . "Date: ". date("d.m.Y") . "Factor: ". $factor . "\n\n");
-	//fputs($myNewContent, "#Date: ". date("d.m.Y") . "Factor: ". $factor . "\n\n");
-	//fputs($myNewContent, "#Factor: ". $factor . "\n\n");
-                
-	while(!feof($myContent)){
-		$myLine = fgets($myContent, 1024);
-		if(preg_match("/\bSIZE\s*(\d+.?\d*)\s*/i",$myLine,$matches)){
-			if(count($matches) <= 2){ 
-				fputs($myNewContent, str_replace($matches[1], multiplicate($matches[1]), $myLine));
-			}
-		}
-		else if(preg_match("/(.*OFFSET)\s*(\d+.?\d*)(\s*)(\d+.?\d*)(\s*)/i",$myLine,$matches)){
-			$myNewOFFSET=$matches[1] . " " .multiplicate($matches[2]) . " " . multiplicate($matches[4]).$matches[5];
-			fputs($myNewContent,$myNewOFFSET);
-		}
-		else if(preg_match("/\bMAXSIZE\s*(\d+.?\d*)\s*/i",$myLine,$matches)){
-			if(count($matches) <= 2){ 
-				fputs($myNewContent, str_replace($matches[1], multiplicate($matches[1]), $myLine));
-			}
-		} 
-		else if(preg_match("/\bMINSIZE\s*(\d+.?\d*)\s*/i",$myLine,$matches)){
-			if(count($matches) <= 2){ 
-				fputs($myNewContent, str_replace($matches[1], multiplicate($matches[1]), $myLine));
-			}
-		}                       
-		else if(preg_match("/\bWIDTH\s*(\d+.?\d*)\s*/i",$myLine,$matches)){ 
-			//fputs($myNewContent, "# ". $myLine);
-			if(count($matches) <= 2){ 
-				fputs($myNewContent, str_replace($matches[1], multiplicate($matches[1]), $myLine));
-			}
-		}
-		else if(preg_match("/\bSYMBOLSCALE\s*(\d+.?\d*)\s*/i",$myLine,$matches)){ 
-			//fputs($myNewContent, "# ". $myLine);
-			if(count($matches) <= 2){ 
-				fputs($myNewContent, str_replace($matches[1], division($matches[1]), $myLine));
-			}
-		}
-		else if(preg_match("/\bMINSCALE\s*(\d+.?\d*)\s*/i",$myLine,$matches)){ 
-			//fputs($myNewContent, "# ". $myLine);
-			if(count($matches) <= 2){ 
-				fputs($myNewContent, str_replace($matches[1], division($matches[1]), $myLine));
-			}
-		}
-		else if(preg_match("/\bMAXSCALE\s*(\d+.?\d*)\s*/i",$myLine,$matches)){ 
-			//fputs($myNewContent, "# ". $myLine);
-			if(count($matches) <= 2){ 
-				fputs($myNewContent, str_replace($matches[1], division($matches[1]), $myLine));
-			}
-		}				
-		else if(preg_match("/\bSYMBOLSET\s*(.*)/i",$myLine,$matches)){ //noch nicht fertig
-			$arraySymbolFiles[$countSymbolsFiles] = str_replace("\"","",$matches[1]);
-			$countSymbolsFiles++;
-			fputs($myNewContent, $myLine);
-		}
-		#catch all
-		else{
-			fputs($myNewContent, $myLine);
-		}        
-	}
-	fclose($myContent);
-	fclose($myNewContent);
-}
-
-function multiplicate($x){
-	global $factor;
-	$x = floatval($x) * $factor;
-	return $x;
-}
-
-function division($x){
-	global $factor;
-	$x = floatval($x) / $factor;
-	return $x;
-}
-
- if(isset($myLocation) && $myLocation != ""){
-	# what is to do...
-	$myFile = basename($myLocation);
-	$myDir = dirname($myLocation);
-	$suffix = strstr($myFile, ".");
-
-	
-	if(!isset($dir)){
-		modify($myDir, $myFile);
-		echo "modified: " . $myDir . "/" . $myFile. "<br />";
-	}
-	else{
-		if($verz = opendir($myDir)){
-			while ($myFile = readdir ($verz)) {
-				if($myFile != ".." && $myFile != "." && is_file($myDir."/".$myFile) && strstr($myFile, $suffix)){
-					modify($myDir, $myFile);                         
-					echo "modified: " . $myDir . "/" . $myFile. "<br />";
-				}
-			}
-			closedir($verz);
-		}
-	}
-} 
-  ?>  
-  </form>
-  </body>
-</html>
\ No newline at end of file

Copied: branches/mapbender/tools/mapFiler.php (from rev 6953, trunk/mapbender/tools/mapFiler.php)
===================================================================
--- branches/mapbender/tools/mapFiler.php	                        (rev 0)
+++ branches/mapbender/tools/mapFiler.php	2010-09-29 11:31:10 UTC (rev 6957)
@@ -0,0 +1,186 @@
+<html>
+  <head>
+    <title>MapFiler Version 0.2 for UMN MapServer 5.x</title>
+    <style></style>
+  <script type='text/javascript' >
+  function validate(){
+  	/*eventuell den Inhalt (Pfad) noch aufbereiten?
+	* Slash und Backslash -> win, linux usw.
+	*/
+	document.form1.location.type = 'text';
+	document.form1.myLocation.value = document.form1.location.value;
+	document.form1.submit();
+  }
+  </script>
+  </head>
+  <body>
+  <form name='form1' action='<?php $PHP_SELF ?>' method='POST'>
+	<b>MapFiler Version 0.3 for UMN MapServer 5.4.x </b>
+	<br><br>changes in Version 0.3
+	<li>multiplicate SIZE MAXSIZE MINSIZE with factor</li>
+	<li>division SYMBOLSCALEDENOM by factor</li>
+	<li>multiplicate WIDTH MINWIDTH MAXWIDTH with factor</li>
+	<li>division MINSCALEDENOM and MAXSCALEDENOM by factor  </li>
+	<li>division LABELMINSCALEDENOM and LABELMAXSCALEDENOM by factor  </li>	
+	<br>
+  
+  <table>
+	<tr>
+		<td>Location:</td>
+		<td>
+			<input type='file' name='location' >
+			<input type='hidden' name='myLocation'>
+		</td>
+	</tr>
+	<tr>
+		<td>all files with the same extension:</td>
+		<td>
+		<input type='checkbox' name='dir'>
+		</td>
+	</tr>
+	<tr>
+		<td>Factor:</td>
+		<td><input type='text' name='factor' value='4'></td>
+	</tr>		
+	<tr>
+		<td><input type='button' value="let's go" onclick='validate()'></td>
+		<td></td>
+	</tr>
+  </table>
+  <?php
+  
+import_request_variables('PG');
+
+/*********PARAMS***************/
+$countSymbolsFiles = 0;
+$arraySymbolsFiles;
+/********************************/
+function modify($myDir, $myFile){
+	global $factor;
+	$myContent = fopen($myDir."/".$myFile, "r") or die("Datei " . $myDir . " / ". $myFile ." konnte nicht zum Lesen ge�ffnet werden!");
+	$myNewContent = fopen($myDir."/".str_replace(".","_".$factor.".",$myFile), "w") or die("Datei " . $myDir . " / ". str_replace(".","_".$factor.".",$myFile) ." konnte nicht zum Schreiben ge�ffnet werden!");
+	fputs($myNewContent, "#Modified by MapbenderTools" . "Date: ". date("d.m.Y") . "Factor: ". $factor . "\n\n");
+	//fputs($myNewContent, "#Date: ". date("d.m.Y") . "Factor: ". $factor . "\n\n");
+	//fputs($myNewContent, "#Factor: ". $factor . "\n\n");
+                
+	while(!feof($myContent)){
+		$myLine = fgets($myContent, 1024);
+		if(preg_match("/\bSIZE\s*(\d+.?\d*)\s*/i",$myLine,$matches)){
+			if(count($matches) <= 2){ 
+				fputs($myNewContent, str_replace($matches[1], multiplicate($matches[1]), $myLine));
+			}
+		}
+		else if(preg_match("/(.*OFFSET)\s*(\d+.?\d*)(\s*)(\d+.?\d*)(\s*)/i",$myLine,$matches)){
+			$myNewOFFSET=$matches[1] . " " .multiplicate($matches[2]) . " " . multiplicate($matches[4]).$matches[5];
+			fputs($myNewContent,$myNewOFFSET);
+		}
+		else if(preg_match("/\bMAXSIZE\s*(\d+.?\d*)\s*/i",$myLine,$matches)){
+			if(count($matches) <= 2){ 
+				fputs($myNewContent, str_replace($matches[1], multiplicate($matches[1]), $myLine));
+			}
+		} 
+		else if(preg_match("/\bMINSIZE\s*(\d+.?\d*)\s*/i",$myLine,$matches)){
+			if(count($matches) <= 2){ 
+				fputs($myNewContent, str_replace($matches[1], multiplicate($matches[1]), $myLine));
+			}
+		}
+		else if(preg_match("/\bMAXWIDTH\s*(\d+.?\d*)\s*/i",$myLine,$matches)){
+			if(count($matches) <= 2){ 
+				fputs($myNewContent, str_replace($matches[1], multiplicate($matches[1]), $myLine));
+			}
+		} 
+		else if(preg_match("/\bMINWIDTH\s*(\d+.?\d*)\s*/i",$myLine,$matches)){
+			if(count($matches) <= 2){ 
+				fputs($myNewContent, str_replace($matches[1], multiplicate($matches[1]), $myLine));
+			}
+		}		
+		else if(preg_match("/\bWIDTH\s*(\d+.?\d*)\s*/i",$myLine,$matches)){ 
+			//fputs($myNewContent, "# ". $myLine);
+			if(count($matches) <= 2){ 
+				fputs($myNewContent, str_replace($matches[1], multiplicate($matches[1]), $myLine));
+			}
+		}
+		else if(preg_match("/\bSYMBOLSCALEDENOM\s*(\d+.?\d*)\s*/i",$myLine,$matches)){ 
+			//fputs($myNewContent, "# ". $myLine);
+			if(count($matches) <= 2){ 
+				fputs($myNewContent, str_replace($matches[1], division($matches[1]), $myLine));
+			}
+		}
+		else if(preg_match("/\bMINSCALEDENOM\s*(\d+.?\d*)\s*/i",$myLine,$matches)){ 
+			//fputs($myNewContent, "# ". $myLine);
+			if(count($matches) <= 2){ 
+				fputs($myNewContent, str_replace($matches[1], division($matches[1]), $myLine));
+			}
+		}
+		else if(preg_match("/\bLABELMAXSCALEDENOM\s*(\d+.?\d*)\s*/i",$myLine,$matches)){ 
+			//fputs($myNewContent, "# ". $myLine);
+			if(count($matches) <= 2){ 
+				fputs($myNewContent, str_replace($matches[1], division($matches[1]), $myLine));
+			}
+		}				
+		else if(preg_match("/\bLABELMINSCALEDENOM\s*(\d+.?\d*)\s*/i",$myLine,$matches)){ 
+			//fputs($myNewContent, "# ". $myLine);
+			if(count($matches) <= 2){ 
+				fputs($myNewContent, str_replace($matches[1], division($matches[1]), $myLine));
+			}
+		}
+		else if(preg_match("/\bMAXSCALEDENOM\s*(\d+.?\d*)\s*/i",$myLine,$matches)){ 
+			//fputs($myNewContent, "# ". $myLine);
+			if(count($matches) <= 2){ 
+				fputs($myNewContent, str_replace($matches[1], division($matches[1]), $myLine));
+			}
+		}				
+
+		else if(preg_match("/\bSYMBOLSET\s*(.*)/i",$myLine,$matches)){ //noch nicht fertig
+			$arraySymbolFiles[$countSymbolsFiles] = str_replace("\"","",$matches[1]);
+			$countSymbolsFiles++;
+			fputs($myNewContent, $myLine);
+		}
+		#catch all
+		else{
+			fputs($myNewContent, $myLine);
+		}        
+	}
+	fclose($myContent);
+	fclose($myNewContent);
+}
+
+function multiplicate($x){
+	global $factor;
+	$x = floatval($x) * $factor;
+	return $x;
+}
+
+function division($x){
+	global $factor;
+	$x = floatval($x) / $factor;
+	return $x;
+}
+
+ if(isset($myLocation) && $myLocation != ""){
+	# what is to do...
+	$myFile = basename($myLocation);
+	$myDir = dirname($myLocation);
+	$suffix = strstr($myFile, ".");
+
+	
+	if(!isset($dir)){
+		modify($myDir, $myFile);
+		echo "modified: " . $myDir . "/" . $myFile. "<br />";
+	}
+	else{
+		if($verz = opendir($myDir)){
+			while ($myFile = readdir ($verz)) {
+				if($myFile != ".." && $myFile != "." && is_file($myDir."/".$myFile) && strstr($myFile, $suffix)){
+					modify($myDir, $myFile);                         
+					echo "modified: " . $myDir . "/" . $myFile. "<br />";
+				}
+			}
+			closedir($verz);
+		}
+	}
+} 
+  ?>  
+  </form>
+  </body>
+</html>
\ No newline at end of file

Copied: branches/mapbender/tools/wms_extent/extent_service.conf (from rev 6926, trunk/mapbender/tools/wms_extent/extent_service.conf)
===================================================================
--- branches/mapbender/tools/wms_extent/extent_service.conf	                        (rev 0)
+++ branches/mapbender/tools/wms_extent/extent_service.conf	2010-09-29 11:31:10 UTC (rev 6957)
@@ -0,0 +1,6 @@
+<?php
+# --------------------------------------------
+# type of mapbender database
+# --------------------------------------------
+DEFINE("EXTENTSERVICEURL","http://".$_SERVER['HTTP_HOST']."/cgi-bin/mapserv?map=/data/mapbender/tools/wms_extent/extents.map&");
+?>

Copied: branches/mapbender/tools/wms_extent/extents.map (from rev 6926, trunk/mapbender/tools/wms_extent/extents.map)
===================================================================
--- branches/mapbender/tools/wms_extent/extents.map	                        (rev 0)
+++ branches/mapbender/tools/wms_extent/extents.map	2010-09-29 11:31:10 UTC (rev 6957)
@@ -0,0 +1,164 @@
+MAP
+NAME "extents"
+STATUS ON
+SIZE 600 600
+MAXSIZE 5000
+UNITS METERS
+SYMBOLSET  "symbolset_mapbender.sym"
+PROJECTION
+	"init=epsg:4326"
+END
+EXTENT 2475000 5425000 2724000 5658000
+WEB	
+	METADATA
+		WMS_TITLE "Layer Extent"
+		WMS_ABSTRACT "Geoportal Rheinland Pfalz, Layer Extent"
+		WMS_ONLINERESOURCE "http://localhost/cgi-bin/mapserv?map=/data/mapbender/tools/extents.map"
+		WMS_FEATURE_INFO_MIME_TYPE    "text/html"	
+		WMS_SRS "epsg:4326 epsg:31467 epsg:31466 epsg:31468 epsg:31469 epsg:31462 epsg:31463 epsg:31492 epsg:31493"
+		wms_extent "2508083 5427840 2681976 5646760"
+		"ows_keywordlist" "Geoportal RLP, Service Layer, WMS, WFS"
+		"ows_fees" "none"
+		"ows_accessconstraints" "none"
+		"ows_addresstype" "postal"
+		"ows_address" "Ferdinand-Sauerbruch-Str. 15"
+		"ows_city" "Koblenz"
+		"ows_stateorprovince" "Rheinland-Pfalz"
+		"ows_postcode" "56073"
+		"ows_country" "Germany"
+		"ows_contactperson" "Armin Retterath" 
+		"ows_contactinformation" "Infos Geoportal-RLP"
+		"ows_contactorganization" "Landesamt für Vermessung und Geobasisinformation Rheinland-Pfalz"
+		"ows_contactposition" "Vermessung und Geobasisinformation"
+		"ows_contactelectronicmailaddress" "armin.retterath at lvermgeo.rlp.de"
+		"wms_contactfacsimiletelephone" "0261/492-466"
+		"wms_contactvoicetelephone" "0261/492-492"
+	END
+END
+SYMBOL
+	NAME 'my_hatch'
+	TYPE hatch
+END
+OUTPUTFORMAT
+  NAME 'png'
+  DRIVER 'GD/PNG'
+  MIMETYPE 'image/png'
+  EXTENSION PNG
+  IMAGEMODE PC256
+  TRANSPARENT ON
+END
+LEGEND
+  STATUS ON
+  KEYSIZE 10 8
+  KEYSPACING 10 10
+  IMAGECOLOR 255 255 255
+  LABEL
+    COLOR 128 128 128
+    TYPE TRUETYPE
+    FONT "arial"
+    SIZE 8
+  END
+END
+#---------------------------------------------------
+LAYER
+	NAME "background" #some service for the background information
+	STATUS ON
+	TYPE LINE
+	CONNECTIONTYPE postgis 
+	CONNECTION   "dbname=<postgisdatabase> user=<username> port=5432 host=<ip>"
+	DATA "the_geom from (select gid , the_geom from gis.landes) as foo using unique gid using SRID=31466"  
+	METADATA
+		WMS_TITLE "Rheinland-Pfalz"
+		WMS_SRS "epsg:31466"
+		WMS_ABSTRACT "Bounding Box Rectangles of Geo Resources registered with the Geoportal Rhineland Palatinate"
+		wms_dataurl_format "text/html"
+		wms_dataurl_href "http://www.mapbender.org/"
+		wms_keywordlist "Geoportal, RLP, Rheinland Pfalz, Umgebungsrechteck, Kartensuche, Dienst, OGC WMS, Open Source Geospatial Foundation, OSGeo"
+		wms_metadataurl_format "text/html"
+		wms_metadataurl_href "http://wiki.osgeo.org/"
+		wms_metadataurl_type "TC211"
+		wms_extent "2508083.25 5427840 2681976 5646759.5"
+	END
+	MINSCALE 0
+	MAXSCALE 0
+	PROJECTION
+		"init=epsg:31466"
+	END
+	CLASS
+		NAME "Rheinland_Pfalz"
+		STYLE
+			OUTLINECOLOR 0 0 0
+			COLOR -1 -1 -1
+		END 
+	END
+END
+#---------------------------------------------------
+LAYER
+	NAME "extent"
+	STATUS ON
+	TYPE POLYGON
+	CONNECTIONTYPE postgis 
+	CONNECTION   "dbname=<postgisdatabase> user=<databaseuser> port=5432 host=<ip>"
+	DATA "the_geom from (select GeomFromText('POLYGON((%minx% %miny%,%minx% %maxy%,%maxx% %maxy%,%maxx% %miny%, %minx% %miny%))',4326) as the_geom,area2d(transform(GeomFromText('POLYGON((%minx% %miny%,%minx% %maxy%,%maxx% %maxy%,%maxx% %miny%, %minx% %miny%))',4326),31466)) as area, 1 as oid ) as foo USING UNIQUE oid USING SRID=4326"
+	METADATA
+		WMS_TITLE "RLP Geo-Services"
+		WMS_SRS "epsg:4326"
+		WMS_ABSTRACT "Bounding Box Rectangles of OWS Services registered with thte Geoportal Rhineland Palatinate"
+		wms_dataurl_format "text/html"
+		wms_dataurl_href "http://www.geoportal.rlp.de"
+		wms_keywordlist "Geoportal, RLP, Rheinland Pfalz, Umgebungsrechteck, Kartensuche, Dienst, OGC WMS, Open Source Geospatial Foundation. OSGeo"
+		wms_metadataurl_format "text/html"
+		wms_metadataurl_href "http://www.geoportal.rlp.de"
+		wms_metadataurl_type "TC211"
+		wms_extent "2508083.25 5427840 2681976 5646759.5"
+	END
+	PROJECTION
+		"init=epsg:4326"
+	END
+ 	CLASS
+		EXPRESSION ([area] > 300000)
+		NAME "bbox2"
+		STYLE
+        		OUTLINECOLOR 135 30 50 
+        		WIDTH 2 
+      		END 
+	END
+END
+#-------------------------------------
+LAYER
+	NAME "ows_layer_target"
+	STATUS DEFAULT
+	TYPE POINT 
+	LABELMAXSCALE 5000000000
+	LABELMINSCALE 0
+	CONNECTIONTYPE postgis
+	CONNECTION   "dbname=<postgisdatabase> user=<databaseuser> port=5432 host=<ip>"
+	DATA "the_geom from (select centroid(GeomFromText('POLYGON((%minx% %miny%,%minx% %maxy%,%maxx% %maxy%,%maxx% %miny%, %minx% %miny%))',4326)) as the_geom,area2d(transform(GeomFromText('POLYGON((%minx% %miny%,%minx% %maxy%,%maxx% %maxy%,%maxx% %miny%, %minx% %miny%))',4326),31466)) as area, 1 as oid ) as foo USING UNIQUE oid USING SRID=4326"
+	LABELCACHE ON
+	METADATA
+		WMS_TITLE "RLP Geo-Services Annotations"
+		WMS_SRS "epsg:4326"
+		WMS_ABSTRACT "Bounding Box Rectangles of OWS Services registered with thte Geoportal Rhineland Palatinate"
+		wms_dataurl_format "text/html"
+		wms_dataurl_href "http://www.mapbender.org/"
+		wms_keywordlist "Geoportal, RLP, Rheinland Pfalz, Umgebungsrechteck, Kartensuche, Dienst,OGC WMS, Open Source Geospatial Foundation. OSGeo"
+		wms_metadataurl_format "text/html"
+		wms_metadataurl_href "http://wiki.osgeo.org/"
+		wms_metadataurl_type "TC211"
+		wms_extent "2508083.25 5427840 2681976 5646759.5"
+	END
+	PROJECTION
+		"init=epsg:4326"
+	END
+	CLASS
+		EXPRESSION ([area] <= 300000)
+		NAME "bbox"
+		STYLE
+			SYMBOL 'target'
+		END
+	END
+END
+#-------------------------------------
+
+
+END

Copied: branches/mapbender/tools/wms_extent/readme.txt (from rev 6926, trunk/mapbender/tools/wms_extent/readme.txt)
===================================================================
--- branches/mapbender/tools/wms_extent/readme.txt	                        (rev 0)
+++ branches/mapbender/tools/wms_extent/readme.txt	2010-09-29 11:31:10 UTC (rev 6957)
@@ -0,0 +1,12 @@
+Tool to show a simple bounding box graphic which is rendered by mapserver.
+Mapbender itselfs comes without an own ows server component. Therefor it is not so easy to generate a simple graphic for the extents (bboxes) of the different resources (wms/layer/wfs/featuretypes/georss/kml) which are registrated in the mapbender meta-database. It will be possible to do it by using a mapbender or openlayers client and render the objects with javascript. An other possibility is to render the bbox and the background by using a wms server component. The bbox can be given as vendor specific parameters to mapserver and the server decides to render the geometry. It is easy to render different objects for different areas of the bounding boxes. For mapserver a postgis database backend is used. The user can define the same database as used for mapbender installation (if postgis is provided).
+Principle:
+Send vsp for bbox to mapserv.cgi and generating a simple polygon by postgis functions on the fly (data string). The polygon and/or the central point will be rendered by the mapserv process itself. The url of the request is defined in a special conf file and can be included by the module which needs the visualization of extents.
+The principle is better than the solution with a special client because no javascript data has to be send thru the browser and the rendering of bounding boxes is not time-consuming.
+
+List of files:
+tools/wms_extent/extent_service.conf
+tools/wms_extent/extents.map
+tools/wms_extent/symbolset_mapbender.sym
+tools/wms_extent/target.png
+

Copied: branches/mapbender/tools/wms_extent/symbolset_mapbender.sym (from rev 6926, trunk/mapbender/tools/wms_extent/symbolset_mapbender.sym)
===================================================================
--- branches/mapbender/tools/wms_extent/symbolset_mapbender.sym	                        (rev 0)
+++ branches/mapbender/tools/wms_extent/symbolset_mapbender.sym	2010-09-29 11:31:10 UTC (rev 6957)
@@ -0,0 +1,8 @@
+SYMBOLSET
+SYMBOL
+  NAME 'target'
+  TYPE PIXMAP
+  IMAGE "target_small.png"
+  END
+END
+

Copied: branches/mapbender/tools/wms_extent/target_small.png (from rev 6926, trunk/mapbender/tools/wms_extent/target_small.png)
===================================================================
(Binary files differ)



More information about the Mapbender_commits mailing list