NCCOOS Trac Projects: Top | Web | Platforms | Processing | Viz | Sprints | Sandbox | (Wind)

root/Chameleon/trunk/Chameleon/ExtractWFSData/ExtractWFSData.php

Revision 13 (checked in by jcleary, 17 years ago)

Latest Chameleon code checkout from previous repository

Line 
1 <?php
2 /**
3  * @project     Chameleon
4  * @revision    $Id: ExtractWFSData.php,v 1.10 2004/12/02 16:55:08 wbronsema Exp $
5  * @purpose     This contains the supporting php code.
6  * @author      William A. Bronsema, C.E.T. (dev@dmsolutions.ca)
7  * @copyright
8  * <b>Copyright (c) 2003, DM Solutions Group Inc.</b>
9  * Permission is hereby granted, free of charge, to any person obtaining a
10  * copy of this software and associated documentation files (the "Software"),
11  * to deal in the Software without restriction, including without limitation
12  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
13  * and/or sell copies of the Software, and to permit persons to whom the
14  * Software is furnished to do so, subject to the following conditions:
15  *
16  * The above copyright notice and this permission notice shall be included
17  * in all copies or substantial portions of the Software.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
22  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25  * DEALINGS IN THE SOFTWARE.
26  **/
27
28 // set the time limit
29 set_time_limit( 120 );
30
31 //set the language resource file
32 $szLanguageResource = str_replace("\\","/",dirname(__FILE__))."/ExtractWFSData.dbf";
33
34 // include the layer attribute handling functions
35 include( dirname(__FILE__)."/../LayerAttributes.php" );
36
37 // set the flag to setup the mapsession
38 if ( !defined("LOAD_MAPSESSION") )
39     define("LOAD_MAPSESSION", 1);
40
41 // include the session handling file (currently only required for MLT)
42 include_once("../session.inc.php");
43 include_once("../CWC2ButtonCache.php");
44
45 // include the ogr handling functions
46 include( COMMON."/ogr/ogr2ogr.php" );
47
48 // check if the ogr module is available
49 $szOGRModuleName = '';
50 $bModuleFound = checkOGRModule( $szOGRModuleName );
51
52 // get the form vars
53 $_FORM = array_merge( $_GET, $_POST );
54
55 /* ============================================================================
56  * Determine the layer specific info
57  * ========================================================================= */
58 // init vars
59 $nCount = 0;
60 $nSelectedLayer = '';
61 $szSelectedLayerName = "";
62 $szErrorNotice = "";
63 $szWFSConnection = "";
64 $szLayerType = "";
65 $bSkipGetFeature = false;
66 $bClearFilter = false;
67 $nLayerCount = $oMapSession->oMap->numlayers;
68 $szSpacialFilter = '';
69 $szExistingWFSFilter = '';
70 $szROIExists = '';
71
72 // loop through layers and determine which ones are selected
73 for ( $i=0; $i<$nLayerCount; $i++ )
74 {
75     // init var
76     $bSelected = false;
77
78     // get layer
79     $oLayer = $oMapSession->oMap->getLayer( $i );
80
81     // check if overide on selected layer is needed
82     if ( isset( $_FORM["selectedlayers"] ) &&
83                                         strlen( $_FORM["selectedlayers"] ) > 0 )
84     {
85         // put layers into array
86         $aszLayers = explode( ",", $_FORM["selectedlayers"] );
87         for( $j=0; $j<count( $aszLayers ); $j++ )
88         {
89             $aszLayers[$j] = trim( $aszLayers[$j] );
90             if ($aszLayers[$j] == $oLayer->name ||
91                 $aszLayers[$j] == $oLayer->getMetadata( "WMS_NAME" ) ||
92                 $aszLayers[$j] == $oLayer->getMetadata( "WMS_TITLE" ))
93             {
94                 $bSelected = true;
95             }
96         }
97         // check if layer is in the array
98         //$bSelected = in_array( trim( $oLayer->name ), $aszLayers );
99     }
100     else
101     {
102         $bSelected = $oLayer->getmetadata("selected") == 1;
103     }
104
105     // process layer if selected
106     if ( $bSelected )
107     {
108         // record the info for first selected layer only
109         if ( strlen( $nSelectedLayer ) <= 0 )
110         {
111             // determine the layer name to use
112             $szSelectedLayerName =  $oLayer->name;
113             // process according to layer type
114             if( $oLayer->connectiontype == MS_WFS )
115             {
116                 // record layer index
117                 $nSelectedLayer = $i;
118
119                 // record the connection string
120                 $szWFSConnection = $oLayer->connection;
121
122                 // set type
123                 $szLayerType = "WFS";
124             }
125             elseif( $oLayer->connectiontype == MS_WMS )
126             {
127                 // record layer index
128                 $nSelectedLayer = $i;
129
130                 // set type
131                 $szLayerType = "WMS";
132                 $szSelectedLayerName = $oLayer->getMetadata( "WMS_NAME" );
133
134                 // resort to layer name for the selected layer name
135                 if ( strlen( $szSelectedLayerName ) <= 0 )
136                 {
137                     $szSelectedLayerName = $oLayer->name;
138                 }
139
140                 // get the connection info only if extracting
141                 if ( isset( $_FORM["txtExtract"] ) && $_FORM["txtExtract"] == 1 )
142                 {
143                     // get the url to perform a describelayer on
144                     $szWMSConnection = trim( $oLayer->connection );
145                     $szUpperCase = strtoupper( $szWMSConnection );
146
147                     // check last char for ? or &
148                     if ( substr( $szWMSConnection, -1 ) != "?" &&
149                          substr( $szWMSConnection, -1 ) != "&" )
150                     {
151                         // check for ?
152                         if ( strpos( $szWMSConnection, "?" ) === false )
153                         {
154                             $szWMSConnection .= "?";
155                         }
156                         else
157                             $szWMSConnection .= "&";
158                     }
159
160                     // check for and add VERSION
161                     if ( strpos( $szUpperCase, "VERSION=" ) === false )
162                         $szWMSConnection .= "VERSION=1.1.0&";
163
164                     // check for and add SERVICE
165                     if ( strpos( $szUpperCase, "SERVICE=" ) === false )
166                         $szWMSConnection .= "SERVICE=WMS&";
167
168                     // add LAYERS
169                     if ( strpos( $szUpperCase, "LAYERS=" ) ===  false )
170                         $szWMSConnection .= "LAYERS=".$szSelectedLayerName."&";
171
172                     // add REQUEST
173                     $szWMSConnection .= "REQUEST=DESCRIBELAYER";
174
175                     // perform a describe layer
176                     if ( !$aszWFSConnection = getWFSResource( $szWMSConnection ) )
177                     {
178                         $szErrorNotice .= $oMLT->get("12", "WMS `DescribeLayer` request failed.  ".
179                             "The server returned the following: %1\$s",
180                             array() );
181                     }
182                     else
183                     {
184                         // record set the wfs connection
185                         $szWFSConnection = $aszWFSConnection['wfs'];
186                     }
187                 }
188             }
189             // increment the counter
190             $nCount++;
191         }
192     }
193 }
194
195 /* ============================================================================
196  * Build spacial filter
197  * ========================================================================= */
198 if ( strlen( $nSelectedLayer ) > 0 )
199 {
200     // get layer
201     $oLayer = $oMapSession->oMap->getLayer( $nSelectedLayer );
202
203     // build new spacial filter for current ROI or extent
204     $szSpacialFilter = buildSpacialFilterString( $oMapSession->oMap, $oLayer );
205
206     // check for existing wfs_filter
207     $szExistingWFSFilter = trim( $oLayer->getmetadata( "wfs_filter" ) );
208
209     // check for spatial tags
210     if ( strlen( $szExistingWFSFilter ) > 0 )
211     {
212         $szTmpFilter = strtolower( $szExistingWFSFilter );
213         if ( strpos( $szTmpFilter, '<bbox' ) !== false ||
214              strpos( $szTmpFilter, '<dwithin' ) !== false ||
215              strpos( $szTmpFilter, '<intersect' ) !== false )
216         {
217             // set the spatial filter variable to be the existing filter
218             $szSpacialFilter = $szExistingWFSFilter;
219
220             // set the notice string
221             $szROIExists = '<br><br>'.$oMLT->get('19',
222                 'Note:<br>This layer has a WFS '.
223                 'filter set that contains spatial attributes which may or '.
224                 'may not match the current ROI/extent.  These spatial '.
225                 'attributes will be used instead of the current ROI/extent '.
226                 'for this data extraction.' );
227         }
228         else
229         {
230             $szSpacialFilter = "<AND>".$szSpacialFilter.
231                 $szExistingWFSFilter."</AND>";
232         }
233     }
234     else
235     {
236         // set flag to clear the metadata item after use
237         $bClearFilter = true;
238     }
239 }
240
241 /* ============================================================================
242  * Perform extraction
243  * ========================================================================= */
244 if ( isset( $_FORM["txtExtract"] ) && $_FORM["txtExtract"] == 1 )
245 {
246     // be sure there is a connection
247     if ( strlen( trim( $szWFSConnection ) ) > 0 )
248     {
249         // create the temp download directory
250         $szDownloadPath = cleanPath( $_SESSION["gszTmpImgPath"] );
251         $szDownloadUrl = cleanPath( $_SESSION["gszTmpWebPath"] );
252         $szUniqid = md5( uniqid( rand(), true ) );
253
254         // check if directory exists
255         if ( !is_dir( $szDownloadPath.$szUniqid."/" ) )
256             @mkdir( $szDownloadPath.$szUniqid."/", 0777 );
257
258         // check for failure
259         if ( !is_dir( $szDownloadPath.$szUniqid."/" ) )
260         {
261             // set flag
262             $bSkipExtract = true;
263
264             // set error message
265             $szErrorNotice .= $oMLT->get("17",
266                                     "Failed to create temp download directory." );
267         }
268         else
269         {
270             // set flag
271             $bSkipExtract = false;
272
273             // update paths
274             $szDownloadPath .= $szUniqid."/";
275             $szDownloadUrl .= $szUniqid."/";
276         }
277
278         // define the temp file name
279         if ( isset( $_FORM["txtDLFilename"] ) &&
280              strlen( trim( $_FORM["txtDLFilename"] ) ) > 0 )
281             $szFile = $_FORM["txtDLFilename"];
282         else
283             $szFile = $szUniqid;
284
285         // perform an executeWFSGetfeature() call if WFS
286         if ( $szLayerType == "WFS" && !$bSkipExtract )
287         {
288             // get layer
289             $oLayer = $oMapSession->oMap->getLayer( $nSelectedLayer );
290
291             // set the filter metadata
292             $oLayer->setmetadata( "wfs_filter", $szSpacialFilter );
293
294             // get features
295             if ( !$bSkipGetFeature )
296             {
297                 // execute
298                 $szTmpGML = $oLayer->executeWFSGetfeature();
299
300                 // clear the filter if necessary
301                 if ( $bClearFilter )
302                 {
303                     $oLayer->removeMetaData( "wfs_filter" );
304                 }
305                 else
306                 {
307                     // otherwise restore it
308                     $oLayer->setmetadata( "wfs_filter", $szExistingWFSFilter );
309                 }
310
311                 // check success
312                 if ( strlen( trim( $szTmpGML ) ) > 0 )
313                 {
314                     // flag success
315                     $szGMLSuccess = "NOERROR";
316
317                     // set extension
318                     $szExt = ".gml";
319
320                     // copy temp gml to download
321                     if ( !copy( $szTmpGML, $szDownloadPath.$szFile.$szExt ) )
322                         $szGMLSuccess .= $oMLT->get("13", "An error occurred ".
323                             "copying the temp gml file.  Please check permissions ".
324                             "on your temp folder." );
325
326                     // delete temp
327                     if ( file_exists( $szTmpGML ) ) unlink( $szTmpGML );
328                 }
329                 else
330                 {
331                     // set error message
332                     $szGMLSuccess = $oMLT->get("14", "An error occurred getting ".
333                         "WFS features for this layer." );
334                 }
335             }
336         }
337         elseif ( !$bSkipExtract ) // layer is WMS
338         {
339             // check last char for ? or &
340             if ( substr( $szWFSConnection, -1 ) != "?" &&
341                  substr( $szWFSConnection, -1 ) != "&" )
342             {
343                 // check for ?
344                 if ( strpos( $szWFSConnection, "?" ) === false )
345                 {
346                     $szWFSConnection .= "?";
347                 }
348                 else
349                     $szWFSConnection .= "&";
350             }
351
352             // copy to uppercase for comparison
353             $szUpperCase = strtoupper( $szWFSConnection );
354
355             // check for service
356             if ( strpos( $szUpperCase, "SERVICE=" ) === false )
357                 $szWFSConnection .= "SERVICE=WFS&";
358
359             // check for version
360             if ( strpos( $szUpperCase, "VERSION=" ) === false )
361                 $szWFSConnection .= "VERSION=1.0.0&";
362
363             // check for type name
364             if ( strpos( $szUpperCase, "TYPENAME=" ) === false )
365             {
366                 // get the type name
367                 if ( isset( $aszWFSConnection['typename'] ) )
368                 {
369                     $szTypeName =  '';
370                     foreach( $aszWFSConnection['typename'] as $szCurrentTypeName )
371                     {
372                         $szTypeName .= $szCurrentTypeName.',';
373                     }
374                     // remove final ','
375                     if ( substr( $szTypeName, -1, 1 ) == ',' )
376                     {
377                         $szTypeName = substr( $szTypeName, 0, -1 );
378                     }
379                 }
380                 else
381                 {
382                     $szTypeName = $szSelectedLayerName;
383                 }
384
385                 $szWFSConnection .= "TYPENAME=".$szTypeName."&";
386             }
387
388             // extract gml
389             $szExt = ".gml";
390             $szTmpFile = getGML( $szWFSConnection.
391                 "request=getfeature&filter=<Filter>".
392                 urlencode( $szSpacialFilter ).'</Filter>' );
393
394             // copy the temp file
395             if ( file_exists( $szTmpFile ) )
396             {
397                 copy( $szTmpFile, $szDownloadPath.$szFile.$szExt );
398                 $szGMLSuccess = 'NOERROR';
399             }
400             else
401             {
402                 $szGMLSuccess = 'Errors';
403             }
404         }
405
406 /* ============================================================================
407  * Check result and convert output if necessary
408  * ========================================================================= */
409         // check result
410         if ( $szGMLSuccess == "NOERROR" && !$bSkipGetFeature )
411         {
412             // convert to shape if necessary
413             if ( isset( $_FORM["selOutputType"] ) &&
414                      strtoupper($_FORM["selOutputType"]) == "SHAPE" )
415             {
416                 // convert & check success
417                 if ( !ogr2ogr( $szDownloadPath.$szFile.$szExt, $szDownloadPath.
418                                               $szFile.".shp","ESRI Shapefile" ) )
419                 {
420                     // give error
421                     $szErrorNotice .= $oMLT->get("11", "Unable to create Shape ".
422                         "file.  It is most likely that no features were found for ".
423                         "this layer in the current region." );
424
425                     // cancel download
426                     $szDownloadUrl = "";
427                 }
428                 else
429                 {
430                     // archive the 3 files
431                     $aSzFiles = array($szDownloadPath.$szFile.".shp",
432                                    $szDownloadPath.$szFile.".shx",
433                                    $szDownloadPath.$szFile.".dbf" );
434
435                         if ( isset( $_FORM["selCompressType"] ) &&
436                      strtoupper($_FORM["selCompressType"]) == "TGZ" )
437                     {
438
439                         if ( !tar( $aSzFiles, $szDownloadPath.$szFile.".tar" ) )
440                             $szErrorNotice .= $oMLT->get("10", "Could not create archive" );
441                         else
442                         {
443                             // delete files
444                             if ( file_exists( $szDownloadPath.$szFile.".shp" ) )
445                                 unlink( $szDownloadPath.$szFile.".shp" );
446                             if ( file_exists( $szDownloadPath.$szFile.".shx" ) )
447                                 unlink( $szDownloadPath.$szFile.".shx" );
448                             if ( file_exists( $szDownloadPath.$szFile.".dbf" ) )
449                                 unlink( $szDownloadPath.$szFile.".dbf" );
450                         }
451
452                         // set the ext name to download
453                                 $szExt = ".tar.gz";
454
455                                 // compress
456                                 gZip( $szDownloadPath.$szFile.".tar", $szDownloadPath.$szFile.$szExt );
457
458                                 // delete the original file
459                                 if ( file_exists( $szDownloadPath.$szFile.".tar" ) )
460                                     unlink( $szDownloadPath.$szFile.".tar" );
461
462                         }
463                         else if ( isset( $_FORM["selCompressType"] ) &&
464                       strtoupper($_FORM["selCompressType"]) == "ZIP" )
465                     {
466                       // combine shape files into zip (compressed)
467                       $szExt = ".zip";
468                       zip( $aSzFiles, $szDownloadPath.$szFile.$szExt );
469                     }
470                 }
471             }
472             else
473                         {
474                                 $aSzFiles = array( $szTmpFile );
475                                 if ( isset( $_FORM["selCompressType"] ) &&
476                                         strtoupper($_FORM["selCompressType"]) == "TGZ" )
477                                 {
478                                         if ( !tar( $aSzFiles, $szDownloadPath.$szFile.".tar" ) )
479                                                 $szErrorNotice .= $oMLT->get("10", "Could not create archive" );
480                                         $szExt = ".tar.gz";
481                                         // compress
482                                         gZip( $szDownloadPath.$szFile.".tar", $szDownloadPath.$szFile.$szExt );
483                         // delete the original file (tar file)
484                         if ( file_exists( $szDownloadPath.$szFile.".tar" ) )
485                                 unlink( $szDownloadPath.$szFile.".tar" );
486                                 }
487                                 else if ( isset( $_FORM["selCompressType"] ) &&
488                                         strtoupper($_FORM["selCompressType"]) == "ZIP" )
489                                 {
490                                         $szExt = ".zip";
491                                         zip( $aSzFiles, $szDownloadPath.$szFile.$szExt );
492                                 }
493                         }
494         }
495         else
496         {
497             // output error
498             $szGMLError = $szGMLSuccess;
499
500             // clear url
501             $szDownloadUrl = "";
502         }
503     }
504     else
505     {
506         // give error message
507         $szErrorNotice .= $oMLT->get("4", "Invalid layer or none selected.  ".
508             "Please ensure that the selected layer is a WFS or WMS layer." );
509     }
510 }
511
512 /* ============================================================================
513  * Determine the output filename to display
514  * ========================================================================= */
515 if ( isset( $_FORM["txtDLFilename"] ) &&
516      strlen( trim( $_FORM["txtDLFilename"] ) ) > 0 )
517 {
518     $szDLFilename = $_FORM["txtDLFilename"];
519 }
520 else
521 {
522     $szDLFilename = $szSelectedLayerName;
523 }
524
525 /* ============================================================================
526  * Make close button
527  * ========================================================================= */   
528 $szCloseButton = makeButton( 'CloseWindow', '', 'ExtractWFSData',
529         "icons/icon_cancel.png", $oCommonMLT->get("Close", "Close"),
530         $oCommonMLT->get("CloseTip", "Close Dialog"), array( 'width' => 75) );
531
532 /**
533  * getGML()
534  *
535  * Postscript:  This function writes the given URL to the given file.
536  *
537  * @param $szURL string - URL to the GML source.
538  * @param $szTmpFile string - Path and filename of the file to write to.
539  * @param $oMLT object - Translation object
540  * @return string - "NOERROR" if successful, error message if failed.
541  * @desc Write url results to given file.
542  */
543  /*
544 function getGML( $szURL, $szTmpFile, $oMLT )
545 {
546     // read the xml datasource
547     $aszFile = file( $szURL );
548
549     // check to see if an error was generated
550     if ( !is_array( $aszFile ) ||
551          strpos( strtoupper( $aszFile[0] ), '<SERVICEEXCEPTIONREPORT' ) !== false )
552     {
553         // give error
554         if ( !is_array( $aszFile ) )
555             $szServerDump = $aszFile;
556         else
557         {
558             $szServerDump = "";
559             foreach(  $aszFile as $line )
560                 $szServerDump .= $line;
561         }
562
563         // return
564         return $oMLT->get("5", "WFS `GetFeature` request failed.  ".
565             "The server returned the following: %1\$s", array( $szServerDump ) );
566     }
567
568     // open the tmp file for writing
569     if ( !( $fp = fopen( $szTmpFile, "w" ) ) )
570     {
571         // open failed so give error
572         return $oMLT->get("6", "File IO.  Unable to open file(%1\$s)",
573                                                             array( $szTmpFile ) );
574     }
575
576     // process url
577     foreach( $aszFile as $line )
578     {
579         // write entry to file
580         fputs($fp, $line."\n");
581     }
582
583     // close the file
584     fclose($fp);
585
586     // return true
587     return "NOERROR";
588 }
589 */
590 /**
591  * parseDesc()
592  *
593  * Postcondition:  This function parses the given array and returns the wfs param.
594  *
595  * @param axValues Array - Mixed array of XML tags to process.
596  * @return string - WFS onlineresource.
597  * @desc Parses array and returns wfs online resource.
598  */
599 function parseDesc( $axValues )
600 {
601     // loop through each item of the array
602     $nCount = count( $axValues );
603     for ( $i=0; $i < $nCount; $i++ )
604     {
605         // only process "LayerDescription" tag
606         if ( strtoupper( $axValues[$i]["tag"] ) == "LAYERDESCRIPTION" )
607             return $axValues[$i]["attributes"]["wfs"];
608     }
609
610     // if here then errors
611     return null;
612
613 // end parseDesc() function
614 }
615
616 /**
617  * getBboxIntersect()
618  *
619  * Postcondition:  This function determines the intersecting bbox between the
620  *                 two given ones.  The input and output format is:
621  *                 "minx,miny max,maxy"
622  *
623  * @param $szBbox1 string - Delimited string of bbox extent.
624  * @param $szBbox2 string - Delimited string of bbox extent.
625  * @return mixed - Intersecting Bbox if found otherwise false.
626  * @desc Returns intersecting Bbox or false if does not exist.
627  */
628 function getBboxIntersect( $szBbox1, $szBbox2 )
629 {
630     // split apart bboxes
631     $aszTmpBboxMinMax = explode( " ", $szBbox1 );
632     $aszTmpBobx = explode( ",", $aszTmpBboxMinMax[0] );
633     $nMinx1 = $aszTmpBobx[0];
634     $nMiny1 = $aszTmpBobx[1];
635     $aszTmpBobx = explode( ",", $aszTmpBboxMinMax[1] );
636     $nMaxx1 = $aszTmpBobx[0];
637     $nMaxy1 = $aszTmpBobx[1];
638     $aszTmpBboxMinMax = explode( " ", $szBbox2 );
639     $aszTmpBobx = explode( ",", $aszTmpBboxMinMax[0] );
640     $nMinx2 = $aszTmpBobx[0];
641     $nMiny2 = $aszTmpBobx[1];
642     $aszTmpBobx = explode( ",", $aszTmpBboxMinMax[1] );
643     $nMaxx2 = $aszTmpBobx[0];
644     $nMaxy2 = $aszTmpBobx[1];
645
646     // compare minx
647     if ( $nMinx1 >= $nMinx2 && $nMinx1 <= $nMaxx2 )
648         $nReturnMinx = $nMinx1;
649     elseif( $nMinx2 >= $nMinx1 && $nMinx2 <= $nMaxx1 )
650         $nReturnMinx = $nMinx2;
651     else
652         return false;
653
654     // compare maxx
655     if ( $nMaxx1 >= $nMinx2 && $nMaxx1 <= $nMaxx2 )
656         $nReturnMaxx = $nMaxx1;
657     elseif( $nMaxx2 >= $nMinx1 && $nMaxx2 <= $nMaxx1 )
658         $nReturnMaxx = $nMaxx2;
659     else
660         return false;
661
662         // compare miny
663     if ( $nMiny1 >= $nMiny2 && $nMiny1 <= $nMaxy2 )
664         $nReturnMiny = $nMiny1;
665     elseif( $nMiny2 >= $nMiny1 && $nMiny2 <= $nMaxy1 )
666         $nReturnMiny = $nMiny2;
667     else
668         return false;
669
670     // compare maxy
671     if ( $nMaxy1 >= $nMiny2 && $nMaxy1 <= $nMaxy2 )
672         $nReturnMaxy = $nMaxy1;
673     elseif( $nMaxy2 >= $nMiny1 && $nMaxy2 <= $nMaxy1 )
674         $nReturnMaxy = $nMaxy2;
675     else
676         return false;
677
678     // return results
679     return $nReturnMinx.",".$nReturnMiny." ".$nReturnMaxx.",".$nReturnMaxy;
680
681 // end getBboxIntersect function
682 }
683
684 function tar( $aszSource, $szDestination )
685 {
686     // include file
687     include( COMMON."/tar/tar.php" );
688
689     // specify filename for output file
690     $tar = new Archive_Tar( $szDestination );
691
692     // build archive
693     if ( !$tar->create( $aszSource ) )
694         return false;
695     else
696         return true;
697 }
698
699 function gZip( $szSource, $szDestination )
700 {
701     $fp = fopen( $szSource, "r" );
702     $data = fread ( $fp, filesize( $szSource ) );
703     fclose( $fp );
704     $zp = gzopen( $szDestination, "w9" );
705     gzwrite( $zp, $data );
706     gzclose( $zp );
707 }
708
709 function zip( $aszSource, $szDestination )
710 {
711     // include file
712     include_once( COMMON."/zip/zip.php" );
713
714     // build archive
715     $szDirName = dirname( $szDestination );
716
717     // specify filename for output file
718     $aParams = array();
719     $aParams[ARCHIVE_ZIP_PARAM_REMOVE_ALL_PATH] = true;
720     $zip = new Archive_Zip( $szDestination );
721     if( ! $zip->create( $aszSource, $aParams ) )
722         return false;
723     else
724         return true;
725 }
726
727 /**
728  * cleanPath()
729  *
730  * Postcondition:  This function takes a path and converts all "\" to "/" and
731  *                 guarantees that the path will end with "/" with no whitespaces.
732  *
733  * @param szPath string - path to clean.
734  * @return string - clean path.
735  * @desc Cleans path and guarantees closing "/".
736  */
737 function cleanPath( $szPath )
738 {
739     // replace "\" and trim whitespace
740     $szReturn = trim( str_replace( "\\", "/", $szPath ) );
741
742     // check for closing "/"
743     if ( substr( $szReturn, -1 ) != "/" )
744         $szReturn .= "/";
745
746     // return
747     return $szReturn;
748 }
749
750 /**
751  * buildSpacialFilterString()
752  *
753  * Postcondition:  This function returns the spacial filter string based on current
754  *                 ROI and extents.
755  *
756  * @param $oMap object - The Map to apply the expression to.
757  * @param $oLayer object - The layer to apply the expression to.
758  * @return String - Filter string.
759  * @desc Builds and returns a properly formatted wfs filter string.
760  **/
761 function buildSpacialFilterString( $oMap, $oLayer )
762 {
763     // get projection
764     $szProjection = trim( $oLayer->getprojection() );
765     if ( strlen( $szProjection ) <= 0 )
766         $szProjection = trim( $oMap->getprojection() );
767     if ( strlen( $szProjection ) > 0 )
768     {
769         $szProjection = substr( $szProjection, 5 );
770         $szProjection = str_replace( 'epsg', 'EPSG', $szProjection );
771     }
772     if ( substr( $szProjection, 0, 4 ) != 'EPSG' )
773     {
774         $szProjection = '';
775     }
776
777     // check for AOI
778     if ( isset( $_SESSION['ROIRENDERER'] ) &&
779          is_array( $_SESSION['ROIRENDERER'] ) &&
780          count( $_SESSION['ROIRENDERER'] ) > 0 )
781     {
782         // loop and build the filter string based on the ROI
783         $bNotFirstExpression = false;
784         $szBbox = '';
785         foreach( $_SESSION['ROIRENDERER'] as $szTmpROI )
786         {
787             // process based on type
788             $szThisBbox = '';
789             switch ( strtoupper($szTmpROI['type'] ) )
790             {
791                 case 'RECTANGLE':
792                     $szThisBbox = buildRectFilter( $szTmpROI['aGeoCoords'],
793                                                             $szProjection );
794                     break;
795                 case 'CIRCLE':
796                     $szThisBbox = buildCircleFilter( $szTmpROI['aGeoCoords'],
797                         $szTmpROI['aGeoCoords'][2]-$szTmpROI['aGeoCoords'][0] );
798                     break;
799                 case 'POLYGON':
800                     $szThisBbox = buildPolygonFilter( $szTmpROI['aGeoCoords'] );
801                     break;
802                 default:
803                     $szBbox .= '';
804             }
805
806             // decide how to add to ROI
807             if ( $bNotFirstExpression )
808             {
809                 switch( $szTmpROI['mode'] )
810                 {
811                     // additive
812                     case 2:
813                         $szBbox = '<OR>'.$szBbox.$szThisBbox.'</OR>';
814                         break;
815                     // subtractive
816                     case 3:
817                         $szBbox = '<AND>'.$szBbox.'<NOT>'.$szThisBbox.'</NOT></AND>';
818                         break;
819                 }
820             }
821             else
822                 $szBbox .= $szThisBbox;
823
824             // set flag
825             $bNotFirstExpression = true;
826         }
827     }
828     else
829     {
830         // use current extents as bbox
831         $szBbox = buildRectFilter(
832                     array( $oMap->extent->minx,
833                            $oMap->extent->miny,
834                            $oMap->extent->maxx,
835                            $oMap->extent->maxy ),
836                     $szProjection );
837     }
838
839     // return the filter string
840     return $szBbox;
841
842 // end of buildFilterString function
843 }
844
845 function buildRectFilter( $adCoords, $szProjection )
846 {
847      return '<BBOX><PropertyName>Name</PropertyName>'.
848                 "<gml:Box srsName='".$szProjection."'><coordinates>".
849                 $adCoords[0].','.
850                 $adCoords[1].' '.
851                 $adCoords[2].','.
852                 $adCoords[3].
853                 '</coordinates></gml:Box></BBOX>';
854 }
855
856 function buildCircleFilter( $adCoords, $dDistance )
857 {
858     return '<DWithin><PropertyName>Name</PropertyName><gml:Point>'.
859            '<gml:coordinates>'.$adCoords[0].','.$adCoords[1].
860            '</gml:coordinates></gml:Point><Distance '.
861            "units='http://www.uomdict.com/uom.html#meters'>".
862            $dDistance.'</Distance></DWithin>';
863 }
864
865 function buildPolygonFilter( $adCoords )
866 {
867     $szReturn = '<Intersect><PropertyName>Name</PropertyName><gml:Polygon>'.
868                 '<gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>';
869
870     // loop and build list of coordinates
871     $nCount = count( $adCoords );
872     $szCoords = '';
873     for( $i=0; $i<$nCount; $i=$i+2 )
874     {
875         $szCoords .= $adCoords[$i].','.$adCoords[$i+1].' ';
876     }
877     $szReturn .= trim( $szCoords );
878     $szReturn .= '</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs>'.
879                  '</gml:Polygon></Intersect>';
880     return $szReturn;
881 }
882 ?>
Note: See TracBrowser for help on using the browser.