[Mapbender-commits] r4459 - in trunk/mapbender: http/classes lib tools

svn_mapbender at osgeo.org svn_mapbender at osgeo.org
Thu Jul 30 11:10:07 EDT 2009


Author: christoph
Date: 2009-07-30 11:10:07 -0400 (Thu, 30 Jul 2009)
New Revision: 4459

Added:
   trunk/mapbender/lib/class_Monitor.php
   trunk/mapbender/tools/mod_monitorCapabilities_defineGetMapBbox.php
Removed:
   trunk/mapbender/http/classes/class_monitor.php
Modified:
   trunk/mapbender/tools/mod_monitorCapabilities_main.php
   trunk/mapbender/tools/mod_monitorCapabilities_write.php
Log:
http://trac.osgeo.org/mapbender/ticket/506

Deleted: trunk/mapbender/http/classes/class_monitor.php
===================================================================
--- trunk/mapbender/http/classes/class_monitor.php	2009-07-30 15:04:27 UTC (rev 4458)
+++ trunk/mapbender/http/classes/class_monitor.php	2009-07-30 15:10:07 UTC (rev 4459)
@@ -1,495 +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__)."/../classes/class_wms.php");
-require_once(dirname(__FILE__)."/../classes/class_bbox.php");
-
-require_once(dirname(__FILE__)."/../extensions/DifferenceEngine.php");
-
-define("MONITOR_DEFAULT_SCALE", 500000);
-define("MONITOR_IMG_WIDTH", 20);
-define("MONITOR_IMG_HEIGHT", 20);
-define("MB_RESOLUTION", 28.35);
-
-class Monitor {
-	/**
-	 *  1 = reachable and in sync with db
-	 *  0 = reachable and out of sync with db
-	 * -1 = unreachable
-	 * -2 = monitoring in progress
-	 * 
-	 */
-	var $result = -1;
-
-	/**
-	 * 1  = the get map request DEFINITELY returns a valid map image
-	 * 0  = the WMS doesn't support XML error format. Who knows if the image is really a map?
-	 * -1 = the get map request doesn't return an image
-	 */
-	var $returnsImage;
-
-	var $comment = "";
-	var $updated = "0";
-	var $supportsXMLException = false;
-	
-	var $timestamp;
-	var $capabilitiesURL;
-	var $mapURL;
-	
-	var $remoteXML;
-	var $localXML;
-	var $capabilitiesDiff;
-	
-	function __construct($wmsId, $uploadId, $autoUpdate) {
-		$this->wmsId = $wmsId;
-		$this->uploadId = $uploadId;
-		$this->autoUpdate = $autoUpdate;
-
-		$this->capabilitiesURL = $this->getUploadURL($this->wmsId, $this->uploadId);
-
-		set_time_limit(TIME_LIMIT);
-		
-		
-		$this->timestamp = time();
-		
-		if ($this->capabilitiesURL) {
-		
-			$remoteWms = new wms();
-			$remoteWms->createObjFromXML($this->capabilitiesURL);
-			$this->remoteXML = $remoteWms->wms_getcapabilities_doc;  
-			$this->localXML = $this->getCapabilitiesDocByWMS($this->wmsId);
-
-			// service unreachable
-			if (!$this->remoteXML) {
-				$this->result = -1;
-				$this->comment = "Connection failed.";
-			}
-			/*
-			 * service available;
-			 * no local copy of capabilities file,
-			 * so it has to be updated anyway
-			 */
-			elseif (!$this->localXML) {
-				$this->result = 0;
-			}
-			/*
-			 * service available;
-			 * check if local copy is different
-			 * to remote capabilties document
-			 */
-			else {
-				/*
-				 * compare to local capabilities document
-				 */
-				// capabilities files match
-				if ($this->localXML == $this->remoteXML) {
-					$this->result = 1;
-					$this->comment = "WMS is stable.";
-				}
-				// capabilities files don't match
-				else {
-					$this->result = 0;
-					$localXMLArray = explode("\n", htmlentities($this->localXML));
-					$remoteXMLArray = explode("\n", htmlentities($this->remoteXML));
-					$this->capabilitiesDiff = $this->outputDiffHtml($localXMLArray,$remoteXMLArray);
-				}
-			}
-			/*
-			 * if the WMS is available,
-			 * 1) get a map image
-			 * 2) update the local backup of the capabilities doc if necessary
-			 */
-			if ($this->result != -1) {
-				
-				$this->mapURL = $this->getMapRequest($this->wmsId);
-				
-				if ($this->isImage($this->mapURL)) {
-					$this->returnsImage = 1;
-				}
-				else {
-					$this->returnsImage = -1;
-				}
-		
-				/*
-				 * if the local backup of the capabilities document
-				 * is deprecated, update the local backup
-				 */
-				if ($this->result == 0) {
-					$mywms = new wms();
-		
-					/* 
-					 * if the capabilities document is valid,
-					 * update it OR mark it as "not up to date"
-					 */ 
-					if ($mywms->createObjFromXML($this->capabilitiesURL)) {
-						if ($this->autoUpdate) {
-							$mywms->updateObjInDB($this->wmsId);
-							$this->updated = "1";
-							$this->comment = "WMS has been updated.";
-						}
-						else {
-							$this->comment = "WMS is not up to date.";
-						}
-					}
-					// capabilities document is invalid
-					else {
-						$this->result = -1;
-						$this->comment = "Invalid getCapabilities request/document or service exception.";
-					}    
-				}
-			}
-		}
-		else {
-			$this->result = -1;
-			$this->comment = "Invalid upload URL.";
-		}
-		$e = new mb_notice("class_monitor: constructor: result = " . $this->result);
-		$e = new mb_notice("class_monitor: constructor: comment = " . $this->comment);
-		$e = new mb_notice("class_monitor: constructor: returnsImage = " . $this->returnsImage);
-	}
-	
-	/**
-	 * 
-	 */
-	public function __toString() {
-		$str = "";
-		$str .= "wmsid: " . $this->wmsId . "\nupload_id: " . $this->uploadId . "\n";
-		$str .= "autoupdate: " . $this->autoUpdate . "\n";
-		$str .= "result: " . $this->result . "\ncomment: " . $this->comment . "\n";
-		$str .= "timestamp: " . $this->timestamp . " (".date("F j, Y, G:i:s", $this->timestamp).")\n";
-		$str .= "getCapabilities URL: " . $this->capabilitiesURL . "\nupdated: " . $this->updated . "\n\n";
-		$str .= "getMap URL: " . $this->mapURL . "\nis image: " . $this->returnsImage . "\n\n";
-		$str .= "-------------------------------------------------------------------\n";
-		$str .= "remote XML:\n\n" . $this->remoteXML . "\n\n";
-		$str .= "-------------------------------------------------------------------\n";
-		$str .= "local XML:\n\n" . $this->localXML . "\n\n";
-		$str .= "-------------------------------------------------------------------\n";
-		$str .= "diff:\n\n" . $this->capabilitiesDiff . "\n\n";
-		$str .= "-------------------------------------------------------------------\n";		
-		return (string) $str;
-	}
-
-	/**
-	 * Update database
-	 */
-	function updateInDB() {
-		$sql = "UPDATE mb_monitor SET updated = $1, status = $2, image = $3, status_comment = $4, upload_url = $5, timestamp_end = $6, map_url = $7, timestamp_begin = $8, caps_diff = $9 WHERE upload_id = $10 AND fkey_wms_id = $11";
-		$v = array($this->updated, $this->result, $this->returnsImage, $this->comment, $this->capabilitiesURL, time(), $this->mapURL, $this->timestamp, $this->capabilitiesDiff, $this->uploadId, $this->wmsId);
-		$t = array('s', 'i', 'i', 's', 's', 's', 's', 's', 's', 's', 'i');
-		$res = db_prep_query($sql,$v,$t);		
-	}
-
-	/*
-	 * Checks if the mapUrl returns an image or an exception
-	 */
-	private function isImage($url) {
-		$headers = get_headers($url, 1);
-		$e = new mb_notice("class_monitor: isImage: map URL is " . $url);
-		$e = new mb_notice("class_monitor: isImage: Content-Type is " . $headers["Content-Type"]);
-		if (preg_match("/xml/", $headers["Content-Type"])) {
-			return false;
-		}
-		return true;
-	}
-
-	/**
-	 * Returns the upload url of some WMS
- 	 */
-	private function getUploadURL($wmsId, $upload_id) {
-		$e = new mb_notice("class_monitor: getUploadURL: wms = " . $wmsId);
-		$e = new mb_notice("class_monitor: getUploadURL: upload_id = " . $upload_id);
-		$sql = "SELECT upload_url FROM mb_monitor WHERE fkey_wms_id = $1 AND upload_id = $2";
-		$v = array($wmsId, $upload_id);
-		$t = array('i', 'i');
-		$res = db_prep_query($sql,$v,$t);
-		$someArray = db_fetch_array($res);
-		$e = new mb_notice("class_monitor: getUploadURL: url = " . $someArray["upload_url"]);
-		return $someArray["upload_url"];
-	}
-	
-	/**
-	 * Returns the character that needs to be appended to 
-	 * a given online resource, in order to append other GET 
-	 * parameters.
-	 * 
-	 * Possible characters: "?", "&", ""
-	 */
-	private function mb_getConjunctionCharacter($onlineresource){
-		// index of character ? in online resource
-		$indexOfChar = mb_strpos($onlineresource,"?");
-	
-		if($indexOfChar) {
-			// no conjunction character needed
-			if($indexOfChar == mb_strlen($onlineresource)-1){ 
-				return "";
-			}
-			// no conjunction character needed
-			else if (mb_substr($onlineresource, mb_strlen($onlineresource)-1) == "&") {
-				return "";
-			}
-			else{
-				return "&";
-			}
-		}
-		return "?";
-	}
-	
-	/**
-	 * retrieves all information necessary to build a map request, 
-	 * concatenates them and returns a valid get map request
-	 */
-	private function getMapRequest($wmsId) {
-	
-		// get map (wms_getmap)
-		// version (wms_version)
-		$sql = "SELECT wms_getmap, wms_version FROM wms WHERE wms_id = $1";
-		$res = db_prep_query($sql, array($wmsId), array('i'));
-		$row = db_fetch_array($res);
-		$getmap = $row["wms_getmap"];
-		$version = $row["wms_version"];
-		
-		//map format
-		$sql = "SELECT * FROM wms_format WHERE data_type = 'map' AND fkey_wms_id = $1";
-		$res = db_prep_query($sql, array($wmsId), array('i'));
-		$row = db_fetch_array($res);
-		$mapFormat = "";
-		while ($row = db_fetch_array($res)) {
-			$mapFormat = urlencode($row["data_format"]);
-			if (preg_match("/png/", $mapFormat) || preg_match("/gif/", $mapFormat) || preg_match("/jp.{1}g/", $mapFormat)) {
-				break;
-			}
-		}
-	
-		// layers (all layers)
-		$sql = "SELECT layer_name FROM layer WHERE fkey_wms_id = $1 AND layer_parent <> '' AND layer_pos > 0";
-		$res = db_prep_query($sql, array($wmsId), array('i'));
-		$layerArray = array();
-		while ($row = db_fetch_array($res)) {
-			array_push($layerArray, urlencode($row["layer_name"]));
-		}
-		$layerList = implode(",", $layerArray);
-		
-		// srs (layer_epsg: epsg)
-		// bbox (layer_epsg: minx, miny, maxx, maxy)
-		$sql = "SELECT epsg, minx, miny, maxx, maxy ";
-		$sql .= "FROM layer_epsg, (SELECT fkey_wms_id, layer_id FROM layer WHERE fkey_wms_id = $1 AND layer_parent = '' AND layer_pos = 0) AS l ";
-		$sql .= "WHERE l.layer_id = layer_epsg.fkey_layer_id AND l.fkey_wms_id = $1";
-		$res = db_prep_query($sql, array($wmsId), array('i'));
-		$bboxArray = array();
-		while ($row = db_fetch_array($res)) {
-			array_push($bboxArray, new Mapbender_bbox($row["minx"], $row["miny"], $row["maxx"], $row["maxy"], $row["epsg"]));
-		}
-	
-		// get a bbox in a preferably non WGS84 epsg to use the scalehints
-		for ($i=0; $i < count($bboxArray); $i++) {
-			$bbox = $bboxArray[$i];			
-			if ($bboxArray[$i]->epsg != "EPSG:4326") {
-				break;
-			}
-		}
-		
-		/*
-		 * transform to 31466 if is 4326
-		 * TODO: extend to other EPSG apart from 31466
-		 */
-		if ($bbox->epsg == "EPSG:4326") {
-			$bbox->transform("EPSG:31466");
-		}
-		
-		/*
-		 * get map and check if result is image 
-		 */
-		// check if this WMS supports exception type XML
-		$sql = "SELECT data_format FROM wms_format WHERE fkey_wms_id = $1 AND data_type = 'exception'";
-		$v = array($wmsId);
-		$t = array('i');
-		$res = db_prep_query($sql,$v,$t);
-		while ($row = db_fetch_array($res)) {
-			$exceptionFormat = $row["data_format"];
-			// set the exception type to xml (if possible)
-			if (preg_match('/xml/', $exceptionFormat)) {
-				$this->supportsXMLException = true;
-				break; 
-			}
-		}
-
-		// correct bbox according to scale
-		$scale = $this->getScaleForWMS($wmsId);
-		$bbox = $this->getBBoxInScale($bbox, $scale);
-
-		return $this->concatenateMapRequest($getmap, $version, $mapFormat, $layerList, $bbox, MONITOR_IMG_WIDTH, MONITOR_IMG_HEIGHT, $exceptionFormat);			 
-	}
-	
-	/**
-	 * updates a given BBox according to a given scale
-	 * 
-	 * @param bbox 
-	 * @param scale 
-	 */
-	private function getBBoxInScale($bbox, $scale) {
-		$e = new mb_notice("class_monitor: getMapRequest: old bbox = " . $bbox);
-		$e = new mb_notice("class_monitor: getMapRequest: old bbox = " . $bbox->min->x . "," . $bbox->min->y . "," . $bbox->max->x . "," . $bbox->max->y);
-		$e = new mb_notice("class_monitor: getMapRequest: scale = " . $scale);
-		if ($scale) {
-			$center = $bbox->min->plus($bbox->max)->times(0.5);
-			$e = new mb_notice("class_monitor: getMapRequest: center = " . $center);
-			
-			/*
-			 * TODO: this formula should have documentation
-			 */
-			$offset =  MONITOR_IMG_WIDTH / (MB_RESOLUTION * 100 * 2) * $scale;
-			$offsetPoint = new Mapbender_point($offset, $offset, $bbox->epsg);
-			$min = $center->minus($offsetPoint);
-			$max = $center->plus($offsetPoint);
-			$bbox->min = $min;
-			$bbox->max = $max;
-			$e = new mb_notice("class_monitor: getMapRequest: new bbox = " . $bbox);
-			$e = new mb_notice("class_monitor: getMapRequest: new bbox = " . $bbox->min->x . "," . $bbox->min->y . "," . $bbox->max->x . "," . $bbox->max->y);
-		}
-		return $bbox;
-	}
-	
-	
-	/**
-	 * Returns an online resource representing a get map request
-	 */
-	private function concatenateMapRequest(	$getmap, $wmsVersion, $mapFormat, $layerList, 
-							$bbox, $width, $height, $exceptionFormat) {
-		/*
-		 * getMap URL
-		 */
-		$mapRequest = $getmap;
-		$mapRequest .= $this->mb_getConjunctionCharacter($getmap);
-		
-		/*
-		 * WMS version
-		 */
-		if ($wmsVersion == "1.0.0") {
-			$mapRequest .= "WMTVER=" . $wmsVersion . "&REQUEST=map&";
-		}
-		else {
-			$mapRequest .= "VERSION=" . $wmsVersion . "&REQUEST=GetMap&SERVICE=WMS&";
-		}
-		
-		/*
-		 * Layer list
-		 */
-		$mapRequest .= "LAYERS=" . $layerList . "&";
-		
-		/*
-		 * Format
-		 */
-		 $mapRequest .= "FORMAT=" . $mapFormat . "&";
-		 
-		/*
-		 * SRS and BBox
-		 */
-		$mapRequest .= "SRS=" . $bbox->epsg . "&";
-		$mapRequest .= "BBOX=" . $bbox->min->x . "," . $bbox->min->y . "," . $bbox->max->x . "," . $bbox->max->y . "&";
-		 
-		/*
-		 * Width and height
-		 */
-		$mapRequest .= "WIDTH=" . $width . "&";
-		$mapRequest .= "HEIGHT=" . $height . "&";
-		 
-		/*
-		 * BGColor
-		 */
-		$mapRequest .= "BGCOLOR=0xffffff&";
-	
-		/*
-		 * Transparency
-		 */
-		if (preg_match("/png/", $mapFormat) || preg_match("/gif/", $mapFormat)) {
-			$mapRequest .= "TRANSPARENT=TRUE&";
-		}
-		 
-		/*
-		 * Exception format
-		 */
-		$mapRequest .= "EXCEPTIONS=" . $exceptionFormat . "&";
-		
-//		return urlencode($mapRequest);	
-		return $mapRequest;	
-	}
-	
-	/**
-	 * Checks if the given WMS has ScaleHints. If yes, a scale is selected and returned.
-	 */
-	private function getScaleForWMS($wmsId) {
-		// get the scalehints
-		$sql = "SELECT layer_minscale, layer_maxscale FROM layer WHERE fkey_wms_id = $1 AND layer_pos = 0 AND layer_parent = '' AND layer_minscale <> layer_maxscale LIMIT 1";
-		$v = array($wmsId);
-		$t = array('i');
-		$res = db_prep_query($sql,$v,$t);
-		$scaleHintArray = db_fetch_array($res);
-		
-		/*
-		 *  determine the scalehint
-		 */
-		// if a scalehint exists 
-		if ($scaleHintArray) {
-			// if upper boundary
-			if ($scaleHintArray["layer_minscale"] < $scaleHintArray["layer_maxscale"]) {
-				// TODO: find a better algorithm with a less obscure scale
-				$scaleHint = round($scaleHintArray["layer_maxscale"] - $scaleHintArray["layer_minscale"]) / 2;				
-			}
-			// if lower boundary
-			else {
-				if ($scaleHintArray["layer_minscale"] < MONITOR_DEFAULT_SCALE) {
-					$scaleHint = MONITOR_DEFAULT_SCALE;
-				}
-				else {
-					// TODO: find a better algorithm with a less obscure scale
-					$scaleHint = $scaleHintArray["layer_minscale"] + 1000;
-				}
-			}
-		}
-		// otherwise, use a default value
-		else {
-			$scaleHint = MONITOR_DEFAULT_SCALE;
-		}
-		return $scaleHint;
-	}
-	
-	/**
-	 * Returns the local backup of the given WMS' capabilities document
-	 */
-	private function getCapabilitiesDocByWMS($wmsId) {
-		$sql = "SELECT wms_getcapabilities_doc FROM wms WHERE wms_id = $1";
-		$v = array($wmsId);
-		$t = array('i');
-		$res = db_prep_query($sql,$v,$t);
-		$someArray = db_fetch_array($res);
-		return $someArray["wms_getcapabilities_doc"];
-	}
-	/*
-	* creates a html diff of the xml documents
-	*/
-	private function outputDiffHtml($localXMLArray,$remoteXMLArray) {
-		$diffObj = new Diff($localXMLArray,$remoteXMLArray);
-		$dft = new TableDiffFormatter();
-		return $dft->format($diffObj);
-	}		
-	
-}
-?>

Added: trunk/mapbender/lib/class_Monitor.php
===================================================================
--- trunk/mapbender/lib/class_Monitor.php	                        (rev 0)
+++ trunk/mapbender/lib/class_Monitor.php	2009-07-30 15:10:07 UTC (rev 4459)
@@ -0,0 +1,387 @@
+<?php
+# $Id: class_layer_monitor.php 791 2007-08-10 10:36:04Z baudson $
+# 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__)."/../../conf/mapbender.conf");
+require_once(dirname(__FILE__)."/../http/classes/class_connector.php");
+require_once(dirname(__FILE__)."/../http/classes/class_mb_exception.php");
+require_once(dirname(__FILE__)."/../http/extensions/DifferenceEngine.php");
+
+class Monitor {
+	/**
+	 *  1 = reachable and in sync with db
+	 *  0 = reachable and out of sync with db
+	 * -1 = unreachable
+	 * -2 = monitoring in progress
+	 * 
+	 */
+	var $result = -1;
+
+	/**
+	 * 1  = the get map request DEFINITELY returns a valid map image
+	 * 0  = the WMS doesn't support XML error format. Who knows if the image is really a map?
+	 * -1 = the get map request doesn't return an image
+	 */
+	var $returnsImage;
+
+	var $comment = "";
+	var $updated = "0";
+	var $supportsXMLException = false;
+	
+	var $timestamp;
+	var $timestamp_cap_begin;
+	var $timestamp_cap_end;
+	var $capabilitiesURL;
+	var $mapURL;
+	
+	var $remoteXML;
+	var $localXML;
+	var $capabilitiesDiff;
+	
+	var $tmpDir = null;
+	
+	function __construct($reportFile, $autoUpdate, $tmpDir) {
+		$this->tmpDir = $tmpDir;
+		
+		$this->reportFile = $tmpDir.$reportFile;
+		//$this->reportFile = $reportFile;
+		$this->wmsId = $this->getTagOutOfXML($this->reportFile,'wms_id');
+		$this->uploadId = $this->getTagOutOfXML($this->reportFile,'upload_id');
+		$this->autoUpdate = $autoUpdate;
+		$e=new mb_notice("Monitor Report File: ".$this->reportFile);
+		$e=new mb_notice("WMS ID: ".$this->wmsId);
+		$this->capabilitiesURL = urldecode($this->getTagOutOfXML($this->reportFile,'getcapurl'));//read out from xml
+		$e=new mb_notice("GetCapURL: ".$this->capabilitiesURL);
+
+		set_time_limit(TIME_LIMIT);
+		
+		
+		$this->timestamp = microtime(TRUE);
+		
+		if ($this->capabilitiesURL) {
+		
+			//$remoteWms = new wms(); #exchange by other handling
+			
+
+			$this->timestamp_cap_begin=microtime(TRUE);//ok
+			
+
+			//$remoteWms->createObjFromXML($this->capabilitiesURL);#exchange by other handling
+			
+			
+			//$this->remoteXML = $remoteWms->wms_getcapabilities_doc;
+			$capObject = new connector($this->capabilitiesURL);
+			//decode and encode to have the same behavior as loading caps to database
+			$this->remoteXML = $capObject->file;
+
+			$this->timestamp_cap_end=microtime(TRUE);
+			//read local copy out of xml
+			$this->localXML = urldecode($this->getTagOutOfXML($this->reportFile,'getcapdoclocal'));
+			$e=new mb_notice("Remote Caps: ".$this->remoteXML);
+			// service unreachable
+			if (!$this->remoteXML) {
+				$this->result = -1;
+				$this->comment = "Connection failed.";
+				//$e=new mb_exception("Connection failed");
+			}
+			/*
+			 * service available;
+			 * no local copy of capabilities file,
+			 * so it has to be updated anyway
+			 */
+			elseif (!$this->localXML) {
+				$this->result = 0;
+				//$e=new mb_exception("No local Copy of Caps available");
+			}
+			/*
+			 * service available;
+			 * check if local copy is different
+			 * to remote capabilties document
+			 */
+			else {
+				/*
+				 * compare to local capabilities document
+				 */
+				// capabilities files match
+				if ($this->localXML == $this->remoteXML) {
+					$this->result = 1;
+					$this->comment = "WMS is stable.";
+					//$e=new mb_exception("Compare ok - Docs ident");
+				
+				}
+				// capabilities files don't match
+				else {
+					$this->result = 0;
+					$this->comment = "WMS is not up to date.";
+					$localXMLArray = explode("\n", htmlentities($this->localXML));
+					$remoteXMLArray = explode("\n", htmlentities($this->remoteXML));
+					$this->capabilitiesDiff = $this->outputDiffHtml($localXMLArray,$remoteXMLArray);
+					//$e=new mb_exception("Problem Docs are out of sync");
+				}
+			}
+			/*
+			 * if the WMS is available,
+			 * 1) get a map image
+			 * 2) update the local backup of the capabilities doc if necessary
+			 */
+			if ($this->result != -1) {
+				
+				$this->mapURL = urldecode($this->getTagOutOfXML($this->reportFile,'getmapurl'));
+				//$e=new mb_exception("mapurl:".$this->mapURL);
+				if ($this->isImage($this->mapURL)) {
+					$this->returnsImage = 1;
+					//$e=new mb_exception("Returns image");
+				}
+				else {
+					$this->returnsImage = -1;
+					//$e=new mb_exception("Returns no image!");
+				}
+				
+
+
+
+
+				//Check for valid XML - validate it again wms 1.1.1 -some problems occur?
+				#$dtd = "../schemas/capabilities_1_1_1.dtd";
+				#$dom = new domDocument;
+				#$dom->loadXML($this->remoteXML);
+				#if (!$dom->validate($dtd)) {
+					#$this->result = -1;
+					#$this->comment = "Invalid getCapabilities request/document or service exception.";
+				#}
+					#else {
+					#$this->comment = "WMS is not up to date but valid!";
+				#}
+
+				//Do a simple check if <WMT_MS_Capabilities version="1.1 is part of the remote Cap Dokument
+				
+				$searchString  = 'WMT_MS_Capabilities';
+				$pos = strpos($this->remoteXML, $searchString);
+				if ($pos === false) {
+    					$this->result = -1;
+					$this->comment = "Invalid getCapabilities request/document or service exception.";
+				}
+
+
+				/*
+				 * if the local backup of the capabilities document
+				 * is deprecated, update the local backup
+				 */
+				#if ($this->result == 0) {
+					//$mywms = new wms();
+		
+					/* 
+					 * if the capabilities document is valid,
+					 * update it OR mark it as "not up to date"
+					 */ 
+					#if ($this->localXML==) {//check validation of capabilities document
+						#if ($this->autoUpdate) {
+							#$mywms->updateObjInDB($this->wmsId);
+							#$this->updated = "1";
+							#$this->comment = "WMS has been updated.";
+							
+						#}
+						#else {
+						#	$this->comment = "WMS is not up to date.";
+						#}
+					#}
+					// capabilities document is invalid
+					#else {
+					#	$this->result = -1;
+					#	$this->comment = "Invalid getCapabilities request/document or service exception.";
+					#}    
+				#}
+			}
+		}
+		else {
+			$this->result = -1;
+			$this->comment = "Invalid upload URL.";
+		}
+		#$e = new mb_notice("class_monitor: constructor: result = " . $this->result);
+		#$e = new mb_notice("class_monitor: constructor: comment = " . $this->comment);
+		#$e = new mb_notice("class_monitor: constructor: returnsImage = " . $this->returnsImage);
+	}
+	
+	/**
+	 * 
+	 */
+	#function toString() {
+		#$str = "";
+		#$str .= "wmsid: " . $this->wmsId . "\nupload_id: " . $this->uploadId . "\n";
+		#$str .= "autoupdate: " . $this->autoUpdate . "\n";
+		#$str .= "result: " . $this->result . "\ncomment: " . $this->comment . "\n";
+		#$str .= "timestamp: " . $this->timestamp . " (".date("F j, Y, G:i:s", $this->timestamp).")\n";
+		#$str .= "getCapabilities URL: " . $this->capabilitiesURL . "\nupdated: " . $this->updated . "\n\n";
+		#$str .= "getMap URL: " . $this->mapURL . "\nis image: " . $this->returnsImage . "\n\n";
+		#$str .= "-------------------------------------------------------------------\n";
+		#$str .= "remote XML:\n\n" . $this->remoteXML . "\n\n";
+		#$str .= "-------------------------------------------------------------------\n";
+		#$str .= "local XML:\n\n" . $this->localXML . "\n\n";
+		#$str .= "-------------------------------------------------------------------\n";
+		#return (string) $str;
+	#}
+
+	/**
+	 * Update database
+	 */
+	function updateInDB() {
+		$sql = "UPDATE mb_monitor SET updated = $1, status = $2, image = $3, status_comment = $4, upload_url = $5, timestamp_end = $6, map_url = $7 , timestamp_begin = $10 WHERE upload_id = $8 AND fkey_wms_id=$9";
+		$v = array($this->updated, $this->result, $this->returnsImage, $this->comment, $this->capabilitiesURL, $this->timestamp_cap_end, $this->mapURL, $this->uploadId, $this->wmsId, $this->timestamp_cap_begin);
+		$t = array('s', 'i', 'i', 's', 's', 's', 's', 's', 'i','s');
+		$res = db_prep_query($sql,$v,$t);		
+	}
+	/**
+	 * Update xml
+	 */
+	function updateInXMLReport() {
+		//create text for diff
+		$difftext = "<html>\n";
+		$difftext .= "<head>\n";
+		$difftext .= "<title>Mapbender - monitor diff results</title>\n";
+		$difftext .= "<meta http-equiv=\"cache-control\" content=\"no-cache\">\n";
+		$difftext .= "<meta http-equiv=\"pragma\" content=\"no-cache\">\n";
+		$difftext .= "<meta http-equiv=\"expires\" content=\"0\">\n";
+		$difftext .= "<meta http-equiv=\"Content-Type\" content=\"text/html; charset='.CHARSET.'\">";	
+		$difftext .= "<style type=\"text/css\">\n";
+		$difftext .= "* {font-family: Arial, \"Courier New\", monospace; font-size: small;}\n";
+		$difftext .= ".diff-context {background: #eee;}\n";
+		$difftext .= ".diff-deletedline {background: #eaa;}\n";
+		$difftext .= ".diff-addedline {background: #aea;}\n";
+		$difftext .= ".diff-blockheader {background: #ccc;}\n";
+		$difftext .= "</style>\n";
+		$difftext .= "</head>\n";
+		$difftext .= "<body>\n";
+		$difftext .= "<table cellpadding=3 cellspacing=0 border=0>\n";
+		$difftext .= "<tr><td align='center' colspan='2'>Local</td><td align='center' colspan='2'>Remote</td></tr>\n";		
+		$difftext .= $this->capabilitiesDiff;
+		$difftext .= "\n\t</table>\n\t";
+		$difftext .= "</body></html>";
+		//write to report
+		$xml=simplexml_load_file($this->reportFile);	
+		$xml->wms->image=$this->returnsImage;
+		$xml->wms->status=$this->result;
+		$xml->wms->getcapduration = intval(($this->timestamp_cap_end-$this->timestamp_cap_begin)*1000);
+		$xml->wms->getcapdocremote = rawurlencode($this->remoteXML);
+		$xml->wms->getcapdiff = rawurlencode($difftext);
+		$xml->wms->comment=$this->comment;
+		$xml->wms->getcapbegin=$this->timestamp_cap_begin;
+		$xml->wms->getcapend=$this->timestamp_cap_end;
+		$xml->asXML($this->reportFile);
+	}
+	/*
+	 * Checks if the mapUrl returns an image or an exception
+	 */
+	function isImage($url) {
+		#$headers = get_headers($url, 1);#controll this function TODO
+		//$e = new mb_notice("class_monitor: isImage: map URL is " . $url);
+		#$e = new mb_notice("class_monitor: isImage: Content-Type is " . $headers["Content-Type"]);
+		#if (preg_match("/xml/", $headers["Content-Type"])) {
+		#	return false;
+		#}
+		$imgObject = new connector($url);
+		$image = $imgObject->file;
+		//write images to tmp folder
+		$imageName=$this->tmpDir."/"."monitor_getmap_image_".md5(uniqid()).".png";
+		$fileMapImg = fopen($imageName, 'w+');
+		$bytesWritten = fwrite($fileMapImg, $image);
+		fclose($fileMapImg);
+
+		//$e = new mb_notice("class_monitor: isImage: path: ".$imageName);
+		//$e = new mb_notice("class_monitor: isImage: Content-Type is " . mime_content_type($image));
+		//$e = new mb_notice("class_monitor: isImage: Content-Type (file) is " . mime_content_type($imageName));
+		if (mime_content_type($imageName)=="image/png") {
+			return true;
+		}
+		return false;
+	}
+
+	/**
+	 * Returns the objects out of the xml file
+ 	 */
+       private function getTagOutOfXML($reportFile,$tagName) {
+		#$e = new mb_notice("class_monitor: getUploadURL: wms = " . $wmsId);
+		#$e = new mb_notice("class_monitor: getUploadURL: upload_id = " . $upload_id);
+		#$sql = "SELECT upload_url FROM mb_monitor WHERE fkey_wms_id = $1 AND upload_id = $2";
+		#$v = array($wmsId, $upload_id);
+		#$t = array('i', 'i');
+		#$res = db_prep_query($sql,$v,$t);
+		#$someArray = db_fetch_array($res);
+		#$e = new mb_notice("class_monitor: getUploadURL: url = " . $someArray["upload_url"]);
+		#$xmlobj = new DOMDocument('1.0');
+  		#$xmlobj->load($reportFile);
+		$xml=simplexml_load_file($reportFile);
+		$result=(string)$xml->wms->$tagName;
+		return $result;
+	}
+	/*
+	* creates a html diff of the xml documents
+	*/
+	private function outputDiffHtml($localXMLArray,$remoteXMLArray) {
+		$diffObj = new Diff($localXMLArray,$remoteXMLArray);
+		$dft = new TableDiffFormatter();
+		return $dft->format($diffObj);
+	}		
+	//TODO get this things out of administration - but without database connection	
+	function is_utf8_string($string) {
+		return preg_match('%(?:
+		[\xC2-\xDF][\x80-\xBF]        # non-overlong 2-byte
+		|\xE0[\xA0-\xBF][\x80-\xBF]               # excluding overlongs
+		|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}      # straight 3-byte
+		|\xED[\x80-\x9F][\x80-\xBF]               # excluding surrogates
+		|\xF0[\x90-\xBF][\x80-\xBF]{2}    # planes 1-3
+		|[\xF1-\xF3][\x80-\xBF]{3}                  # planes 4-15
+		|\xF4[\x80-\x8F][\x80-\xBF]{2}    # plane 16
+		)+%xs', $string);
+	}
+	
+	function is_utf8_xml($xml) {
+		return preg_match('/<\?xml[^>]+encoding="utf-8"[^>]*\?>/is', $xml);
+	}
+	
+	function is_utf8 ($data) {
+		return ($this->is_utf8_xml($data) || $this->is_utf8_string($data));
+	}
+	
+	function char_encode($data) {
+		if (CHARSET == "UTF-8") {
+			if (!$this->is_utf8($data)) {
+				$e = new mb_notice("Conversion: ISO-8859-1 to UTF-8");
+				return utf8_encode($data);
+			}
+		}
+		else {
+			if ($this->is_utf8($data)) {
+				$e = new mb_notice("Conversion: UTF-8 to ISO-8859-1");
+				return utf8_decode($data);
+			}
+		}
+		$e = new mb_notice("No conversion: is " . CHARSET);
+		return $data;
+	}
+
+	function char_decode($data) {
+		if (CHARSET == "UTF-8") {
+			if ($this->is_utf8($data)) {
+				$e = new mb_notice("Conversion: UTF-8 to ISO-8859-1");
+				return utf8_decode($data);
+			}
+		}
+		$e = new mb_notice("no conversion: is " . CHARSET);
+		return $data;
+	}
+}

Added: trunk/mapbender/tools/mod_monitorCapabilities_defineGetMapBbox.php
===================================================================
--- trunk/mapbender/tools/mod_monitorCapabilities_defineGetMapBbox.php	                        (rev 0)
+++ trunk/mapbender/tools/mod_monitorCapabilities_defineGetMapBbox.php	2009-07-30 15:10:07 UTC (rev 4459)
@@ -0,0 +1,272 @@
+<?php
+define("MONITOR_DEFAULT_SCALE", 500000);
+define("MONITOR_IMG_WIDTH", 20);
+define("MONITOR_IMG_HEIGHT", 20);
+define("MB_RESOLUTION", 28.35);
+/**
+	 * retrieves all information necessary to build a map request, 
+	 * concatenates them and returns a valid get map request
+	 */
+	 function getMapRequest($wmsId,$version,$getmap) {
+
+		//map format
+		$sql = "SELECT * FROM wms_format WHERE fkey_wms_id = $1 AND data_type = 'map'";
+		$res = db_prep_query($sql, array($wmsId), array('i'));
+		$row = db_fetch_array($res);
+		$mapFormat = "";
+		while ($row = db_fetch_array($res)) {
+			$mapFormat = urlencode($row["data_format"]);
+			if (preg_match("/png/", $mapFormat) || preg_match("/gif/", $mapFormat) || preg_match("/jp.{1}g/", $mapFormat)) {
+				break;
+			}
+		}
+		
+		//do the request as simple png for all layers, cause this is the minimum that all should support. The function above get only the last format out of the database!
+		$mapFormat = "image/png";
+	
+		// layers (all layers)
+		$sql = "SELECT layer_name FROM layer WHERE fkey_wms_id = $1 AND layer_parent <> '' AND layer_pos > 0";
+		$res = db_prep_query($sql, array($wmsId), array('i'));
+		$layerArray = array();
+		while ($row = db_fetch_array($res)) {
+			array_push($layerArray, urlencode($row["layer_name"]));
+		}
+		$layerList = implode(",", $layerArray);
+	        //Styles
+		$styleList='';
+		for($i=0; $i<count($layerArray);$i++){
+			$styleList .= ',';								}
+		$styleList=substr($styleList,1);
+		// srs (layer_epsg: epsg)
+		// bbox (layer_epsg: minx, miny, maxx, maxy)
+		//first read out root layer_id - cause this request is needed more than once!
+		$sql = "SELECT layer_id from layer WHERE fkey_wms_id = $1 AND layer_pos = 0 AND layer_parent = ''";
+		$res = db_prep_query($sql, array($wmsId), array('i'));
+		$row = db_fetch_array($res);
+		$rootLayerId = $row["layer_id"];
+		//get bbox of the root layer
+		$sql = "SELECT epsg, minx, miny, maxx, maxy ";
+		$sql .= "FROM layer_epsg WHERE fkey_layer_id = $1";
+		//this is done only for root layers!
+		$res = db_prep_query($sql, array($rootLayerId), array('i'));
+		//push all bboxes from mb_db into one array as mb_bbox object
+		$bboxArray = array();
+		while ($row = db_fetch_array($res)) {
+			array_push($bboxArray, new Mapbender_bbox($row["minx"], $row["miny"], $row["maxx"], $row["maxy"], $row["epsg"]));
+		}
+	
+		// get a bbox in a preferably non WGS84 epsg to use the scalehints
+		for ($i=0; $i < count($bboxArray); $i++) {
+			$bbox = $bboxArray[$i];		//read out the object	
+			if ($bboxArray[$i]->epsg != "EPSG:4326") {
+				break; //it ends if some none epsg:4326 bbox was found -maybe this behavior can be exchanged TODO
+			}
+		}
+		
+		/*
+		 * transform to 31466 if is 4326 - this is done if the loop before dont give other bbox than epsg:4326  
+		 * TODO: extend to other EPSG apart from 31466
+		 */
+		if ($bbox->epsg == "EPSG:4326") {
+			$bbox->transform("EPSG:31466");
+		}
+		
+		/*
+		 * get map and check if result is image 
+		 */
+		// check if this WMS supports exception type XML
+		$sql = "SELECT data_format FROM wms_format WHERE fkey_wms_id = $1 AND data_type = 'exception'";
+		$v = array($wmsId);
+		$t = array('i');
+		$res = db_prep_query($sql,$v,$t);
+		while ($row = db_fetch_array($res)) {
+			$exceptionFormat = $row["data_format"];
+			// set the exception type to xml (if possible)
+			if (preg_match('/xml/', $exceptionFormat)) {
+				$supportsXMLException = true;
+				break; 
+			}
+		}
+
+		// correct bbox according to scale
+		$scale = getScaleForWMS($wmsId);
+		//echo "layer_id: ".$rootLayerId."\n";
+		//echo "Scale: ".$scale."\n";
+		//var_dump($bbox);
+		//echo "\n";
+		$e = new mb_exception("monitorDefineGetMapBBOX: BBOX berechnen fuer wms " . $wmsId);
+		if (($bbox!=NULL) and ($bbox->min!=NULL) and ($bbox->max!=NULL)) {
+			$bbox = getBBoxInScale($bbox, $scale);
+			return concatenateMapRequest($getmap, $version, $mapFormat, $layerList, $styleList,$bbox, MONITOR_IMG_WIDTH, MONITOR_IMG_HEIGHT, $exceptionFormat);
+		}
+		else {
+			return "Monitor Error: The root-layer of the service dont include a BBOX";			
+		}
+		 
+	}
+	
+	/**
+	 * updates a given BBox according to a given scale
+	 * 
+	 * @param bbox 
+	 * @param scale 
+	 */
+	 function getBBoxInScale($bbox, $scale) {
+		#$e = new mb_notice("class_monitor: getMapRequest: old bbox = " . $bbox);
+		#$e = new mb_notice("class_monitor: getMapRequest: old bbox = " . $bbox->min->x . "," . $bbox->min->y . "," . $bbox->max->x . "," . $bbox->max->y);
+		#$e = new mb_notice("class_monitor: getMapRequest: scale = " . $scale);
+		if ($scale) {
+			$e = new mb_exception("monitorDefineGetMapBBOX: minmaxwerte? " . $bbox->max." ".$bbox->min);
+			$center = $bbox->min->plus($bbox->max)->times(0.5);
+		#	$e = new mb_notice("class_monitor: getMapRequest: center = " . $center);
+			
+			/*
+			 * TODO: this formula should have documentation
+			 */
+			$offset =  MONITOR_IMG_WIDTH / (MB_RESOLUTION * 100 * 2) * $scale;
+			$offsetPoint = new Mapbender_point($offset, $offset, $bbox->epsg);
+			$min = $center->minus($offsetPoint);
+			$max = $center->plus($offsetPoint);
+			$bbox->min = $min;
+			$bbox->max = $max;
+			#$e = new mb_notice("class_monitor: getMapRequest: new bbox = " . $bbox);
+			#$e = new mb_notice("class_monitor: getMapRequest: new bbox = " . $bbox->min->x . "," . $bbox->min->y . "," . $bbox->max->x . "," . $bbox->max->y);
+		}
+		return $bbox;
+	}
+	
+	
+	/**
+	 * Returns an online resource representing a get map request
+	 */
+	 function concatenateMapRequest(	$getmap, $wmsVersion, $mapFormat, $layerList, $sytleList,
+							$bbox, $width, $height, $exceptionFormat) {
+		/*
+		 * getMap URL
+		 */
+		$mapRequest = $getmap;
+		$mapRequest .= mb_getConjunctionCharacter($getmap);
+		
+		/*
+		 * WMS version
+		 */
+		if ($wmsVersion == "1.0.0") {
+			$mapRequest .= "WMTVER=" . $wmsVersion . "&REQUEST=map&";
+		}
+		else {
+			$mapRequest .= "VERSION=" . $wmsVersion . "&REQUEST=GetMap&SERVICE=WMS&";
+		}
+		
+		/*
+		 * Layer list
+		 */
+		$mapRequest .= "LAYERS=" . $layerList . "&";
+		/*
+		 * Sytle List
+		 */
+		$mapRequest .= "STYLES=" . $styleList ."&"; 
+		
+		/*
+		 * Format
+		 */
+		 $mapRequest .= "FORMAT=" . $mapFormat . "&";
+		 
+		/*
+		 * SRS and BBox
+		 */
+		$mapRequest .= "SRS=" . $bbox->epsg . "&";
+		$mapRequest .= "BBOX=" . $bbox->min->x . "," . $bbox->min->y . "," . $bbox->max->x . "," . $bbox->max->y . "&";
+		 
+		/*
+		 * Width and height
+		 */
+		$mapRequest .= "WIDTH=" . $width . "&";
+		$mapRequest .= "HEIGHT=" . $height . "&";
+		 
+		/*
+		 * BGColor
+		 */
+		$mapRequest .= "BGCOLOR=0xffffff&";
+	
+		/*
+		 * Transparency
+		 */
+		if (preg_match("/png/", $mapFormat) || preg_match("/gif/", $mapFormat)) {
+			$mapRequest .= "TRANSPARENT=TRUE&";
+		}
+		 
+		/*
+		 * Exception format
+		 */
+		$mapRequest .= "EXCEPTIONS=" . $exceptionFormat . "&";
+		
+//		return urlencode($mapRequest);	
+		return $mapRequest;	
+	}
+	
+	/**
+	 * Checks if the given WMS has ScaleHints. If yes, a scale is selected and returned.
+	 */
+	 function getScaleForWMS($rootLayerId) {
+		// get the scalehints
+		$sql = "SELECT layer_minscale, layer_maxscale FROM layer WHERE layer_id = $1 AND layer_minscale <> layer_maxscale LIMIT 1";
+		$v = array($rootLayerId);
+		$t = array('i');
+		$res = db_prep_query($sql,$v,$t);
+		$scaleHintArray = db_fetch_array($res);
+		
+		/*
+		 *  determine the scalehint
+		 */
+		// if a scalehint exists 
+		if ($scaleHintArray) {
+			// if upper boundary
+			if ($scaleHintArray["layer_minscale"] < $scaleHintArray["layer_maxscale"]) {
+				// TODO: find a better algorithm with a less obscure scale
+				$scaleHint = round($scaleHintArray["layer_maxscale"] - $scaleHintArray["layer_minscale"]) / 2;				
+			}
+			// if lower boundary
+			else {
+				if ($scaleHintArray["layer_minscale"] < MONITOR_DEFAULT_SCALE) {
+					$scaleHint = MONITOR_DEFAULT_SCALE;
+				}
+				else {
+					// TODO: find a better algorithm with a less obscure scale
+					$scaleHint = $scaleHintArray["layer_minscale"] + 1000;
+				}
+			}
+		}
+		// otherwise, use a default value
+		else {
+			$scaleHint = MONITOR_DEFAULT_SCALE;
+		}
+		return $scaleHint;
+	}
+/**
+	 * Returns the character that needs to be appended to 
+	 * a given online resource, in order to append other GET 
+	 * parameters.
+	 * 
+	 * Possible characters: "?", "&", ""
+	 */
+	function mb_getConjunctionCharacter($onlineresource){
+		// index of character ? in online resource
+		$indexOfChar = mb_strpos($onlineresource,"?");
+	
+		if($indexOfChar) {
+			// no conjunction character needed
+			if($indexOfChar == mb_strlen($onlineresource)-1){ 
+				return "";
+			}
+			// no conjunction character needed
+			else if (mb_substr($onlineresource, mb_strlen($onlineresource)-1) == "&") {
+				return "";
+			}
+			else{
+				return "&";
+			}
+		}
+		return "?";
+	}
+
+?>

Modified: trunk/mapbender/tools/mod_monitorCapabilities_main.php
===================================================================
--- trunk/mapbender/tools/mod_monitorCapabilities_main.php	2009-07-30 15:04:27 UTC (rev 4458)
+++ trunk/mapbender/tools/mod_monitorCapabilities_main.php	2009-07-30 15:10:07 UTC (rev 4459)
@@ -1,8 +1,4 @@
 <?php
-# $Id: mod_monitorCapabilities_main.php 1240 2007-10-24 09:27:00Z baudson $
-# http://www.mapbender.org/index.php/Monitor_Capabilities
-# 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)
@@ -16,22 +12,23 @@
 # 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_validateSession.php");
-require_once(dirname(__FILE__)."/../../conf/mapbender.conf");
-//session_start();
-//import_request_variables("PG");
-require_once(dirname(__FILE__)."/../classes/class_administration.php");
-$con = db_connect($DBSERVER,$OWNER,$PW);
-db_select_db(DB,$con);
+
+require_once dirname(__FILE__) ."/../core/globalSettings.php";
+require_once dirname(__FILE__) ."/../http/classes/class_administration.php";
+require_once dirname(__FILE__) ."/../tools/mod_monitorCapabilities_defineGetMapBbox.php";
+require_once dirname(__FILE__) ."/../http/classes/class_bbox.php";
+
+#do db close at the most reasonable point 
 $admin = new administration();
 
-//$user = "root";
-$user = "";
-$gui = "";
-$cl = 0;
+$user = null;
+$group = null;
+$application = null;
 
+$cl = false;
 
-function getConjunctionCharacter($onlineresource){
+// can be replaced by existing functionality
+function getConjunctionCharacter($onlineresource) {
 	if(strstr($onlineresource, "?")) {
 		$lastChar = substr($onlineresource,strlen($onlineresource)-1, 1);  
 		if ($lastChar == "?" || $lastChar == "&") {return "";}
@@ -40,174 +37,301 @@
 	else {return "?";} 
 }
 
-// retrieve username and gui_id
-if ($_REQUEST['user']) {
-	$cl = 0;
-	//browser
-	echo "browser";
-	$user = $_REQUEST['user'];
-	$gui = $_REQUEST['gui'];
+function getTagOutOfXML($reportFile,$tagName) {
+	$xml=simplexml_load_file($reportFile);
+	$result=(string)$xml->wms->$tagName;
+	return $result;
 }
-elseif ($_SERVER["argv"][1]) {
-	$cl = 1;
-	//command line
-	$p1 = $_SERVER["argv"][1];
-	$p2 = $_SERVER["argv"][2];
-	if (substr($p1, 0,5) == "user:") {
-		$user = substr($p1, 5);
-		if (substr($p2, 0,4) == "gui:") {
-			$gui = substr($p2, 4);
+
+//command line
+if ($_SERVER["argc"] > 0) {
+	$cl = true;
+
+	if ($_SERVER["argc"] > 1 && $_SERVER["argv"][1] !== "") {
+		$param = $_SERVER["argv"][1];
+		if (substr($param, 0,5) == "user:") {
+			$user = substr($param, 5);
 		}
+		if (substr($param, 0,6) == "group:") {
+			$group = substr($param, 6);
+		}
 	}
+	else {
+		echo _mb("Specify a user ID or a group ID to monitor.") . "\n\n";
+		echo "php5 <script name> user:<user_id> \n\n";
+		echo "php5 <script name> group:<group_id> \n\n";
+	}
 }
+//browser
+else if ($_GET['user'] || $_GET['group'] || $_GET['app']) {
+	$user = $_GET['user'] ? intval($_GET['user']) : null;
+	$group = $_GET['group'] ? intval($_GET['group']) : null;
+}
 else {
-	echo "Please specify a username!\n";die();
+	echo _mb("Please specify a user ID or a group ID!") . " ";
+	echo _mb("You can pass the GET arguments 'user' or 'group'!");
+	die;
 }
 
-$userid = $admin->getUserIdByUserName($user);
+$br = "<br><br>";
+if ($cl) {
+	$br = "\n\n";
+}
 
-/*
- * if the current user is a valid user...
- */
-if ($userid) {
-	$ownguis = $admin->getGuisByOwner($userid,true);
-	/*
-	 * if monitoring is restricted to a single GUI...
-	 */
-	if ($gui) {
-		// ... abort if the GUI doesn't exist
-		if (!$admin->guiExists($gui)) {
-			echo "GUI " . $gui . " doesn't exist.\n"; die();
-		}
-		// ... add the GUI to the array of GUIs that will be monitored
-		elseif (in_array($gui, $ownguis)) {
-			$ownguis = array($gui);
-		} 
-		// ... abort if the GUI is not owned by the current user
-		else {
-			echo "User " . $user . " is not owner of GUI " . $gui . ".\n"; die();
-		}
+$userIdArray = array();
+
+//loop for doing the monitor for all registrating institutions ****************
+if (!is_null($group)) {
+	echo "monitoriing " . $group;
+	if (!is_numeric($group)) {
+		echo _mb("Parameter 'group' must be numeric.");
+		die;
 	}
+
+	//read out user who are subadmins - only their services are controlled - til now
+	$sql = "SELECT fkey_mb_user_id FROM mb_user_mb_group WHERE " . 
+		"fkey_mb_group_id = (SELECT mb_group_id FROM mb_group WHERE " . 
+		"mb_group_id = $1)";
+
+	$v = array($group);
+	$t = array('i');
+	$res = db_prep_query($sql,$v,$t);
+
+	$userIdArray = array();
+	while ($row = db_fetch_array($res)) {
+		$userIdArray[] = $row["fkey_mb_user_id"];
+	}
 }
-/*
- * if current user is not a valid user, abort
- */
+else if (!is_null($user)) {
+	if (!is_numeric($user)) {
+		echo _mb("Parameter 'user' must be numeric.");
+		die;
+	}
+	$userIdArray = array($user);
+}
 else {
-	echo $user . " is not a valid username.\n";	die();
+	if ($_SERVER["argc"] > 0) {
+		echo _mb("Specify a user ID or a group ID to monitor.") . "\n\n";
+		echo "php5 <script name> user:<user_id> \n\n";
+		echo "php5 <script name> group:<group_id> \n\n";
+	}
+	else {
+		echo _mb("Please specify a user ID or a group ID!") . " ";
+		echo _mb("You can pass the GET arguments 'user' or 'group'!");
+	}
+	die;
 }
 
-/**
- * Array of WMS IDs. These are the WMS that the user owns.
- */
-$wms_id_own = $admin->getWmsByOwnGuis($ownguis);
+if (count($userIdArray) === 0) {
+	echo _mb("No user found for the given parameters.");
+	die;
+}
 
-// initialise monitoring processes
-echo "Starting monitoring cycle...\n\n";
-if ($cl == 0) echo "<br/><br/>";
-echo "WMS services are requested for availability.\n"; 
-if ($cl == 0) echo "<br/>";
-echo "Capabilities documents are requested and all changes synchronized with the database cache.\n\n";
-if ($cl == 0) echo "<br/><br/>";
+$user_id_all = $userIdArray;
+echo $br ."Count of registrating users: " . count($user_id_all) . $br;
 
-$time = strval(time()-2);
+$time_array = array();
 
-for ($k=0; $k<count($wms_id_own); $k++) {
-	$sql = "SELECT wms_upload_url FROM wms WHERE wms_id = $1";
-	$v = array($wms_id_own[$k]);
-	$t = array('i');
-	$res = db_prep_query($sql,$v,$t);
-	$someArray = db_fetch_row($res);
-	$url = $someArray[0];
-	
-	if (!$upload_url || $upload_url == "") {
-		$sql = "SELECT wms_version, wms_getcapabilities FROM wms WHERE wms_id = $1";
+for ($iz = 0; $iz < count($user_id_all); $iz++) {
+	$userid = $user_id_all[$iz];
+
+	//get all owned wms
+	$wms_id_own = $admin->getWmsByWmsOwner($userid);
+
+	// initialize monitoring processes
+	echo "Starting monitoring cycle...$br";
+	echo "WMS services are requested for availability.$br"; 
+	echo "Capabilities documents are requested and compared to the infos in the service db.$br";
+
+	//new: time user-monitoring cycle must stored in array
+	$time_array[$userid] = strval(time());
+	//wait 2 seconds to give enough time between to different users the time can differ also for one user!
+	sleep(1);
+
+	$time = $time_array[$userid];
+
+	for ($k=0; $k<count($wms_id_own); $k++) {
+		
+		//get relevant data out of registry
+		$sql = "SELECT wms_upload_url, wms_getcapabilities_doc, " . 
+			"wms_version, wms_getcapabilities, wms_getmap FROM wms " . 
+			"WHERE wms_id = $1";
 		$v = array($wms_id_own[$k]);
 		$t = array('i');
 		$res = db_prep_query($sql,$v,$t);
-		$someArray = db_fetch_row($res);
+		$someArray = db_fetch_array($res);
+		$url = $someArray['wms_upload_url'];
+		
+		$capDoc = $someArray['wms_getcapabilities_doc'];
+		$version = $someArray['wms_version'];
+		$capabilities = $someArray['wms_getcapabilities'];
+		$getmap = $someArray['wms_getmap'];
+		$getMapUrl = getMapRequest($wms_id_own[$k], $version, $getmap);
 
-		$version = $someArray[0];
-		$capabilities = $someArray[1]; 	
-		if ($version == "1.0.0" ) {
-			$url = $capabilities . getConjunctionCharacter($capabilities) . "REQUEST=capabilities&WMTVER=1.0.0";
-		}
-		else {
-			$url = $capabilities . getConjunctionCharacter($capabilities) . "REQUEST=GetCapabilities&SERVICE=WMS&VERSION=" . $version;	
-		}
-	}
-	
-	$sql = "INSERT INTO mb_monitor (upload_id, fkey_wms_id, status, status_comment, timestamp_begin, timestamp_end, upload_url, updated) ";
-	$sql .= "VALUES ($1, $2, $3, $4, $5, $6, $7, $8)";
-	$v = array($time,$wms_id_own[$k],"-2","Monitoring is still in progress...", time(),time(),$url,"0");
-	$t = array('s', 'i', 's', 's', 's', 's', 's', 's');
-	$res = db_prep_query($sql,$v,$t);
-}
+		// for the case when there is no upload url - however - we need the 
+		// url to the capabilities file
+   		if (!$url || $url == "") {
+			$capabilities=$admin->checkURL($capabilities);
+			if ($version == "1.0.0" ) {
+				$url = $capabilities . "REQUEST=capabilities&WMTVER=1.0.0";
+			}
+			else {
+				$url = $capabilities . "REQUEST=GetCapabilities&" . 
+					"SERVICE=WMS&VERSION=" . $version;
+			}
+   		}
+		//$url is the url to the service which should be monitored in this cycle
+		//initialize monitoriung in db (set status=-2)
+		echo "initialize monitoring for user: " . $userid . 
+			" WMS: " . $wms_id_own[$k] . $br;
+			$sql = "INSERT INTO mb_monitor (upload_id, fkey_wms_id, " . 
+				"status, status_comment, timestamp_begin, timestamp_end, " . 
+				"upload_url, updated)";
+		$sql .= "VALUES ($1, $2, $3, $4, $5, $6, $7, $8)";
 
-for ($k=0; $k<count($wms_id_own); $k++) {
+		$v = array(
+			$time,
+			$wms_id_own[$k],
+			"-2",
+			"Monitoring is still in progress...", 
+			time(),
+			"0",
+			$url,
+			"0"
+		);
+		$t = array('s', 'i', 's', 's', 's', 's', 's', 's');
+		$res = db_prep_query($sql,$v,$t);
 
-	if (intval(AUTO_UPDATE)) {
-		$exec = PHP_PATH . "php5 mod_monitorCapabilities_write.php ".$wms_id_own[$k]." ".$time." 1 > ../tmp/output_".$time."_".$wms_id_own[$k].".txt &";
+		// Decode orig capabilities out of db cause they are converted before 
+		// saving them while upload
+		$capDoc=$admin->char_decode($capDoc);
+
+		// do the next to exchange the update before by another behavior! - 
+		// look in class_monitor.php !
+		$currentFilename = "wms_monitor_report_" . $time . "_" . 
+			$wms_id_own[$k] . "_" . $userid . ".xml";
+ 		$report = fopen("./tmp/" . $currentFilename,"a");
+		$lb = chr(13).chr(10);
+
+		fwrite($report,"<monitorreport>".$lb);
+		fwrite($report,"<wms>".$lb);
+		fwrite($report,"<wms_id>".$wms_id_own[$k]."</wms_id>".$lb);
+		fwrite($report,"<upload_id>".$time."</upload_id>".$lb);
+		fwrite($report,"<getcapbegin></getcapbegin>".$lb);
+		fwrite($report,"<getcapurl>".urlencode($url)."</getcapurl>".$lb);
+		fwrite($report,"<getcapdoclocal>".urlencode($capDoc)."</getcapdoclocal>".$lb);
+		fwrite($report,"<getcapdocremote></getcapdocremote>".$lb);
+		fwrite($report,"<getcapdiff></getcapdiff>".$lb);
+		fwrite($report,"<getcapend></getcapend>".$lb);
+		fwrite($report,"<getcapduration></getcapduration>".$lb);
+		fwrite($report,"<getmapurl>".urlencode($getMapUrl)."</getmapurl>".$lb);
+		fwrite($report,"<status>-2</status>".$lb);
+		fwrite($report,"<image></image>".$lb);
+		fwrite($report,"<comment>Monitoring in progress...</comment>".$lb);
+		fwrite($report,"<timeend></timeend>".$lb);
+		fwrite($report,"</wms>".$lb);
+		fwrite($report,"</monitorreport>".$lb);
+		fclose($report);
+
+		// start of the monitoring processes on shell 
+		// (maybe problematic for windows os)
+   		$exec = "php5 " . dirname(__FILE__) . "/mod_monitorCapabilities_write.php " . 
+			$currentFilename . " 0 > /dev/null &";
+   		exec($exec);
 	}
-	else {
-		$exec = PHP_PATH . "php5 mod_monitorCapabilities_write.php ".$wms_id_own[$k]." ".$time." 0 > ../tmp/output_".$time."_".$wms_id_own[$k].".txt &";
-	}
-	exec($exec);
+	echo "Monitoring start cycle for user: ".$userid." has ended. " . 
+		"(Altogether: " . count($wms_id_own) . " WMS monitorings started).$br";
 }
-echo "Monitoring Cycle completed (total: " . count($wms_id_own) . " wms).\n\n";
-if ($cl == 0) echo "<br/><br/>";
-set_time_limit(2*TIME_LIMIT);
+//set time limit (mapbender.conf)
+set_time_limit(TIME_LIMIT);
+// wait until all monitoring processes are finished
+echo "please wait " . TIME_LIMIT . " seconds for the monitoring to finish...$br";
 
-// wait until all monitoring processes are finished
-echo "please wait " . TIME_LIMIT . " seconds for the monitoring to finish...\n\n";
-if ($cl == 0) echo "<br/><br/>";
 sleep(TIME_LIMIT);
+//when time limit has ended: begin to collect results for every registrating user
+for ($iz = 0; $iz < count($user_id_all); $iz++) {
+	// when time limit has ended: begin to collect results for every 
+	// registrating user
+	$problemOWS = array();//define array with id's of problematic wms
+	$commentProblemOWS = array();
+	$userid = $user_id_all[$iz];
+	//get the old upload_id from the monitoring to identify it in the database
+	$time = $time_array[$userid];	
+	//read sequencialy all user owned xml files from tmp and update the 
+	// records in the database 
+	$wms_id_own = $admin->getWmsByWmsOwner($userid);
+	for ($k = 0; $k < count($wms_id_own); $k++) {
+		$monitorFile = "./tmp/wms_monitor_report_" . $time . "_" . 
+			$wms_id_own[$k] . "_".$userid.".xml";
+		$status = getTagOutOfXML($monitorFile,"status");
+		$status_comment = getTagOutOfXML($monitorFile,"comment");
+		$cap_diff = getTagOutOfXML($monitorFile,"getcapdiff");
+		$image = getTagOutOfXML($monitorFile,"image");
+		$map_url = urldecode(getTagOutOfXML($monitorFile,"getmapurl"));
+		$timestamp_begin = getTagOutOfXML($monitorFile,"getcapbegin");
+		$timestamp_end = getTagOutOfXML($monitorFile,"getcapend");
 
-$sql = "SELECT fkey_wms_id, status, status_comment, timestamp_begin, timestamp_end, upload_url FROM mb_monitor WHERE upload_id = $1";
-$v = array($time);
-$t = array('i');
-$res = db_prep_query($sql,$v,$t);
+		$sql = "UPDATE mb_monitor SET updated = $1, status = $2, " . 
+			"image = $3, status_comment = $4, timestamp_end = $5, " . 
+			"map_url = $6 , timestamp_begin = $7, caps_diff = $8 " . 
+			"WHERE upload_id = $9 AND fkey_wms_id=$10 ";
 
-$cnt=0;
-while ($row = db_fetch_array($res)) {
-	$status[$cnt] = intval(db_result($res,$cnt,"status"));
-	$wms_id[$cnt] = db_result($res,$cnt,"fkey_wms_id");
-	$comment[$cnt] = db_result($res,$cnt,"status_comment");
-	$upload_url[$cnt] = db_result($res,$cnt,"upload_url");
-	$timestamp_begin[$cnt] = db_result($res,0,"timestamp_begin");
-	$timestamp_end[$cnt] = db_result($res,0,"timestamp_end");
-	$cnt++;
-}
+		// check if status = -2 return new comment and status -1, 
+		// push into problematic array
+		if ($status == '-1' or $status == '-2') {
+			$status_comment = "Monitoring process timed out.";
+			$status = '-1';
+			array_push($problemOWS,$wms_id_own[$k]);
+			array_push($commentProblemOWS,$status_comment);
+		} 
 
-$body = "";
-for ($i=0; $i<$cnt; $i++) {
-	// if monitoring is still in progress and time limit has expired, update database
-	if ($status[$i] == -2 && intval(time())-intval($timestamp_begin[$i]) > intval(TIME_LIMIT)) {
-		$comment[$i] = "Monitoring process timed out.";
-		$status[$i] = -1;	
-		$new_sql = "UPDATE mb_monitor SET status = '-1', image = '-1', status_comment = 'Monitoring process timed out.', timestamp_end = $1 WHERE fkey_wms_id = $2 AND upload_id = $3";
-		$new_v = array((intval($upload_id[$i])+intval(TIME_LIMIT)), $wms_id[$i], $time);
-		$new_t = array('s', 'i', 's');
-		$new_res = db_prep_query($new_sql,$new_v,$new_t);
+		$v = array(
+			'0', 
+			intval($status), 
+			intval($image), 
+			$status_comment, 
+			(string)intval($timestamp_end), 
+			$map_url, 
+			(string)intval($timestamp_begin), 
+			$cap_diff,
+			(string)$time, 
+			$wms_id_own[$k]
+		);
+		$t = array('s', 'i', 'i', 's', 's', 's', 's', 'i','s');
+		$res = db_prep_query($sql,$v,$t);
 	}
-	// compose mail message
-	echo $wms_id[$i] . ": status " . $status[$i] . "\n";
-	if ($cl == 0) echo "<br/><br/>";
-	if ($status[$i] == -1) {
-		$body .= $admin->getWmsTitleByWmsId($wms_id[$i]) . " (" . $wms_id[$i] . "): " . $comment[$i] . "\n\n";
+	$body = "";
+	echo "\nmonitoring info in db for user: ".$userid."\n";
+	//loop for single monitor requests that has problems
+	for ($i=0; $i < count($problemOWS); $i++) {
+		$body .= $br . $admin->getWmsTitleByWmsId($problemOWS[$i]) . 
+			" (" . $problemOWS[$i] . "): " . $commentProblemOWS[$i] . $br;
 	}
-}
-
-// Send an email to the user
-if ($body) {
-	$error_msg = "";
-	if ($admin->getEmailByUserId($userid)) {
-//		$admin->sendEmail(MAILADMIN, MAILADMINNAME, $admin->getEmailByUserId($userid), $user, "WMS monitor report " . date("F j, Y, G:i:s", $time), utf8_decode($body), &$error_msg);
+	unset($problemOWS);
+	unset($commentProblemOWS);
+	//end of loop for single monitor requests
+	// Send an email to the user if body string exists
+	if ($body) {
+		$error_msg = "";
+		if ($admin->getEmailByUserId($userid)) {
+			$admin->sendEmail(
+				MAILADMIN, 
+				MAILADMINNAME, 
+				$admin->getEmailByUserId($userid), 
+				$user, 
+				"Mapbender monitoring report " . date("F j, Y, G:i:s", $time), 
+				utf8_decode($body), 
+				&$error_msg
+			);
+		}
+		else {
+			$error_msg = "Email address of user '" . 
+				$admin->getUserNameByUserId($userid) . 
+				"' unknown!\n";
+		}
+		if ($error_msg) {
+			echo "\n ERROR: " . $error_msg;
+		}
 	}
-	else {
-		$error_msg = "Email address of user '" . $admin->getUserNameByUserId($userid) . "' unknown!\n";
-	}
-	if ($error_msg) {
-		echo "\n ERROR: " . $error_msg;
-	}
 }
-?>
+?>
\ No newline at end of file

Modified: trunk/mapbender/tools/mod_monitorCapabilities_write.php
===================================================================
--- trunk/mapbender/tools/mod_monitorCapabilities_write.php	2009-07-30 15:04:27 UTC (rev 4458)
+++ trunk/mapbender/tools/mod_monitorCapabilities_write.php	2009-07-30 15:10:07 UTC (rev 4459)
@@ -1,41 +1,19 @@
 <?php
-# $Id: mod_monitorCapabilities_write.php 1235 2007-10-23 15:42:55Z baudson $
-# http://www.mapbender.org/index.php/Monitor_Capabilities
-# 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__)."/../lib/class_Monitor.php");
 
-session_start();
-
-require_once(dirname(__FILE__)."/../classes/class_monitor.php");
-
 /*
  * incoming parameters from command line
  */
-if ($_SERVER["argc"] != 4) {
-	echo "Insufficient arguments! Monitoring aborted.";
-	die();
+if ($_SERVER["argc"] != 3) {
+	echo _mb("Insufficient arguments! Monitoring aborted.");
+	die;
 }
 
-$wmsId = $_SERVER["argv"][1];
-$uploadId = $_SERVER["argv"][2];
-$autoUpdate = intval($_SERVER["argv"][3]);
+$reportFile = $_SERVER["argv"][1];
 
-$monitor = new Monitor($wmsId, $uploadId, $autoUpdate);
+$autoUpdate = intval($_SERVER["argv"][2]);
 
-echo $monitor;	
+$monitor = new Monitor($reportFile, $autoUpdate, "./tmp/");
 
-$monitor->updateInDB();
-?>
\ No newline at end of file
+$monitor->updateInXMLReport();
+?>



More information about the Mapbender_commits mailing list