Esempio n. 1
0
 private static function VerifyWhitelistInternal($fsConf, $mimeType, $forbiddenAction, $requiredAction, $requiredRepresentation, $site, $userName)
 {
     $supportedActions = null;
     $supportedRepresentations = null;
     if (!empty($fsConf) && array_key_exists("Actions", $fsConf)) {
         $supportedActions = $fsConf["Actions"];
     }
     if (!empty($fsConf) && array_key_exists("Representations", $fsConf)) {
         $supportedRepresentations = $fsConf["Representations"];
     }
     // If a required features array is passed in, verify against the given configuration, throw on any inconsistencies
     if ($requiredAction != null) {
         if (!empty($supportedActions) && !array_key_exists($requiredAction, $supportedActions)) {
             //But that same key is not present on the declared supported actions
             //print ("\nThis resource is not whitelisted for this API operation ($userName): $requiredAction");
             if ($forbiddenAction != null && is_callable($forbiddenAction)) {
                 call_user_func_array($forbiddenAction, array("This action is not whitelisted", $mimeType));
                 return;
             }
         }
         if (!empty($supportedActions) && array_key_exists($requiredAction, $supportedActions)) {
             $acl = $supportedActions[$requiredAction];
             if (!MgUtils::ValidateAcl($userName, $site, $acl)) {
                 if ($forbiddenAction != null && is_callable($forbiddenAction)) {
                     call_user_func_array($forbiddenAction, array("This this action for this user is not whitelisted", $mimeType));
                     return;
                 }
             }
         }
     }
     // Same for representations
     if ($requiredRepresentation != null) {
         if (!empty($supportedRepresentations) && !array_key_exists($requiredRepresentation, $supportedRepresentations)) {
             //But that same key is not present on the declared supported representations
             //print ("\nThis resource is not whitelisted for this requested representation ($userName): $requiredRepresentation");
             if ($forbiddenAction != null && is_callable($forbiddenAction)) {
                 call_user_func_array($forbiddenAction, array("This representation is not whitelisted", $mimeType));
                 return;
             }
         }
         if (!empty($supportedRepresentations) && array_key_exists($requiredRepresentation, $supportedRepresentations)) {
             $acl = $supportedRepresentations[$requiredRepresentation];
             if (!MgUtils::ValidateAcl($userName, $site, $acl)) {
                 if ($forbiddenAction != null && is_callable($forbiddenAction)) {
                     call_user_func_array($forbiddenAction, array("This representation for this user is not whitelisted", $mimeType));
                     return;
                 }
             }
         }
     }
 }
Esempio n. 2
0
    public function testRoleInAcl()
    {
        $groupXml = '<?xml version="1.0" encoding="UTF-8"?>
<GroupList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="GroupList-1.0.0.xsd">
    <Group>
        <Name>Everyone</Name>
        <Description>Built-in group to include all users</Description>
    </Group>
</GroupList>';
        $br = TestUtils::mockByteReader($this, $groupXml);
        $this->assertEquals("text/xml", $br->GetMimeType());
        $this->assertEquals($groupXml, $br->ToString());
        $site = $this->getMockBuilder("MgSite")->getMock();
        $site->method("EnumerateGroups")->will($this->returnValue($br));
        $roleMethodMap = array(array("Author", new FakeStringCollection(array("Authors"))), array("Anonymous", new FakeStringCollection(array("Users"))));
        $site->method("EnumerateRoles")->will($this->returnValueMap($roleMethodMap));
        $conf1 = array("AllowUsers" => array("Administrator"), "AllowGroups" => array("Foo"), "AllowRoles" => array("Users"));
        $this->assertFalse(MgUtils::ValidateAcl("Author", $site, $conf1));
        $conf2 = array("AllowUsers" => array("Administrator"), "AllowGroups" => array("Foo"), "AllowRoles" => array("Users"));
        $this->assertTrue(MgUtils::ValidateAcl("Anonymous", $site, $conf2));
    }
Esempio n. 3
0
 private static function BoxValue($value, $type, $fmt = "xml")
 {
     $resp = "";
     if ($fmt == "xml") {
         $resp .= '<?xml version="1.0" encoding="utf-8"?>';
         $resp .= "<PrimitiveValue>";
         $resp .= "<Type>{$type}</Type>";
         if ($type == "String") {
             $resp .= "<Value>" . MgUtils::EscapeXmlChars($value) . "</Value>";
         } else {
             $resp .= "<Value>{$value}</Value>";
         }
         $resp .= "</PrimitiveValue>";
     } else {
         //json
         $val = $value;
         if ($type == "String") {
             $val = '"' . MgUtils::EscapeJsonString($val) . '"';
         }
         $resp = '{"PrimitiveValue":{"Type":"' . $type . '","Value":' . $val . '}}';
     }
     return $resp;
 }
Esempio n. 4
0
 protected function WriteOutput($output)
 {
     $this->app->response->header("Content-Type", $this->GetMimeType());
     //Apply download headers
     $downloadFlag = $this->app->request->params("download");
     if ($downloadFlag && ($downloadFlag === "1" || $downloadFlag === "true")) {
         $name = $this->app->request->params("downloadname");
         if (!$name) {
             $name = "download";
         }
         $this->app->response->header("Content-Disposition", "attachment; filename=" . MgUtils::GetFileNameFromMimeType($name, $this->GetMimeType()));
     }
     $this->app->response->write($output);
 }
 public function TransformCoordinates()
 {
     $source = $this->app->request->post("from");
     $target = $this->app->request->post("to");
     $coordList = $this->app->request->post("coords");
     $format = $this->app->request->post("format");
     if ($format == null) {
         $format = "xml";
     }
     $fmt = $this->ValidateRepresentation($format, array("xml", "json"));
     if ($source == null) {
         $this->BadRequest($this->app->localizer->getText("E_MISSING_REQUIRED_PARAMETER", "from"), $this->GetMimeTypeForFormat($format));
     }
     if ($target == null) {
         $this->BadRequest($this->app->localizer->getText("E_MISSING_REQUIRED_PARAMETER", "to"), $this->GetMimeTypeForFormat($format));
     }
     if ($coordList == null) {
         $this->BadRequest($this->app->localizer->getText("E_MISSING_REQUIRED_PARAMETER", "coords"), $this->GetMimeTypeForFormat($format));
     }
     try {
         $factory = new MgCoordinateSystemFactory();
         $sourceCs = $factory->CreateFromCode($source);
         $targetCs = $factory->CreateFromCode($target);
         $trans = $factory->GetTransform($sourceCs, $targetCs);
         $coords = explode(",", $coordList);
         $output = "<?xml version=\"1.0\" encoding=\"utf-8\"?><CoordinateCollection>";
         foreach ($coords as $coordPair) {
             $tokens = explode(" ", trim($coordPair));
             $tokenCount = count($tokens);
             if ($tokenCount === 2) {
                 $txCoord = $trans->Transform(floatval($tokens[0]), floatval($tokens[1]));
                 $output .= "<Coordinate><X>" . $txCoord->GetX() . "</X><Y>" . $txCoord->GetY() . "</Y></Coordinate>";
             } else {
                 //TODO: We should accept a partial response, but there's currently no way an empty <Coordinate/> tag survives the
                 //XML to JSON conversion, so we have to throw lest we return an inconsisten partial result
                 $this->ServerError($this->app->localizer->getText("E_INVALID_COORDINATE_PAIR", $coordPair, $tokenCount), $this->GetMimeTypeForFormat($format));
             }
         }
         $output .= "</CoordinateCollection>";
         if ($fmt === "json") {
             $this->app->response->header("Content-Type", MgMimeType::Json);
             $json = MgUtils::Xml2Json($output);
             $this->app->response->write($json);
         } else {
             $this->app->response->header("Content-Type", MgMimeType::Xml);
             $this->app->response->write($output);
         }
     } catch (MgException $ex) {
         $this->OnException($ex, $this->GetMimeTypeForFormat($format));
     }
 }
Esempio n. 6
0
 public static function FeatureToCzml($reader, $agfRw, $transform, $geometryName, $style, $idName = NULL)
 {
     if (!$reader->IsNull($geometryName)) {
         $agf = null;
         $geom = null;
         try {
             $agf = $reader->GetGeometry($geometryName);
             $geom = $agfRw->Read($agf, $transform);
         } catch (MgException $ex) {
             //Bail on bad geometries
             return "";
         }
         $idIndex = -1;
         if ($idName != NULL) {
             $idIndex = $reader->GetPropertyIndex($idName);
         }
         //Write ID
         $idVal = "";
         if ($idIndex >= 0 && !$reader->IsNull($idIndex)) {
             $propType = $reader->GetPropertyType($idIndex);
             switch ($propType) {
                 case MgPropertyType::DateTime:
                     $dt = $reader->GetDateTime($idIndex);
                     $idVal = '"' . $dt->ToString() . '"';
                     break;
                 case MgPropertyType::Double:
                     $idVal = $reader->GetDouble($idIndex);
                     break;
                 case MgPropertyType::Int16:
                     $idVal = $reader->GetInt16($idIndex);
                     break;
                 case MgPropertyType::Int32:
                     $idVal = $reader->GetInt32($idIndex);
                     break;
                 case MgPropertyType::Int64:
                     $idVal = $reader->GetInt64($idIndex);
                     break;
                 case MgPropertyType::Single:
                     $idVal = $reader->GetSingle($idIndex);
                     break;
                 case MgPropertyType::String:
                     $idVal = MgUtils::EscapeJsonString($reader->GetString($idIndex));
                     break;
             }
         } else {
             $idVal = uniqid();
         }
         $elevIndex = -1;
         $extrude = 0.0;
         try {
             $elevIndex = $reader->GetPropertyIndex(MgRestConstants::PROP_Z_EXTRUSION);
             if ($elevIndex >= 0) {
                 switch ($reader->GetPropertyType($elevIndex)) {
                     case MgPropertyType::Int16:
                         $extrude = $reader->GetInt16($elevIndex);
                         break;
                     case MgPropertyType::Int32:
                         $extrude = $reader->GetInt32($elevIndex);
                         break;
                     case MgPropertyType::Int64:
                         $extrude = $reader->GetInt64($elevIndex);
                         break;
                     case MgPropertyType::Double:
                         $extrude = $reader->GetDouble($elevIndex);
                         break;
                     case MgPropertyType::Single:
                         $extrude = $reader->GetSingle($elevIndex);
                         break;
                 }
             }
             //TODO: If units not in meters, convert it to meters
         } catch (MgException $ex) {
         }
         switch ($geom->GetGeometryType()) {
             case MgGeometryType::Point:
             case MgGeometryType::LineString:
             case MgGeometryType::Polygon:
                 $geomCzml = self::GeometryToCzml($geom, $reader, $style, $extrude);
                 if ($geomCzml == null) {
                     return "";
                 }
                 return self::SingleFeatureToCzml($idVal, $reader, $geomCzml);
             case MgGeometryType::MultiLineString:
                 //For multi-geometry features, we split this off into separate packets, one packet for
                 //each component geometry
                 $parts = array();
                 $featId = uniqid();
                 for ($i = 0; $i < $geom->GetCount(); $i++) {
                     $idValComp = $idVal . "_segment_" . $i . "_" . $featId;
                     $lineStr = $geom->GetLineString($i);
                     $geomCzml = self::GeometryToCzml($lineStr, $reader, $style, $extrude);
                     if ($geomCzml == null) {
                         continue;
                     }
                     array_push($parts, self::SingleFeatureToCzml($idValComp, $reader, $geomCzml));
                 }
                 return implode(",", $parts);
             default:
                 return "";
         }
     } else {
         return "";
     }
 }
Esempio n. 7
0
 private function ValidateAcl($siteConn, $config)
 {
     $site = $siteConn->GetSite();
     if ($this->userName == null && $this->sessionId != null) {
         $this->userName = $site->GetUserForSession();
     }
     return MgUtils::ValidateAcl($this->userName, $site, $config);
 }
Esempio n. 8
0
 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;
     }
 }
 public function EnumerateResources($resId, $format)
 {
     //Check for unsupported representations
     $fmt = $this->ValidateRepresentation($format, array("xml", "json", "html"));
     $resIdStr = $resId->ToString();
     $sessionId = $this->GetRequestParameter("session", "");
     $mimeType = $this->GetMimeTypeForFormat($fmt);
     try {
         $this->EnsureAuthenticationForSite($sessionId, false, $mimeType);
         $siteConn = new MgSiteConnection();
         $siteConn->Open($this->userInfo);
         $site = $siteConn->GetSite();
     } catch (MgException $ex) {
         $this->OnException($ex, $mimeType);
         return;
     }
     $this->VerifyWhitelist($resIdStr, $mimeType, "ENUMERATERESOURCES", $fmt, $site, $this->userName);
     $pathInfo = $this->app->request->getPathInfo();
     $selfUrl = $this->app->config("SelfUrl");
     $that = $this;
     $this->EnsureAuthenticationForHttp(function ($req, $param) use($that, $fmt, $resIdStr, $selfUrl, $pathInfo) {
         $param->AddParameter("OPERATION", "ENUMERATERESOURCES");
         $param->AddParameter("VERSION", "1.0.0");
         $param->AddParameter("TYPE", $that->GetRequestParameter("type"));
         $param->AddParameter("COMPUTECHILDREN", $that->GetBooleanRequestParameter("computechildren", "0"));
         //Default the depth to 1 if not specified (think of the MapGuide Server!)
         $param->AddParameter("DEPTH", $that->GetRequestParameter("depth", "1"));
         if ($fmt === "json") {
             $param->AddParameter("FORMAT", MgMimeType::Json);
         } else {
             if ($fmt === "xml") {
                 $param->AddParameter("FORMAT", MgMimeType::Xml);
             } else {
                 if ($fmt === "html") {
                     $thisUrl = $selfUrl . $pathInfo;
                     //Chop off the list.html
                     $rootPath = substr($thisUrl, 0, strlen($thisUrl) - strlen("list.html"));
                     $folderPath = substr($pathInfo, 0, strlen($pathInfo) - strlen("list.html"));
                     $tokens = explode("/", $pathInfo);
                     if (count($tokens) > 3) {
                         //Pop off list.html and current folder name
                         array_pop($tokens);
                         array_pop($tokens);
                         $parentPath = implode("/", $tokens);
                         $param->AddParameter("XSLPARAM.PARENTPATHROOT", $selfUrl . $parentPath);
                     }
                     $param->AddParameter("XSLPARAM.ASSETPATH", MgUtils::GetSelfUrlRoot($selfUrl) . "/assets");
                     $param->AddParameter("XSLPARAM.FOLDERPATH", $folderPath);
                     $param->AddParameter("XSLPARAM.ROOTPATH", $rootPath);
                     $param->AddParameter("FORMAT", MgMimeType::Xml);
                     $param->AddParameter("X-OVERRIDE-CONTENT-TYPE", MgMimeType::Html);
                     $param->AddParameter("XSLSTYLESHEET", "ResourceList.xsl");
                 }
             }
         }
         $param->AddParameter("RESOURCEID", $resIdStr);
         $that->ExecuteHttpRequest($req);
     }, false, "", $sessionId, $mimeType);
 }
Esempio n. 10
0
    $assetUrlRoot = $app->config("SelfUrl") . "/doc";
    $docTpl = $app->config("AppRootDir") . "/assets/doc/viewer.tpl";
    $smarty = new Smarty();
    $smarty->setCompileDir($app->config("Cache.RootDir") . "/templates_c");
    $smarty->assign("title", $app->localizer->getText("L_PRODUCT_API_REFERENCE", "mapguide-rest"));
    $smarty->assign("docUrl", $docUrl);
    $smarty->assign("docAssetRoot", $assetUrlRoot);
    $output = $smarty->fetch($docTpl);
    $app->response->header("Content-Type", "text/html");
    $app->response->setBody($output);
});
$app->get("/apidoc/:file", function ($file) use($app) {
    if (MgUtils::StringEndsWith($file, ".json")) {
        $file = str_replace(".json", "", $file);
    }
    $prefix = MgUtils::GetApiVersionNamespace($app, "/apidoc");
    if (strlen($prefix) > 0) {
        $path = $app->config("AppRootDir") . "/doc/data/{$prefix}/{$file}.json";
    } else {
        $path = $app->config("AppRootDir") . "/doc/data/{$file}.json";
    }
    $doc = json_decode(file_get_contents($path));
    if (strlen($prefix) > 0) {
        $doc->basePath = $app->config("SelfUrl") . "/{$prefix}";
    } else {
        $doc->basePath = $app->config("SelfUrl");
    }
    $doc->swaggerVersion = SWAGGER_API_VERSION;
    $doc->apiVersion = MG_REST_API_VERSION;
    $app->response->header("Content-Type", "application/json");
    $app->response->setBody(json_encode($doc));
Esempio n. 11
0
 private function OutputXml($schemas)
 {
     $read = 0;
     $agfRw = new MgAgfReaderWriter();
     $wktRw = new MgWktReaderWriter();
     $this->writer->SetHeader("Content-Type", MgMimeType::Xml);
     $this->writer->StartChunking();
     $output = "<?xml version=\"1.0\" encoding=\"utf-8\"?><FeatureSet>";
     if (!$this->IsEmpty($schemas)) {
         $classXml = $this->featSvc->SchemaToXml($schemas);
         $classXml = substr($classXml, strpos($classXml, "<xs:schema"));
         $output .= $classXml;
     }
     $hasMoreFeatures = $this->reader->ReadNext();
     $writeXmlFooter = false;
     if ($hasMoreFeatures) {
         $output .= "<Features>";
         $this->writer->WriteChunk($output);
         $output = "";
         $writeXmlFooter = true;
     }
     $propCount = $this->reader->GetPropertyCount();
     while ($hasMoreFeatures) {
         $read++;
         if ($this->limit > 0 && $read > $this->limit) {
             break;
         }
         $output = "<Feature>";
         for ($i = 0; $i < $propCount; $i++) {
             $name = $this->reader->GetPropertyName($i);
             $propType = $this->reader->GetPropertyType($i);
             $output .= "<Property><Name>{$name}</Name>";
             if (!$this->reader->IsNull($i)) {
                 $output .= "<Value>";
                 switch ($propType) {
                     case MgPropertyType::Boolean:
                         //NOTE: It appears PHP booleans are not string-able
                         $output .= $this->reader->GetBoolean($i) ? "true" : "false";
                         break;
                     case MgPropertyType::Byte:
                         $output .= $this->reader->GetByte($i);
                         break;
                     case MgPropertyType::DateTime:
                         $dt = $this->reader->GetDateTime($i);
                         $output .= $dt->ToString();
                         break;
                     case MgPropertyType::Decimal:
                     case MgPropertyType::Double:
                         $output .= $this->reader->GetDouble($i);
                         break;
                     case MgPropertyType::Geometry:
                         try {
                             $agf = $this->reader->GetGeometry($i);
                             $geom = $this->transform != null ? $agfRw->Read($agf, $this->transform) : $agfRw->Read($agf);
                             $output .= $wktRw->Write($geom);
                         } catch (MgException $ex) {
                         }
                         break;
                     case MgPropertyType::Int16:
                         $output .= $this->reader->GetInt16($i);
                         break;
                     case MgPropertyType::Int32:
                         $output .= $this->reader->GetInt32($i);
                         break;
                     case MgPropertyType::Int64:
                         $output .= $this->reader->GetInt64($i);
                         break;
                     case MgPropertyType::Single:
                         $output .= $this->reader->GetSingle($i);
                         break;
                     case MgPropertyType::String:
                         $output .= MgUtils::EscapeXmlChars($this->reader->GetString($i));
                         break;
                 }
                 $output .= "</Value>";
             }
             $output .= "</Property>";
         }
         $output .= "</Feature>";
         $this->writer->WriteChunk($output);
         $output = "";
         $hasMoreFeatures = $this->reader->ReadNext();
     }
     if ($writeXmlFooter) {
         $output .= "</Features>";
     }
     $output .= "</FeatureSet>";
     $this->writer->WriteChunk($output);
     $this->writer->EndChunking();
     $this->reader->Close();
 }
 private function PutVectorTileXYZ($map, $groupName, $siteConn, $metersPerUnit, $csFactory, $path, $boundsMinx, $boundsMinY, $boundsMaxX, $boundsMaxY, $layerNames)
 {
     $wktRw = new MgWktReaderWriter();
     $agfRw = new MgAgfReaderWriter();
     $resSvc = $siteConn->CreateService(MgServiceType::ResourceService);
     $featSvc = $siteConn->CreateService(MgServiceType::FeatureService);
     $mapCsWkt = $map->GetMapSRS();
     $layers = $map->GetLayers();
     $groups = $map->GetLayerGroups();
     $baseGroup = $groups->GetItem($groupName);
     $layerCount = $layers->GetCount();
     $firstFeature = true;
     $scale = self::GetScaleFromBounds($map, self::XYZ_TILE_WIDTH, self::XYZ_TILE_HEIGHT, $metersPerUnit, $boundsMinx, $boundsMinY, $boundsMaxX, $boundsMaxY);
     $fp = fopen($path, "w");
     fwrite($fp, '{ "type": "FeatureCollection", "features": [');
     for ($i = 0; $i < $layerCount; $i++) {
         $layer = $layers->GetItem($i);
         $parentGroup = $layer->GetGroup();
         if ($parentGroup != null && $parentGroup->GetObjectId() == $baseGroup->GetObjectId()) {
             if (!self::IsLayerVisibleAtScale($layer, $resSvc, $scale)) {
                 continue;
             }
             //If list of layer names specified, skip if this layer is not in that list
             if ($layerNames != null) {
                 $bFound = false;
                 foreach ($layerNames as $layerName) {
                     if ($layer->GetName() == $layerName) {
                         $bFound = true;
                         break;
                     }
                 }
                 if (!$bFound) {
                     continue;
                 }
             }
             $wktPoly = MgUtils::MakeWktPolygon($boundsMinx, $boundsMinY, $boundsMaxX, $boundsMaxY);
             $geom = $wktRw->Read($wktPoly);
             $clsDef = $layer->GetClassDefinition();
             $clsProps = $clsDef->GetProperties();
             $idProps = $clsDef->GetIdentityProperties();
             $idName = NULL;
             if ($idProps->GetCount() == 1) {
                 $idp = $idProps->GetItem(0);
                 $idName = $idp->GetName();
             }
             $fsId = new MgResourceIdentifier($layer->GetFeatureSourceId());
             //Set up forward and inverse transforms. Inverse for transforming map bounding box
             //Forward for transforming source geometries to map space
             $xform = self::GetTransform($featSvc, $fsId, $clsDef, $mapCsWkt, $csFactory);
             $query = new MgFeatureQueryOptions();
             $geomName = $layer->GetFeatureGeometryName();
             if ($xform != null) {
                 $sourceCs = $xform->GetSource();
                 $targetCs = $xform->GetTarget();
                 $invXform = $csFactory->GetTransform($targetCs, $sourceCs);
                 $txgeom = $geom->Transform($invXform);
                 $query->SetSpatialFilter($geomName, $txgeom, MgFeatureSpatialOperations::EnvelopeIntersects);
             } else {
                 $query->SetSpatialFilter($geomName, $geom, MgFeatureSpatialOperations::EnvelopeIntersects);
             }
             for ($p = 0; $p < $clsProps->GetCount(); $p++) {
                 $propDef = $clsProps->GetItem($p);
                 $query->AddFeatureProperty($propDef->GetName());
             }
             //If we're rendering a vector tile for a single layer, we don't need these special attributes
             if ($layerNames == NULL || count($layerNames) > 1) {
                 $query->AddComputedProperty("_displayIndex", $layerCount - $i);
                 $query->AddComputedProperty("_layer", "'" . $layer->GetName() . "'");
                 $query->AddComputedProperty("_selectable", $layer->GetSelectable() ? "true" : "false");
             }
             $reader = $layer->SelectFeatures($query);
             $read = 0;
             while ($reader->ReadNext()) {
                 $read++;
                 if (!$reader->IsNull($geomName)) {
                     if (!$firstFeature) {
                         fwrite($fp, ",");
                     }
                     try {
                         $output = MgGeoJsonWriter::FeatureToGeoJson($reader, $agfRw, $xform, $idName);
                         fwrite($fp, $output);
                         $firstFeature = false;
                     } catch (MgException $ex) {
                     }
                 }
             }
             $reader->Close();
         }
     }
     fwrite($fp, ']}');
     fclose($fp);
     return $path;
 }
Esempio n. 13
0
 static function ApplyCommonLayerProperties($layer, $op, $groups)
 {
     $bChanged = self::ApplyCommonProperties($layer, $op, $groups);
     if (isset($op->SetSelectable)) {
         $ov = $layer->GetSelectable();
         $nv = MgUtils::StringToBool($op->SetSelectable);
         if ($ov != $nv) {
             $layer->SetSelectable($nv);
             $bChanged = true;
         }
     }
     return $bChanged;
 }
 public function GetFeaturesKml($resId, $format = "kml")
 {
     //Check for unsupported representations
     $fmt = $this->ValidateRepresentation($format, array("kml", "kmz"));
     $bbox = $this->GetRequestParameter("bbox", null);
     $dpi = $this->GetRequestParameter("dpi", 96);
     $width = $this->GetRequestParameter("width", null);
     $height = $this->GetRequestParameter("height", null);
     $drawOrder = $this->GetRequestParameter("draworder", null);
     $sessionId = "";
     if ($resId->GetRepositoryType() == MgRepositoryType::Session) {
         $sessionId = $resId->GetRepositoryName();
     } else {
         $sessionId = $this->GetRequestParameter("session", "");
     }
     if ($width == null) {
         $this->BadRequest($this->app->localizer->getText("E_MISSING_REQUIRED_PARAMETER", "width"), $this->GetMimeTypeForFormat($format));
     }
     if ($height == null) {
         $this->BadRequest($this->app->localizer->getText("E_MISSING_REQUIRED_PARAMETER", "height"), $this->GetMimeTypeForFormat($format));
     }
     if ($drawOrder == null) {
         $this->BadRequest($this->app->localizer->getText("E_MISSING_REQUIRED_PARAMETER", "draworder"), $this->GetMimeTypeForFormat($format));
     }
     if ($bbox == null) {
         $this->BadRequest($this->app->localizer->getText("E_MISSING_REQUIRED_PARAMETER", "bbox"), $this->GetMimeTypeForFormat($format));
     }
     //We still need the mapagent URL so that GETFEATURESKML can generate legend icons from
     //within the operation
     $agentUri = MgUtils::GetSelfUrlRoot($this->app->config("SelfUrl")) . "/../mapagent/mapagent.fcgi";
     $that = $this;
     $this->EnsureAuthenticationForHttp(function ($req, $param) use($that, $fmt, $resId, $bbox, $width, $height, $drawOrder, $dpi) {
         $param->AddParameter("OPERATION", "GETFEATURESKML");
         $param->AddParameter("VERSION", "1.0.0");
         $param->AddParameter("LAYERDEFINITION", $resId->ToString());
         $param->AddParameter("BBOX", $bbox);
         $param->AddParameter("WIDTH", $width);
         $param->AddParameter("HEIGHT", $height);
         $param->AddParameter("DRAWORDER", $drawOrder);
         $param->AddParameter("DPI", $dpi);
         $param->AddParameter("FORMAT", strtoupper($fmt));
         $param->AddParameter("X-CHUNK-RESPONSE", "true");
         $that->ExecuteHttpRequest($req);
     }, true, $agentUri, $sessionId);
 }
Esempio n. 15
0
 private function CreateAreaStyle($query, $ruleNode)
 {
     $style = new stdClass();
     $sym2DNodes = $ruleNode->getElementsByTagName("AreaSymbolization2D");
     $sym2DNode = $sym2DNodes->item(0);
     $labelNodes = $ruleNode->getElementsByTagName("Label");
     $fillNodes = $sym2DNode->getElementsByTagName("Fill");
     $strokeNodes = $sym2DNode->getElementsByTagName("Stroke");
     if ($labelNodes->length == 1) {
     }
     if ($fillNodes->length == 1) {
         $colorExpr = $fillNodes->item(0)->getElementsByTagName("ForegroundColor")->item(0)->nodeValue;
         $color = MgUtils::HtmlToRgba($colorExpr);
         if ($color === FALSE) {
             //Does not parse into a color. Assume FDO expression
             $colorAlias = "EXPR_AREA_FILL_COLOR_" . $this->areaStyleNo++;
             $query->AddComputedProperty($colorAlias, $colorExpr);
             $style->fillColor = function ($reader) use($colorAlias) {
                 $colorStr = MgUtils::GetBasicValueFromReader($reader, $colorAlias);
                 return MgUtils::HtmlToRgba($colorStr);
             };
         } else {
             $style->fillColor = function ($reader) use($color) {
                 return $color;
             };
         }
     }
     if ($strokeNodes->length == 1) {
         $style->outline = true;
         $colorExpr = $strokeNodes->item(0)->getElementsByTagName("Color")->item(0)->nodeValue;
         $color = MgUtils::HtmlToRgba($colorExpr);
         if ($color === FALSE) {
             //Does not parse into a color. Assume FDO expression
             $colorAlias = "EXPR_AREA_OUTLINE_COLOR_" . $this->areaStyleNo++;
             $query->AddComputedProperty($colorAlias, $colorExpr);
             $style->outlineColor = function ($reader) use($colorAlias) {
                 $colorStr = MgUtils::GetBasicValueFromReader($reader, $colorAlias);
                 return MgUtils::HtmlToRgba($colorStr);
             };
         } else {
             $style->outlineColor = function ($reader) use($color) {
                 return $color;
             };
         }
     }
     return $style;
 }
 public function GeneratePlot($sessionId, $mapName, $format)
 {
     $fmt = $this->ValidateRepresentation($format, array("dwf", "pdf"));
     $this->EnsureAuthenticationForSite($sessionId);
     $siteConn = new MgSiteConnection();
     $siteConn->Open($this->userInfo);
     $map = new MgMap($siteConn);
     $map->Open($mapName);
     $mappingSvc = $siteConn->CreateService(MgServiceType::MappingService);
     $title = $this->GetRequestParameter("title", "");
     $paperSize = $this->GetRequestParameter("papersize", 'A4');
     $orientation = $this->GetRequestParameter("orientation", 'P');
     $marginLeft = floatval($this->GetRequestParameter("marginleft", 0.5));
     $marginRight = floatval($this->GetRequestParameter("marginright", 0.5));
     $marginTop = floatval($this->GetRequestParameter("margintop", $title == "" ? 0.5 : 1.0));
     $marginBottom = floatval($this->GetRequestParameter("marginbottom", 0.5));
     if ($fmt == "dwf") {
         $size = MgUtils::GetPaperSize($this->app, $paperSize);
         //If landscape, flip the width/height
         $width = $orientation == 'L' ? MgUtils::MMToIn($size[1]) : MgUtils::MMToIn($size[0]);
         $height = $orientation == 'L' ? MgUtils::MMToIn($size[0]) : MgUtils::MMToIn($size[1]);
         $printLayoutStr = $this->GetRequestParameter("printlayout", null);
         $dwfVersion = new MgDwfVersion("6.01", "1.2");
         $plotSpec = new MgPlotSpecification($width, $height, MgPageUnitsType::Inches);
         $plotSpec->SetMargins($marginLeft, $marginTop, $marginRight, $marginBottom);
         $layout = null;
         if ($printLayoutStr != null) {
             $layoutRes = new MgResourceIdentifier($printLayoutStr);
             $layout = new MgLayout($layoutRes, $title, MgPageUnitsType::Inches);
         }
         $br = $mappingSvc->GeneratePlot($map, $plotSpec, $layout, $dwfVersion);
         //Apply download headers
         $downloadFlag = $this->app->request->params("download");
         if ($downloadFlag && ($downloadFlag === "1" || $downloadFlag === "true")) {
             $name = $this->app->request->params("downloadname");
             if (!$name) {
                 $name = "download";
             }
             $name .= ".dwf";
             $this->app->response->header("Content-Disposition", "attachment; filename=" . $name);
         }
         $this->OutputByteReader($br);
     } else {
         //pdf
         $bLayered = $this->app->request->params("layeredpdf");
         if ($bLayered == null) {
             $bLayered = false;
         } else {
             $bLayered = $bLayered == "1" || $bLayered == "true";
         }
         $renderingService = $siteConn->CreateService(MgServiceType::RenderingService);
         $plotter = new MgPdfPlotter($this->app, $renderingService, $map);
         $plotter->SetTitle($title);
         $plotter->SetPaperType($paperSize);
         $plotter->SetOrientation($orientation);
         $plotter->ShowCoordinates(true);
         $plotter->ShowNorthArrow(true);
         $plotter->ShowScaleBar(true);
         $plotter->ShowDisclaimer(true);
         $plotter->SetLayered($bLayered);
         $plotter->SetMargins($marginTop, $marginBottom, $marginLeft, $marginRight);
         $mapCenter = $map->GetViewCenter();
         //Apply download headers
         $downloadFlag = $this->app->request->params("download");
         if ($downloadFlag && ($downloadFlag === "1" || $downloadFlag === "true")) {
             $name = $this->app->request->params("downloadname");
             if (!$name) {
                 $name = "download";
             }
             $name .= ".pdf";
             $plotter->Plot($mapCenter->GetCoordinate(), $map->GetViewScale(), $name);
         } else {
             $plotter->Plot($mapCenter->GetCoordinate(), $map->GetViewScale());
         }
     }
 }
Esempio n. 17
0
 protected function FormatException($type, $errorMessage, $details, $phpTrace, $status = 500, $mimeType = MgMimeType::Html)
 {
     return MgUtils::FormatException($this->app, $type, $errorMessage, $details, $phpTrace, $status, $mimeType);
 }
Esempio n. 18
0
 public function Plot($center = NULL, $scale = NULL, $downloadFileName = NULL)
 {
     $legendWidthPx = 250;
     $legendWidthIn = 0;
     if ($this->showLegend) {
         $legendWidthIn = MgUtils::PxToIn($legendWidthPx, $this->legendDpi);
     }
     // Create new PDF document, the default "PDF_UNIT" value is "mm"
     $this->pdf = new TCPDF($this->orientation, PDF_UNIT, $this->paperType, true, "UTF-8", false);
     $this->font = "dejavusans";
     $this->pdf->AddFont($this->font);
     // Set margins
     $this->pdf->SetMargins(0, 0, 0);
     $this->pdf->SetHeaderMargin(0);
     $this->pdf->SetFooterMargin(0);
     // Prevent adding page automatically
     $this->pdf->SetAutoPageBreak(false);
     // Remove default header/footer
     $this->pdf->setPrintHeader(false);
     $this->pdf->setPrintFooter(false);
     // Set default font size
     $this->pdf->SetFont($this->font, "", 16);
     // Add a page
     $this->pdf->AddPage();
     // The print size determines the size of the PDF, not the size of the map and legend images
     // we want to request back to put into this PDF.
     //
     // What that means is that we should draw the surrounding print elements first (title, scale, disclaimer),
     // then adjust the image request sizes to ensure they (and element drawn on top like coordinates) will fit
     // correctly in the remaining space.
     //
     // Title, scale and disclaimer rendering will all return Metrics objects that will give us the information
     // needed for the size adjustments
     // Draw Title
     $mTitle = $this->DrawTitle();
     $mScale = NULL;
     if ($this->showScaleBar) {
         // Draw Scale
         $mScale = $this->DrawScale($scale);
     }
     // Draw declaration
     if ($this->showDisclaimer && strlen($this->disclaimer) > 0) {
         $offX = $mScale != NULL ? $mScale->x + $mScale->w : 0;
         $mDec = $this->DrawDeclaration($offX, $legendWidthIn);
     } else {
         $mDec = new MgPdfPlotMetrics(0, 0, 0, 0);
     }
     // Adjust width and height of the images we want to request to compensate for surrounding print elements that have been rendered
     // Check the size of the disclaimer and adjust height
     $idealHeight = $this->pdf->getPageHeight() - ($mDec->h - ($mScale != NULL ? $mScale->h : 0)) - $this->margin[0] - $this->margin[1];
     //var_dump($idealHeight);
     //var_dump($printSize);
     //die;
     if ($idealHeight < $this->printSize->height) {
     }
     $this->printSize->height = $idealHeight;
     $idealWidth = $this->pdf->getPageWidth() - $this->margin[2] - $this->margin[3];
     if ($this->showLegend) {
         $idealWidth -= $legendWidthIn;
     }
     if ($idealWidth < $this->printSize->width) {
     }
     $this->printSize->width = $idealWidth;
     $link = "";
     $align = "";
     $resize = false;
     $palign = "";
     $ismask = false;
     $imgmask = false;
     $border = 1;
     $fitbox = false;
     $hidden = false;
     $fitonpage = false;
     // Draw legend if specified
     if ($this->showLegend) {
         $legendfilelocation = $this->RenderLegend(MgUtils::InToPx($legendWidthIn, $this->legendDpi), MgUtils::InToPx($this->printSize->height, $this->legendDpi));
         $this->pdf->Image($legendfilelocation, $this->margin[2], $this->margin[0], $legendWidthIn, $this->printSize->height, MgImageFormats::Png, $link, $align, $resize, $this->dpi, $palign, $ismask, $imgmask, $border, $fitbox, $hidden, $fitonpage);
         @unlink($legendfilelocation);
     }
     if ($this->bLayered) {
         $layerNames = array();
         $tiledGroupNames = array();
         $mapLayers = $this->map->GetLayers();
         $mapGroups = $this->map->GetLayerGroups();
         //Collect all visible layers
         for ($i = $mapLayers->GetCount() - 1; $i >= 0; $i--) {
             $layer = $mapLayers->GetItem($i);
             if ($layer->IsVisible() && $layer->GetLayerType() == MgLayerType::Dynamic) {
                 array_push($layerNames, $layer->GetName());
             }
         }
         for ($i = $mapGroups->GetCount() - 1; $i >= 0; $i--) {
             $group = $mapGroups->GetItem($i);
             if ($group->IsVisible() && $group->GetLayerGroupType() != MgLayerGroupType::Normal) {
                 array_push($tiledGroupNames, $group->GetName());
             }
         }
         $bgColor = new MgColor("FFFFFF00");
         //Turn off all layers and tiled groups first
         for ($i = 0; $i < $mapGroups->GetCount(); $i++) {
             $group = $mapGroups->GetItem($i);
             if ($group->GetLayerGroupType() != MgLayerGroupType::Normal) {
                 $group->SetVisible(false);
             }
         }
         for ($i = 0; $i < $mapLayers->GetCount(); $i++) {
             $layer = $mapLayers->GetItem($i);
             if ($layer->GetLayerType() == MgLayerType::Dynamic) {
                 $layer->SetVisible(false);
             }
         }
         //Plot this map background
         $filelocation = $this->RenderMap(MgUtils::InToPx($this->printSize->width, $this->dpi), MgUtils::InToPx($this->printSize->height, $this->dpi), $center, $scale);
         // Draw Map background
         $this->pdf->Image($filelocation, $this->showLegend ? $this->margin[2] + $legendWidthIn : $this->margin[2], $this->margin[0], $this->printSize->width, $this->printSize->height, MgImageFormats::Png, $link, $align, $resize, $this->dpi, $palign, $ismask, $imgmask, $border, $fitbox, $hidden, $fitonpage);
         @unlink($filelocation);
         $prevLayerName = NULL;
         $prevGroupName = NULL;
         //Plot each tiled group individually
         foreach ($tiledGroupNames as $groupName) {
             if ($prevGroupName != NULL) {
                 $mapGroups->GetItem($prevGroupName)->SetVisible(false);
             }
             $mapGroups->GetItem($groupName)->SetVisible(true);
             $print = true;
             $view = true;
             $lock = false;
             $this->pdf->startLayer($groupName, $print, $view, $lock);
             $filelocation = $this->RenderMap(MgUtils::InToPx($this->printSize->width, $this->dpi), MgUtils::InToPx($this->printSize->height, $this->dpi), $center, $scale, $bgColor);
             // Draw Map
             $this->pdf->Image($filelocation, $this->showLegend ? $this->margin[2] + $legendWidthIn : $this->margin[2], $this->margin[0], $this->printSize->width, $this->printSize->height, MgImageFormats::Png, $link, $align, $resize, $this->dpi, $palign, $ismask, $imgmask, $border, $fitbox, $hidden, $fitonpage);
             @unlink($filelocation);
             $prevGroupName = $groupName;
             $this->pdf->endLayer();
         }
         //Now plot each layer individually
         foreach ($layerNames as $layerName) {
             if ($prevLayerName != NULL) {
                 $mapLayers->GetItem($prevLayerName)->SetVisible(false);
             }
             $mapLayers->GetItem($layerName)->SetVisible(true);
             $print = true;
             $view = true;
             $lock = false;
             $this->pdf->startLayer($layerName, $print, $view, $lock);
             $filelocation = $this->RenderMap(MgUtils::InToPx($this->printSize->width, $this->dpi), MgUtils::InToPx($this->printSize->height, $this->dpi), $center, $scale, $bgColor);
             // Draw Map
             $this->pdf->Image($filelocation, $this->showLegend ? $this->margin[2] + $legendWidthIn : $this->margin[2], $this->margin[0], $this->printSize->width, $this->printSize->height, MgImageFormats::Png, $link, $align, $resize, $this->dpi, $palign, $ismask, $imgmask, $border, $fitbox, $hidden, $fitonpage);
             @unlink($filelocation);
             $prevLayerName = $layerName;
             $this->pdf->endLayer();
         }
     } else {
         $filelocation = $this->RenderMap(MgUtils::InToPx($this->printSize->width, $this->dpi), MgUtils::InToPx($this->printSize->height, $this->dpi), $center, $scale);
         // Draw Map
         $this->pdf->Image($filelocation, $this->showLegend ? $this->margin[2] + $legendWidthIn : $this->margin[2], $this->margin[0], $this->printSize->width, $this->printSize->height, MgImageFormats::Png, $link, $align, $resize, $this->dpi, $palign, $ismask, $imgmask, $border, $fitbox, $hidden, $fitonpage);
         @unlink($filelocation);
     }
     // Draw coordiates if specified
     $mExt = NULL;
     if ($this->showCoordinates) {
         // Draw Extent coordinates
         $mExt = $this->DrawExtentCS($legendWidthIn);
     }
     $this->app->response->header("Content-Type", "application/pdf");
     $mode = 'I';
     $name = 'Map.pdf';
     if (strlen($this->title) > 0) {
         $name = $this->title . '.pdf';
     }
     if ($downloadFileName != NULL) {
         $mode = 'D';
         $name = $downloadFileName;
     }
     // Close and output PDF document
     $this->pdf->Output($name, $mode);
 }
Esempio n. 19
0
 /**
  * Queries the configured feature source and returns a MgReader based on the current GET query parameters and adapter configuration
  */
 protected function CreateQueryOptions($single)
 {
     $query = new MgFeatureQueryOptions();
     $this->EnsureQualifiedClassName();
     $tokens = explode(":", $this->className);
     $clsDef = null;
     $clsDef = $this->featSvc->GetClassDefinition($this->featureSourceId, $tokens[0], $tokens[1]);
     if ($single === true) {
         if ($this->featureId == null) {
             throw new Exception($this->app->localizer->getText("E_NO_FEATURE_ID_SET"));
         }
         $idType = MgPropertyType::String;
         if ($this->featureIdProp == null) {
             $idProps = $clsDef->GetIdentityProperties();
             if ($idProps->GetCount() == 0) {
                 throw new Exception($this->app->localizer->getText("E_CANNOT_QUERY_NO_ID_PROPS", $this->className, $this->featureSourceId->ToString()));
             } else {
                 if ($idProps->GetCount() > 1) {
                     throw new Exception($this->app->localizer->getText("E_CANNOT_QUERY_MULTIPLE_ID_PROPS", $this->className, $this->featureSourceId->ToString()));
                 } else {
                     $idProp = $idProps->GetItem(0);
                     $this->featureIdProp = $idProp->GetName();
                     $idType = $idProp->GetDataType();
                 }
             }
         } else {
             $props = $clsDef->GetProperties();
             $iidx = $props->IndexOf($this->featureIdProp);
             if ($iidx >= 0) {
                 $propDef = $props->GetItem($iidx);
                 if ($propDef->GetPropertyType() != MgFeaturePropertyType::DataProperty) {
                     throw new Exception($this->app->localizer->getText("E_ID_PROP_NOT_DATA", $this->featureIdProp));
                 }
             } else {
                 throw new Exception($this->app->localizer->getText("E_ID_PROP_NOT_FOUND", $this->featureIdProp));
             }
         }
         if ($idType == MgPropertyType::String) {
             $query->SetFilter($this->featureIdProp . " = '" . $this->featureId . "'");
         } else {
             $query->SetFilter($this->featureIdProp . " = " . $this->featureId);
         }
     } else {
         $flt = $this->app->request->get("filter");
         if ($flt != null) {
             $query->SetFilter($flt);
         }
         $bbox = $this->app->request->get("bbox");
         if ($bbox != null) {
             $parts = explode(",", $bbox);
             if (count($parts) == 4) {
                 $wktRw = new MgWktReaderWriter();
                 $geom = $wktRw->Read(MgUtils::MakeWktPolygon($parts[0], $parts[1], $parts[2], $parts[3]));
                 $query->SetSpatialFilter($clsDef->GetDefaultGeometryPropertyName(), $geom, MgFeatureSpatialOperations::EnvelopeIntersects);
             }
         }
     }
     if (isset($this->app->ComputedProperties)) {
         $compProps = $this->app->ComputedProperties;
         foreach ($compProps as $alias => $expression) {
             $this->computedPropertyList[$alias] = $expression;
         }
     }
     $bAppliedComputedProperties = false;
     if (count($this->computedPropertyList) > 0) {
         foreach ($this->computedPropertyList as $alias => $expression) {
             $query->AddComputedProperty($alias, $expression);
             $bAppliedComputedProperties = true;
         }
     }
     //If computed properties were applied, add all properties from the class definition if no
     //explicit property list supplied
     if ($bAppliedComputedProperties && count($this->propertyList) == 0) {
         $clsProps = $clsDef->GetProperties();
         for ($i = 0; $i < $clsProps->GetCount(); $i++) {
             $propDef = $clsProps->GetItem($i);
             $query->AddFeatureProperty($propDef->GetName());
         }
     } else {
         if (count($this->propertyList) > 0) {
             foreach ($this->propertyList as $propName) {
                 $query->AddFeatureProperty($propName);
             }
         }
     }
     $orderby = $this->app->request->get("orderby");
     $orderOptions = $this->app->request->get("orderoption");
     if ($orderby != null) {
         if ($orderOptions == null) {
             $orderOptions = "asc";
         }
         $orderPropNames = explode(",", $orderby);
         //If you have a comma in your property names, it's your own fault :)
         $orderProps = new MgStringCollection();
         foreach ($orderPropNames as $propName) {
             $orderProps->Add($propName);
         }
         $orderOpt = MgOrderingOption::Ascending;
         if (strtolower($orderOptions) === "desc") {
             $orderOpt = MgOrderingOption::Descending;
         }
         $query->SetOrderingFilter($orderProps, $orderOpt);
     }
     return $query;
 }
Esempio n. 20
0
 *        tags={"session"},
 *          @SWG\Parameter(name="session", in="path", required=true, type="string", description="Your MapGuide Session ID"),
 *          @SWG\Parameter(name="resName", in="path", required=true, type="string", description="The feature source name"),
 *          @SWG\Parameter(name="type", in="path", required=true, type="string", description="xml or json", enum={"json", "xml"}),
 *          @SWG\Parameter(name="active", in="query", required=false, type="boolean", description="Return only active long transactions if true, otherwise returns all long transactions"),
 *        @SWG\Response(response=400, description="You supplied a bad request due to one or more missing or invalid parameters"),
 *        @SWG\Response(response=401, description="Session ID or MapGuide credentials not specified"),
 *        @SWG\Response(response=500, description="An error occurred during the operation")
 *     )
 */
$app->get("/session/:sessionId/:resName.FeatureSource/longtransactions.:format", function ($sessionId, $resName, $format) use($app) {
    $count = count($resourcePath);
    if ($count > 0) {
        $resourcePath[$count - 1] = $resourcePath[$count - 1] . ".FeatureSource";
    }
    $resId = MgUtils::ParseLibraryResourceID($resourcePath);
    $ctrl = new MgFeatureServiceController($app);
    $ctrl->GetLongTransactions($resId, $format);
});
/**
 *     @SWG\Get(
 *        path="/session/{session}/{resName}.FeatureSource/schemas",
 *        operationId="GetSchemaNames",
 *        summary="Gets the schema names of a feature source",
 *        tags={"session"},
 *          @SWG\Parameter(name="session", in="path", required=true, type="string", description="Your MapGuide Session ID"),
 *          @SWG\Parameter(name="resName", in="path", required=true, type="string", description="The feature source name"),
 *          @SWG\Parameter(name="type", in="path", required=true, type="string", description="xml or json", enum={"json", "xml"}),
 *        @SWG\Response(response=400, description="You supplied a bad request due to one or more missing or invalid parameters"),
 *        @SWG\Response(response=401, description="Session ID or MapGuide credentials not specified"),
 *        @SWG\Response(response=500, description="An error occurred during the operation")
Esempio n. 21
0
 /**
  * Handles PUT requests for this adapter. Overridable. Does nothing if not overridden.
  */
 public function HandlePut($single)
 {
     $trans = null;
     try {
         $tokens = explode(":", $this->className);
         $schemaName = $tokens[0];
         $className = $tokens[1];
         if ($this->app->REQUEST_BODY_DOCUMENT == null) {
             $doc = new DOMDocument();
             $doc->loadXML($this->app->request->getBody());
         } else {
             $doc = $this->app->REQUEST_BODY_DOCUMENT;
         }
         $commands = new MgFeatureCommandCollection();
         $classDef = $this->featSvc->GetClassDefinition($this->featureSourceId, $schemaName, $className);
         $filter = "";
         //If single-record, infer filter from URI
         if ($single === true) {
             $idProps = $classDef->GetIdentityProperties();
             if ($idProps->GetCount() != 1) {
                 $app->halt(400, $this->app->localizer->getText("E_CANNOT_APPLY_UPDATE_CANNOT_UNIQUELY_IDENTIFY", $this->featureId, $idProps->GetCount()));
             } else {
                 $idProp = $idProps->GetItem(0);
                 if ($idProp->GetDataType() == MgPropertyType::String) {
                     $filter = $idProp->GetName() . " = '" . $this->featureId . "'";
                 } else {
                     $filter = $idProp->GetName() . " = " . $this->featureId;
                 }
             }
         } else {
             //Otherwise, use the filter from the request envelope (if specified)
             $filterNode = $doc->getElementsByTagName("Filter");
             if ($filterNode->length == 1) {
                 $filter = $filterNode->item(0)->nodeValue;
             }
         }
         $classDef = $this->featSvc->GetClassDefinition($this->featureSourceId, $schemaName, $className);
         $props = MgUtils::ParseSingleFeatureDocument($this->app, $classDef, $doc, "UpdateProperties");
         $updateCmd = new MgUpdateFeatures("{$schemaName}:{$className}", $props, $filter);
         $commands->Add($updateCmd);
         if ($this->useTransaction) {
             $trans = $this->featSvc->BeginTransaction($this->featureSourceId);
         }
         //HACK: Due to #2252, we can't call UpdateFeatures() with NULL MgTransaction, so to workaround
         //that we call the original UpdateFeatures() overload with useTransaction = false if we find a
         //NULL MgTransaction
         if ($trans == null) {
             $result = $this->featSvc->UpdateFeatures($this->featureSourceId, $commands, false);
         } else {
             $result = $this->featSvc->UpdateFeatures($this->featureSourceId, $commands, $trans);
         }
         if ($trans != null) {
             $trans->Commit();
         }
         $this->OutputUpdateFeaturesResult($commands, $result, $classDef);
     } catch (MgException $ex) {
         if ($trans != null) {
             $trans->Rollback();
         }
         $this->OnException($ex);
     }
 }
 public function SelectFeatures($resId, $schemaName, $className, $format)
 {
     //Check for unsupported representations
     $fmt = $this->ValidateRepresentation($format, array("xml", "html", "geojson"));
     $mimeType = $this->GetMimeTypeForFormat($fmt);
     try {
         $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, "SELECTFEATURES", $fmt, $site, $this->userName);
         $featSvc = $siteConn->CreateService(MgServiceType::FeatureService);
         $query = new MgFeatureQueryOptions();
         $filter = $this->GetRequestParameter("filter", "");
         $propList = $this->GetRequestParameter("properties", "");
         $orderby = $this->GetRequestParameter("orderby", "");
         $orderOptions = $this->GetRequestParameter("orderoption", "asc");
         $maxFeatures = $this->GetRequestParameter("maxfeatures", "");
         $transformto = $this->GetRequestParameter("transformto", "");
         $bbox = $this->GetRequestParameter("bbox", "");
         $pageSize = $this->GetRequestParameter("pagesize", -1);
         $pageNo = $this->GetRequestParameter("page", -1);
         //Internal debugging flag
         $chunk = $this->GetBooleanRequestParameter("chunk", true);
         if ($pageNo >= 0 && $pageSize === -1) {
             $this->BadRequest($this->app->localizer->getText("E_MISSING_REQUIRED_PARAMETER", "pagesize"), $mimeType);
         }
         if ($filter !== "") {
             $query->SetFilter($filter);
         }
         $limit = -1;
         if ($maxFeatures !== "") {
             $limit = intval($maxFeatures);
         }
         if ($propList !== "") {
             $propNames = explode(",", $propList);
             //If you have a comma in your property names, it's your own fault :)
             foreach ($propNames as $propName) {
                 $query->AddFeatureProperty($propName);
             }
         }
         if ($orderby !== "") {
             $orderPropNames = explode(",", $orderby);
             //If you have a comma in your property names, it's your own fault :)
             $orderProps = new MgStringCollection();
             foreach ($orderPropNames as $propName) {
                 $orderProps->Add($propName);
             }
             $orderOpt = MgOrderingOption::Ascending;
             if (strtolower($orderOptions) === "desc") {
                 $orderOpt = MgOrderingOption::Descending;
             }
             $query->SetOrderingFilter($orderProps, $orderOpt);
         }
         $transform = null;
         if ($transformto !== "") {
             $transform = MgUtils::GetTransform($featSvc, $resId, $schemaName, $className, $transformto);
         }
         if ($bbox !== "") {
             $parts = explode(",", $bbox);
             if (count($parts) == 4) {
                 $wktRw = new MgWktReaderWriter();
                 $geom = $wktRw->Read(MgUtils::MakeWktPolygon($parts[0], $parts[1], $parts[2], $parts[3]));
                 //Transform the bbox if we have the flag indicating so
                 $bboxIsTargetCs = $this->GetBooleanRequestParameter("bboxistargetcs", false);
                 if ($bboxIsTargetCs) {
                     //Because it has been declared the bbox is in target coordiantes, we have to transform that bbox back to the
                     //source, which means we need an inverse transform
                     $invTx = MgUtils::GetTransform($featSvc, $resId, $schemaName, $className, $transformto, true);
                     $geom = $geom->Transform($invTx);
                 }
                 $clsDef = $featSvc->GetClassDefinition($resId, $schemaName, $className);
                 $query->SetSpatialFilter($clsDef->GetDefaultGeometryPropertyName(), $geom, MgFeatureSpatialOperations::EnvelopeIntersects);
             }
         }
         $reader = $featSvc->SelectFeatures($resId, "{$schemaName}:{$className}", $query);
         $owriter = null;
         if ($chunk === "0") {
             $owriter = new MgSlimChunkWriter($this->app);
         } else {
             $owriter = new MgHttpChunkWriter();
         }
         if ($pageSize > 0) {
             if ($pageNo < 1) {
                 $pageNo = 1;
             }
             $pageReader = new MgPaginatedFeatureReader($reader, $pageSize, $pageNo, $limit);
             $result = new MgReaderChunkedResult($featSvc, $pageReader, $limit, $owriter, $this->app->localizer);
         } else {
             $result = new MgReaderChunkedResult($featSvc, $reader, $limit, $owriter, $this->app->localizer);
         }
         $result->CheckAndSetDownloadHeaders($this->app, $format);
         if ($transform != null) {
             $result->SetTransform($transform);
         }
         if ($fmt === "html") {
             $result->SetHtmlParams($this->app);
         }
         $result->Output($format);
     } catch (MgException $ex) {
         $this->OnException($ex, $mimeType);
     }
 }
Esempio n. 23
0
 public static function ParseSingleFeatureXml($app, $classDef, $xml, $featureNodeName = "Feature", $propertyNodeName = "Property")
 {
     $doc = new DOMDocument($xml);
     $doc->loadXML($xml);
     return MgUtils::ParseSingleFeatureDocument($app, $classDef, $doc, $featureNodeName, $propertyNodeName);
 }
Esempio n. 24
0
$config = array_merge($config, $logConfig);
//Pull in the appropriate string bundle
$strings = (require_once dirname(__FILE__) . "/app/res/lang/" . $config["Locale"] . ".php");
$app = new \Slim\Slim($config);
//Override error handler for unhandled exceptions
$app->error(function ($err) use($app) {
    $title = $app->localizer->getText("E_UNHANDLED_EXCEPTION");
    $mimeType = MgMimeType::Html;
    //As part of validating the desired representation, this variable will be set, this will tell us
    //what mime type to shape the response
    if (isset($app->requestedMimeType)) {
        $mimeType = $app->requestedMimeType;
    }
    $details = $app->localizer->getText("E_PHP_EXCEPTION_DETAILS", $err->getMessage(), $err->getFile(), $err->getLine());
    $app->response->header("Content-Type", $mimeType);
    $app->response->setBody(MgUtils::FormatException($app, "UnhandledError", $title, $details, $err->getTraceAsString(), 500, $mimeType));
});
$app->localizer = new Localizer($strings);
//Set server version
$ver = explode(".", SITE_ADMINISTRATOR_VERSION, 4);
$app->MG_VERSION = array(intval($ver[0]), intval($ver[1]), intval($ver[2]), intval($ver[3]));
$app->config("SelfUrl", $app->request->getUrl() . $app->request->getRootUri());
$un = new URL\Normalizer($app->config("SelfUrl") . "/" . $app->config("MapGuide.MapAgentUrl"));
$app->config("MapGuide.MapAgentUrl", $un->normalize());
/*
var_dump($app->localizer->getText("E_METHOD_NOT_SUPPORTED"));
var_dump($app->localizer->getText("E_METHOD_NOT_SUPPORTED", "test"));
var_dump($app->localizer->getText("E_METHOD_NOT_SUPPORTED", 123));
var_dump($app->localizer->getText("I_DONT_EXIST"));
var_dump($app->localizer->getText("I_DONT_EXIST", "test"));
var_dump($app->localizer->getText("I_DONT_EXIST", 123));
Esempio n. 25
0
 public static function FeatureToGeoJson($reader, $agfRw, $transform, $idName = NULL)
 {
     $idVal = NULL;
     $propVals = array();
     $geomJson = "";
     $idIndex = -1;
     if ($idName != NULL) {
         $idIndex = $reader->GetPropertyIndex($idName);
     }
     $propCount = $reader->GetPropertyCount();
     for ($i = 0; $i < $propCount; $i++) {
         $name = $reader->GetPropertyName($i);
         $propType = $reader->GetPropertyType($i);
         if (!$reader->IsNull($i)) {
             if ($idIndex == $i) {
                 switch ($propType) {
                     case MgPropertyType::DateTime:
                         $dt = $reader->GetDateTime($i);
                         $idVal = '"' . $dt->ToString() . '"';
                         break;
                     case MgPropertyType::Double:
                         $idVal = $reader->GetDouble($i);
                         break;
                     case MgPropertyType::Int16:
                         $idVal = $reader->GetInt16($i);
                         break;
                     case MgPropertyType::Int32:
                         $idVal = $reader->GetInt32($i);
                         break;
                     case MgPropertyType::Int64:
                         $idVal = $reader->GetInt64($i);
                         break;
                     case MgPropertyType::Single:
                         $idVal = $reader->GetSingle($i);
                         break;
                     case MgPropertyType::String:
                         $idVal = '"' . MgUtils::EscapeJsonString($reader->GetString($i)) . '"';
                         break;
                 }
             } else {
                 switch ($propType) {
                     case MgPropertyType::Boolean:
                         //NOTE: It appears PHP booleans are not string-able
                         array_push($propVals, '"' . $name . '": ' . ($reader->GetBoolean($i) ? "true" : "false"));
                         break;
                     case MgPropertyType::Byte:
                         array_push($propVals, '"' . $name . '": ' . $reader->GetByte($i));
                         break;
                     case MgPropertyType::DateTime:
                         $dt = $reader->GetDateTime($i);
                         array_push($propVals, '"' . $name . '": "' . $dt->ToString() . '"');
                         break;
                     case MgPropertyType::Decimal:
                     case MgPropertyType::Double:
                         array_push($propVals, '"' . $name . '": ' . $reader->GetDouble($i));
                         break;
                     case MgPropertyType::Geometry:
                         try {
                             $agf = $reader->GetGeometry($i);
                             $geom = $transform != null ? $agfRw->Read($agf, $transform) : $agfRw->Read($agf);
                             $geomJson = self::ToGeoJson($geom);
                         } catch (MgException $ex) {
                             $geomJson = '"geometry": null';
                         }
                         break;
                     case MgPropertyType::Int16:
                         array_push($propVals, '"' . $name . '": ' . $reader->GetInt16($i));
                         break;
                     case MgPropertyType::Int32:
                         array_push($propVals, '"' . $name . '": ' . $reader->GetInt32($i));
                         break;
                     case MgPropertyType::Int64:
                         array_push($propVals, '"' . $name . '": ' . $reader->GetInt64($i));
                         break;
                     case MgPropertyType::Single:
                         array_push($propVals, '"' . $name . '": ' . $reader->GetSingle($i));
                         break;
                     case MgPropertyType::String:
                         array_push($propVals, '"' . $name . '": "' . MgUtils::EscapeJsonString($reader->GetString($i)) . '"');
                         break;
                 }
             }
         } else {
             array_push($propVals, '"' . $name . '": null');
         }
     }
     $output = '{ "type": "Feature", ';
     $idJson = "";
     if ($idVal !== NULL) {
         $idJson = '"id": ' . $idVal . ', ';
         $output .= $idJson;
     }
     if ($geomJson !== "") {
         $output .= $geomJson . ', "properties": {' . implode(",", $propVals) . "} }\n";
     } else {
         $output .= '"properties": {' . implode(",", $propVals) . "} }\n";
     }
     return $output;
 }