function add_layer_definition_to_map($layerDefinition, $layerName, $layerLegendLabel, $sessionId, $resourceService, &$map) { global $schemaDirectory; // Validate the XML. $domDocument = new DOMDocument(); $domDocument->loadXML($layerDefinition); if (!$domDocument->schemaValidate($schemaDirectory . "LayerDefinition-1.3.0.xsd")) { echo "ERROR: The new XML document is invalid.<BR>\n."; return NULL; } // Save the new layer definition to the session repository $byteSource = new MgByteSource($layerDefinition, strlen($layerDefinition)); $byteSource->SetMimeType(MgMimeType::Xml); $resourceID = new MgResourceIdentifier("Session:{$sessionId}//{$layerName}.LayerDefinition"); $resourceService->SetResource($resourceID, $byteSource->GetReader(), null); $newLayer = add_layer_resource_to_map($resourceID, $resourceService, $layerName, $layerLegendLabel, $map); return $newLayer; }
include dirname(__FILE__) . "/../../mapadmin/constants.php"; try { MgInitializeWebTier(dirname(__FILE__) . "/../../webconfig.ini"); if (array_key_exists("USERNAME", $_POST) && array_key_exists("PASSWORD", $_POST)) { $siteConn = new MgSiteConnection(); $userInfo = new MgUserInformation($_POST["USERNAME"], $_POST["PASSWORD"]); $siteConn->Open($userInfo); $resSvc = $siteConn->CreateService(MgServiceType::ResourceService); //Commercial sample $res1 = new MgResourceIdentifier("Library://Samples/Sheboygan/Maps/SheboyganCommercial.MapDefinition"); $bs1 = new MgByteSource(dirname(__FILE__) . "/SheboyganCommercial.MapDefinition.xml"); $br1 = $bs1->GetReader(); $resSvc->SetResource($res1, $br1, null); //Mixed sample $res2 = new MgResourceIdentifier("Library://Samples/Sheboygan/Maps/SheboyganMixed.MapDefinition"); $bs2 = new MgByteSource(dirname(__FILE__) . "/SheboyganMixed.MapDefinition.xml"); $br2 = $bs2->GetReader(); $resSvc->SetResource($res2, $br2, null); ?> <p>Sample resources required for OpenLayers integration samples loaded.</p> <p><a href="../../samples.php">Return to samples</a></p> <?php } else { ?> <p>To load the sample resources required for OpenLayers integration samples, login as Administrator</p> <p><strong>NOTE: Make sure you have already downloaded the <a href="http://download.osgeo.org/mapguide/releases/2.0.0/samples/Sheboygan.mgp">Sheboygan Dataset</a> and load this in via the <a href="../../mapadmin/login.php">MapGuide Site Administrator</a> first before loading these OpenLayers integration sample resources</strong></p> <form action="load.php" method="post"> Username: <input type="text" name="USERNAME" id="USERNAME" /> <br/> Password: <input type="password" name="PASSWORD" id="PASSWORD" /> <br/>
function BuildLayerDefinitionContent($dataSource, $featureName, $tip) { $layerTempl = file_get_contents("../viewerfiles/linelayerdef.templ"); $xmlStr = sprintf($layerTempl, $dataSource, $featureName, "GEOM", $tip, 1, "ff0000"); $src = new MgByteSource($xmlStr, strlen($xmlStr)); return $src->GetReader(); }
echo "<body>\n"; $layerName = 'Library://TrevorWekel/PerfTest/Sdf1.FeatureSource'; $res = new MgByteSource("../../TestData/FeatureService/Sdf1.FeatureSource"); echo "Updating resource " . $layerName . "\n"; ob_flush(); $id = new MgResourceIdentifier($layerName); try { $svc->SetResource($id, $res->GetReader(), null); } catch (MgException $e) { // Resource already exists, probably ok. echo $e->GetDetails() . "\n"; ob_flush(); } $shortFileName = $_POST["file"]; if (strlen($shortFileName) <= 0) { echo "Need file argument. Exiting\n"; return; } $fileName = "../../TestData/FeatureService/" . $shortFileName; $res = new MgByteSource($fileName); $rdr = $res->GetReader(); echo "Starting data transmission of " . filesize($fileName) . " bytes from " . $fileName . " \n."; ob_flush(); $opStart = microtime(true); $svc->SetResourceData($id, $shortFileName, "File", $rdr); $opEnd = microtime(true); $diffTime = $opEnd - $opStart; echo "Transmission completed in " . $diffTime . " seconds\n"; echo "Effective bandwidth was " . filesize($fileName) / $diffTime / 1000000 . " million bytes/sec\n"; echo "</body>\n"; echo "</html>\n";
function ApplyResourcePackage($paramSet) { try { $arrayParam = array(); $package = null; $packageSource = null; $this->unitTestParamVm->Execute("Select ParamValue from Params WHERE ParamSet={$paramSet} AND ParamName=\"PACKAGE\""); $arrayParam["PACKAGE"] = Utils::GetPath($this->unitTestParamVm->GetString("ParamValue")); $packageSource = new MgByteSource($arrayParam["PACKAGE"]); $package = $packageSource->GetReader(); $byteReader = $this->resourceSrvc->ApplyResourcePackage($package); return Utils::GetResponse($byteReader); } catch (MgException $e) { return new Result(get_class($e), "text/plain"); } catch (SqliteException $s) { return new Result($s->GetExceptionMessage(), "text/plain"); } }
public function LaunchResourcePreview($resId) { $sessionId = ""; if ($resId->GetRepositoryType() == MgRepositoryType::Session) { $sessionId = $resId->GetRepositoryName(); } else { $sessionId = $this->app->request->params("session"); } $this->EnsureAuthenticationForSite($sessionId, true); $siteConn = new MgSiteConnection(); $siteConn->Open($this->userInfo); if ($sessionId == null) { $site = $siteConn->GetSite(); $sessionId = $site->CreateSession(); $userInfo = new MgUserInformation($sessionId); $siteConn->Open($userInfo); } $selfUrl = MgUtils::GetSelfUrlRoot($this->app->config("SelfUrl")); switch ($resId->GetResourceType()) { case MgResourceType::FeatureSource: $this->app->redirect("{$selfUrl}/../schemareport/describeschema.php?viewer=basic&schemaName=&className=&resId=" . $resId->ToString() . "&sessionId=" . $sessionId); break; case MgResourceType::LayerDefinition: $resSvc = $siteConn->CreateService(MgServiceType::ResourceService); $featSvc = $siteConn->CreateService(MgServiceType::FeatureService); $bbox = $this->GetLayerBBOX($featSvc, $resSvc, $resId); $content = file_get_contents(dirname(__FILE__) . "/../res/preview_mapdefinition.xml"); $content = sprintf($content, $bbox->coordsys, $bbox->minx, $bbox->maxx, $bbox->miny, $bbox->maxy, $this->CreateLayerXmlFragment($resId), ""); //echo $content; die; $mdfSource = new MgByteSource($content, strlen($content)); $mdfbr = $mdfSource->GetReader(); $mdfPreviewId = new MgResourceIdentifier("Session:{$sessionId}//Preview.MapDefinition"); $resSvc->SetResource($mdfPreviewId, $mdfbr, NULL); $content = file_get_contents(dirname(__FILE__) . "/../res/preview_weblayout.xml"); $content = sprintf($content, $mdfPreviewId->ToString()); $source = new MgByteSource($content, strlen($content)); $br = $source->GetReader(); $previewId = new MgResourceIdentifier("Session:{$sessionId}//Preview.WebLayout"); $resSvc->SetResource($previewId, $br, NULL); $this->app->redirect("{$selfUrl}/../mapviewerajax/?SESSION={$sessionId}&USERNAME=Anonymous&WEBLAYOUT=" . $previewId->ToString()); break; case MgResourceType::MapDefinition: $resSvc = $siteConn->CreateService(MgServiceType::ResourceService); //$map = new MgMap(); //$map->Create($resSvc, $mdfId, $resId->GetName()); //$sel = new MgSelection($map); //$sel->Save($resSvc, $resId->GetName()); //$map->Save($resSvc, $resId); $content = file_get_contents(dirname(__FILE__) . "/../res/preview_weblayout.xml"); $content = sprintf($content, $resId->ToString()); $source = new MgByteSource($content, strlen($content)); $br = $source->GetReader(); $previewId = new MgResourceIdentifier("Session:{$sessionId}//Preview.WebLayout"); $resSvc->SetResource($previewId, $br, NULL); $this->app->redirect("{$selfUrl}/../mapviewerajax/?SESSION={$sessionId}&USERNAME=Anonymous&WEBLAYOUT=" . $previewId->ToString()); break; case MgResourceType::SymbolDefinition: $resSvc = $siteConn->CreateService(MgServiceType::ResourceService); $mapSvc = $siteConn->CreateService(MgServiceType::MappingService); $content = file_get_contents(dirname(__FILE__) . "/../res/preview_symbollayer.xml"); $content = sprintf($content, $resId->ToString()); $ldfSource = new MgByteSource($content, strlen($content)); $ldfBr = $ldfSource->GetReader(); $ldfId = new MgResourceIdentifier("Session:{$sessionId}//SymbolPreview.LayerDefinition"); $resSvc->SetResource($ldfId, $ldfBr, NULL); $br = $mapSvc->GenerateLegendImage($ldfId, 42, 100, 50, "PNG", 4, 0); //NOXLATE $this->OutputByteReader($br); break; case "WatermarkDefinition": $resSvc = $siteConn->CreateService(MgServiceType::ResourceService); $content = file_get_contents(dirname(__FILE__) . "/../res/preview_mapdefinition.xml"); $content = sprintf($content, self::XY_COORDSYS, 0, 0, 0, 0, "", $this->CreateWatermarkFragment($resId)); //echo $content; die; $mdfSource = new MgByteSource($content, strlen($content)); $mdfbr = $mdfSource->GetReader(); $mdfPreviewId = new MgResourceIdentifier("Session:{$sessionId}//Preview.MapDefinition"); $resSvc->SetResource($mdfPreviewId, $mdfbr, NULL); $content = file_get_contents(dirname(__FILE__) . "/../res/preview_weblayout.xml"); $content = sprintf($content, $mdfPreviewId->ToString()); $source = new MgByteSource($content, strlen($content)); $br = $source->GetReader(); $previewId = new MgResourceIdentifier("Session:{$sessionId}//Preview.WebLayout"); $resSvc->SetResource($previewId, $br, NULL); $this->app->redirect("{$selfUrl}/../mapviewerajax/?SESSION={$sessionId}&USERNAME=Anonymous&WEBLAYOUT=" . $previewId->ToString()); break; default: $this->BadRequest($this->app->localizer->getText("E_UNPREVIEWABLE_RESOURCE_TYPE"), MgMimeType::Html); break; } }
function CreateDataPropertyForType($property) { switch ($property->GetDataType()) { case MgPropertyType::Null: return null; break; case MgPropertyType::Boolean: return new MgBooleanProperty($property->GetName(), false); break; case MgPropertyType::Byte: return new MgByteProperty($property->GetName(), 0); break; case MgPropertyType::DateTime: return new MgDateTimeProperty($property->GetName(), new MgDateTime()); break; case MgPropertyType::Single: return new MgSingleProperty($property->GetName(), 0); break; case MgPropertyType::Double: return new MgDoubleProperty($property->GetName(), 0); break; case MgPropertyType::Int16: return new MgInt16Property($property->GetName(), 0); break; case MgPropertyType::Int32: return new MgInt32Property($property->GetName(), 0); break; case MgPropertyType::Int64: return new MgInt64Property($property->GetName(), 0); break; case MgPropertyType::String: return new MgStringProperty($property->GetName(), ''); break; case MgPropertyType::Blob: $byteSource = new MgByteSource("", 0); return new MgBlobProperty($property->GetName(), $byteSource->GetReader()); break; case MgPropertyType::Clob: $byteSource = new MgByteSource("", 0); return new MgClobProperty($property->GetName(), $byteSource->GetReader()); break; default: return null; } }
function ApplyTheme() { $resourceService = $this->site->CreateService(MgServiceType::ResourceService); $featureService = $this->site->CreateService(MgServiceType::FeatureService); $map = new MgMap(); $map->Open($resourceService, $this->args['MAPNAME']); $layers = $map->GetLayers(); $layer = $layers->GetItem($this->args['LAYERNAME']); $resId = new MgResourceIdentifier($layer->GetFeatureSourceId()); $layerDefResId = $layer->GetLayerDefinition(); $byteReader = $resourceService->GetResourceContent($layerDefResId); // Load the Layer Definition and Navigate to the specified <VectorScaleRange> $doc = DOMDocument::loadXML($byteReader->ToString()); $nodeList = $doc->getElementsByTagName('VectorScaleRange'); $vectorScaleRangecElement = $nodeList->item($this->args['SCALERANGEINDEX']); $areaTypeStyle = $vectorScaleRangecElement->getElementsByTagName('AreaTypeStyle')->item(0); // Remove any existing <AreaRule> elements. $areaRuleList = $areaTypeStyle->getElementsByTagName('AreaRule'); $ruleCount = $areaRuleList->length; for ($index = 0; $index < $ruleCount; $index++) { $areaTypeStyle->removeChild($areaRuleList->item(0)); } // Now create the new <AreaRule> elements. $areaRuleTemplate = file_get_contents("templates/arearuletemplate.xml"); $aggregateOptions = new MgFeatureAggregateOptions(); $portion = 0.0; $increment = $this->args['NUMRULES'] > 1 ? $increment = 1.0 / ($this->args['NUMRULES'] - 1) : 1.0; if ($this->args['DISTRO'] == 'INDIV_DIST') { $aggregateOptions->AddFeatureProperty($this->args['PROPERTYNAME']); $aggregateOptions->SelectDistinct(true); $dataReader = $featureService->SelectAggregate($resId, $layer->GetFeatureClassName(), $aggregateOptions); while ($dataReader->ReadNext()) { $value = $this->GetFeaturePropertyValue($dataReader, $this->args['PROPERTYNAME']); $filterText = '"' . $this->args['PROPERTYNAME'] . '" = '; if ($this->args['DATATYPE'] == MgPropertyType::String) { $filterText .= "'" . $value . "'"; } else { $filterText .= $value; } $areaRuleXML = sprintf($areaRuleTemplate, $this->args['PROPERTYNAME'] . ': ' . $value, $filterText, $this->InterpolateColor($portion, $this->args['FILLFROM'], $this->args['FILLTO'], $this->args['FILLTRANS']), $this->InterpolateColor($portion, $this->args['LINEFROM'], $this->args['LINETO'], 0)); $areaDoc = DOMDocument::loadXML($areaRuleXML); $areaNode = $doc->importNode($areaDoc->documentElement, true); $areaTypeStyle->appendChild($areaNode); $portion += $increment; } $dataReader->Close(); } else { $values = array(); $aggregateOptions->AddComputedProperty('THEME_VALUE', $this->args['DISTRO'] . '("' . $this->args['PROPERTYNAME'] . '",' . $this->args['NUMRULES'] . ',' . $this->args['MINVALUE'] . ',' . $this->args['MAXVALUE'] . ')'); $dataReader = $featureService->SelectAggregate($resId, $layer->GetFeatureClassName(), $aggregateOptions); while ($dataReader->ReadNext()) { $value = $this->GetFeaturePropertyValue($dataReader, 'THEME_VALUE'); array_push($values, $value); } $dataReader->Close(); for ($i = 0; $i < count($values) - 1; $i++) { $filterText = '"' . $this->args['PROPERTYNAME'] . '" >= ' . $values[$i] . ' AND "' . $this->args['PROPERTYNAME']; if ($i == count($values) - 1) { $filterText .= '" <= ' . $values[$i + 1]; } else { $filterText .= '" < ' . $values[$i + 1]; } $areaRuleXML = sprintf($areaRuleTemplate, $this->args['PROPERTYNAME'] . ': ' . $values[$i] . ' - ' . $values[$i + 1], $filterText, $this->InterpolateColor($portion, $this->args['FILLFROM'], $this->args['FILLTO'], $this->args['FILLTRANS']), $this->InterpolateColor($portion, $this->args['LINEFROM'], $this->args['LINETO'], 0)); $areaDoc = DOMDocument::loadXML($areaRuleXML); $areaNode = $doc->importNode($areaDoc->documentElement, true); $areaTypeStyle->appendChild($areaNode); $portion += $increment; } } // Now save our new layer definition to the session and add it to the map. $layerDefinition = $doc->saveXML(); $uniqueName = $this->MakeUniqueLayerName($map, $this->args['LAYERNAME'], $this->args['THEMENAME']); $legendLabel = $layer->GetLegendLabel(); if (strlen(trim($this->args['THEMENAME'])) > 0) { $legendLabel .= ' (' . $this->args['THEMENAME'] . ')'; } $layerResId = new MgResourceIdentifier('Session:' . $this->args['SESSION'] . '//' . $uniqueName . '.LayerDefinition'); $byteSource = new MgByteSource($layerDefinition, strlen($layerDefinition)); $resourceService->SetResource($layerResId, $byteSource->GetReader(), null); $newLayer = new MgLayer($layerResId, $resourceService); $newLayer->SetName($uniqueName); $newLayer->SetLegendLabel($legendLabel); $newLayer->SetDisplayInLegend($layer->GetDisplayInLegend()); $newLayer->SetVisible(true); $newLayer->SetSelectable($layer->GetLegendLabel()); $layers->Insert($layers->IndexOf($layer), $newLayer); $map->Save($resourceService); return $uniqueName; }
function SetupTestData() { global $adminUser; global $adminPass; global $user1User; global $user1Pass; global $user2User; global $user2Pass; global $userGroup; $webConfigPath = dirname(__FILE__) . "/../../webconfig.ini"; MgInitializeWebTier($webConfigPath); $mgp = dirname(__FILE__) . "/data/Sheboygan.mgp"; if (!file_exists($mgp)) { echo "Please put Sheboygan.mgp into the /data directory before running this test suite"; die; } if (!is_dir(dirname(__FILE__) . "/../conf/data/test_anonymous/")) { mkdir(dirname(__FILE__) . "/../conf/data/test_anonymous/"); } copy(dirname(__FILE__) . "/data/restcfg_anonymous.json", dirname(__FILE__) . "/../conf/data/test_anonymous/restcfg.json"); if (!is_dir(dirname(__FILE__) . "/../conf/data/test_author/")) { mkdir(dirname(__FILE__) . "/../conf/data/test_author/"); } copy(dirname(__FILE__) . "/data/restcfg_author.json", dirname(__FILE__) . "/../conf/data/test_author/restcfg.json"); if (!is_dir(dirname(__FILE__) . "/../conf/data/test_administrator/")) { mkdir(dirname(__FILE__) . "/../conf/data/test_administrator/"); } copy(dirname(__FILE__) . "/data/restcfg_administrator.json", dirname(__FILE__) . "/../conf/data/test_administrator/restcfg.json"); if (!is_dir(dirname(__FILE__) . "/../conf/data/test_wfsuser/")) { mkdir(dirname(__FILE__) . "/../conf/data/test_wfsuser/"); } copy(dirname(__FILE__) . "/data/restcfg_wfsuser.json", dirname(__FILE__) . "/../conf/data/test_wfsuser/restcfg.json"); if (!is_dir(dirname(__FILE__) . "/../conf/data/test_wmsuser/")) { mkdir(dirname(__FILE__) . "/../conf/data/test_wmsuser/"); } copy(dirname(__FILE__) . "/data/restcfg_wmsuser.json", dirname(__FILE__) . "/../conf/data/test_wmsuser/restcfg.json"); if (!is_dir(dirname(__FILE__) . "/../conf/data/test_group/")) { mkdir(dirname(__FILE__) . "/../conf/data/test_group/"); } copy(dirname(__FILE__) . "/data/restcfg_group.json", dirname(__FILE__) . "/../conf/data/test_group/restcfg.json"); if (!is_dir(dirname(__FILE__) . "/../conf/data/test_mixed/")) { mkdir(dirname(__FILE__) . "/../conf/data/test_mixed/"); } copy(dirname(__FILE__) . "/data/restcfg_mixed.json", dirname(__FILE__) . "/../conf/data/test_mixed/restcfg.json"); $source = new MgByteSource($mgp); $br = $source->GetReader(); $siteConn = new MgSiteConnection(); $userInfo = new MgUserInformation($adminUser, $adminPass); $siteConn->Open($userInfo); $site = new MgSite(); $site->Open($userInfo); //Set up any required users try { $site->AddGroup($userGroup, "Group for mapguide-rest test suite users"); } catch (MgException $ex) { } try { $site->AddUser($user1User, $user1User, $user1Pass, "Test user for mapguide-rest test suite"); } catch (MgException $ex) { } try { $site->AddUser($user2User, $user2User, $user2Pass, "Test user for mapguide-rest test suite"); } catch (MgException $ex) { } try { $groups = new MgStringCollection(); $users = new MgStringCollection(); $groups->Add($userGroup); $users->Add($user1User); $users->Add($user2User); $site->GrantGroupMembershipsToUsers($groups, $users); } catch (MgException $ex) { } $resSvc = $siteConn->CreateService(MgServiceType::ResourceService); $resSvc->ApplyResourcePackage($br); $srcId = new MgResourceIdentifier("Library://Samples/Sheboygan/Data/Parcels.FeatureSource"); $dstId = new MgResourceIdentifier("Library://RestUnitTests/Parcels.FeatureSource"); $resSvc->CopyResource($srcId, $dstId, true); $bsWriteable = new MgByteSource(dirname(__FILE__) . "/data/Parcels_Writeable.FeatureSource.xml"); $brWriteable = $bsWriteable->GetReader(); $resSvc->SetResource($dstId, $brWriteable, null); $rdsdfsource = new MgByteSource(dirname(__FILE__) . "/data/RedlineLayer.sdf"); $rdsdfrdr = $rdsdfsource->GetReader(); $resId = new MgResourceIdentifier("Library://RestUnitTests/RedlineLayer.FeatureSource"); $rdXml = '<?xml version="1.0"?><FeatureSource xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:noNamespaceSchemaLocation="FeatureSource-1.0.0.xsd"><Provider>OSGeo.SDF</Provider><Parameter><Name>File</Name><Value>%MG_DATA_FILE_PATH%RedlineLayer.sdf</Value></Parameter></FeatureSource>'; $rdXmlSource = new MgByteSource($rdXml, strlen($rdXml)); $rdXmlRdr = $rdXmlSource->GetReader(); $resSvc->SetResource($resId, $rdXmlRdr, null); $resSvc->SetResourceData($resId, "RedlineLayer.sdf", MgResourceDataType::File, $rdsdfrdr); }
public function UpdateMapLayersAndGroups($sessionId, $mapName, $format) { //Check for unsupported representations $fmt = $this->ValidateRepresentation($format, array("xml", "json")); try { $this->EnsureAuthenticationForSite($sessionId); $siteConn = new MgSiteConnection(); $siteConn->Open($this->userInfo); $resSvc = $siteConn->CreateService(MgServiceType::ResourceService); $map = new MgMap($siteConn); $map->Open($mapName); if ($fmt == "json") { $body = $this->app->request->getBody(); $json = json_decode($body); if ($json == NULL) { throw new Exception($this->app->localizer->getText("E_MALFORMED_JSON_BODY")); } } else { $body = $this->app->request->getBody(); $jsonStr = MgUtils::Xml2Json($body); $json = json_decode($jsonStr); } if (!isset($json->UpdateMap)) { throw new Exception($this->app->localizer->getText("E_MALFORMED_JSON_BODY")); } /* Expected structure /UpdateMap /Operation [1...n] /Type - [AddLayer|UpdateLayer|RemoveLayer|AddGroup|UpdateGroup|RemoveGroup] /Name /ResourceId /SetLegendLabel /SetDisplayInLegend /SetExpandInLegend /SetVisible /SetSelectable /InsertAt */ $layers = $map->GetLayers(); $groups = $map->GetLayerGroups(); $um = $json->UpdateMap; $updateStats = new stdClass(); $updateStats->AddedLayers = 0; $updateStats->UpdatedLayers = 0; $updateStats->RemovedLayers = 0; $updateStats->AddedGroups = 0; $updateStats->UpdatedGroups = 0; $updateStats->RemovedGroups = 0; $this->app->log->debug("Operations found: " . count($um->Operation)); for ($i = 0; $i < count($um->Operation); $i++) { $op = $um->Operation[$i]; switch ($op->Type) { case "AddLayer": $resId = new MgResourceIdentifier($op->ResourceId); $layer = new MgLayer($resId, $resSvc); $layer->SetName($op->Name); self::ApplyCommonLayerProperties($layer, $op, $groups); if (isset($op->InsertAt)) { $layers->Insert(intval($op->InsertAt), $layer); } else { $layers->Add($layer); } $this->app->log->debug("Add Layer: " . $op->Name); $updateStats->AddedLayers++; break; case "UpdateLayer": $layer = $layers->GetItem($op->Name); if (self::ApplyCommonLayerProperties($layer, $op, $groups)) { $this->app->log->debug("Updated Layer: " . $op->Name); $updateStats->UpdatedLayers++; } break; case "RemoveLayer": $layer = $layers->GetItem($op->Name); if ($layers->Remove($layer)) { $this->app->log->debug("Removed Layer: " . $op->Name); $updateStats->RemovedLayers++; } break; case "AddGroup": $group = new MgLayerGroup($op->Name); self::ApplyCommonGroupProperties($group, $op, $groups); if (isset($op->InsertAt)) { $groups->Insert(intval($op->InsertAt), $group); } else { $groups->Add($group); } $this->app->log->debug("Add Group: " . $op->Name); $updateStats->AddedGroups++; break; case "UpdateGroup": $gidx = $groups->IndexOf($op->Name); if ($gidx < 0) { if ($op->AddIfNotExists) { $group = new MgLayerGroup($op->Name); self::ApplyCommonGroupProperties($group, $op, $groups); if (isset($op->InsertAt)) { $groups->Insert(intval($op->InsertAt), $group); } else { $groups->Add($group); } $this->app->log->debug("Add Group: " . $op->Name); $updateStats->AddedGroups++; } else { throw new Exception($this->app->localizer->getText("E_GROUP_NOT_FOUND", $op->Name)); } } else { $group = $groups->GetItem($gidx); if (self::ApplyCommonGroupProperties($group, $op, $groups)) { $this->app->log->debug("Updated Group: " . $op->Name); $updateStats->UpdatedGroups++; } } break; case "RemoveGroup": $group = $groups->GetItem($op->Name); if ($groups->Remove($group)) { $this->app->log->debug("Removed Group: " . $op->Name); $updateStats->RemovedGroups++; } break; } } if ($updateStats->AddedLayers > 0 || $updateStats->UpdatedLayers > 0 || $updateStats->RemovedLayers > 0 || $updateStats->AddedGroups > 0 || $updateStats->UpdatedGroups > 0 || $updateStats->RemovedGroups > 0) { $map->Save(); } $response = "<UpdateMapResult>"; $response .= "<AddedLayers>"; $response .= $updateStats->AddedLayers; $response .= "</AddedLayers>"; $response .= "<UpdatedLayers>"; $response .= $updateStats->UpdatedLayers; $response .= "</UpdatedLayers>"; $response .= "<RemovedLayers>"; $response .= $updateStats->RemovedLayers; $response .= "</RemovedLayers>"; $response .= "<AddedGroups>"; $response .= $updateStats->AddedGroups; $response .= "</AddedGroups>"; $response .= "<UpdatedGroups>"; $response .= $updateStats->UpdatedGroups; $response .= "</UpdatedGroups>"; $response .= "<RemovedGroups>"; $response .= $updateStats->RemovedGroups; $response .= "</RemovedGroups>"; $response .= "</UpdateMapResult>"; $bs = new MgByteSource($response, strlen($response)); $bs->SetMimeType(MgMimeType::Xml); $br = $bs->GetReader(); if ($format == "json") { $this->OutputXmlByteReaderAsJson($br); } else { $this->OutputByteReader($br); } } catch (MgException $ex) { $this->OnException($ex, $this->GetMimeTypeForFormat($format)); } }
function SetProps() { global $site; global $userInfo; global $errInvalidWFSFile; // Get WFS reader $serverAdmin = new MgServerAdmin(); $serverAdmin->Open($userInfo); $wfsReader = $serverAdmin->GetDocument('Wfs:OgcWfsService.config'); // Set WFS metadata $wfsData = ""; $chunk = ""; do { $chunkSize = $wfsReader->Read($chunk, 4096); $wfsData = $wfsData . $chunk; } while ($chunkSize != 0); $keywordsStr = ""; foreach ($this->keywords as $keyword) { $keywordsStr = $keywordsStr . '<item>' . $keyword . '</item>'; } $this->serviceMetadata[WFS_KEYWORDS_ITEM] = $keywordsStr; foreach ($this->serviceMetadata as $serviceItem => $serviceVal) { $itemPos = strpos($wfsData, $serviceItem); if ($itemPos === false) { throw new Exception($errInvalidWFSFile); } $valStartPos = strpos($wfsData, '>', $itemPos); $valEndPos = strpos($wfsData, '</Define>', $itemPos); if ($valStartPos === false || $valEndPos === false || $valStartPos >= $valEndPos) { throw new Exception($errInvalidWFSFile); } $wfsData = substr_replace($wfsData, $serviceVal, $valStartPos + 1, $valEndPos - $valStartPos - 1); } // Save wfs config $wfsByteSource = new MgByteSource($wfsData, strlen($wfsData)); $wfsByteSource->SetMimeType($wfsReader->GetMimeType()); $serverAdmin->SetDocument('Wfs:OgcWfsService.config', $wfsByteSource->GetReader()); $serverAdmin->Close(); }
try { $sessionId = $site->CreateSession(); $siteConn = new MgSiteConnection(); $siteConn->Open($userInfo); // Define some constants $webLayout = "Library://Samples/Layouts/PHPSamples.WebLayout"; $title = "MapGuide Developer's Guide PHP Samples"; // We check for the existence of the specified WebLayout // // If it doesn't exist, we load a copy from the WebLayout.xml on disk. This is a basic example // of programmatically loading resource content into to the repository. $wlResId = new MgResourceIdentifier($webLayout); $resSvc = $siteConn->CreateService(MgServiceType::ResourceService); if (!$resSvc->ResourceExists($wlResId)) { $wlPath = dirname(__FILE__) . "//WebLayout.xml"; $wlByteSource = new MgByteSource($wlPath); $wlByteReader = $wlByteSource->GetReader(); // NOTE: The Author account generally has write access into the site repository // which is why we're doing it like this. // If this was an Anonymous user, they can't write into the session repository. We would normally // load our content into a session-based repository and modify $webLayout to point to our // session loaded resource $resSvc->SetResource($wlResId, $wlByteReader, null); } } catch (MgException $e) { echo "ERROR: " . $e->GetExceptionMessage("eng") . "\n"; echo $e->GetStackTrace("eng") . "\n"; } ?> <html>
function ApplyTheme() { $resourceService = $this->site->CreateService(MgServiceType::ResourceService); $featureService = $this->site->CreateService(MgServiceType::FeatureService); $map = new MgMap($this->site); $map->Open($this->args['MAPNAME']); $layers = $map->GetLayers(); $layer = $layers->GetItem($this->args['LAYERNAME']); $resId = new MgResourceIdentifier($layer->GetFeatureSourceId()); $layerDefResId = $layer->GetLayerDefinition(); $byteReader = $resourceService->GetResourceContent($layerDefResId); $filter = $layer->GetFilter(); // Load the Layer Definition and Navigate to the specified <VectorScaleRange> $doc = new DOMDocument(); $doc->loadXML($byteReader->ToString()); $version = $doc->documentElement->getAttribute('version'); $template = 'templates/arearuletemplate-'.$version.'.xml'; $layerDefList = $doc->getElementsByTagName('VectorLayerDefinition'); $layerDef = $layerDefList->item(0); $nodeList = $layerDef->getElementsByTagName('VectorScaleRange'); $vectorScaleRangecElement = $nodeList->item($this->args['SCALERANGEINDEX']); $listLength = $nodeList->length; for($index = 0; $index < $listLength; $index++) { $layerDef->removeChild($nodeList->item(0)); } $layerDef->appendChild($vectorScaleRangecElement); $areaTypeStyle = $vectorScaleRangecElement->getElementsByTagName('AreaTypeStyle')->item(0); // Remove any existing <AreaRule> elements. if($areaTypeStyle != null) { $areaRuleList = $areaTypeStyle->getElementsByTagName('AreaRule'); $ruleCount = $areaRuleList->length; for($index = 0; $index < $ruleCount; $index++) { $areaTypeStyle->removeChild($areaRuleList->item(0)); } $hasChild = $areaTypeStyle->hasChildNodes(); if($hasChild) { $element = $areaTypeStyle->childNodes->item(0); } } $CompositeTypeStyles = $vectorScaleRangecElement->getElementsByTagName('CompositeTypeStyle'); $isEnhancedStyle = ($CompositeTypeStyles->length != 0); // Remove any existing <CompositeTypeStyle> elements with Polygon <GeometryContext>. if($isEnhancedStyle) { $template = 'templates/arearuletemplate-'.$version.'-Enhanced.xml'; $styleCount = $CompositeTypeStyles->length; for($index = 0; $index < $styleCount; $index++) { $CompositeTypeStyle = $CompositeTypeStyles->item($index); $GeometryContexts = $CompositeTypeStyle->getElementsByTagName('GeometryContext'); $contextCount = $GeometryContexts->length; for($i = 0; $i < $contextCount; $i++) { $GeometryContext = $GeometryContexts->item($i); if($GeometryContext->nodeValue == 'Polygon') { $vectorScaleRangecElement->removeChild($CompositeTypeStyle); $index--; $styleCount--; break; } } } } // Now create the new <AreaRule> or <CompositeTypeStyle> elements. $areaRuleTemplate = file_get_contents($template); $aggregateOptions = new MgFeatureAggregateOptions(); $portion = 0.0; $increment = ($this->args['NUMRULES'] > 1) ? $increment = 1.0 / ($this->args['NUMRULES'] - 1) : 1.0; if ($this->args['DISTRO'] == 'INDIV_DIST') { $values = array(); $aggregateOptions->AddComputedProperty('THEME_VALUE', 'UNIQUE("' . $this->args['PROPERTYNAME'] . '")'); if($filter != '') $aggregateOptions->SetFilter($filter); $dataReader = $layer->SelectAggregate($aggregateOptions); while ($dataReader->ReadNext()) { $value = $this->GetFeaturePropertyValue($dataReader, 'THEME_VALUE'); array_push($values, $value); } $dataReader->Close(); if ($this->args['DATATYPE'] == MgPropertyType::String) sort($values, SORT_STRING); else sort($values, SORT_NUMERIC); for ($i = 0; $i < count($values); $i++) { $filterText = '"' . $this->args['PROPERTYNAME'] . '" = '; if ($this->args['DATATYPE'] == MgPropertyType::String) $filterText .= "'" . $values[$i] . "'"; else $filterText .= $values[$i]; $areaRuleXML = sprintf($areaRuleTemplate, $this->args['PROPERTYNAME'] . ': ' . $values[$i], $filterText, $this->InterpolateColor($portion, $this->args['FILLFROM'], $this->args['FILLTO'], $this->args['FILLTRANS']), $this->InterpolateColor($portion, $this->args['LINEFROM'], $this->args['LINETO'], 0)); $areaDoc = new DOMDocument(); $areaDoc->loadXML($areaRuleXML); $areaNode = $doc->importNode($areaDoc->documentElement, true); if($areaTypeStyle != null) { if($hasChild) { $areaTypeStyle->insertBefore($areaNode, $element); } else { $areaTypeStyle->appendChild($areaNode); } } if($isEnhancedStyle) { $compositeTypeStyle = $doc->createElement('CompositeTypeStyle'); $compositeTypeStyle->appendChild($areaNode); $vectorScaleRangecElement->appendChild($compositeTypeStyle); } $portion += $increment; } } else { $values = array(); $aggregateOptions->AddComputedProperty('THEME_VALUE', $this->args['DISTRO'] . '("' . $this->args['PROPERTYNAME'] . '",' . $this->args['NUMRULES'] . ',' . $this->args['MINVALUE'] . ',' . $this->args['MAXVALUE'] . ')'); if($filter != '') $aggregateOptions->SetFilter($filter); $dataReader = $layer->SelectAggregate($aggregateOptions); while ($dataReader->ReadNext()) { $value = $this->GetFeaturePropertyValue($dataReader, 'THEME_VALUE'); array_push($values, $value); } $dataReader->Close(); for ($i = 0; $i < count($values) - 1; $i++) { $filterText = '"' . $this->args['PROPERTYNAME'] . '" >= ' . $values[$i] . ' AND "' . $this->args['PROPERTYNAME']; if ($i == count($values) - 2) $filterText .= '" <= ' . $values[$i + 1]; else $filterText .= '" < ' . $values[$i + 1]; $areaRuleXML = sprintf($areaRuleTemplate, $this->args['PROPERTYNAME'] . ': ' . $values[$i] . ' - ' . $values[$i + 1], $filterText, $this->InterpolateColor($portion, $this->args['FILLFROM'], $this->args['FILLTO'], $this->args['FILLTRANS']), $this->InterpolateColor($portion, $this->args['LINEFROM'], $this->args['LINETO'], 0)); $areaDoc = new DOMDocument(); $areaDoc->loadXML($areaRuleXML); $areaNode = $doc->importNode($areaDoc->documentElement, true); if($areaTypeStyle != null) { if($hasChild) { $areaTypeStyle->insertBefore($areaNode, $element); } else { $areaTypeStyle->appendChild($areaNode); } } if($isEnhancedStyle) { $compositeTypeStyle = $doc->createElement('CompositeTypeStyle'); $compositeTypeStyle->appendChild($areaNode); $vectorScaleRangecElement->appendChild($compositeTypeStyle); } $portion += $increment; } } // Now save our new layer definition to the session and add it to the map. $layerDefinition = $doc->saveXML(); $uniqueName = $this->MakeUniqueLayerName($map, $this->args['LAYERNAME'], $this->args['THEMENAME']); $legendLabel = $layer->GetLegendLabel(); if (strlen(trim($this->args['THEMENAME'])) > 0 ) $legendLabel .= ' (' . $this->args['THEMENAME'] . ')'; $layerResId = new MgResourceIdentifier('Session:' . $this->args['SESSION'] . '//' . $uniqueName . '.LayerDefinition'); $byteSource = new MgByteSource($layerDefinition, strlen($layerDefinition)); $resourceService->SetResource($layerResId, $byteSource->GetReader(), null); $newLayer = new MgLayer($layerResId, $resourceService); $newLayer->SetName($uniqueName); $newLayer->SetLegendLabel($legendLabel); $newLayer->SetDisplayInLegend($layer->GetDisplayInLegend()); $newLayer->SetVisible(true); $newLayer->SetSelectable($layer->GetLegendLabel()); $layers->Insert($layers->IndexOf($layer), $newLayer); $map->Save(); return $uniqueName; }
$recordedDate = new MgDataPropertyDefinition("RecordedDate"); $recordedDate->SetDataType(MgPropertyType::DateTime); $recordedDate->SetNullable(false); $props->Add($id); $idProps->Add($id); $props->Add($pid); $props->Add($name); $props->Add($comment); $props->Add($recordedDate); $classes = $schema->GetClasses(); $classes->Add($clsDef); $createParams = new MgFileFeatureSourceParams("OSGeo.SDF"); $createParams->SetFeatureSchema($schema); $featSvc->CreateFeatureSource($commentsId, $createParams); //Web Layout demonstrating intergration with REST-enabled published data $bs3 = new MgByteSource(dirname(__FILE__) . "/RESTWebLayout.mgp"); $br3 = $bs3->GetReader(); $resSvc->ApplyResourcePackage($br3); ?> <div class="container"> <p>Sample resources required for OpenLayers integration samples loaded.</p> <p><a class="btn btn-primary" href="../index.php">Return to samples</a></p> </div> <?php } else { ?> <div class="container"> <div class="well"> <p>To load the sample resources required for OpenLayers integration samples, login as Administrator</p> </div> <div class="alert alert-info">Make sure you have already downloaded the <a href="http://download.osgeo.org/mapguide/releases/2.0.0/samples/Sheboygan.mgp">Sheboygan Dataset</a> and load this in via the <a href="../../../mapadmin/login.php">MapGuide Site Administrator</a> first before loading these OpenLayers integration sample resources</div>
$rsvc = $site->CreateService(MgServiceType::ResourceService); $wkt = "LOCALCS[\"Non-Earth (Meter)\",LOCAL_DATUM[\"Local Datum\",0],UNIT[\"Meter\", 1],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH]]"; $featureName = 'Library://TrevorWekel/NewSdf.FeatureSource'; $id = new MgResourceIdentifier($featureName); $intFeature = new IntKeyFeature(); $stringFeature = new StringKeyFeature(); $schema = new MgFeatureSchema("TestSchema", "Temporary test schema"); $schema->GetClasses()->Add($intFeature->ClassDefinition()); $params = new MgCreateSdfParams("ArbitraryXY", $wkt, $schema); $src = new MgByteSource("NewSdf.MapDefinition"); $rid = new MgResourceIdentifier("Library://TrevorWekel/NewSdf.MapDefinition"); $rsvc->SetResource($rid, $src->GetReader(), null); $src = new MgByteSource("NewSdfInt.LayerDefinition"); $rid = new MgResourceIdentifier("Library://TrevorWekel/NewSdfInt.LayerDefinition"); $rsvc->SetResource($rid, $src->GetReader(), null); $src = new MgByteSource("NewSdfString.LayerDefinition"); $rid = new MgResourceIdentifier("Library://TrevorWekel/NewSdfString.LayerDefinition"); $rsvc->SetResource($rid, $src->GetReader(), null); echo "Deleting existing feature source\n"; $rsvc->DeleteResource($id); echo "Creating new feature source\n"; $fsvc->CreateFeatureSource($id, $params); // We need to add some data to the sdf before using it. The spatial context // reader must have an extent. $cmdColl = new MgFeatureCommandCollection(); for ($i = 1; $i <= 20; $i++) { $insert = $intFeature->InsertCommand($i); $cmdColl->Add($insert); } echo "Updating features\n"; $fsvc->UpdateFeatures($id, $cmdColl, false);
private function DescribeRuntimeMapXml($mapDefinition, $map, $sessionId, $mapName, $iconFormat, $iconWidth, $iconHeight, $reqFeatures, $iconsPerScaleRange, $resSvc, $mappingSvc) { //TODO: Caching opportunity here $admin = new MgServerAdmin(); $admin->Open($this->userInfo); $siteVersion = $admin->GetSiteVersion(); $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; $xml .= "<RuntimeMap xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"RuntimeMap-2.6.0.xsd\">\n"; // ---------------------- Site Version --------------------------- // $xml .= "<SiteVersion>{$siteVersion}</SiteVersion>\n"; // ---------------------- Session ID --------------------------- // $xml .= "<SessionId>{$sessionId}</SessionId>\n"; // ---------------------- Map Name --------------------------- // $xml .= "<Name>{$mapName}</Name>\n"; // ---------------------- Map Definition --------------------------- // $xml .= "<MapDefinition>{$mapDefinition}</MapDefinition>\n"; // ---------------------- Background Color --------------------------- // $bgColor = $map->GetBackgroundColor(); $xml .= "<BackgroundColor>{$bgColor}</BackgroundColor>\n"; // ---------------------- Display DPI --------------------------- // $dpi = $map->GetDisplayDpi(); $xml .= "<DisplayDpi>{$dpi}</DisplayDpi>"; // ---------------------- Icon MIME Type --------------------------- // if (($reqFeatures & self::REQUEST_LAYER_ICONS) == self::REQUEST_LAYER_ICONS) { switch ($iconFormat) { case "JPG": $xml .= "<IconMimeType>" . MgMimeType::Jpeg . "</IconMimeType>\n"; break; case "GIF": $xml .= "<IconMimeType>" . MgMimeType::Gif . "</IconMimeType>\n"; break; case "PNG8": $xml .= "<IconMimeType>" . MgMimeType::Png . "</IconMimeType>\n"; break; default: $xml .= "<IconMimeType>" . MgMimeType::Png . "</IconMimeType>\n"; break; } } // ---------------------- Coordinate System --------------------------- // $csFactory = new MgCoordinateSystemFactory(); $metersPerUnit = 1.0; $wkt = $map->GetMapSRS(); $csCode = ""; $epsg = ""; try { $cs = $csFactory->Create($wkt); $metersPerUnit = $cs->ConvertCoordinateSystemUnitsToMeters(1.0); $epsg = $cs->GetEpsgCode(); $csCode = $cs->GetCsCode(); } catch (MgException $ex) { } $xml .= "<CoordinateSystem>\n<Wkt>{$wkt}</Wkt>\n<MentorCode>{$csCode}</MentorCode>\n<EpsgCode>{$epsg}</EpsgCode>\n<MetersPerUnit>{$metersPerUnit}</MetersPerUnit>\n</CoordinateSystem>"; // ---------------------- Map Extents--------------------------- // $extents = $map->GetMapExtent(); $ll = $extents->GetLowerLeftCoordinate(); $ur = $extents->GetUpperRightCoordinate(); $minX = $ll->GetX(); $minY = $ll->GetY(); $maxX = $ur->GetX(); $maxY = $ur->GetY(); $xml .= "<Extents>\n<LowerLeftCoordinate><X>{$minX}</X><Y>{$minY}</Y></LowerLeftCoordinate>\n<UpperRightCoordinate><X>{$maxX}</X><Y>{$maxY}</Y></UpperRightCoordinate></Extents>\n"; $layerDefinitionMap = array(); // ---------------------- Optional things if requested --------------------------- // if (($reqFeatures & self::REQUEST_LAYER_STRUCTURE) == self::REQUEST_LAYER_STRUCTURE) { $layers = $map->GetLayers(); $layerCount = $layers->GetCount(); //Build our LayerDefinition map for code below that requires it if (($reqFeatures & self::REQUEST_LAYER_ICONS) == self::REQUEST_LAYER_ICONS) { $layerIds = new MgStringCollection(); for ($i = 0; $i < $layerCount; $i++) { $layer = $layers->GetItem($i); $ldfId = $layer->GetLayerDefinition(); $layerIds->Add($ldfId->ToString()); } $layerContents = $resSvc->GetResourceContents($layerIds, null); $layerIdCount = $layerIds->GetCount(); for ($i = 0; $i < $layerIdCount; $i++) { $ldfId = $layerIds->GetItem($i); $content = $layerContents->GetItem($i); $layerDefinitionMap[$ldfId] = $content; } } // ----------- Some pre-processing before we do groups/layers ------------- // $groups = $map->GetLayerGroups(); $groupCount = $groups->GetCount(); for ($i = 0; $i < $groupCount; $i++) { $group = $groups->GetItem($i); $parent = $group->GetGroup(); $xml .= self::CreateGroupItem($group, $parent); } $doc = new DOMDocument(); for ($i = 0; $i < $layerCount; $i++) { $layer = $layers->GetItem($i); $parent = $layer->GetGroup(); $ldf = $layer->GetLayerDefinition(); $layerId = $ldf->ToString(); $layerDoc = null; if (array_key_exists($layerId, $layerDefinitionMap)) { $doc->loadXML($layerDefinitionMap[$layerId]); $layerDoc = $doc; } $xml .= self::CreateLayerItem($reqFeatures, $iconsPerScaleRange, $iconFormat, $iconWidth, $iconHeight, $layer, $parent, $layerDoc, $mappingSvc); } } else { //Base Layer Groups need to be outputted regardless, otherwise a client application doesn't have enough information to build GETTILEIMAGE requests $groups = $map->GetLayerGroups(); $groupCount = $groups->GetCount(); for ($i = 0; $i < $groupCount; $i++) { $group = $groups->GetItem($i); if ($group->GetLayerGroupType() != MgLayerGroupType::BaseMap) { continue; } $parent = $group->GetGroup(); $xml .= self::CreateGroupItem($group, $parent); } } // ------------------------ Finite Display Scales (if any) ------------------------- // $fsCount = $map->GetFiniteDisplayScaleCount(); if ($fsCount > 0) { for ($i = 0; $i < $fsCount; $i++) { $xml .= "<FiniteDisplayScale>"; $xml .= $map->GetFiniteDisplayScaleAt($i); $xml .= "</FiniteDisplayScale>"; } } $xml .= "</RuntimeMap>"; $bs = new MgByteSource($xml, strlen($xml)); $bs->SetMimeType(MgMimeType::Xml); $br = $bs->GetReader(); return $br; }
echo ""; return; } } $fixedupHtml = FixupPageReferences($orgHtml, $webLayout, $dwf, GetRootVirtualFolder() . "/", $locale); if ($pageName == $cmdListPage) { //filter out unused commands // InitializeWebTier(); $cred = new MgUserInformation($sessionId); $cred->SetClientIp(GetClientIp()); $cred->SetClientAgent(GetClientAgent()); $site = new MgSiteConnection(); $site->Open($cred); $wli = new MgResourceIdentifier($webLayout); $src = new MgByteSource($fixedupHtml, strlen($fixedupHtml)); $resourceSrvc = $site->CreateService(MgServiceType::ResourceService); $wl = new MgWebLayout($resourceSrvc, $wli); $pagestream = $wl->ProcessGettingStartedPage($src->GetReader(), $dwf); if ($pagestream == null) { echo $fixedupHtml; } else { echo $pagestream->ToString(); } } else { echo $fixedupHtml; } } catch (MgException $e) { $errorMsg = EscapeForHtml($e->GetDetails()); echo $errorMsg; return;
function UploadMarkup() { $locale = "en"; if (array_key_exists("LOCALE", $this->args)) { $locale = $this->args["LOCALE"]; } $uploadFileParts = pathinfo($_FILES["UPLOADFILE"]["name"]); $fdoProvider = $this->GetProviderFromExtension($uploadFileParts["extension"]); if ($fdoProvider == null) { throw new Exception(GetLocalizedString("REDLINEUPLOADUNKNOWNPROVIDER", $locale)); } $resourceService = $this->site->CreateService(MgServiceType::ResourceService); $featureService = $this->site->CreateService(MgServiceType::FeatureService); $bs = new MgByteSource($_FILES["UPLOADFILE"]["tmp_name"]); $br = $bs->GetReader(); //Use file name to drive all parameters $baseName = $uploadFileParts["filename"]; $this->UniqueMarkupName($baseName); //Guard against potential duplicates $ext = $uploadFileParts["extension"]; $markupLayerResId = new MgResourceIdentifier($this->GetResourceIdPrefix() . $baseName . ".LayerDefinition"); $markupFsId = new MgResourceIdentifier($this->GetResourceIdPrefix() . $baseName . '.FeatureSource'); //Set up feature source document $dataName = $baseName . "." . $ext; $fileParam = "File"; $shpFileParts = array(); if (strcmp($fdoProvider, "OSGeo.SHP") == 0) { $dataName = null; $fileParam = "DefaultFileLocation"; $zip = new ZipArchive(); if ($zip->open($_FILES["UPLOADFILE"]["tmp_name"]) === TRUE) { for ($i = 0; $i < $zip->numFiles; $i++) { $stat = $zip->statIndex($i); $filePath = tempnam(sys_get_temp_dir(), "upload"); //Dump to temp file file_put_contents($filePath, $zip->getFromIndex($i)); //Stash for later upload and cleanup $entry = $stat["name"]; $shpFileParts[$entry] = $filePath; if (substr($entry, strlen($entry) - strlen(".shp")) == ".shp") { $dataName = $entry; } } //Abort if we can't find a .shp file. This is not a valid zip file if ($dataName == null) { throw new Exception(GetLocalizedString("REDLINEUPLOADSHPZIPERROR", $locale)); } } else { throw new Exception(GetLocalizedString("REDLINEUPLOADSHPZIPERROR", $locale)); } } $extraXml = ""; if (strcmp($fdoProvider, "OSGeo.SDF") == 0) { //Need to set ReadOnly = false for SDF $extraXml = "<Parameter><Name>ReadOnly</Name><Value>FALSE</Value></Parameter>"; } $fsXml = sprintf(file_get_contents("templates/markupfeaturesource.xml"), $fdoProvider, $fileParam, $dataName, $extraXml); $bs2 = new MgByteSource($fsXml, strlen($fsXml)); $resourceService->SetResource($markupFsId, $bs2->GetReader(), null); if (count($shpFileParts) > 0) { foreach ($shpFileParts as $name => $path) { $bs3 = new MgByteSource($path); $resourceService->SetResourceData($markupFsId, $name, "File", $bs3->GetReader()); //Cleanup unlink($path); } } else { //Not a SHP file $resourceService->SetResourceData($markupFsId, $dataName, "File", $bs->GetReader()); } //Query the geometry types $schemas = $featureService->DescribeSchema($markupFsId, "", null); $schema = $schemas->GetItem(0); $classes = $schema->GetClasses(); $klass = $classes->GetItem(0); $geomProp = $klass->GetDefaultGeometryPropertyName(); $clsProps = $klass->GetProperties(); $className = $schema->GetName() . ":" . $klass->GetName(); $geomTypes = -1; if ($clsProps->IndexOf($geomProp) >= 0) { $geom = $clsProps->GetItem($geomProp); $geomTypes = $geom->GetGeometryTypes(); //Since we're here. Validate the schema requirements. If this was created by this widget previously //it will be valid $idProps = $klass->GetIdentityProperties(); if ($idProps->GetCount() != 1) { throw new Exception(GetLocalizedString("REDLINEUPLOADINVALIDSCHEMA", $locale)); } else { //Must be auto-generated (implying numerical as well) $keyProp = $idProps->GetItem(0); if (!$keyProp->IsAutoGenerated()) { throw new Exception(GetLocalizedString("REDLINEUPLOADINVALIDSCHEMA", $locale)); } } if ($clsProps->IndexOf("Text") < 0) { throw new Exception(GetLocalizedString("REDLINEUPLOADINVALIDSCHEMA", $locale)); } } else { throw new Exception(GetLocalizedString("REDLINEUPLOADINVALIDSCHEMA", $locale)); } //Set up default style args $this->args["MARKUPNAME"] = $baseName; $this->args["MARKERCOLOR"] = DefaultStyle::MARKER_COLOR; $this->args["MARKERTYPE"] = DefaultStyle::MARKER_TYPE; $this->args["MARKERSIZEUNITS"] = DefaultStyle::MARKER_SIZE_UNITS; $this->args["MARKERSIZE"] = DefaultStyle::MARKER_SIZE; $this->args["LINECOLOR"] = DefaultStyle::LINE_COLOR; $this->args["LINEPATTERN"] = DefaultStyle::LINE_PATTERN; $this->args["LINESIZEUNITS"] = DefaultStyle::LINE_SIZE_UNITS; $this->args["LINETHICKNESS"] = DefaultStyle::LINE_THICKNESS; $this->args["FILLPATTERN"] = DefaultStyle::FILL_PATTERN; $this->args["FILLTRANSPARENCY"] = DefaultStyle::FILL_TRANSPARENCY; $this->args["FILLFORECOLOR"] = DefaultStyle::FILL_FORE_COLOR; $this->args["FILLBACKCOLOR"] = DefaultStyle::FILL_BACK_COLOR; $this->args["FILLBACKTRANS"] = DefaultStyle::FILL_BACK_TRANS; $this->args["BORDERPATTERN"] = DefaultStyle::BORDER_PATTERN; $this->args["BORDERSIZEUNITS"] = DefaultStyle::BORDER_SIZE_UNITS; $this->args["BORDERCOLOR"] = DefaultStyle::BORDER_COLOR; $this->args["BORDERTHICKNESS"] = DefaultStyle::BORDER_THICKNESS; $this->args["LABELSIZEUNITS"] = DefaultStyle::LABEL_SIZE_UNITS; $this->args["LABELFONTSIZE"] = DefaultStyle::LABEL_FONT_SIZE; //Omission is considered false, which is the default. If you ever change //the default style values, uncomment the matching "true" values //$this->args["LABELBOLD"] = DefaultStyle::LABEL_BOLD; //$this->args["LABELITALIC"] = DefaultStyle::LABEL_ITALIC; //$this->args["LABELUNDERLINE"] = DefaultStyle::LABEL_UNDERLINE; $this->args["LABELFORECOLOR"] = DefaultStyle::LABEL_FORE_COLOR; $this->args["LABELBACKCOLOR"] = DefaultStyle::LABEL_BACK_COLOR; $this->args["LABELBACKSTYLE"] = DefaultStyle::LABEL_BACK_STYLE; $markupLayerDefinition = $this->CreateMarkupLayerDefinitionContent($markupFsId->ToString(), $className); $layerBs = new MgByteSource($markupLayerDefinition, strlen($markupLayerDefinition)); //Save to new resource or overwrite existing $resourceService->SetResource($markupLayerResId, $layerBs->GetReader(), null); //Add to markup registry $cmds = new MgFeatureCommandCollection(); $props = new MgPropertyCollection(); $props->Add(new MgStringProperty("ResourceId", $markupFsId->ToString())); $props->Add(new MgStringProperty("LayerDefinition", $markupLayerResId->ToString())); $props->Add(new MgStringProperty("Name", $markupLayerResId->GetName())); $props->Add(new MgStringProperty("FdoProvider", $fdoProvider)); $props->Add(new MgInt32Property("GeometryTypes", $geomTypes)); $insertCmd = new MgInsertFeatures("Default:MarkupRegistry", $props); $cmds->Add($insertCmd); $res = $featureService->UpdateFeatures($this->markupRegistryId, $cmds, false); MarkupManager::CleanupReaders($res); //Add to map $this->args["MARKUPLAYER"] = $markupLayerResId->ToString(); $this->OpenMarkup(); }
*/ /* //Point Rules $markSymbol = LayerDefinitionFactory::CreateMarkSymbol("", "", 5, 5, "FF800000"); $textSymbol = LayerDefinitionFactory::CreateTextSymbol("", "10", "FF808000"); $pointRule = LayerDefinitionFactory::CreatePointRule("TestPoint", "", $textSymbol, $markSymbol); $pointStyle = LayerDefinitionFactory::CreatePointTypeStyle($pointRule); $scaleRange = LayerDefinitionFactory::CreateScaleRange('0', '1000000000000', $pointStyle); */ //Create layer definition $layerDef = LayerDefinitionFactory::CreateLayerDefinition('Library://NewParcels.LayerDefinition', 'Parcels', 'SHPGEOM', $scaleRange); //Uncomment to check out the generated xml //file_put_contents('test.xml',$layerDef); $byteSource = new MgByteSource($layerDef, strlen($layerDef)); $byteReader = $byteSource->GetReader(); $cred = new MgUserInformation(); $cred->SetMgUsernamePassword('Anonymous', ''); $cred->SetClientIp(GetClientIp()); $cred->SetClientAgent(GetClientAgent()); $siteConn = new MgSiteConnection(); $siteConn->Open($cred); $svc = $siteConn->CreateService(MgServiceType::ResourceService); $resId = new MgResourceIdentifier('Library://Test/NewLayer.LayerDefinition'); try { $svc->SetResource($resId, $byteReader, null); } catch (MgException $e) { $errorMsg = EscapeForHtml($e->GetExceptionMessage()); echo $errorMsg; }
public function SetResourceContentOrHeader($resId, $format) { //Check for unsupported representations $fmt = $this->ValidateRepresentation($format, array("xml", "json")); try { $sessionId = ""; if ($resId->GetRepositoryType() == MgRepositoryType::Session) { $sessionId = $resId->GetRepositoryName(); } $this->EnsureAuthenticationForSite($sessionId); $siteConn = new MgSiteConnection(); $siteConn->Open($this->userInfo); $contentFilePath = $this->GetFileUploadPath("content"); $headerFilePath = null; //Header not supported for session-based resources if ($resId->GetRepositoryType() != MgRepositoryType::Session) { $headerFilePath = $this->GetFileUploadPath("header"); } $resSvc = $siteConn->CreateService(MgServiceType::ResourceService); $site = $siteConn->GetSite(); $resIdStr = $resId->ToString(); $mimeType = $this->GetMimeTypeForFormat($fmt); if ($contentFilePath) { $this->VerifyWhitelist($resIdStr, $mimeType, "SETRESOURCE", $fmt, $site, $this->userName); } if ($headerFilePath) { $this->VerifyWhitelist($resIdStr, $mimeType, "SETRESOURCEHEADER", $fmt, $site, $this->userName); } $content = null; $header = null; if ($contentFilePath != null) { $cntSource = new MgByteSource($contentFilePath); $content = $cntSource->GetReader(); } if ($headerFilePath != null) { $hdrSource = new MgByteSource($headerFilePath); $header = $hdrSource->GetReader(); } if ($fmt == "json") { if ($content != null) { $body = $content->ToString(); $json = json_decode($body); if ($json == NULL) { throw new Exception($this->app->localizer->getText("E_MALFORMED_JSON_BODY")); } $body = MgUtils::Json2Xml($json); $cntSource = new MgByteSource($body, strlen($body)); $content = $cntSource->GetReader(); } if ($header != null) { $body = $header->ToString(); $json = json_decode($body); if ($json == NULL) { throw new Exception($this->app->localizer->getText("E_MALFORMED_JSON_BODY")); } $body = MgUtils::Json2Xml($json); $hdrSource = new MgByteSource($body, strlen($body)); $header = $hdrSource->GetReader(); } } $resSvc->SetResource($resId, $content, $header); $this->app->response->setStatus(201); $body = MgBoxedValue::String($resId->ToString(), $fmt); if ($fmt == "xml") { $this->app->response->header("Content-Type", MgMimeType::Xml); } else { $this->app->response->header("Content-Type", MgMimeType::Json); } $this->app->response->setBody($body); } catch (MgException $ex) { $this->OnException($ex); } }
function CreateParcelMarkerLayer($resourceService, $parcelMarkerDataResId, $sessionId) { // Load the ParcelMarker layer definition template into // a PHP DOM object, find the "ResourceId" element, and // modify its content to reference the temporary // feature source. $doc = DOMDocument::load('parcelmarker.xml'); $featureSourceNode = $doc->getElementsByTagName('ResourceId')->item(0); $featureSourceNode->nodeValue = $parcelMarkerDataResId->ToString(); // Get the updated layer definition from the DOM object // and save it to the session repository using the // ResourceService object. $layerDefinition = $doc->saveXML(); $byteSource = new MgByteSource($layerDefinition, strlen($layerDefinition)); $byteSource->SetMimeType(MgMimeType::Xml); $tempLayerResId = new MgResourceIdentifier("Session:" . $sessionId . "//ParcelMarker.LayerDefinition"); $resourceService->SetResource($tempLayerResId, $byteSource->GetReader(), null); // Create an MgLayer object based on the new layer definition // and return it to the caller. $parcelMarkerLayer = new MgLayer($tempLayerResId, $resourceService); $parcelMarkerLayer->SetName("ParcelMarker"); $parcelMarkerLayer->SetLegendLabel("ParcelMarker"); $parcelMarkerLayer->SetDisplayInLegend(true); $parcelMarkerLayer->SetSelectable(false); return $parcelMarkerLayer; }
public function SelectAggregates($resId, $schemaName, $className, $type, $format) { //Check for unsupported representations $fmt = $this->ValidateRepresentation($format, array("xml", "json")); $mimeType = $this->GetMimeTypeForFormat($fmt); try { $aggType = $this->ValidateValueInDomain($type, array("count", "bbox", "distinctvalues"), $this->GetMimeTypeForFormat($format)); $distinctPropName = $this->GetRequestParameter("property", ""); if ($aggType === "distinctvalues" && $distinctPropName === "") { $this->BadRequest($this->app->localizer->getText("E_MISSING_REQUIRED_PARAMETER", "property"), $this->GetMimeTypeForFormat($format)); } $sessionId = ""; if ($resId->GetRepositoryType() == MgRepositoryType::Session) { $sessionId = $resId->GetRepositoryName(); } $this->EnsureAuthenticationForSite($sessionId, true, $mimeType); $siteConn = new MgSiteConnection(); $siteConn->Open($this->userInfo); $site = $siteConn->GetSite(); $this->VerifyWhitelist($resId->ToString(), $mimeType, "SELECTAGGREGATES", $fmt, $site, $this->userName); $resSvc = $siteConn->CreateService(MgServiceType::ResourceService); $featSvc = $siteConn->CreateService(MgServiceType::FeatureService); $query = new MgFeatureAggregateOptions(); $capsXml = MgUtils::GetProviderCapabilties($featSvc, $resSvc, $resId); $supportsDistinct = !(strstr($capsXml, "<SupportsSelectDistinct>true</SupportsSelectDistinct>") === false); $supportsCount = !(strstr($capsXml, "<Name>Count</Name>") === false); $supportsSpatialExtents = !(strstr($capsXml, "<Name>SpatialExtents</Name>") === false); switch ($type) { case "count": $count = MgUtils::GetFeatureCount($featSvc, $resId, $schemaName, $className, $supportsCount); $output = "<?xml version=\"1.0\" encoding=\"utf-8\"?><AggregateResult>"; $output .= "<Type>count</Type>"; $output .= "<Total>{$count}</Total>"; $output .= "</AggregateResult>"; $bs = new MgByteSource($output, strlen($output)); $bs->SetMimeType(MgMimeType::Xml); $br = $bs->GetReader(); if ($fmt === "json") { $this->OutputXmlByteReaderAsJson($br); } else { $this->OutputByteReader($br); } break; case "bbox": $geomName = $this->app->request->get("property"); $txTo = $this->app->request->get("transformto"); $bounds = MgUtils::GetFeatureClassMBR($this->app, $featSvc, $resId, $schemaName, $className, $geomName, $txTo); $iterator = $bounds->extentGeometry->GetCoordinates(); $csCode = $bounds->csCode; $csWkt = $bounds->coordinateSystem; $epsg = $bounds->epsg; $firstTime = true; $minX = null; $minY = null; $maxX = null; $maxY = null; while ($iterator->MoveNext()) { $x = $iterator->GetCurrent()->GetX(); $y = $iterator->GetCurrent()->GetY(); if ($firstTime) { $maxX = $x; $minX = $x; $maxY = $y; $minY = $y; $firstTime = false; } if ($maxX < $x) { $maxX = $x; } if ($minX > $x || $minX == 0) { $minX = $x; } if ($maxY < $y) { $maxY = $y; } if ($minY > $y || $minY == 0) { $minY = $y; } } $output = "<?xml version=\"1.0\" encoding=\"utf-8\"?><AggregateResult>"; $output .= "<Type>bbox</Type>"; $output .= "<BoundingBox>"; $output .= "<CoordinateSystem>"; $output .= "<Code>{$csCode}</Code><EPSG>{$epsg}</EPSG>"; $output .= "</CoordinateSystem>"; $output .= "<LowerLeft><X>{$minX}</X><Y>{$minY}</Y></LowerLeft>"; $output .= "<UpperRight><X>{$maxX}</X><Y>{$maxY}</Y></UpperRight>"; $output .= "</BoundingBox>"; $output .= "</AggregateResult>"; $bs = new MgByteSource($output, strlen($output)); $bs->SetMimeType(MgMimeType::Xml); $br = $bs->GetReader(); if ($fmt === "json") { $this->OutputXmlByteReaderAsJson($br); } else { $this->OutputByteReader($br); } break; case "distinctvalues": $values = MgUtils::GetDistinctValues($featSvc, $resId, $schemaName, $className, $distinctPropName); $output = "<?xml version=\"1.0\" encoding=\"utf-8\"?><AggregateResult>"; $output .= "<Type>distinctvalues</Type>"; $output .= "<ValueList>"; foreach ($values as $val) { $output .= "<Value>" . MgUtils::EscapeXmlChars($val) . "</Value>"; } $output .= "</ValueList>"; $output .= "</AggregateResult>"; $bs = new MgByteSource($output, strlen($output)); $bs->SetMimeType(MgMimeType::Xml); $br = $bs->GetReader(); if ($fmt === "json") { $this->OutputXmlByteReaderAsJson($br); } else { $this->OutputByteReader($br); } break; } } catch (MgException $ex) { $this->OnException($ex, $mimeType); } }
} } // Create a map definition $mapfactory = new MapDefinitionFactory(); $mapDefinition = CreateMapDef($mapfactory, $className, $resName, $mbr->coordinateSystem, $minX, $maxX, $minY, $maxY); // Save the map definition to a resource stored in the session repository $byteSource = new MgByteSource($mapDefinition, strlen($mapDefinition)); $byteSource->SetMimeType(MgMimeType::Xml); $resName = 'Session:' . $sessionId . '//' . $className . '.MapDefinition'; $resId = new MgResourceIdentifier($resName); $resourceSrvc->SetResource($resId, $byteSource->GetReader(), null); // Create a web layout $webfactory = new WebLayoutFactory(); $webLayout = CreateWebLay($webfactory, $resName, $useBasicViewer); // Save the web layout to a resource stored in the session repository $byteSource = new MgByteSource($webLayout, strlen($webLayout)); $byteSource->SetMimeType(MgMimeType::Xml); if ($useBasicViewer) { $resName = 'Session:' . $sessionId . '//' . $className . '.WebLayout'; $viewerRequest = '../mapviewerajax/?SESSION=' . $sessionId . '&WEBLAYOUT=' . $resName; } else { $resName = 'Session:' . $sessionId . '//' . $className . '.ApplicationDefinition'; $viewerRequest = '../fusion/templates/mapguide/preview/indexNoLegend.html?SESSION=' . $sessionId . '&APPLICATIONDEFINITION=' . $resName; } $resId = new MgResourceIdentifier($resName); $resourceSrvc->SetResource($resId, $byteSource->GetReader(), null); } catch (MgSessionExpiredException $s) { $validSession = 0; echo ErrorMessages::SessionExpired; } catch (MgException $mge) { $validSession = 0;
function ShowSpatialFilter() { $result = true; $sdfResId = new MgResourceIdentifier('Session:' . $this->args['SESSION'] . '//Filter.FeatureSource'); $resourceService = $this->site->CreateService(MgServiceType::ResourceService); $featureService = $this->site->CreateService(MgServiceType::FeatureService); $updateCommands = new MgFeatureCommandCollection(); $map = new MgMap(); $map->Open($resourceService, $this->args['MAPNAME']); $layer = null; $layers = $map->GetLayers(); if ($layers->Contains('_QuerySpatialFilter')) { $layer = $layers->GetItem('_QuerySpatialFilter'); $updateCommands->Add(new MgDeleteFeatures('Filter', "ID like '%'")); } else { // Create the Feature Source (SDF) $sdfSchema = $this->CreateFilterSchema(); $sdfParams = new MgCreateSdfParams('MAPCS', $map->GetMapSRS(), $sdfSchema); $featureService->CreateFeatureSource($sdfResId, $sdfParams); // Create the Layer $layerResId = new MgResourceIdentifier('Session:' . $this->args['SESSION'] . '//Filter.LayerDefinition'); $layerDefinition = file_get_contents("templates/filterlayerdefinition.xml"); $layerDefinition = sprintf($layerDefinition, $sdfResId->ToString()); $byteSource = new MgByteSource($layerDefinition, strlen($layerDefinition)); $resourceService->SetResource($layerResId, $byteSource->GetReader(), null); $layer = new MgLayer($layerResId, $resourceService); $layer->SetName('_QuerySpatialFilter'); $layer->SetLegendLabel('_QuerySpatialFilter'); $layer->SetDisplayInLegend(false); $layer->SetSelectable(false); $layers->Insert(0, $layer); } // Make the layer visible $layer->SetVisible(true); $map->Save($resourceService); // Add the geometry to the filter feature source $polygon = $this->CreatePolygonFromGeomText($this->args['GEOMTEXT']); $agfWriter = new MgAgfReaderWriter(); $byteReader = $agfWriter->Write($polygon); $propertyValues = new MgPropertyCollection(); $propertyValues->Add(new MgGeometryProperty('Geometry', $byteReader)); $updateCommands->Add(new MgInsertFeatures('Filter', $propertyValues)); $featureService->UpdateFeatures($sdfResId, $updateCommands, false); return $result; }
function AddUser($username, $password, $email) { try { $user = new MgUserInformation(MG_ADMIN_USER, MG_ADMIN_PASSWD); $siteConnection = new MgSiteConnection(); $siteConnection->Open($user); $site = $siteConnection->GetSite(); $username = trim($username); $fullname = $username; $site->AddUser($username, $username, $password, $fullname); //set author role $usersToGrant = new MgStringCollection(); $roleToUpdate = new MgStringCollection(); $roleToUpdate->Add(MgRole::Author); $usersToGrant->Add($username); $site->GrantRoleMembershipsToUsers($roleToUpdate, $usersToGrant); // Create user directory in repository: // Create Header $headerContent = $this->GetUserFolderHeader($username); $header_byteSource = new MgByteSource($headerContent, strlen($headerContent)); $header_byteSource->setMimeType("text/xml"); $header_byteReader = $header_byteSource->GetReader(); $resourceService = $siteConnection->CreateService(MgServiceType::ResourceService); // Create Folder $id = new MgResourceIdentifier(MG_USER_DIRECTORY_ROOT . $username . '/'); $resourceService->SetResource($id, NULL, $header_byteReader); $encryptedPassword = crypt($password, SALT); $success = $this->db->queryExec('INSERT INTO users (username, password, disabled, email) VALUES ("' . $username . '", "' . $encryptedPassword . '", 0, "' . $email . '" );'); if ($success) { $userId = $this->db->lastInsertRowid(); //setup default prefs foreach ($this->aszInitialPrefs as $key => $value) { $result = $this->db->SingleQuery('SELECT prefid FROM prefs WHERE name="' . $key . '";'); if ($result) { $prefid = $result; } //TODO: improve efficiency by combining queries $this->AddUserPref($userId, $prefid, $value); } return $this->GetUser($userId); } else { echo "<Error>Failed to insert user</Error>"; return FALSE; } } catch (MgDuplicateUserException $du_e) { echo '<Error>Duplicate user!</Error>'; return FALSE; } catch (MgException $e) { echo "<Error>" . $e->GetMessage() . "\n"; echo $e->GetDetails() . "\n"; echo $e->GetStackTrace() . "</Error>\n"; return FALSE; } }
$siteConn->Open($userInfo); $resourceSrvc = $siteConn->CreateService(MgServiceType::ResourceService); $webLayoutName = "Session:" . $adminSession . "//" . "Map" . rand() . "." . MgResourceType::WebLayout; $webLayOutId = new MgResourceIdentifier($webLayoutName); // get contents of a file into a string try { //under Liunx, we should use '/' instead of '\\' $filename = "profilingmapxml/MapViewerTemplate.xml"; $handle = fopen($filename, "r"); $contents = fread($handle, filesize($filename)); fclose($handle); } catch (Exception $e) { echo $e->getMessage(); } $contents = str_replace("{0}", $mapDefiniton, $contents); $content_byteSource = new MgByteSource($contents, strlen($contents)); $content_byteSource->setMimeType("text/xml"); $content_byteReader = $content_byteSource->GetReader(); $resourceSrvc->SetResource($webLayOutId, $content_byteReader, null); //pass the seesion ID with the url, so when the map viewer is opened, there is no need to re-enter the password $ajaxViewerFolder = "mapviewerajax/?"; //when user installed the ajax java viewer, the apache will add a redict //from mapviewerajax to mapviewerjava, and change the relative path to absolute path //which casues the cross-domain problem //now we check if we install the ajax java, then use the "mapviewerjava/ajaxviewer.jsp?" directly to avoid this problem $os = DIRECTORY_SEPARATOR == '\\' ? "winNT" : "linux"; //under the linux system, the mapviewerjava is always installed, so if someone is running apache + java on linux, //the admin should manually change the line 51 as: //if(file_exists("../mapviewerjava/ajaxviewer.jsp")) if ("winNT" == $os && file_exists("../mapviewerjava/ajaxviewer.jsp")) { $ajaxViewerFolder = "mapviewerjava/ajaxviewer.jsp?";
function BuildLayerDefinitionContent() { global $dataSource, $featureName, $ffcolor, $fbcolor, $transparent, $linestyle, $thickness, $lcolor, $fillstyle, $foretrans; $xtrans = sprintf("%02x", 255 * $foretrans / 100); $layerTempl = file_get_contents("../viewerfiles/arealayerdef.templ"); $xmlStr = sprintf($layerTempl, $dataSource, $featureName, "GEOM", $fillstyle, $xtrans . $ffcolor, $transparent ? "00" . $fbcolor : "ff" . $fbcolor, $linestyle, $thickness, $lcolor); $src = new MgByteSource($xmlStr, strlen($xmlStr)); return $src->GetReader(); }