[fusion-commits] r2214 - in sandbox/jxlib-3.0: common/php layers/MapServer/php

svn_fusion at osgeo.org svn_fusion at osgeo.org
Thu Sep 2 10:21:53 EDT 2010


Author: pagameba
Date: 2010-09-02 14:21:53 +0000 (Thu, 02 Sep 2010)
New Revision: 2214

Modified:
   sandbox/jxlib-3.0/common/php/Utilities.php
   sandbox/jxlib-3.0/layers/MapServer/php/Common.php
   sandbox/jxlib-3.0/layers/MapServer/php/CreateSession.php
   sandbox/jxlib-3.0/layers/MapServer/php/LoadMap.php
   sandbox/jxlib-3.0/layers/MapServer/php/Session.php
Log:
updating sandbox with code to make fusion work with platform sessions and to load resources directly from the platform.

Modified: sandbox/jxlib-3.0/common/php/Utilities.php
===================================================================
--- sandbox/jxlib-3.0/common/php/Utilities.php	2010-09-02 02:52:59 UTC (rev 2213)
+++ sandbox/jxlib-3.0/common/php/Utilities.php	2010-09-02 14:21:53 UTC (rev 2214)
@@ -25,7 +25,8 @@
  */
 
 /* recursively convert a variable to its json representation */
-function var2json($var) {
+if (!function_exists('var2json')) {
+  function var2json($var) {
     if (function_exists('json_encode')) {
         $result = json_encode($var);
     } else {
@@ -61,8 +62,10 @@
 
     return utf8_encode($result);
 }
+}
 
-function xml2json($domElement) {
+if (!function_exists('xml2json')) {
+  function xml2json($domElement) {
     $result = '';
     if ($domElement->nodeType == XML_COMMENT_NODE) {
         return '';
@@ -166,6 +169,7 @@
     }
     return $result;
 }
+}
 
 /**
  * this function determines if a path represents an absolute path and returns
@@ -173,7 +177,8 @@
  * @param szPath string the path to test
  * @result boolean true if the path is absolute, false otherwise
  */
-function isAbsolutePath( $szPath ) {
+if (!function_exists('isAbsolutePath')) {
+  function isAbsolutePath( $szPath ) {
     if ($szPath == "") { return false; }
     if ($szPath[0] == "/" || preg_match('/^(\w:)/', $szPath)) {
         return true;
@@ -181,8 +186,8 @@
         return false;
     }
 }
+}
 
-
 /**
  * This function translate $szDestPath (relative or absolute)
  * to a absolute path based on $szOrigPath.
@@ -190,7 +195,8 @@
  * @param $szDestPath string Destination path to translate
  * @param $szOrigPath string Reference path
  */
-function resolvePath2 ($szDestPath, $szOrigPath) {
+if (!function_exists('resolvePath2')) {
+  function resolvePath2 ($szDestPath, $szOrigPath) {
     // If one or other path is missing or absolute, return it.
     if ($szDestPath == "") { return $szOrigPath; }
     if ($szOrigPath == "") { return $szDestPath; }
@@ -229,6 +235,7 @@
     //Rest of the function
     return $szPrefix.$szPath;
 }
+}
 
 /**
  * Recursive ereg_replace
@@ -239,7 +246,8 @@
  *
  * @return string szString with the matching result replaced.
  */
-function iterate_ereg_replace ( $szPattern, $szReplacement, $szString) {
+if (!function_exists('iterate_ereg_replace')) {
+  function iterate_ereg_replace ( $szPattern, $szReplacement, $szString) {
     $szResult = $szString;
     do {
         $szString = $szResult;
@@ -248,8 +256,11 @@
 
     return $szResult;
 }
+}
 
-function arguments($argv) {
+
+if (!function_exists('arguments')) {
+  function arguments($argv) {
     $_ARG = array();
     foreach ($argv as $arg) {
         if (ereg('--[a-zA-Z0-9]*=.*',$arg)) {
@@ -266,8 +277,10 @@
     }
     return $_ARG;
 }
+}
 
-function loadFusionConfig() {
+if (!function_exists('loadFusionConfig')) {
+  function loadFusionConfig() {
     /* json decode only in PHP 5.2 and later */
     if (function_exists('json_decode')) {
         $configFile = realpath(dirname(__FILE__)."/../../config.json");
@@ -291,5 +304,6 @@
         }
     }
 }
+}
 
 ?>

Modified: sandbox/jxlib-3.0/layers/MapServer/php/Common.php
===================================================================
--- sandbox/jxlib-3.0/layers/MapServer/php/Common.php	2010-09-02 02:52:59 UTC (rev 2213)
+++ sandbox/jxlib-3.0/layers/MapServer/php/Common.php	2010-09-02 14:21:53 UTC (rev 2214)
@@ -64,7 +64,7 @@
 /* handle restoring a session */
 if (isset($REQUEST_VARS['session'])) {
     $sessionID = $REQUEST_VARS['session'];
-    initializeSession( "sid", "", $sessionID );
+    initializeSession( "session", "", $sessionID );
 }
 
 if (isset($_REQUEST['mapname'])) { 

Modified: sandbox/jxlib-3.0/layers/MapServer/php/CreateSession.php
===================================================================
--- sandbox/jxlib-3.0/layers/MapServer/php/CreateSession.php	2010-09-02 02:52:59 UTC (rev 2213)
+++ sandbox/jxlib-3.0/layers/MapServer/php/CreateSession.php	2010-09-02 14:21:53 UTC (rev 2214)
@@ -32,7 +32,8 @@
 include(dirname(__FILE__).'/Common.php');
 include('../../../common/php/Utilities.php');
 
-initializeSession( "sid", "", "" );
+$cookie = isset($_COOKIE['session'])?$_COOKIE['session']:"";
+initializeSession( "session", "", $cookie);
 $sessionId = session_id();
 loadFusionConfig();
 

Modified: sandbox/jxlib-3.0/layers/MapServer/php/LoadMap.php
===================================================================
--- sandbox/jxlib-3.0/layers/MapServer/php/LoadMap.php	2010-09-02 02:52:59 UTC (rev 2213)
+++ sandbox/jxlib-3.0/layers/MapServer/php/LoadMap.php	2010-09-02 14:21:53 UTC (rev 2214)
@@ -1,420 +1,439 @@
-<?php
-/**
- * LoadMap
- *
- * $Id$
- *
- * Copyright (c) 2007, DM Solutions Group Inc.
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included
- * in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
- * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- */
-
-/*****************************************************************************
- * Purpose: Load a mapfile into the session and return information about the
- *          map to the client
- *****************************************************************************/
-
-/* Common starts the session */
-include(dirname(__FILE__).'/../../../common/php/Utilities.php');
-include(dirname(__FILE__).'/Common.php');
-include(dirname(__FILE__).'/Utilities.php');
-
-/* if scales are not set, these become the default values */
-define('MIN_SCALE', 1);
-define('MAX_SCALE', 1000000000);
-
-/* could potentially make this optional */
-$moveToSession = true;
-
-/**
-   TODO make it possible to specify only a relative path
-   in the WebLayout and have this code know where to
-   look for it on the server somehow
- */
-
-/* only do something if a mapfile was requested */
-if (isset($_REQUEST['mapfile'])) {
-
-    /* look for mapFileRoot specified in config.json and test to see if the map path in appdef is realitive to it.*/
-    $configObj = $_SESSION['fusionConfig'];
-    $szFusionRoot = dirname(__FILE__).'/../../../'; // TODO : not a very elegant way of doing this
-    $szDblSeparator = DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR;
-
-    $szMapFromFusionRoot = str_replace($szDblSeparator,DIRECTORY_SEPARATOR,$szFusionRoot.DIRECTORY_SEPARATOR.$_REQUEST['mapfile']);
-    $szMapFileRoot = str_replace($szDblSeparator,DIRECTORY_SEPARATOR,$configObj->mapserver->mapFileRoot.DIRECTORY_SEPARATOR.$_REQUEST['mapfile']);
-
-    if( file_exists($szMapFileRoot) ) {
-        /* use the realitive path specified in config.json */
-        $szMapFile = $szMapFileRoot;
-    }
-    else
-    {
-        if( file_exists($szMapFromFusionRoot) ) {
-            /* use the realitive path from fusion install root */
-            $szMapFile = $szMapFromFusionRoot;
-        }
-        else
-        {
-            /* use absolute path from appdef */
-            $szMapFile = $_REQUEST['mapfile'];
-        }
-    }
-
-    $oMap = ms_newMapObj($szMapFile);
-
-    /* optionally move the mapfile to the session */
-    if ($moveToSession) {
-        //path to map file in the session is used by the client
-        $mapId = getSessionSavePath().($oMap->name).".map";
-        //modify various paths if necessary
-        $pathToMap = dirname($szMapFile);
-        $cwd = getcwd();
-        chdir($pathToMap);
-        $shapePath = $oMap->shapepath;
-        $oMap->set('shapepath', realpath($shapePath));
-        $symbolSet = $oMap->symbolsetfilename;
-        if ($symbolSet != '') {
-            $oMap->setSymbolSet(realpath($symbolSet));
-        }
-        $fontSet = $oMap->fontsetfilename;
-        if ($fontSet != '') {
-            $oMap->setFontSet(realpath($fontSet));
-        }
-        /* need to modify all image symbols reference in the map file
-         eg STYLE
-             SYMBOL "../etc/markers/target-7.gif" : this is relative to the map file
-        */
-
-        for ($i=0; $i<$oMap->numlayers; $i++)
-        {
-            $oLayer = &$oMap->GetLayer($i);
-            /* check layername for invalid URI characters and replace */
-            $oLayer->set("name",replaceInvalidLayerName($oLayer->name));
-
-            for ($j=0; $j<$oLayer->numclasses; $j++)
-            {
-                $oClass = $oLayer->GetClass($j);
-                /* if keyimage is defined, change the path*/
-                if ($oClass->keyimage && strlen($oClass->keyimage) > 0)
-                {
-                     $oClass->set("keyimage", realpath($oClass->keyimage));
-                }
-                for ($k=0; $k<$oClass->numstyles; $k++)
-                {
-                    $oStyle = $oClass->getStyle($k);
-                    if ($oStyle->symbolname != "")
-                    {
-                        if (file_exists(realpath($oStyle->symbolname)))
-                        {
-                            $oStyle->set("symbolname", realpath($oStyle->symbolname));
-                        }
-                    }
-                }
-            }
-        }
-        $oMap->save($mapId);
-        chdir($cwd);
-    } else {
-        $mapId = $_REQUEST['mapfile'];
-    }
-} elseif (isset($_SESSION['maps']) && isset($_SESSION['maps'][$mapName])) {
-    $oMap = ms_newMapObj($_SESSION['maps'][$mapName]);
-    $mapId = getSessionSavePath().($oMap->name).".map";
-}
-
-$mapObj = NULL;
-if ($oMap) {
-    header('Content-type: application/json');
-    header('X-JSON: true');
-    $mapObj->sessionId = $sessionID;
-    $mapObj->mapId = $mapId;
-
-    $mapObj->metadata = NULL;
-    if (isset($_REQUEST['map_metadata'])) {
-        $mapMetadataKeys = explode(',',$_REQUEST['map_metadata']);
-        foreach($mapMetadataKeys as $key) {
-            $mapObj->metadata->$key = $oMap->getMetadata($key);
-        }
-    }
-
-    $mapObj->projString = $oMap->getProjection();
-    $mapObj->metersPerUnit = GetMetersPerUnit($oMap->units);
-
-    $mapObj->dpi = $oMap->resolution;
-    $mapObj->imagetype = $oMap->imagetype;
-    $mapObj->mapName = $oMap->name;
-    if (!isset($_SESSION['maps'])) {
-        $_SESSION['maps'] = array();
-    }
-    if (!isset($_SESSION['maps'][$mapObj->mapName])) {
-        $_SESSION['maps'][$mapObj->mapName] = $mapId;
-    }
-    $mapObj->extent = array( $oMap->extent->minx, $oMap->extent->miny,
-                             $oMap->extent->maxx, $oMap->extent->maxy );
-    $minScale = $oMap->web->minscale == -1 ? MIN_SCALE : $oMap->web->minscale;
-    $maxScale = $oMap->web->maxscale == -1 ? MAX_SCALE : $oMap->web->maxscale;
-    $title = $oMap->getmetadata('legend_title');
-    $mapObj->mapTitle = $title == "" ? $mapObj->mapName : $title;
-    //layers
-    $mapObj->layers = array();
-    for ($i=0;$i<$oMap->numlayers;$i++)
-    {
-        $layer=$oMap->getLayer($i);
-        $layerObj = NULL;
-
-        /* Status Default - If a layer is status Default trac it in layerObj */
-        if($layer->status == MS_DEFAULT)
-            $layerObj->statusdefault = true;
-         else
-            $layerObj->statusdefault = false;
-
-        /* rename layes names with invalid characters */
-        $layer->set("name",replaceInvalidLayerName($layer->name));
-
-        $layerObj->metadata = NULL;
-        if (isset($_REQUEST['layer_metadata'])) {
-            $layerMetadataKeys = explode(',',$_REQUEST['layer_metadata']);
-            foreach($layerMetadataKeys as $key) {
-                $layerObj->metadata->$key = $layer->getMetadata($key);
-            }
-        }
-
-        //$extent = $layer->getExtent();
-        $layerObj->extent = NULL;
-        $layerObj->extent->minx = NULL;
-        $layerObj->extent->maxx = NULL;
-        $layerObj->extent->miny = NULL;
-        $layerObj->extent->maxy = NULL;
-
-         // only proceed if extent is valid
-        if( isset($GLOBALS["extent"]) )
-        {
-            $layerObj->extent->minx = $extent->minx;
-            $layerObj->extent->maxx = $extent->maxx;
-            $layerObj->extent->miny = $extent->miny;
-            $layerObj->extent->maxy = $extent->maxy;
-        }
-
-         $layerObj->propertyMappings = '';
-         $layerObj->uniqueId = $i;
-         $layerObj->layerName = $layer->name;
-         switch($layer->type) {
-             case MS_LAYER_POINT:
-                $type = 0;
-                break;
-             case MS_LAYER_LINE:
-                $type = 1;
-                break;
-             case MS_LAYER_POLYGON:
-                $type = 2;
-                break;
-             case MS_LAYER_RASTER:
-                $type = 4;
-                break;
-             case MS_LAYER_ANNOTATION:
-                $type = 8;
-                break;
-             default:
-                $type = 0;
-         }
-         $layerObj->layerTypes = array($type);
-
-         $displayInLegend = strtolower($layer->getMetaData('displayInLegend'));
-         $layerObj->displayInLegend = $displayInLegend == 'false' ? false : true;
-
-         $expandInLegend = strtolower($layer->getMetaData('expandInLegend'));
-         $layerObj->expandInLegend = $expandInLegend == 'false' ? false : true;
-         $layerObj->resourceId = $layer->name;
-         $layerObj->parentGroup = $layer->group;
-
-         $legendLabel = $layer->getMetaData('legendLabel');
-         if ($legendLabel == '') {
-             $legendLabel = $layer->name;
-         }
-         $layerObj->legendLabel = $legendLabel;
-
-         $selectable = strtolower($layer->getMetaData('selectable'));
-         $layerObj->selectable = $selectable == 'true' ? true : false;
-
-         $layerObj->visible = ($layer->status == MS_ON || $layer->status == MS_DEFAULT);
-         $layerObj->actuallyVisible = true;
-
-         $editable = strtolower($layer->getMetaData('editable'));
-         $layerObj->editable = $editable == 'true' ? true : false;
-
-         /* process the classes.  The legend expects things
-          * organized by scale range so we have to first
-          * find all the scale breaks, then create ranges
-          * for each scale break pair, then slot the classes
-          * into the scale ranges that they apply to.
-          */
-
-         $aScaleRanges = array();
-         //create a default scale range for the layer as a whole
-         $layerMin = $layer->minscale == -1 ? $minScale : $layer->minscale;
-         $layerMax = $layer->maxscale == -1 ? $maxScale : $layer->maxscale;
-
-        /* check to see that the layer has a vaild scale range
-         * inside the defined map's main min max scale ranges
-         * set them to the maps scale ranges if they exceede 
-         */
-        if($layer->minscale != -1 && $layerMin < $minScale)
-            $layerMin = $minScale;
-
-        if($layer->maxscale != -1 && $layerMax > $maxScale)
-            $layerMax = $maxScale;
-
-         //find all the unique scale breaks in this layer
-         $aScaleBreaks = array($layerMin, $layerMax);
-         for ($j=0; $j<$layer->numclasses; $j++) {
-             $oClass = $layer->getClass($j);
-             $classMin = $oClass->minscale == -1 ? $layerMin : max($oClass->minscale, $layerMin);
-             $classMax = $oClass->maxscale == -1 ? $layerMax : min($oClass->maxscale, $layerMax);
-             if (!in_array($classMin, $aScaleBreaks)) {
-                 array_push($aScaleBreaks, $classMin);
-             }
-             if (!in_array($classMax, $aScaleBreaks)) {
-                 array_push($aScaleBreaks, $classMax);
-             }
-         }
-         //sort them
-         sort($aScaleBreaks);
-
-         //create scale ranges for each pair of breaks
-         for ($j=0; $j<count($aScaleBreaks)-1; $j++) {
-             $scaleRange = NULL;
-             $scaleRange->minScale = $aScaleBreaks[$j];
-             $scaleRange->maxScale = $aScaleBreaks[$j+1];
-             $scaleRange->styles = array();
-             array_push($aScaleRanges, $scaleRange);
-         }
-
-         //create classes and slot them into the scale breaks
-         for ($j=0; $j<$layer->numclasses; $j++) {
-             $oClass = $layer->getClass($j);
-             $classObj = NULL;
-             // Use formatted legend label as defined by CLASS->TITLE
-             $classObj->legendLabel = $oClass->title != '' ? $oClass->title : $oClass->name;
-             $classObj->filter = $oClass->getExpression();
-             $classMin = $oClass->minscale == -1 ? $layerMin : max($oClass->minscale, $layerMin);
-             $classMax = $oClass->maxscale == -1 ? $layerMax : min($oClass->maxscale, $layerMax);
-             $classObj->minScale = $classMin;
-             $classObj->maxScale = $classMax;
-             $classObj->index = $j;
-             for ($k=0; $k<count($aScaleRanges); $k++) {
-                 if ($classMin < $aScaleRanges[$k]->maxScale &&
-                     $classMax > $aScaleRanges[$k]->minScale) {
-                     array_push($aScaleRanges[$k]->styles, $classObj);
-                 }
-             }
-         }
-         //$layerObj->scaleRanges = $aScaleRanges;
-         $_SESSION['scale_ranges'][$mapName][$layer->name] = $aScaleRanges;
-         /*get the min/max scale for the layer*/
-        $nCount = count($aScaleRanges);
-        $layerObj->minScale = $aScaleRanges[0]->minScale;
-        $layerObj->maxScale = $aScaleRanges[0]->maxScale;
-        for ($j=1; $j<$nCount; $j++)
-        {
-            $layerObj->minScale = min($layerObj->minScale, $aScaleRanges[$j]->minScale);
-            $layerObj->maxScale = max($layerObj->maxScale, $aScaleRanges[$j]->maxScale);
-        }
-        array_push($mapObj->layers, $layerObj);
-    }
-    $mapObj->groups = array();
-    $aGroups = $oMap->getAllGroupNames();
-    foreach($aGroups as $groupName) {
-        $aLayerIndexes = $oMap->getLayersIndexByGroup($groupName);
-        if (count($aLayerIndexes) > 0) {
-            array_push($mapObj->groups, getGroupObject($oMap->getLayer($aLayerIndexes[0])));
-        }
-    }
-    echo var2json($mapObj);
-}
-
-function getGroupObject($layer) {
-    $group = NULL;
-    $group->groupName = $layer->group;
-    $ll = $layer->getMetaData('groupLegendLabel');
-    $group->legendLabel = $ll != '' ? $ll : $group->groupName;
-    $group->uniqueId = $group->groupName;
-    $b = $layer->getMetaData('groupDisplayInLegend');
-    $group->displayInLegend = ($b == 'false') ? false : true;
-    $b = $layer->getMetaData('groupExpandInLegend');
-    $group->expandInLegend = ($b == 'false') ? false : true;
-    $group->layerGroupType = '';
-    /* parent is always not set for mapserver since we can't have nested groups */
-    $group->parentUniqueId = '';
-    $group->parent = '';
-    $b = $layer->getMetaData('groupVisible');
-    $group->visible = ($b == 'false') ? false : true;
-    $group->actuallyVisible = $layer->isVisible();
-    $group->groupParent = $layer->getMetaData('groupParent');
-
-    return $group;
-}
-
-function GetMetersPerUnit($unit)
-{
-    if ($unit == MS_INCHES)
-      return 0.0254;
-    else if ($unit == MS_FEET)
-      return 0.3048;
-    else if ($unit == MS_MILES)
-      return 1609.344;
-    else if ($unit == MS_METERS)
-      return 1;
-    else if ($unit == MS_KILOMETERS)
-      return 1000;
-    else if ($unit == MS_DD)
-      return 111118.7516;
-    else if ($unit == MS_PIXELS)
-      return 1;
-
-}
-
-function replaceInvalidLayerName($szLayerName){
-    /*
-    bug http://trac.osgeo.org/fusion/ticket/96 - Invalid characters in layer name (pdeschamps)
-
-    Fusion requests the map imavge via the Mapserver CGI to toggle the layer visibility.
-    The layer paramerter for the cgi uses spaces as a delimiter for the layer names this creates
-    an issue for the mapserver binary to toggle layers that have these reserved URI characters.
-    also removing characters that could pose potential issues with json.
-    */
-    $aInvalidLayerNameCharacters = array();
-    $aInvalidLayerNameCharacters[0] ="&";
-    $aInvalidLayerNameCharacters[1] =" ";
-    $aInvalidLayerNameCharacters[2] ="#";
-    $aInvalidLayerNameCharacters[3] ="\\";
-    $aInvalidLayerNameCharacters[4] ="=";
-    $aInvalidLayerNameCharacters[5] ="/";
-    $aInvalidLayerNameCharacters[6] ="'";
-
-    $aReplace[0] = "_";
-    $aReplace[1] = "_";
-    $aReplace[2] = "_";
-    $aReplace[3] = "_";
-    $aReplace[4] = "_";
-    $aReplace[5] = "_";
-    $aReplace[6] = "_";
-
-    return str_replace($aInvalidLayerNameCharacters,$aReplace,$szLayerName);
-}
-
-?>
+<?php
+/**
+ * LoadMap
+ *
+ * $Id$
+ *
+ * Copyright (c) 2007, DM Solutions Group Inc.
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+/*****************************************************************************
+ * Purpose: Load a mapfile into the session and return information about the
+ *          map to the client
+ *****************************************************************************/
+/* Common starts the session */
+include(dirname(__FILE__).'/../../../common/php/Utilities.php');
+include(dirname(__FILE__).'/Common.php');
+include(dirname(__FILE__).'/Utilities.php');
+
+/* if scales are not set, these become the default values */
+define('MIN_SCALE', 1);
+define('MAX_SCALE', 1000000000);
+
+/* could potentially make this optional */
+$moveToSession = true;
+$modifyPaths = false;
+
+/**
+   TODO make it possible to specify only a relative path
+   in the WebLayout and have this code know where to
+   look for it on the server somehow
+ */
+
+/* only do something if a mapfile was requested */
+if (isset($_REQUEST['mapfile'])) {
+
+    /* look for mapFileRoot specified in config.json and test to see if the map path in appdef is realitive to it.*/
+    $configObj = $_SESSION['fusionConfig'];
+    $szFusionRoot = dirname(__FILE__).'/../../../'; // TODO : not a very elegant way of doing this
+    $szDblSeparator = DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR;
+
+    $szMapFromFusionRoot = str_replace($szDblSeparator,DIRECTORY_SEPARATOR,$szFusionRoot.DIRECTORY_SEPARATOR.$_REQUEST['mapfile']);
+    $szMapFileRoot = str_replace($szDblSeparator,DIRECTORY_SEPARATOR,$configObj->mapserver->mapFileRoot.DIRECTORY_SEPARATOR.$_REQUEST['mapfile']);
+
+    if( file_exists($szMapFileRoot) ) {
+        /* use the realitive path specified in config.json */
+        $szMapFile = $szMapFileRoot;
+    }
+    else
+    {
+        if( file_exists($szMapFromFusionRoot) ) {
+            /* use the realitive path from fusion install root */
+            $szMapFile = $szMapFromFusionRoot;
+        }
+        else
+        {
+            /* use absolute path from appdef */
+            $szMapFile = $_REQUEST['mapfile'];
+        }
+    }
+
+    $sMapFileContents = '';
+    if (strpos($szMapFile, 'platform://') === 0) {
+        include_once($configObj->mapserver->platformPath . "/include/Common.php");
+        global $platformDefaultConfig;
+        $platformContext = new PlatformContext($platformDefaultConfig);
+        $platformContext->RestoreSession(session_id());
+
+        $mapGen = new Map($platformContext, substr($szMapFile, 10));
+        if ($mapGen->Exists()) {
+            $result = $mapGen->Save();
+            if ($result->IsOk()) {
+                $sMapFileContents = $result->Get('MAPDATA');
+            }
+        }
+    } else {
+        $sMapFileContents = file_get_contents($szMapFile);
+    }
+    $oMap = ms_newMapObjFromString($sMapFileContents);
+
+    /* optionally move the mapfile to the session */
+    if ($moveToSession) {
+        //path to map file in the session is used by the client
+        $mapId = getSessionSavePath().($oMap->name).".map";
+        //modify various paths if necessary
+        if ($modifyPaths) {
+          $pathToMap = dirname($szMapFile);
+          $cwd = getcwd();
+          chdir($pathToMap);
+          $shapePath = $oMap->shapepath;
+          $oMap->set('shapepath', realpath($shapePath));
+          $symbolSet = $oMap->symbolsetfilename;
+          if ($symbolSet != '') {
+              $oMap->setSymbolSet(realpath($symbolSet));
+          }
+          $fontSet = $oMap->fontsetfilename;
+          if ($fontSet != '') {
+              $oMap->setFontSet(realpath($fontSet));
+          }
+          /* need to modify all image symbols reference in the map file
+           eg STYLE
+               SYMBOL "../etc/markers/target-7.gif" : this is relative to the map file
+          */
+  
+          for ($i=0; $i<$oMap->numlayers; $i++)
+          {
+              $oLayer = &$oMap->GetLayer($i);
+              /* check layername for invalid URI characters and replace */
+              $oLayer->set("name",replaceInvalidLayerName($oLayer->name));
+  
+              for ($j=0; $j<$oLayer->numclasses; $j++)
+              {
+                  $oClass = $oLayer->GetClass($j);
+                  /* if keyimage is defined, change the path*/
+                  if ($oClass->keyimage && strlen($oClass->keyimage) > 0)
+                  {
+                       $oClass->set("keyimage", realpath($oClass->keyimage));
+                  }
+                  for ($k=0; $k<$oClass->numstyles; $k++)
+                  {
+                      $oStyle = $oClass->getStyle($k);
+                      if ($oStyle->symbolname != "")
+                      {
+                          if (file_exists(realpath($oStyle->symbolname)))
+                          {
+                              $oStyle->set("symbolname", realpath($oStyle->symbolname));
+                          }
+                      }
+                  }
+              }
+          }
+          chdir($cwd);
+        }
+        $oMap->save($mapId);
+    } else {
+        $mapId = $_REQUEST['mapfile'];
+    }
+} elseif (isset($_SESSION['maps']) && isset($_SESSION['maps'][$mapName])) {
+    $oMap = ms_newMapObj($_SESSION['maps'][$mapName]);
+    $mapId = getSessionSavePath().($oMap->name).".map";
+}
+
+$mapObj = NULL;
+if ($oMap) {
+    header('Content-type: application/json');
+    header('X-JSON: true');
+    $mapObj->sessionId = $sessionID;
+    $mapObj->mapId = $mapId;
+
+    $mapObj->metadata = NULL;
+    if (isset($_REQUEST['map_metadata'])) {
+        $mapMetadataKeys = explode(',',$_REQUEST['map_metadata']);
+        foreach($mapMetadataKeys as $key) {
+            $mapObj->metadata->$key = $oMap->getMetadata($key);
+        }
+    }
+
+    $mapObj->projString = $oMap->getProjection();
+    $mapObj->metersPerUnit = GetMetersPerUnit($oMap->units);
+
+    $mapObj->dpi = $oMap->resolution;
+    $mapObj->imagetype = $oMap->imagetype;
+    $mapObj->mapName = $oMap->name;
+    if (!isset($_SESSION['maps'])) {
+        $_SESSION['maps'] = array();
+    }
+    if (!isset($_SESSION['maps'][$mapObj->mapName])) {
+        $_SESSION['maps'][$mapObj->mapName] = $mapId;
+    }
+    $mapObj->extent = array( $oMap->extent->minx, $oMap->extent->miny,
+                             $oMap->extent->maxx, $oMap->extent->maxy );
+    $minScale = $oMap->web->minscale == -1 ? MIN_SCALE : $oMap->web->minscale;
+    $maxScale = $oMap->web->maxscale == -1 ? MAX_SCALE : $oMap->web->maxscale;
+    $title = $oMap->getmetadata('legend_title');
+    $mapObj->mapTitle = $title == "" ? $mapObj->mapName : $title;
+    //layers
+    $mapObj->layers = array();
+    for ($i=0;$i<$oMap->numlayers;$i++)
+    {
+        $layer=$oMap->getLayer($i);
+        $layerObj = NULL;
+
+        /* Status Default - If a layer is status Default trac it in layerObj */
+        if($layer->status == MS_DEFAULT)
+            $layerObj->statusdefault = true;
+         else
+            $layerObj->statusdefault = false;
+
+        /* rename layes names with invalid characters */
+        $layer->set("name",replaceInvalidLayerName($layer->name));
+
+        $layerObj->metadata = NULL;
+        if (isset($_REQUEST['layer_metadata'])) {
+            $layerMetadataKeys = explode(',',$_REQUEST['layer_metadata']);
+            foreach($layerMetadataKeys as $key) {
+                $layerObj->metadata->$key = $layer->getMetadata($key);
+            }
+        }
+
+        //$extent = $layer->getExtent();
+        $layerObj->extent = NULL;
+        $layerObj->extent->minx = NULL;
+        $layerObj->extent->maxx = NULL;
+        $layerObj->extent->miny = NULL;
+        $layerObj->extent->maxy = NULL;
+
+         // only proceed if extent is valid
+        if( isset($GLOBALS["extent"]) )
+        {
+            $layerObj->extent->minx = $extent->minx;
+            $layerObj->extent->maxx = $extent->maxx;
+            $layerObj->extent->miny = $extent->miny;
+            $layerObj->extent->maxy = $extent->maxy;
+        }
+
+         $layerObj->propertyMappings = '';
+         $layerObj->uniqueId = $i;
+         $layerObj->layerName = $layer->name;
+         switch($layer->type) {
+             case MS_LAYER_POINT:
+                $type = 0;
+                break;
+             case MS_LAYER_LINE:
+                $type = 1;
+                break;
+             case MS_LAYER_POLYGON:
+                $type = 2;
+                break;
+             case MS_LAYER_RASTER:
+                $type = 4;
+                break;
+             case MS_LAYER_ANNOTATION:
+                $type = 8;
+                break;
+             default:
+                $type = 0;
+         }
+         $layerObj->layerTypes = array($type);
+
+         $displayInLegend = strtolower($layer->getMetaData('displayInLegend'));
+         $layerObj->displayInLegend = $displayInLegend == 'false' ? false : true;
+
+         $expandInLegend = strtolower($layer->getMetaData('expandInLegend'));
+         $layerObj->expandInLegend = $expandInLegend == 'false' ? false : true;
+         $layerObj->resourceId = $layer->name;
+         $layerObj->parentGroup = $layer->group;
+
+         $legendLabel = $layer->getMetaData('legendLabel');
+         if ($legendLabel == '') {
+             $legendLabel = $layer->name;
+         }
+         $layerObj->legendLabel = $legendLabel;
+
+         $selectable = strtolower($layer->getMetaData('selectable'));
+         $layerObj->selectable = $selectable == 'true' ? true : false;
+
+         $layerObj->visible = ($layer->status == MS_ON || $layer->status == MS_DEFAULT);
+         $layerObj->actuallyVisible = true;
+
+         $editable = strtolower($layer->getMetaData('editable'));
+         $layerObj->editable = $editable == 'true' ? true : false;
+
+         /* process the classes.  The legend expects things
+          * organized by scale range so we have to first
+          * find all the scale breaks, then create ranges
+          * for each scale break pair, then slot the classes
+          * into the scale ranges that they apply to.
+          */
+
+         $aScaleRanges = array();
+         //create a default scale range for the layer as a whole
+         $layerMin = $layer->minscale == -1 ? $minScale : $layer->minscale;
+         $layerMax = $layer->maxscale == -1 ? $maxScale : $layer->maxscale;
+
+        /* check to see that the layer has a vaild scale range
+         * inside the defined map's main min max scale ranges
+         * set them to the maps scale ranges if they exceede 
+         */
+        if($layer->minscale != -1 && $layerMin < $minScale)
+            $layerMin = $minScale;
+
+        if($layer->maxscale != -1 && $layerMax > $maxScale)
+            $layerMax = $maxScale;
+
+         //find all the unique scale breaks in this layer
+         $aScaleBreaks = array($layerMin, $layerMax);
+         for ($j=0; $j<$layer->numclasses; $j++) {
+             $oClass = $layer->getClass($j);
+             $classMin = $oClass->minscale == -1 ? $layerMin : max($oClass->minscale, $layerMin);
+             $classMax = $oClass->maxscale == -1 ? $layerMax : min($oClass->maxscale, $layerMax);
+             if (!in_array($classMin, $aScaleBreaks)) {
+                 array_push($aScaleBreaks, $classMin);
+             }
+             if (!in_array($classMax, $aScaleBreaks)) {
+                 array_push($aScaleBreaks, $classMax);
+             }
+         }
+         //sort them
+         sort($aScaleBreaks);
+
+         //create scale ranges for each pair of breaks
+         for ($j=0; $j<count($aScaleBreaks)-1; $j++) {
+             $scaleRange = NULL;
+             $scaleRange->minScale = $aScaleBreaks[$j];
+             $scaleRange->maxScale = $aScaleBreaks[$j+1];
+             $scaleRange->styles = array();
+             array_push($aScaleRanges, $scaleRange);
+         }
+
+         //create classes and slot them into the scale breaks
+         for ($j=0; $j<$layer->numclasses; $j++) {
+             $oClass = $layer->getClass($j);
+             $classObj = NULL;
+             // Use formatted legend label as defined by CLASS->TITLE
+             $classObj->legendLabel = $oClass->title != '' ? $oClass->title : $oClass->name;
+             $classObj->filter = $oClass->getExpression();
+             $classMin = $oClass->minscale == -1 ? $layerMin : max($oClass->minscale, $layerMin);
+             $classMax = $oClass->maxscale == -1 ? $layerMax : min($oClass->maxscale, $layerMax);
+             $classObj->minScale = $classMin;
+             $classObj->maxScale = $classMax;
+             $classObj->index = $j;
+             for ($k=0; $k<count($aScaleRanges); $k++) {
+                 if ($classMin < $aScaleRanges[$k]->maxScale &&
+                     $classMax > $aScaleRanges[$k]->minScale) {
+                     array_push($aScaleRanges[$k]->styles, $classObj);
+                 }
+             }
+         }
+         //$layerObj->scaleRanges = $aScaleRanges;
+         $_SESSION['scale_ranges'][$mapName][$layer->name] = $aScaleRanges;
+         /*get the min/max scale for the layer*/
+        $nCount = count($aScaleRanges);
+        $layerObj->minScale = $aScaleRanges[0]->minScale;
+        $layerObj->maxScale = $aScaleRanges[0]->maxScale;
+        for ($j=1; $j<$nCount; $j++)
+        {
+            $layerObj->minScale = min($layerObj->minScale, $aScaleRanges[$j]->minScale);
+            $layerObj->maxScale = max($layerObj->maxScale, $aScaleRanges[$j]->maxScale);
+        }
+        array_push($mapObj->layers, $layerObj);
+    }
+    $mapObj->groups = array();
+    $aGroups = $oMap->getAllGroupNames();
+    foreach($aGroups as $groupName) {
+        $aLayerIndexes = $oMap->getLayersIndexByGroup($groupName);
+        if (count($aLayerIndexes) > 0) {
+            array_push($mapObj->groups, getGroupObject($oMap->getLayer($aLayerIndexes[0])));
+        }
+    }
+    echo var2json($mapObj);
+}
+
+function getGroupObject($layer) {
+    $group = NULL;
+    $group->groupName = $layer->group;
+    $ll = $layer->getMetaData('groupLegendLabel');
+    $group->legendLabel = $ll != '' ? $ll : $group->groupName;
+    $group->uniqueId = $group->groupName;
+    $b = $layer->getMetaData('groupDisplayInLegend');
+    $group->displayInLegend = ($b == 'false') ? false : true;
+    $b = $layer->getMetaData('groupExpandInLegend');
+    $group->expandInLegend = ($b == 'false') ? false : true;
+    $group->layerGroupType = '';
+    /* parent is always not set for mapserver since we can't have nested groups */
+    $group->parentUniqueId = '';
+    $group->parent = '';
+    $b = $layer->getMetaData('groupVisible');
+    $group->visible = ($b == 'false') ? false : true;
+    $group->actuallyVisible = $layer->isVisible();
+    $group->groupParent = $layer->getMetaData('groupParent');
+
+    return $group;
+}
+
+function GetMetersPerUnit($unit)
+{
+    if ($unit == MS_INCHES)
+      return 0.0254;
+    else if ($unit == MS_FEET)
+      return 0.3048;
+    else if ($unit == MS_MILES)
+      return 1609.344;
+    else if ($unit == MS_METERS)
+      return 1;
+    else if ($unit == MS_KILOMETERS)
+      return 1000;
+    else if ($unit == MS_DD)
+      return 111118.7516;
+    else if ($unit == MS_PIXELS)
+      return 1;
+
+}
+
+function replaceInvalidLayerName($szLayerName){
+    /*
+    bug http://trac.osgeo.org/fusion/ticket/96 - Invalid characters in layer name (pdeschamps)
+
+    Fusion requests the map imavge via the Mapserver CGI to toggle the layer visibility.
+    The layer paramerter for the cgi uses spaces as a delimiter for the layer names this creates
+    an issue for the mapserver binary to toggle layers that have these reserved URI characters.
+    also removing characters that could pose potential issues with json.
+    */
+    $aInvalidLayerNameCharacters = array();
+    $aInvalidLayerNameCharacters[0] ="&";
+    $aInvalidLayerNameCharacters[1] =" ";
+    $aInvalidLayerNameCharacters[2] ="#";
+    $aInvalidLayerNameCharacters[3] ="\\";
+    $aInvalidLayerNameCharacters[4] ="=";
+    $aInvalidLayerNameCharacters[5] ="/";
+    $aInvalidLayerNameCharacters[6] ="'";
+
+    $aReplace[0] = "_";
+    $aReplace[1] = "_";
+    $aReplace[2] = "_";
+    $aReplace[3] = "_";
+    $aReplace[4] = "_";
+    $aReplace[5] = "_";
+    $aReplace[6] = "_";
+
+    return str_replace($aInvalidLayerNameCharacters,$aReplace,$szLayerName);
+}
+
+?>

Modified: sandbox/jxlib-3.0/layers/MapServer/php/Session.php
===================================================================
--- sandbox/jxlib-3.0/layers/MapServer/php/Session.php	2010-09-02 02:52:59 UTC (rev 2213)
+++ sandbox/jxlib-3.0/layers/MapServer/php/Session.php	2010-09-02 14:21:53 UTC (rev 2214)
@@ -62,489 +62,494 @@
     $GLOBALS['bLockSession'] = false;
 }
 
-/**
- * _open Called by PHP session manager when a session is opened.
- * We just set the save path and session name into global variable.
- *
- * @param szSavePath String containing the absolute path where to
- *        save session info.
- * @param szSessionName String contqaining the session name.
- */
-function _open($szSavePath, $szSessionName)
-{
-    if ($GLOBALS["bDebug"])
-    {
-      debug_msg("Opened() $szSavePath, $szSessionName");
-      debug_msg("session_id() says ".session_id());
-    }
+if (!function_exists("_open")) {
+  /**
+   * _open Called by PHP session manager when a session is opened.
+   * We just set the save path and session name into global variable.
+   *
+   * @param szSavePath String containing the absolute path where to
+   *        save session info.
+   * @param szSessionName String contqaining the session name.
+   */
+  function _open($szSavePath, $szSessionName)
+  {
+      if ($GLOBALS["bDebug"])
+      {
+        debug_msg("Opened() $szSavePath, $szSessionName");
+        debug_msg("session_id() says ".session_id());
+      }
 
-    $GLOBALS['gszSessSavePath'] = $szSavePath;
-    $GLOBALS['gszSessName'] = $szSessionName;
-    $GLOBALS['gszSessId'] = session_id();
+      $GLOBALS['gszSessSavePath'] = $szSavePath;
+      $GLOBALS['gszSessName'] = $szSessionName;
+      $GLOBALS['gszSessId'] = session_id();
 
-    $szSessionDir = $GLOBALS['gszSessSavePath']."/sess_".$GLOBALS['gszSessId'];
-    $szSessionFile = $szSessionDir."/session_file";
-    $szLockFile = $szSessionDir."/lock";
+      $szSessionDir = $GLOBALS['gszSessSavePath']."/sess_".$GLOBALS['gszSessId'];
+      $szSessionFile = $szSessionDir."/session_file";
+      $szLockFile = $szSessionDir."/lock";
 
-    clearstatcache();
-    if (!file_exists($szSessionDir))
-    {
-        mkdir($szSessionDir);
-    }
+      clearstatcache();
+      if (!file_exists($szSessionDir))
+      {
+          mkdir($szSessionDir);
+      }
 
-    if ( PHP_OS == "WINNT" || PHP_OS == "WIN32" || $GLOBALS['bLockSession'])
-    {
-        $i=0;
-        while ($i < ini_get("max_execution_time") - 2 ) //wait at most 2 seconds less than the execution time for the lock
-        {
-            clearstatcache();
-            if (!file_exists($szLockFile))
-            {
-                break;
-            }
-            if ($GLOBALS["bDebug"])
-            {
-                debug_msg("pausing in open()");
-            }
-            $i++;
-            sleep(1);
-        }
-        $fh = fopen( $szLockFile, "w+" );
-        if ($fh !== false)
-        {
-            fwrite( $fh, "1" );
-            fclose($fh);
-            if ($GLOBALS["bDebug"])
-            {
-                debug_msg("created lock file in open()");
-            }
-        }
-    }
+      if ( PHP_OS == "WINNT" || PHP_OS == "WIN32" || $GLOBALS['bLockSession'])
+      {
+          $i=0;
+          while ($i < ini_get("max_execution_time") - 2 ) //wait at most 2 seconds less than the execution time for the lock
+          {
+              clearstatcache();
+              if (!file_exists($szLockFile))
+              {
+                  break;
+              }
+              if ($GLOBALS["bDebug"])
+              {
+                  debug_msg("pausing in open()");
+              }
+              $i++;
+              sleep(1);
+          }
+          $fh = fopen( $szLockFile, "w+" );
+          if ($fh !== false)
+          {
+              fwrite( $fh, "1" );
+              fclose($fh);
+              if ($GLOBALS["bDebug"])
+              {
+                  debug_msg("created lock file in open()");
+              }
+          }
+      }
 
-    return(true);
-}
+      return(true);
+  }
 
-/**
- * _close Called by PHP session manager when a session is closed,
- * not destroyed. In this case we do nothing.
- */
-function _close()
-{
-    if ($GLOBALS["bDebug"])
-    {
-      debug_msg("Closed()");
-    }
-    if ( PHP_OS == "WINNT" || PHP_OS == "WIN32" || $GLOBALS['bLockSession'])
-    {
-        $szLockFile = $GLOBALS['gszSessSavePath']."/sess_".$GLOBALS["gszSessId"]."/lock";
-        if ($GLOBALS["bDebug"])
-        {
-            debug_msg("checking lock file $szLockFile");
-        }
-        clearstatcache();
-        if ( @is_file( $szLockFile )  )
-        {
-            @unlink( $szLockFile );
-            if ($GLOBALS["bDebug"])
-            {
-                debug_msg("removed lock file $szLockFile");
-            }
-        }
-        else
-        {
-            if ($GLOBALS["bDebug"])
-            {
-                debug_msg("lock file $szLockFile is missing.");
-            }
+  /**
+   * _close Called by PHP session manager when a session is closed,
+   * not destroyed. In this case we do nothing.
+   */
+  function _close()
+  {
+      if ($GLOBALS["bDebug"])
+      {
+        debug_msg("Closed()");
+      }
+      if ( PHP_OS == "WINNT" || PHP_OS == "WIN32" || $GLOBALS['bLockSession'])
+      {
+          $szLockFile = $GLOBALS['gszSessSavePath']."/sess_".$GLOBALS["gszSessId"]."/lock";
+          if ($GLOBALS["bDebug"])
+          {
+              debug_msg("checking lock file $szLockFile");
+          }
+          clearstatcache();
+          if ( @is_file( $szLockFile )  )
+          {
+              @unlink( $szLockFile );
+              if ($GLOBALS["bDebug"])
+              {
+                  debug_msg("removed lock file $szLockFile");
+              }
+          }
+          else
+          {
+              if ($GLOBALS["bDebug"])
+              {
+                  debug_msg("lock file $szLockFile is missing.");
+              }
 
-        }
-    }
-    return(true);
-}
+          }
+      }
+      return(true);
+  }
 
-/**
- * _read Called by PHP session manager when the session file
- * is read. In this case we just return the file content of
- * session_file file.
- */
-function _read($szId)
-{
-    $GLOBALS["gszSessId"] = $szId;
+  /**
+   * _read Called by PHP session manager when the session file
+   * is read. In this case we just return the file content of
+   * session_file file.
+   */
+  function _read($szId)
+  {
+      $GLOBALS["gszSessId"] = $szId;
 
-    if ($GLOBALS["bDebug"])
-    {
-      debug_msg("Read() $szId");
-    }
+      if ($GLOBALS["bDebug"])
+      {
+        debug_msg("Read() $szId");
+      }
 
-    $szSessionDir = $GLOBALS['gszSessSavePath']."/sess_".$szId;
-    $szSessionFile = $szSessionDir."/session_file";
+      $szSessionDir = $GLOBALS['gszSessSavePath']."/sess_".$szId;
+      $szSessionFile = $szSessionDir."/session_file";
 
-    clearstatcache();
-    if (!file_exists($szSessionDir))
-    {
-        mkdir($szSessionDir);
-    }
+      clearstatcache();
+      if (!file_exists($szSessionDir))
+      {
+          mkdir($szSessionDir);
+      }
 
-    if ($fp = @fopen($szSessionFile, "r"))
-    {
-        $szSessionData = fread($fp, filesize($szSessionFile));
-        fclose( $fp );
-        return($szSessionData);
-    }
-    else
-    {
-        return(""); // Must return "" here.
-    }
-}
+      if ($fp = @fopen($szSessionFile, "r"))
+      {
+          $szSessionData = fread($fp, filesize($szSessionFile));
+          fclose( $fp );
+          return($szSessionData);
+      }
+      else
+      {
+          return(""); // Must return "" here.
+      }
+  }
 
-/**
- * _write Called by PHP session manager when session should be
- * saved.
- *
- * @param szId String containing the unique identifier of current
- *             session.
- * @param szSessionData String containig the session file content
- *                      to be saved.
- */
-function _write($szId, $szSessionData)
-{
-    $result = false;
-    if ($GLOBALS["bDebug"])
-    {
-      debug_msg("Write() $szId $szSessionData");
-    }
+  /**
+   * _write Called by PHP session manager when session should be
+   * saved.
+   *
+   * @param szId String containing the unique identifier of current
+   *             session.
+   * @param szSessionData String containig the session file content
+   *                      to be saved.
+   */
+  function _write($szId, $szSessionData)
+  {
+      $result = false;
+      if ($GLOBALS["bDebug"])
+      {
+        debug_msg("Write() $szId $szSessionData");
+      }
 
-    $szSessionFile = $GLOBALS['gszSessSavePath']."/sess_".$szId.
-                     "/session_file";
+      $szSessionFile = $GLOBALS['gszSessSavePath']."/sess_".$szId.
+                       "/session_file";
 
-    // touch command don't works under windows for directory.
-    // since it is only needed for unix (for now) I'll test
-    // the platform and bypass this call is windows platform.
-    if ( !(PHP_OS == "WINNT" || PHP_OS == "WIN32") )
-        @touch($GLOBALS['gszSessSavePath']."/sess_".$szId);
+      // touch command don't works under windows for directory.
+      // since it is only needed for unix (for now) I'll test
+      // the platform and bypass this call is windows platform.
+      if ( !(PHP_OS == "WINNT" || PHP_OS == "WIN32") )
+          @touch($GLOBALS['gszSessSavePath']."/sess_".$szId);
 
-    if ($fp = @fopen($szSessionFile, "w"))
-    {
-        $result = fwrite($fp, $szSessionData);
-        fclose($fp);
+      if ($fp = @fopen($szSessionFile, "w"))
+      {
+          $result = fwrite($fp, $szSessionData);
+          fclose($fp);
 
-    }
-    return($result);
-}
+      }
+      return($result);
+  }
 
-/**
- * _destroy Called by PHP session manager when it should be explicitly
- * destroyed now.
- */
-function _destroy($szId)
-{
-    if ($GLOBALS["bDebug"])
-    {
-      debug_msg("Destroy $szId");
-    }
-    if ( (PHP_OS == "WINNT" || PHP_OS == "WIN32"|| $GLOBALS['bLockSession']) )
-    {
-        $szLockFile = $GLOBALS['gszSessSavePath']."/sess_".$GLOBALS["gszSessId"]."/lock";
+  /**
+   * _destroy Called by PHP session manager when it should be explicitly
+   * destroyed now.
+   */
+  function _destroy($szId)
+  {
+      if ($GLOBALS["bDebug"])
+      {
+        debug_msg("Destroy $szId");
+      }
+      if ( (PHP_OS == "WINNT" || PHP_OS == "WIN32"|| $GLOBALS['bLockSession']) )
+      {
+          $szLockFile = $GLOBALS['gszSessSavePath']."/sess_".$GLOBALS["gszSessId"]."/lock";
 
-        if ( @is_file( $szLockFile )  )
-        {
-            @unlink( $szLockFile );
-        }
-    }
-  /*
-    if ($GLOBALS['gszGarbageColectionCallBackFunction'] != "")
-    {
-        if (function_exists($GLOBALS['gszGarbageColectionCallBackFunction']))
-            eval($GLOBALS['gszGarbageColectionCallBackFunction']);
-    }
+          if ( @is_file( $szLockFile )  )
+          {
+              @unlink( $szLockFile );
+          }
+      }
+    /*
+      if ($GLOBALS['gszGarbageColectionCallBackFunction'] != "")
+      {
+          if (function_exists($GLOBALS['gszGarbageColectionCallBackFunction']))
+              eval($GLOBALS['gszGarbageColectionCallBackFunction']);
+      }
 
-    $bReturn = true;
+      $bReturn = true;
 
-    if (!$szDir = @opendir($GLOBALS['gszSessSavePath']))
-    {
-        return false;
-    }
+      if (!$szDir = @opendir($GLOBALS['gszSessSavePath']))
+      {
+          return false;
+      }
 
-    while($szFile = readdir($szDir))
-    {
-        if (!strstr($szFile,'sess_'.$szId))
-            continue;
+      while($szFile = readdir($szDir))
+      {
+          if (!strstr($szFile,'sess_'.$szId))
+              continue;
 
-        $bReturn = (deleteDirectory($GLOBALS['gszSessSavePath']."/".
-                                    $szFile)) ? $bReturn : false;
-    }
-    closedir($szDir);
+          $bReturn = (deleteDirectory($GLOBALS['gszSessSavePath']."/".
+                                      $szFile)) ? $bReturn : false;
+      }
+      closedir($szDir);
 
-    return $bReturn;
-  */
-  return true;
-}
+      return $bReturn;
+    */
+    return true;
+  }
 
-/**
- * _gc Called by PHP session manager when a session is started or
- * register (not all the time) depending og session.gc_probability
- */
-function _gc($nMaxLifeTime)
-{
-   if ($GLOBALS["bDebug"])
-    {
-      debug_msg("_gc called");
-    }
-    if ($GLOBALS['gszGarbageColectionCallBackFunction'] != "")
-    {
-        if (function_exists($GLOBALS['gszGarbageColectionCallBackFunction']))
-            eval($GLOBALS['gszGarbageColectionCallBackFunction']);
-    }
+  /**
+   * _gc Called by PHP session manager when a session is started or
+   * register (not all the time) depending og session.gc_probability
+   */
+  function _gc($nMaxLifeTime)
+  {
+     if ($GLOBALS["bDebug"])
+      {
+        debug_msg("_gc called");
+      }
+      if ($GLOBALS['gszGarbageColectionCallBackFunction'] != "")
+      {
+          if (function_exists($GLOBALS['gszGarbageColectionCallBackFunction']))
+              eval($GLOBALS['gszGarbageColectionCallBackFunction']);
+      }
 
-    if ( !(PHP_OS == "WINNT" || PHP_OS == "WIN32") )
-    {
-      @touch($GLOBALS['gszSessSavePath']."/deleteme", time()-$nMaxLifeTime*60);
-      system("find ".$GLOBALS['gszSessSavePath']." -name sess_* ! -newer ".
-             $GLOBALS['gszSessSavePath']."/deleteme -exec rm -rf {} \; ");
+      if ( !(PHP_OS == "WINNT" || PHP_OS == "WIN32") )
+      {
+        @touch($GLOBALS['gszSessSavePath']."/deleteme", time()-$nMaxLifeTime*60);
+        system("find ".$GLOBALS['gszSessSavePath']." -name sess_* ! -newer ".
+               $GLOBALS['gszSessSavePath']."/deleteme -exec rm -rf {} \; ");
 
-      return true;
-    }
+        return true;
+      }
 
-    $bReturn = true;
+      $bReturn = true;
 
-    if (!$hDir = @opendir($GLOBALS['gszSessSavePath']))
-    {
-        return false;
-    }
+      if (!$hDir = @opendir($GLOBALS['gszSessSavePath']))
+      {
+          return false;
+      }
 
-    while($szFile = readdir($hDir))
-    {
-        if (!strstr($szFile,'sess_'))
-            continue;
+      while($szFile = readdir($hDir))
+      {
+          if (!strstr($szFile,'sess_'))
+              continue;
 
-        if (strpos($szFile,'sess_') != 0)
-            continue;
+          if (strpos($szFile,'sess_') != 0)
+              continue;
 
-        $szSessionDir = $GLOBALS['gszSessSavePath']."/".$szFile;
-        $szSessionFile = $szSessionDir."/session_file";
+          $szSessionDir = $GLOBALS['gszSessSavePath']."/".$szFile;
+          $szSessionFile = $szSessionDir."/session_file";
 
-        if (!($mtime = @filemtime($szSessionFile)))
-        {
-            $bReturn=false;
-            continue;
-        }
+          if (!($mtime = @filemtime($szSessionFile)))
+          {
+              $bReturn=false;
+              continue;
+          }
 
-        if (time() > $mtime + $nMaxLifeTime)
-        {
-            $bReturn = (deleteDirectory($szSessionDir)) ? $bReturn : false;
-        }
-        closedir($hDir);
+          if (time() > $mtime + $nMaxLifeTime)
+          {
+              $bReturn = (deleteDirectory($szSessionDir)) ? $bReturn : false;
+          }
+          closedir($hDir);
 
-        return $bReturn;
-    }
-}
+          return $bReturn;
+      }
+  }
 
-////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////
+  ////////////////////////////////////////////////////////////////
+  ////////////////////////////////////////////////////////////////
+  ////////////////////////////////////////////////////////////////
 
-function deleteDirectory($szFile)
-{
-    if (PHP_OS != "WINNT" && PHP_OS != "WIN32")
-        chmod($szFile,0777);
+  function deleteDirectory($szFile)
+  {
+      if (PHP_OS != "WINNT" && PHP_OS != "WIN32")
+          chmod($szFile,0777);
 
-    if (is_dir($szFile))
-    {
-        $handle = opendir($szFile);
-        while($szFileName = readdir($handle))
-        {
-            if ($szFileName != "." && $szFileName != "..")
-            {
-                deleteDirectory($szFile."/".$szFileName);
-            }
-        }
-        closedir($handle);
-        rmdir($szFile);
-    }
-    else
-    {
-        unlink($szFile);
-    }
-}
+      if (is_dir($szFile))
+      {
+          $handle = opendir($szFile);
+          while($szFileName = readdir($handle))
+          {
+              if ($szFileName != "." && $szFileName != "..")
+              {
+                  deleteDirectory($szFile."/".$szFileName);
+              }
+          }
+          closedir($handle);
+          rmdir($szFile);
+      }
+      else
+      {
+          unlink($szFile);
+      }
+  }
 
-function installSessionDirectoryHandler($szGCCallBack="")
-{
-    $GLOBALS['gszGarbageColectionCallBackFunction'] = $szGCCallBack;
+  function installSessionDirectoryHandler($szGCCallBack="")
+  {
+      $GLOBALS['gszGarbageColectionCallBackFunction'] = $szGCCallBack;
 
-    // Set handler functions
-    session_set_save_handler("_open",
-                             "_close",
-                             "_read",
-                             "_write",
-                             "_destroy",
-                             "_gc");
-}
+      // Set handler functions
+      session_set_save_handler("_open",
+                               "_close",
+                               "_read",
+                               "_write",
+                               "_destroy",
+                               "_gc");
+  }
 
-function initializeSession( $szSessName="sid", $szSessSavePath="", $szSessionID="" )
-{
+  function initializeSession( $szSessName="sid", $szSessSavePath="", $szSessionID="" )
+  {
     
-    if ($GLOBALS["bDebug"])
-    {
-      debug_msg("initializeSession( $szSessName, $szSessSavePath, $szSessionID )");
-    }
+      if ($GLOBALS["bDebug"])
+      {
+        debug_msg("initializeSession( $szSessName, $szSessSavePath, $szSessionID )");
+      }
 
     
-    //if session was run already don't execute again
-    if (isset($GLOBALS['session_started']))
-    {
-        return true;   
-    }
-    if ($szSessName == "")
-    {
-        echo "<FONT color=#FF0000>FATAL ERROR: Sessionname not specified</FONT>";
-        exit;
-    }
-    else
-        ini_set("session.name", $szSessName);
+      //if session was run already don't execute again
+      if (isset($GLOBALS['session_started']))
+      {
+          return true;   
+      }
+      if ($szSessName == "")
+      {
+          echo "<FONT color=#FF0000>FATAL ERROR: Sessionname not specified</FONT>";
+          exit;
+      }
+      else
+          ini_set("session.name", $szSessName);
 
-    if ($szSessSavePath != "")
-    {
-        ini_set("session.save_path", $szSessSavePath);
-    }
+      if ($szSessSavePath != "")
+      {
+          ini_set("session.save_path", $szSessSavePath);
+      }
 
-    clearstatcache();
-    // Check if save path is writable
-    if (!(file_exists(ini_get("session.save_path")) &&
-          is_writable(ini_get("session.save_path"))))
-    {
-        echo "<FONT COLOR=#DD0000>FATAL ERROR: Session save path (".ini_get("session.save_path").") doesn't exist or is not writable</FONT>";
-        exit;
-    }
+      clearstatcache();
+      // Check if save path is writable
+      if (!(file_exists(ini_get("session.save_path")) &&
+            is_writable(ini_get("session.save_path"))))
+      {
+          echo "<FONT COLOR=#DD0000>FATAL ERROR: Session save path (".ini_get("session.save_path").") doesn't exist or is not writable</FONT>";
+          exit;
+      }
 
-    //turn off cookies for propagating session ids
-    ini_set( "session.use_cookies", "0" );
+      //turn off cookies for propagating session ids
+      ini_set( "session.use_cookies", "0" );
 
-    // turn off tranparent SID (becuase of buffer problem)
-    ini_set( "session.use_trans_sid", "0" );
+      // turn off tranparent SID (becuase of buffer problem)
+      ini_set( "session.use_trans_sid", "0" );
 
-    // intialize tmp id
-    $szTmpID = "";
+      // intialize tmp id
+      $szTmpID = "";
 
-    // check both get and post variables
-    if ( isset($GLOBALS['_GET'][ini_get('session.name')]) )
-        $szTmpID = $GLOBALS['_GET'][ini_get('session.name')];
-    elseif (isset($GLOBALS['_POST'][ini_get('session.name')]))
-        $szTmpID = $GLOBALS['_POST'][ini_get('session.name')];
+      // check both get and post variables
+      if ( isset($GLOBALS['_GET'][ini_get('session.name')]) )
+          $szTmpID = $GLOBALS['_GET'][ini_get('session.name')];
+      elseif (isset($GLOBALS['_POST'][ini_get('session.name')]))
+          $szTmpID = $GLOBALS['_POST'][ini_get('session.name')];
 
-    // create new if necessary
-    if ( strlen( $szTmpID ) <= 0 )
-    {
-        if ($GLOBALS["bDebug"])
-        {
-            debug_msg("creating a new session because .$szTmpID. has zero characters ");
-        }
-        // create new and set IP flag
-        if ( strlen( $szSessionID ) > 0 )
-        {
-            $szTmpID = $szSessionID;
-        }
-        else            
-        {
-            $szTmpID = uniqid("");
-        }
-        $bNewSession = true;
-        if ($GLOBALS["bDebug"])
-        {
-            debug_msg("creating a new session with id ");
-        }
-   }
-    else
-        $bNewSession = false;
+      // create new if necessary
+      if ( strlen( $szTmpID ) <= 0 )
+      {
+          if ($GLOBALS["bDebug"])
+          {
+              debug_msg("creating a new session because .$szTmpID. has zero characters ");
+          }
+          // create new and set IP flag
+          if ( strlen( $szSessionID ) > 0 )
+          {
+              $szTmpID = $szSessionID;
+          }
+          else            
+          {
+              $szTmpID = uniqid("");
+          }
+          $bNewSession = true;
+          if ($GLOBALS["bDebug"])
+          {
+              debug_msg("creating a new session with id ");
+          }
+     }
+      else
+          $bNewSession = false;
 
-    // initialize flag variable
-    $bSessionOK = true;
+      // initialize flag variable
+      $bSessionOK = true;
 
-    // set the session ID
-    session_id( $szTmpID );
+      // set the session ID
+      session_id( $szTmpID );
 
-    // Check if session is expired
-    if (!$bNewSession)
-    {
-        $szSavePath = getSessionSavePath();
-        $szSessionFile = $szSavePath."/session_file";
+      // Check if session is expired
+      if (!$bNewSession)
+      {
+          $szSavePath = getSessionSavePath();
+          $szSessionFile = $szSavePath."/session_file";
 
-        if (file_exists($szSessionFile))
-            if ($atime=@filemtime($szSessionFile))
-                if (time() > $atime + ini_get("session.gc_maxlifetime"))
-                {
-                    $szTmpID = uniqid("");
+          if (file_exists($szSessionFile))
+              if ($atime=@filemtime($szSessionFile))
+                  if (time() > $atime + ini_get("session.gc_maxlifetime"))
+                  {
+                      $szTmpID = uniqid("");
 
-                    // reset the session ID
-                    session_id( $szTmpID );
+                      // reset the session ID
+                      session_id( $szTmpID );
 
-                    $bNewSession = true;
-                    $bSessionOK = false;
-                }
-    }
+                      $bNewSession = true;
+                      $bSessionOK = false;
+                  }
+      }
 
-    //start the session
-    session_start();
-    register_shutdown_function( "session_write_close" );
+      //start the session
+      session_start();
+      register_shutdown_function( "session_write_close" );
 
   
-    // set IP if a new session
-    if ( $bNewSession ) $_SESSION["gszRemoteAdd"] = $_SERVER["REMOTE_ADDR"];
+      // set IP if a new session
+      if ( $bNewSession ) $_SESSION["gszRemoteAdd"] = $_SERVER["REMOTE_ADDR"];
 
-/* ============================================================================
- * Check IP to see if it is the same
- * ========================================================================= */
+  /* ============================================================================
+   * Check IP to see if it is the same
+   * ========================================================================= */
 
-    // check if the IP has been set and validate
-    if ( isset( $_SESSION["gszRemoteAdd"] ) &&
-                                   strlen(trim($_SESSION["gszRemoteAdd"])) > 0 )
-    {
-        // check if IP matches current client
-        if ( trim( $_SESSION["gszRemoteAdd"] ) !=
-                                               trim( $_SERVER["REMOTE_ADDR"] ) )
-        {
-            // possible security breach void session
-            /* if the session address is the loopback interface then it is
-             * likely that the application was configured to use an external
-             * address but someone is trying to test locally using localhost
-             */
-            if ($_SESSION['gszRemoteAdd'] != '127.0.0.1')
-            {
-                $bSessionOK = false;
-            }
-        }
-    }
-    else
-    {
-        // possible security breach void session
-        $bSessionOK = false;
-    }
+      // check if the IP has been set and validate
+      if ( isset( $_SESSION["gszRemoteAdd"] ) &&
+                                     strlen(trim($_SESSION["gszRemoteAdd"])) > 0 )
+      {
+          // check if IP matches current client
+          if ( trim( $_SESSION["gszRemoteAdd"] ) !=
+                                                 trim( $_SERVER["REMOTE_ADDR"] ) )
+          {
+              // possible security breach void session
+              /* if the session address is the loopback interface then it is
+               * likely that the application was configured to use an external
+               * address but someone is trying to test locally using localhost
+               */
+              if ($_SESSION['gszRemoteAdd'] != '127.0.0.1')
+              {
+                  $bSessionOK = false;
+              }
+          }
+      }
+      else
+      {
+          // possible security breach void session
+          $bSessionOK = false;
+      }
     
-    // return success or failure and set global so we
-    // know session has been inited.
-    if ($bSessionOK)
-    {
-        $GLOBALS['session_started'] = true;
-    }
+      // return success or failure and set global so we
+      // know session has been inited.
+      if ($bSessionOK)
+      {
+          $GLOBALS['session_started'] = true;
+      }
     
         
-    return $bSessionOK;
+      return $bSessionOK;
 
-// end intializeSession() function
-}
+  // end intializeSession() function
+  }
 
-function getSessionSavePath()
-{
-    $szReturn  = ini_get("session.save_path")."/sess_".session_id()."/";
-    $szReturn = str_replace( "\\", "/", $szReturn );
-    return $szReturn;
+  function getSessionSavePath()
+  {
+      $szReturn  = ini_get("session.save_path")."/sess_".session_id()."/";
+      $szReturn = str_replace( "\\", "/", $szReturn );
+      return $szReturn;
+  }
+
+  function debug_msg( $szMsg )
+  {
+      list($usec, $sec) = explode(" ",microtime()); 
+      $ts = sprintf( "%s.%4d", date( "H:s", $sec), round( 10000 * $usec )); 
+      $fh = fopen($GLOBALS['szDebugDir']."session.log", "a+");
+      fwrite($fh, "$ts : ".$GLOBALS['szDebugPage']." : $szMsg\n");
+      fclose($fh);
+  }
+
+
 }
 
-function debug_msg( $szMsg )
-{
-    list($usec, $sec) = explode(" ",microtime()); 
-    $ts = sprintf( "%s.%4d", date( "H:s", $sec), round( 10000 * $usec )); 
-    $fh = fopen($GLOBALS['szDebugDir']."session.log", "a+");
-    fwrite($fh, "$ts : ".$GLOBALS['szDebugPage']." : $szMsg\n");
-    fclose($fh);
-}
 ?>



More information about the fusion-commits mailing list