Exemple #1
0
function GenerateLegend()
{
    global $sessionID, $mapName, $width, $height, $offsetX, $offsetY, $xPad, $yPad, $iconWidth, $iconHeight, $xIndent, $groupIcon, $fontIndex, $textColor;
    $userInfo = new MgUserInformation($sessionID);
    $siteConnection = new MgSiteConnection();
    $siteConnection->Open($userInfo);
    $resourceService = $siteConnection->CreateService(MgServiceType::ResourceService);
    $mappingService = $siteConnection->CreateService(MgServiceType::MappingService);
    $map = new MgMap();
    $map->Open($resourceService, $mapName);
    $scale = $map->GetViewScale();
    $image = imagecreatetruecolor($width, $height);
    $white = imagecolorallocate($image, 255, 255, 255);
    $textColor = imagecolorallocate($image, 0, 0, 0);
    imagefilledrectangle($image, 0, 0, $width, $height, $white);
    ProcessGroupsForLegend($mappingService, $resourceService, $map, $scale, NULL, $image);
    header("Content-type: image/png");
    imagepng($image);
    //Uncomment to see what PHP-isms get spewed out that may be tripping up rendering
    //Also replace instances of "////print_r" with "//print_r" to insta-uncomment all debugging calls
    /*
    ob_start();
    imagepng($image);
    $im = base64_encode(ob_get_contents());
    ob_end_clean();
    header("Content-type: text/html", true);
    echo "<img src='data:image/png;base64,".$im."' alt='legend image'></img>";
    */
    imagecolordeallocate($image, $white);
    imagecolordeallocate($image, $textColor);
    imagedestroy($image);
}
Exemple #2
0
function GenerateMap($size)
{
    global $sessionID, $mapName, $captureBox, $printSize, $normalizedCapture, $rotation, $scaleDenominator, $printDpi, $drawNorthArrow;
    $userInfo = new MgUserInformation($sessionID);
    $siteConnection = new MgSiteConnection();
    $siteConnection->Open($userInfo);
    $resourceService = $siteConnection->CreateService(MgServiceType::ResourceService);
    $renderingService = $siteConnection->CreateService(MgServiceType::RenderingService);
    $map = new MgMap();
    $map->Open($resourceService, $mapName);
    $selection = new MgSelection($map);
    // Calculate the generated picture size
    $envelope = $captureBox->Envelope();
    $normalizedE = $normalizedCapture->Envelope();
    $size1 = new Size($envelope->getWidth(), $envelope->getHeight());
    $size2 = new Size($normalizedE->getWidth(), $normalizedE->getHeight());
    $toSize = new Size($size1->width / $size2->width * $size->width, $size1->height / $size2->height * $size->height);
    $center = $captureBox->GetCentroid()->GetCoordinate();
    $map->SetDisplayDpi($printDpi);
    $colorString = $map->GetBackgroundColor();
    // The returned color string is in AARRGGBB format. But the constructor of MgColor needs a string in RRGGBBAA format
    $colorString = substr($colorString, 2, 6) . substr($colorString, 0, 2);
    $color = new MgColor($colorString);
    $mgReader = $renderingService->RenderMap($map, $selection, $center, $scaleDenominator, $toSize->width, $toSize->height, $color, "PNG", false);
    $tempImage = sys_get_temp_dir() . DIRECTORY_SEPARATOR . "mgo" . uniqid();
    $mgReader->ToFile($tempImage);
    $image = imagecreatefrompng($tempImage);
    unlink($tempImage);
    // Rotate the picture back to be normalized
    $normalizedImg = imagerotate($image, -$rotation, 0);
    // Free the original image
    imagedestroy($image);
    // Crop the normalized image
    $croppedImg = imagecreatetruecolor($size->width, $size->height);
    imagecopy($croppedImg, $normalizedImg, 0, 0, (imagesx($normalizedImg) - $size->width) / 2, (imagesy($normalizedImg) - $size->height) / 2, $size->width, $size->height);
    // Free the normalized image
    imagedestroy($normalizedImg);
    if ($drawNorthArrow) {
        // Draw the north arrow on the map
        DrawNorthArrow($croppedImg);
    }
    header("Content-type: image/png");
    imagepng($croppedImg);
    //Uncomment to see what PHP-isms get spewed out that may be tripping up rendering
    //Also replace instances of "////print_r" with "//print_r" to insta-uncomment all debugging calls
    /*
    ob_start();
    imagepng($croppedImg);
    $im = base64_encode(ob_get_contents());
    ob_end_clean();
    header("Content-type: text/html", true);
    echo "<img src='data:image/png;base64,".$im."' alt='legend image'></img>";
    */
    imagedestroy($croppedImg);
}
function GenerateMap($size)
{
    global $sessionID, $mapName, $captureBox, $printSize, $normalizedCapture, $rotation, $scaleDenominator, $printDpi;
    InitializeWebTier();
    $userInfo = new MgUserInformation($sessionID);
    $siteConnection = new MgSiteConnection();
    $siteConnection->Open($userInfo);
    $resourceService = $siteConnection->CreateService(MgServiceType::ResourceService);
    $renderingService = $siteConnection->CreateService(MgServiceType::RenderingService);
    $map = new MgMap();
    $map->Open($resourceService, $mapName);
    $selection = new MgSelection($map);
    // Calculate the generated picture size
    $envelope = $captureBox->Envelope();
    $normalizedE = $normalizedCapture->Envelope();
    $size1 = new Size($envelope->getWidth(), $envelope->getHeight());
    $size2 = new Size($normalizedE->getWidth(), $normalizedE->getHeight());
    $toSize = new Size($size1->width / $size2->width * $size->width, $size1->height / $size2->height * $size->height);
    $center = $captureBox->GetCentroid()->GetCoordinate();
    $map->SetDisplayDpi($printDpi);
    $colorString = $map->GetBackgroundColor();
    // The returned color string is in AARRGGBB format. But the constructor of MgColor needs a string in RRGGBBAA format
    $colorString = substr($colorString, 2, 6) . substr($colorString, 0, 2);
    $color = new MgColor($colorString);
    $mgReader = $renderingService->RenderMap($map, $selection, $center, $scaleDenominator, $toSize->width, $toSize->height, $color, "PNG", false);
    $tempImage = sys_get_temp_dir() . DIRECTORY_SEPARATOR . "mgo" . uniqid();
    $mgReader->ToFile($tempImage);
    $image = imagecreatefrompng($tempImage);
    unlink($tempImage);
    // Rotate the picture back to be normalized
    $normalizedImg = imagerotate($image, -$rotation, 0);
    // Free the original image
    imagedestroy($image);
    // Crop the normalized image
    $croppedImg = imagecreatetruecolor($size->width, $size->height);
    imagecopy($croppedImg, $normalizedImg, 0, 0, (imagesx($normalizedImg) - $size->width) / 2, (imagesy($normalizedImg) - $size->height) / 2, $size->width, $size->height);
    // Free the normalized image
    imagedestroy($normalizedImg);
    // Draw the north arrow on the map
    DrawNorthArrow($croppedImg);
    header("Content-type: image/png");
    imagepng($croppedImg);
    imagedestroy($croppedImg);
}
 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());
         }
     }
 }
Exemple #5
0
function BuildViewer($forDwf = true)
{
    global $debug, $webLayoutDefinition, $cmds, $locale;
    global $sessionId, $username, $password, $orgSessionId;
    global $mapName;
    global $product;
    SetLocalizedFilesPath(GetLocalizationPath());
    try {
        // Initialize web tier with the site configuration file.
        InitializeWebTier();
        //fetch the parameters for this request
        //
        GetRequestParameters();
        //Open a connection with the server
        //
        $createSession = true;
        $cred = new MgUserInformation();
        if ($sessionId != '') {
            $cred->SetMgSessionId($sessionId);
            $createSession = false;
        } else {
            if ($username != '') {
                $cred->SetMgUsernamePassword($username, $password);
            } else {
                requestAuthentication();
                return;
            }
        }
        $site = new MgSiteConnection();
        $cred->SetLocale($locale);
        $cred->SetClientIp(GetClientIp());
        $cred->SetClientAgent(GetClientAgent());
        $site->Open($cred);
        if ($createSession) {
            $site1 = $site->GetSite();
            $sessionId = $site1->CreateSession();
            if ($forDwf == false) {
                $orgSessionId = $sessionId;
            }
        }
        //Get a MgWebLayout object initialized with the specified web layout definition
        //
        $webLayout = null;
        try {
            $resourceSrvc = $site->CreateService(MgServiceType::ResourceService);
            $webLayoutId = new MgResourceIdentifier($webLayoutDefinition);
            $webLayout = new MgWebLayout($resourceSrvc, $webLayoutId);
        } catch (MgUnauthorizedAccessException $e) {
            requestAuthentication();
            return;
        } catch (MgException $e) {
            $shortError = $e->GetExceptionMessage();
            $longErrorMsg = EscapeForHtml($e->GetDetails());
            header("HTTP/1.1 559 ");
            header('Content-Type: text/html; charset=utf-8');
            header("Status: 559 {$shortError}");
            echo "<html>\n<body>\n";
            echo $longErrorMsg;
            echo "</body>\n</html>\n";
            return;
        }
        //calculate the size of the variable elements of the viewer
        //
        $toolBar = $webLayout->GetToolBar();
        $statusBar = $webLayout->GetStatusBar();
        $taskPane = $webLayout->GetTaskPane();
        $infoPane = $webLayout->GetInformationPane();
        $taskBar = $taskPane->GetTaskBar();
        $mapDef = $webLayout->GetMapDefinition();
        $startupScriptCode = $webLayout->GetStartupScript();
        $selectionColor = $webLayout->GetSelectionColor();
        $mapImgFormat = $webLayout->GetMapImageFormat();
        $selImgFormat = $webLayout->GetSelectionImageFormat();
        $pointBuffer = $webLayout->GetPointSelectionBuffer();
        $showTaskPane = $taskPane->IsVisible();
        $showTaskBar = $taskBar->IsVisible();
        $showStatusbar = $statusBar->IsVisible();
        $showToolbar = $toolBar->IsVisible();
        $taskPaneWidth = $taskPane->GetWidth();
        $toolbarHeight = 30;
        $taskbarHeight = 30;
        $statusbarHeight = 26;
        $taskWidth = $showTaskPane ? $taskPaneWidth : 0;
        $toolbarHeight = $showToolbar ? $toolbarHeight : 0;
        $taskbarHeight = $showTaskBar ? $taskbarHeight : 0;
        $statusbarHeight = $showStatusbar ? $statusbarHeight : 0;
        //Encode the initial url so that it does not trip any sub-frames (especially if this url has parameters)
        $taskPaneUrl = urlencode($taskPane->GetInitialTaskUrl());
        $vpath = GetSurroundVirtualPath();
        $defHome = false;
        if ($taskPaneUrl == "") {
            $taskPaneUrl = "gettingstarted.php";
            $defHome = true;
        }
        $mapDefinitionUrl = urlencode($mapDef);
        // NOTE:
        //
        // We don't open a MgMap because it is being created by mapframe.php that is also probably running
        // as this script is running. However the naming convention is fixed enough that we can figure out
        // what to pass to the Task Pane
        $resId = new MgResourceIdentifier($mapDef);
        $mapName = $resId->GetName();
        $title = $webLayout->GetTitle();
        $enablePingServer = $webLayout->GetEnablePingServer();
        $showLegend = $infoPane->IsLegendBandVisible();
        $showProperties = $infoPane->IsPropertiesBandVisible();
        if ($showLegend || $showProperties) {
            if ($infoPane->IsVisible()) {
                $infoWidth = $infoPane->GetWidth();
                if ($infoWidth < 5) {
                    $infoWidth = 5;
                }
                //ensure visible
            } else {
                $showProperties = $showLegend = false;
                $infoWidth = 0;
            }
        } else {
            $infoWidth = 0;
        }
        //calculate the url of the inner pages
        //
        $srcToolbar = $showToolbar ? 'src="' . $vpath . 'toolbar.php?LOCALE=' . $locale . '"' : '';
        $srcStatusbar = $showStatusbar ? 'src="' . $vpath . 'statusbar.php?LOCALE=' . $locale . '"' : "";
        $srcTaskFrame = $showTaskPane ? 'src="' . $vpath . 'taskframe.php?MAPNAME=' . $mapName . '&WEBLAYOUT=' . urlencode($webLayoutDefinition) . '&DWF=' . ($forDwf ? "1" : "0") . '&SESSION=' . ($sessionId != "" ? $sessionId : "") . '&LOCALE=' . $locale . '"' : '';
        $srcTaskBar = 'src="' . $vpath . 'taskbar.php?LOCALE=' . $locale . '"';
        //view center
        //
        $ptCenter = $webLayout->GetCenter();
        if ($ptCenter == null) {
            $center = "null";
        } else {
            $coord = $ptCenter->GetCoordinate();
            $center = sprintf("new Point(%f, %f)", $coord->GetX(), $coord->GetY());
        }
        //Process commands and declare command objects
        //
        $commands = $webLayout->GetCommands();
        $cmdObjects = "";
        $cmdObject = "";
        $navCmdIndex = 0;
        $searchCmdIndex = 0;
        $measureCmdIndex = 0;
        $printCmdIndex = 0;
        $scriptCmdIndex = 0;
        $userCode = "";
        $userCodeCalls = "\nswitch(funcIndex)\n{\n";
        $selAwareCmdCount = 0;
        $selAwareCmds = "";
        for ($i = 0; $i < $commands->GetCount(); $i++) {
            $cmd = $commands->GetItem($i);
            if (!$cmd->IsUsed()) {
                continue;
            }
            $tgtViewer = $cmd->GetTargetViewerType();
            if (($tgtViewer == MgWebTargetViewerType::Dwf) != ($forDwf == true) && $tgtViewer != MgWebTargetViewerType::All) {
                continue;
            }
            $name = $cmd->GetName();
            $action = $cmd->GetAction();
            if ($action == MgWebActions::Search) {
                $cols = "var resCols" . $searchCmdIndex . " = new Array();\n";
                if ($cmd->GetResultColumnCount() > 0) {
                    for ($j = 0; $j < $cmd->GetResultColumnCount(); $j++) {
                        $col = sprintf("resCols%d[%d] = new ResultColumn(\"%s\", \"%s\");\n", $searchCmdIndex, $j, StrEscape($cmd->GetColumnDisplayNameAt($j)), StrEscape($cmd->GetColumnPropertyNameAt($j)));
                        $cols = $cols . $col;
                    }
                }
                $cmdObjects = $cmdObjects . $cols;
                // declare a new search command object
                $cmdObject = sprintf("commands[%d] = new SearchCommand(\"%s\", \"%s\", %d, \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", resCols%d, \"%s\", %d, %d, \"%s\");\n", $i, StrEscape($name), StrEscape($cmd->GetLabel()), $cmd->GetAction(), $cmd->GetIconUrl(), $cmd->GetDisabledIconUrl(), StrEscape($cmd->GetTooltip()), StrEscape($cmd->GetDescription()), $cmd->GetLayer(), StrEscape($cmd->GetPrompt()), $searchCmdIndex, StrEscape($cmd->GetFilter()), $cmd->GetMatchLimit(), $cmd->GetTarget(), $cmd->GetTargetName());
                $searchCmdIndex++;
            } else {
                if ($action == MgWebActions::InvokeUrl) {
                    // create the parameter objects
                    $params = "var navParams" . $navCmdIndex . " = new Array();\n";
                    $layers = "var layers" . $navCmdIndex . " = new Array();\n";
                    if ($cmd->GetParameterCount() > 0) {
                        for ($j = 0; $j < $cmd->GetParameterCount(); $j++) {
                            $param = sprintf("navParams%d[%d] = new NavParam(\"%s\", \"%s\");\n", $navCmdIndex, $j, $cmd->GetParameterNameAt($j), $cmd->GetParameterValueAt($j));
                            $params = $params . $param;
                        }
                    }
                    for ($j = 0; $j < $cmd->GetLayerCount(); $j++) {
                        $layer = sprintf("layers%d[%d] = \"%s\";\n", $navCmdIndex, $j, $cmd->GetLayerNameAt($j));
                        $layers = $layers . $layer;
                    }
                    $cmdObjects = $cmdObjects . $params . $layers;
                    if ($cmd->DisabledIfSelectionEmpty() || $cmd->GetLayerCount() > 0) {
                        $selAwareCmds = $selAwareCmds . sprintf("selectionAwareCmds[%d] = %d;\n", $selAwareCmdCount, $i);
                        $selAwareCmdCount++;
                    }
                    // declare a new invokeurl command object
                    $cmdObject = sprintf("commands[%d] = new InvokeUrlCommand(\"%s\", %d, \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", navParams%d, %s, layers%d, %d, \"%s\");\n", $i, StrEscape($name), $cmd->GetAction(), $cmd->GetIconUrl(), $cmd->GetDisabledIconUrl(), StrEscape($cmd->GetTooltip()), StrEscape($cmd->GetDescription()), $cmd->GetUrl(), $navCmdIndex, $cmd->DisabledIfSelectionEmpty() ? "true" : "false", $navCmdIndex, $cmd->GetTarget(), $cmd->GetTargetName());
                    $navCmdIndex++;
                } else {
                    if ($action == MgWebActions::Buffer || $action == MgWebActions::SelectWithin || $action == MgWebActions::Measure || $action == MgWebActions::ViewOptions || $action == MgWebActions::GetPrintablePage) {
                        if ($action == MgWebActions::Measure) {
                            if ($measureCmdIndex != 0) {
                                throw new Exception(GetLocalizedString("ALREADYINMEASURE", $locale));
                            }
                            $measureCmdIndex = $i;
                        } else {
                            if ($action == MgWebActions::SelectWithin) {
                                $selAwareCmds = $selAwareCmds . sprintf("selectionAwareCmds[%d] = %d;\n", $selAwareCmdCount, $i);
                                $selAwareCmdCount++;
                            }
                        }
                        // declare a new ui target command object
                        $cmdObject = sprintf("commands[%d] = new UiTargetCommand(\"%s\", %d, \"%s\", \"%s\", \"%s\", \"%s\", %d, \"%s\");\n", $i, StrEscape($name), $cmd->GetAction(), $cmd->GetIconUrl(), $cmd->GetDisabledIconUrl(), StrEscape($cmd->GetTooltip()), StrEscape($cmd->GetDescription()), $cmd->GetTarget(), $cmd->GetTargetName());
                    } else {
                        if ($action == MgWebActions::Help) {
                            // declare a new help  command object
                            $cmdObject = sprintf("commands[%d] = new HelpCommand(\"%s\", %d, \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", %d, \"%s\");\n", $i, StrEscape($name), $cmd->GetAction(), $cmd->GetIconUrl(), $cmd->GetDisabledIconUrl(), StrEscape($cmd->GetTooltip()), StrEscape($cmd->GetDescription()), $cmd->GetUrl(), $cmd->GetTarget(), $cmd->GetTargetName());
                        } else {
                            if ($action == MgWebActions::PrintMap) {
                                // declare the print layouts
                                $layouts = "var layouts" . $printCmdIndex . " = new Array();\n";
                                for ($j = 0; $j < $cmd->GetPrintLayoutCount(); $j++) {
                                    $layout = "";
                                    $layout = sprintf("layouts%d[%d] = \"%s\";\n", $printCmdIndex, $j, $cmd->GetPrintLayoutAt($j));
                                    $layouts = $layouts . $layout;
                                }
                                $cmdObjects = $cmdObjects . $layouts;
                                // declare a new print command object
                                $cmdObject = sprintf("commands[%d] = new PrintCommand(\"%s\", %d, \"%s\", \"%s\", \"%s\", \"%s\", layouts%d);\n", $i, StrEscape($name), $cmd->GetAction(), $cmd->GetIconUrl(), $cmd->GetDisabledIconUrl(), StrEscape($cmd->GetTooltip()), StrEscape($cmd->GetDescription()), $printCmdIndex);
                                $printCmdIndex++;
                            } else {
                                if ($action == MgWebActions::InvokeScript) {
                                    // declare a new basic command object
                                    $cmdObject = sprintf("commands[%d] = new InvokeScriptCommand(\"%s\", %d, \"%s\", \"%s\", \"%s\", \"%s\", %d);\n", $i, StrEscape($name), $cmd->GetAction(), $cmd->GetIconUrl(), $cmd->GetDisabledIconUrl(), StrEscape($cmd->GetTooltip()), StrEscape($cmd->GetDescription()), $scriptCmdIndex);
                                    $userCode = $userCode . "\nfunction UserFunc" . $scriptCmdIndex . "()\n{\n" . $cmd->GetScriptCode() . "\n}\n";
                                    $userCodeCalls = $userCodeCalls . sprintf("case %d: UserFunc%d(); break;\n", $scriptCmdIndex, $scriptCmdIndex);
                                    $scriptCmdIndex++;
                                } else {
                                    // declare a new basic command object
                                    $cmdObject = sprintf("commands[%d] = new BasicCommand(\"%s\", %d, \"%s\", \"%s\", \"%s\", \"%s\");\n", $i, $name, $cmd->GetAction(), $cmd->GetIconUrl(), $cmd->GetDisabledIconUrl(), StrEscape($cmd->GetTooltip()), StrEscape($cmd->GetDescription()));
                                }
                            }
                        }
                    }
                }
            }
            $cmdObjects = $cmdObjects . $cmdObject;
            $cmds[$name] = $i;
        }
        $userCodeCalls = $userCodeCalls . "\n}\n";
        //Declare toolbar items
        //
        $toolbarDef = DeclareUiItems($toolBar->GetWidgets(), "toolbarItems");
        //Declare task items
        $taskListDef = DeclareUiItems($taskBar->GetTaskList(), "taskItems");
        //Declare context menu items
        $ctxMenu = $webLayout->GetContextMenu();
        if ($ctxMenu->IsVisible()) {
            $ctxMenuDef = DeclareUiItems($ctxMenu, "ctxMenuItems");
        } else {
            $ctxMenuDef = "";
        }
        //task items texts
        //
        $taskItemTexts = "";
        $taskButtons = $taskBar->GetTaskButtons();
        for ($i = 0; $i < 4; $i++) {
            $btn = $taskButtons->GetWidget($i);
            if ($i > 0) {
                $taskItemTexts = $taskItemTexts . ",";
            }
            $taskItemTexts = $taskItemTexts . '"' . StrEscape($btn->GetName()) . '",' . '"' . StrEscape($btn->GetTooltip()) . '",' . '"' . StrEscape($btn->GetDescription()) . '",' . '"' . StrEscape($btn->GetIconUrl()) . '",' . '"' . StrEscape($btn->GetDisabledIconUrl()) . '"';
        }
        //transmit the session to the map pane if one was specified to this request
        if ($orgSessionId != "") {
            $sessionParam = "&SESSION=" . $orgSessionId;
        } else {
            $sessionParam = "";
        }
        //load the frameset template and format it
        $frameset = "";
        $viewerType = $forDwf ? "DWF" : "HTML";
        if ($showTaskBar) {
            $frameSetTempl = file_get_contents("../viewerfiles/framesettaskbar.templ");
            $frameset = sprintf($frameSetTempl, $statusbarHeight, $taskWidth, $toolbarHeight, $srcToolbar, $vpath . "mapframe.php", $mapDefinitionUrl, $viewerType, $showLegend ? 1 : 0, $showProperties ? 1 : 0, $infoWidth, $locale, $webLayout->GetHyperlinkTarget(), $webLayout->GetHyperlinkTargetFrame(), $webLayout->IsZoomControlVisible() ? 1 : 0, $selectionColor, $mapImgFormat, $selImgFormat, $pointBuffer, $sessionParam, $vpath . "formframe.php", $taskbarHeight + 1, $srcTaskBar, $srcTaskFrame, $srcStatusbar);
        } else {
            $frameSetTempl = file_get_contents("../viewerfiles/framesetnotaskbar.templ");
            $frameset = sprintf($frameSetTempl, $toolbarHeight, $statusbarHeight, $srcToolbar, $taskWidth, $vpath . "mapframe.php", $mapDefinitionUrl, $viewerType, $showLegend ? 1 : 0, $showProperties ? 1 : 0, $infoWidth, $locale, $webLayout->GetHyperlinkTarget(), $webLayout->GetHyperlinkTargetFrame(), $webLayout->IsZoomControlVisible() ? 1 : 0, $selectionColor, $mapImgFormat, $selImgFormat, $pointBuffer, $sessionParam, $srcTaskFrame, $vpath . "formframe.php", $srcStatusbar);
        }
        $homePageUrl = urldecode($taskPaneUrl);
        if (strlen($homePageUrl) < 8 || strncasecmp($homePageUrl, "http://", 7) != 0) {
            $homePageUrl = $vpath . $homePageUrl;
        }
        //load the HTML template and format it
        //
        $templ = Localize(file_get_contents("../viewerfiles/mainframe.templ"), $locale, GetClientOS());
        print sprintf($templ, $title, GetRootVirtualFolder() . "/mapagent/mapagent.fcgi", $enablePingServer ? 1 : 0, $site->GetSite()->GetSessionTimeout(), $locale, $showToolbar ? 1 : 0, $showStatusbar ? 1 : 0, $showTaskPane ? 1 : 0, $showTaskPane ? 0 : ($showTaskBar ? 1 : 0), $homePageUrl, $defHome ? "1" : "0", $webLayoutDefinition, $mapDef, $taskWidth, $center, $webLayout->GetScale(), StrEscape($title), $forDwf ? "1" : "0", $cmdObjects, $toolbarDef, $taskListDef, $ctxMenuDef, $userCode, $taskItemTexts, $selAwareCmds, $startupScriptCode, $vpath . "quickplotpanel.php", $vpath . "measureui.php", $vpath . "searchprompt.php", $vpath . "bufferui.php", $vpath . "selectwithinui.php", $userCodeCalls, $vpath . "viewoptions.php", $frameset);
    } catch (MgUserNotFoundException $e) {
        requestAuthentication();
    } catch (MgAuthenticationFailedException $e) {
        requestAuthentication();
    } catch (MgException $e) {
        // This should be a 500 error of some sort, but
        // in order to give a nice custom error message, it looks as
        // if we shortcut things by using a 200 status.
        $shortError = $e->GetExceptionMessage();
        $longErrorMsg = EscapeForHtml($e->GetDetails());
        header("HTTP/1.1 200 ");
        header('Content-Type: text/html; charset=utf-8');
        header("Status: 200 {$shortError}");
        echo "<html>\n<body>\n";
        echo $longErrorMsg;
        echo "</body>\n</html>\n";
    } catch (Exception $ne) {
        $errorMsg = EscapeForHtml($ne->GetMessage());
        echo $errorMsg;
    }
}
Exemple #6
0
 function GetAllMapResources()
 {
     try {
         global $site;
         global $userInfo;
         global $mapResources;
         $mapResourcesXml = "";
         // Enumerates all maps in the library
         $resourceID = new MgResourceIdentifier("Library://");
         //connect to the site and get a resource service instance
         $siteConn = new MgSiteConnection();
         $siteConn->Open($userInfo);
         $resourceService = $siteConn->CreateService(MgServiceType::ResourceService);
         $byteReader = $resourceService->EnumerateResources($resourceID, -1, "MapDefinition");
         $chunk = "";
         do {
             $chunkSize = $byteReader->Read($chunk, 4096);
             $mapResourcesXml = $mapResourcesXml . $chunk;
         } while ($chunkSize != 0);
         $resourceList = new DOMDocument();
         $resourceList->loadXML($mapResourcesXml);
         $resourceIdNodeList = $resourceList->documentElement->getElementsByTagName("ResourceId");
         for ($i = 0; $i < $resourceIdNodeList->length; $i++) {
             $mapResourceID = $resourceIdNodeList->item($i)->nodeValue;
             $shortMapName = strrchr($mapResourceID, '/');
             $shortMapName = substr($shortMapName, 1, strlen($shortMapName) - 15);
             $mapResources[$i]["FullNames"] = $mapResourceID;
             $mapResources[$i]["ShortNames"] = $shortMapName;
         }
         usort($mapResources, "CompareMapName");
     } catch (Exception $exc) {
         $errorMsg = $exc->getMessage();
     }
 }
 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));
     }
 }
Exemple #8
0
    <meta http-equiv="content-script-type" content="text/javascript">
    <meta http-equiv="content-style-type" content="text/css">
    <link href="../styles/globalStyles.css" rel="stylesheet"  type="text/css">
    <link href="../styles/otherStyles.css" rel="stylesheet" type="text/css">
  </head>
  <body class="AppFrame">
    <h1 class="AppHeading">Layer Visibility</h1>
    <?php 
require_once '../common/common.php';
try {
    MgInitializeWebTier($webconfigFilePath);
    $args = $_SERVER['REQUEST_METHOD'] == "POST" ? $_POST : $_GET;
    $sessionId = $args['SESSION'];
    $mapName = $args['MAPNAME'];
    $userInfo = new MgUserInformation($sessionId);
    $siteConnection = new MgSiteConnection();
    $siteConnection->Open($userInfo);
    $map = new MgMap($siteConnection);
    $map->Open($mapName);
    $layers = $map->GetLayers();
    // Get layer collection
    echo "<p>Layers, in draw order:</p>";
    echo '<table class="taskPane" cellspacing="0">';
    echo '<tr><th class="rowHead">Layer</th><th>GetVisible()</th><th>IsVisible()</th></tr>';
    $count = $layers->GetCount();
    for ($i = 0; $i < $count; $i++) {
        $layer = $layers->GetItem($i);
        echo "<tr><td class=\"rowHead\">" . $layer->GetName() . "</td><td>" . ($layer->GetVisible() ? 'on' : 'off') . "</td><td>" . ($layer->IsVisible() ? 'on' : 'off') . "</td></tr>\n";
    }
    echo '</table>';
} catch (MgException $e) {
Exemple #9
0
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
//
//
// Usage:
// php-cgi updateResource.php user=SomeUserName num=NumberOfResources loop=LoopCount
//
//
require_once "../../../Web/src/PhpApi/constants.php";
require_once "Utils.php";
try {
    Utils::MapAgentInit(WEBCONFIGINI);
    $site = new MgSiteConnection();
    $cred = new MgUserInformation();
    $cred->SetMgUsernamePassword("Administrator", "admin");
    $cred->SetLocale("en");
    $site->Open($cred);
    $svc = $site->CreateService(MgServiceType::ResourceService);
} catch (MgException $exc) {
    header("HTTP/1.1 559" . $exc->GetExceptionMessage());
    $hdr = "Status: 559 " . $exc->GetExceptionMessage();
    header($hdr);
    echo "<html>\n";
    echo "<body>\n";
    echo $hdr . "\n";
    echo $exc->GetExceptionMessage() . "\n";
    echo $exc->GetDetails() . "\n";
    echo "</body>\n";
 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 GetTileXYZ($resId, $groupName, $x, $y, $z, $type, $layerNames = NULL)
 {
     $fmt = $this->ValidateRepresentation($type, array("json", "png", "png8", "jpg", "gif"));
     $path = self::GetTilePath($this->app, $resId, $groupName, $z, $x, $y, $type, $layerNames);
     clearstatcache();
     $dir = dirname($path);
     $lockPath = "{$dir}/lock_" . $y . ".lck";
     $attempts = 0;
     while (!@is_dir($dir)) {
         try {
             mkdir($dir, 0777, true);
         } catch (Exception $e) {
             //Another tile request may have already created this since
             $attempts++;
             //Bail after MAX_RETRY_ATTEMPTS
             if ($attempts >= self::MAX_RETRY_ATTEMPTS) {
                 $this->ServerError($this->app->localizer->getText("E_FAILED_TO_CREATE_DIR_AFTER_N_ATTEMPTS", $attempts), $this->GetMimeTypeForFormat($type));
             }
         }
     }
     //If there's a dangling lock file, attempt to remove it
     if (file_exists($lockPath)) {
         unlink($lockPath);
     }
     $fpLockFile = fopen($lockPath, "a+");
     //Message of any exception caught will be set to this variable
     $tileError = null;
     $requestId = rand();
     $this->app->log->debug("({$requestId}) Checking if {$path} exists");
     $attempts = 0;
     while (!file_exists($path)) {
         //Bail after MAX_RETRY_ATTEMPTS
         if ($attempts >= self::MAX_RETRY_ATTEMPTS) {
             $this->ServerError($this->app->localizer->getText("E_FAILED_TO_GENERATE_TILE_AFTER_N_ATTEMPTS", $attempts), $this->GetMimeTypeForFormat($type));
         }
         $attempts++;
         $this->app->log->debug("({$requestId}) {$path} does not exist. Locking for writing");
         $bLocked = false;
         flock($fpLockFile, LOCK_EX);
         fwrite($fpLockFile, ".");
         $bLocked = true;
         $this->app->log->debug("({$requestId}) Acquired lock for {$path}. Checking if path exists again.");
         //check once more to see if the cache file was created while waiting for
         //the lock
         clearstatcache();
         if (!file_exists($path)) {
             try {
                 $this->app->log->debug("({$requestId}) Rendering tile to {$path}");
                 $bOldPath = true;
                 if ($type != "json") {
                     //if this is MGOS 3.0 and we're dealing with a tile set, we invoke GETTILEIMAGE as that we can pass in Tile Set Definition
                     //resource ids without issues. We cannot create MgMaps from Tile Set Definitions that are not using the default tile provider.
                     //
                     //The given tile set is assumed to be using the XYZ provider, the case where the Tile Set Definition is using the default provider
                     //is not handled
                     if ($this->app->MG_VERSION[0] >= 3 && $resId->GetResourceType() == "TileSetDefinition") {
                         $bOldPath = false;
                         $sessionId = "";
                         if ($resId->GetRepositoryType() === MgRepositoryType::Session && $this->app->request->get("session") == null) {
                             $sessionId = $resId->GetRepositoryName();
                         }
                         $resIdStr = $resId->ToString();
                         $that = $this;
                         $this->EnsureAuthenticationForHttp(function ($req, $param) use($that, $resIdStr, $groupName, $x, $y, $z, $requestId, $path) {
                             $param->AddParameter("OPERATION", "GETTILEIMAGE");
                             $param->AddParameter("VERSION", "1.2.0");
                             $param->AddParameter("MAPDEFINITION", $resIdStr);
                             $param->AddParameter("BASEMAPLAYERGROUPNAME", $groupName);
                             $param->AddParameter("SCALEINDEX", $z);
                             $param->AddParameter("TILEROW", $x);
                             $param->AddParameter("TILECOL", $y);
                             $that->app->log->debug("({$requestId}) Executing GETTILEIMAGE");
                             $that->ExecuteHttpRequest($req, function ($result, $status) use($path) {
                                 if ($status == 200) {
                                     //Need to dump the rendered tile to the specified path so the caching stuff below can still do its thing
                                     $resultObj = $result->GetResultObject();
                                     $sink = new MgByteSink($resultObj);
                                     $sink->ToFile($path);
                                 }
                             });
                         }, true, "", $sessionId);
                         //Tile access can be anonymous, so allow for it if credentials/session specified, but if this is a session-based Map Definition, use the session id as the nominated one
                     }
                 }
                 //Pre MGOS 3.0 code path
                 if ($bOldPath) {
                     $this->app->log->debug("({$requestId}) Going down old code path");
                     $this->EnsureAuthenticationForSite("", true);
                     $siteConn = new MgSiteConnection();
                     $siteConn->Open($this->userInfo);
                     $map = new MgMap($siteConn);
                     $map->Create($resId, "VectorTileMap");
                     $renderSvc = $siteConn->CreateService(MgServiceType::RenderingService);
                     $groups = $map->GetLayerGroups();
                     $baseGroup = $groups->GetItem($groupName);
                     //Will throw MgObjectNotFoundException -> 404 if no such group exists
                     $factory = new MgCoordinateSystemFactory();
                     $mapCsWkt = $map->GetMapSRS();
                     $mapCs = $factory->Create($mapCsWkt);
                     $mapExtent = $map->GetMapExtent();
                     $mapExLL = $mapExtent->GetLowerLeftCoordinate();
                     $mapExUR = $mapExtent->GetUpperRightCoordinate();
                     $metersPerUnit = $mapCs->ConvertCoordinateSystemUnitsToMeters(1.0);
                     $this->app->log->debug("({$requestId}) Calc bounds from XYZ");
                     //XYZ to lat/lon math. From this we can convert to the bounds in the map's CS
                     //
                     //Source: http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames
                     $n = pow(2, $z);
                     $lonMin = $x / $n * 360.0 - 180.0;
                     $latMin = rad2deg(atan(sinh(pi() * (1 - 2 * $y / $n))));
                     $lonMax = ($x + 1) / $n * 360.0 - 180.0;
                     $latMax = rad2deg(atan(sinh(pi() * (1 - 2 * ($y + 1) / $n))));
                     $boundsMinX = min($lonMin, $lonMax);
                     $boundsMinY = min($latMin, $latMax);
                     $boundsMaxX = max($lonMax, $lonMin);
                     $boundsMaxY = max($latMax, $latMin);
                     if ($mapCs->GetCsCode() != "LL84") {
                         $llCs = $factory->CreateFromCode("LL84");
                         $trans = $factory->GetTransform($llCs, $mapCs);
                         $ul = $trans->Transform($lonMin, $latMin);
                         $lr = $trans->Transform($lonMax, $latMax);
                         $boundsMinX = min($lr->GetX(), $ul->GetX());
                         $boundsMinY = min($lr->GetY(), $ul->GetY());
                         $boundsMaxX = max($lr->GetX(), $ul->GetX());
                         $boundsMaxY = max($lr->GetY(), $ul->GetY());
                     }
                     //Set all layers under group to be visible
                     $layers = $map->GetLayers();
                     $layerCount = $layers->GetCount();
                     $groupCount = $groups->GetCount();
                     //Turn all groups that are not the given group to be hidden
                     for ($i = 0; $i < $groupCount; $i++) {
                         $group = $groups->GetItem($i);
                         if ($group->GetName() != $groupName) {
                             $group->SetVisible(false);
                         } else {
                             $group->SetVisible(true);
                         }
                     }
                     for ($i = 0; $i < $layerCount; $i++) {
                         $layer = $layers->GetItem($i);
                         $group = $layer->GetGroup();
                         if (null == $group) {
                             continue;
                         }
                         if ($group->GetName() != $groupName && $layer->GetLayerType() == MgLayerType::Dynamic) {
                             $layer->SetVisible(false);
                             continue;
                         }
                         if ($layer->GetLayerType() == MgLayerType::Dynamic) {
                             $layer->SetVisible(true);
                         }
                     }
                     if ($type == "json") {
                         //error_log("($requestId) Render vector tile");
                         $this->PutVectorTileXYZ($map, $groupName, $siteConn, $metersPerUnit, $factory, $path, $boundsMinX, $boundsMinY, $boundsMaxX, $boundsMaxY, $layerNames);
                     } else {
                         $format = strtoupper($type);
                         //error_log("($requestId) Render image tile");
                         $this->PutTileImageXYZ($map, $groupName, $renderSvc, $path, $format, $boundsMinX, $boundsMinY, $boundsMaxX, $boundsMaxY, $layerNames, $requestId);
                     }
                 }
             } catch (MgException $ex) {
                 if ($bLocked) {
                     $this->app->log->debug("({$requestId}) MgException caught " . $ex->GetDetails() . "\n" . $ex->getTraceAsString() . "\n. Releasing lock for {$path}");
                     $tileError = $ex->GetExceptionMessage();
                     flock($fpLockFile, LOCK_UN);
                     $bLocked = false;
                 }
                 if ($ex instanceof MgResourceNotFoundException || $ex instanceof MgObjectNotFoundException) {
                     $this->NotFound($ex->GetExceptionMessage(), $this->GetMimeTypeForFormat($fmt));
                 } else {
                     if ($ex instanceof MgConnectionFailedException) {
                         $this->ServiceUnavailable($ex->GetExceptionMessage(), $this->GetMimeTypeForFormat($fmt));
                     }
                 }
             } catch (Exception $ex) {
                 if ($bLocked) {
                     $tileError = get_class($ex) . " - " . $ex->getMessage();
                     $this->app->log->debug("({$requestId}) Exception caught ({$tileError}). Releasing lock for {$path}");
                     flock($fpLockFile, LOCK_UN);
                     $bLocked = false;
                 }
             }
         }
         if ($bLocked) {
             $this->app->log->debug("({$requestId}) Releasing lock for {$path}");
             flock($fpLockFile, LOCK_UN);
             $bLocked = false;
         }
     }
     //An exception occurred, try to clean up lock before bailing
     if ($tileError != null) {
         try {
             fclose($fpLockFile);
             unlink($lockPath);
         } catch (Exception $ex) {
             $this->app->log->debug("({$requestId}) Failed to delete lock file. Perhaps another concurrent request to the same tile is happening?");
         }
         throw new Exception($tileError);
     }
     $modTime = filemtime($path);
     $this->app->lastModified($modTime);
     $this->app->log->debug("({$requestId}) Acquiring shared lock for {$path}");
     //acquire shared lock for reading to prevent a problem that could occur
     //if a tile exists but is only partially generated.
     flock($fpLockFile, LOCK_SH);
     $this->app->log->debug("({$requestId}) Outputting {$path}");
     $ext = strtoupper(pathinfo($path, PATHINFO_EXTENSION));
     $mimeType = "";
     switch ($ext) {
         case "PNG":
             //MgImageFormats::Png:
             $mimeType = MgMimeType::Png;
             break;
         case "GIF":
             //MgImageFormats::Gif:
             $mimeType = MgMimeType::Gif;
             break;
         case "JPG":
             //MgImageFormats::Jpeg:
             $mimeType = MgMimeType::Jpeg;
             break;
         case "JSON":
             $mimeType = MgMimeType::Json;
             break;
     }
     $this->app->response->header("Content-Type", $mimeType);
     $this->app->expires("+6 months");
     $this->app->response->header("Cache-Control", "max-age=31536000, must-revalidate");
     $this->app->response->setBody(file_get_contents($path));
     $this->app->log->debug("({$requestId}) Releasing shared lock for {$path}");
     //Release lock
     flock($fpLockFile, LOCK_UN);
     //Try to delete the lock file
     try {
         fclose($fpLockFile);
         unlink($lockPath);
     } catch (Exception $ex) {
         $this->app->log->debug("({$requestId}) Failed to delete lock file. Perhaps another concurrent request to the same tile is happening?");
     }
 }
Exemple #12
0
        <?php 
$sessionId = $_GET['sessionId'];
$resName = $_GET['resId'];
$schemaName = $_GET['schemaName'];
$className = $_GET['className'];
$viewer = $_GET['viewer'];
try {
    $thisFile = __FILE__;
    $pos = strrpos($thisFile, '\\');
    if ($pos == false) {
        $pos = strrpos($thisFile, '/');
    }
    $configFilePath = substr($thisFile, 0, $pos + 1) . "../webconfig.ini";
    MgInitializeWebTier($configFilePath);
    $userInfo = new MgUserInformation($sessionId);
    $site = new MgSiteConnection();
    $site->Open($userInfo);
    $featureSrvc = $site->CreateService(MgServiceType::FeatureService);
    $resId = new MgResourceIdentifier($resName);
    $classCollection = $featureSrvc->GetClasses($resId, $schemaName);
    $firstClass = substr(strrchr($classCollection->GetItem(0), ":"), 1);
    $classNames = new MgStringCollection();
    $classNames->Add($className);
    $xml = $featureSrvc->DescribeSchemaAsXml($resId, $schemaName, $classNames);
    // Parse the xml for encoded characters, however, the 'xmlns' attribute under 'targetNamespace' element
    // cannot contain the translated or encoded characters. This replaces '-xffXX-' with 'ffXX' for that
    // particular string while the rest of the encoded chars are translated properly.
    $subXml = substr($xml, strpos($xml, 'xs:element'), -1);
    $subXml = preg_replace("/-x([A-Za-z0-9]{1,4})-/e", "html_entity_decode('&#'.hexdec('\$1').';',ENT_NOQUOTES,'UTF-8')", $subXml);
    $subXml = preg_replace("/_x([A-Za-z0-9]{1,4})-/e", "html_entity_decode('&#'.hexdec('\$1').';',ENT_NOQUOTES,'UTF-8')", $subXml);
    $xml = substr_replace($xml, $subXml, strpos($xml, 'xs:element'), -1);
 public function EnumerateRolesForUser($userName, $format)
 {
     $sessionId = $this->app->request->params("session");
     try {
         //Check for unsupported representations
         $fmt = $this->ValidateRepresentation($format, array("xml", "json"));
         $this->EnsureAuthenticationForSite($sessionId, false, $this->GetMimeTypeForFormat($format));
         $siteConn = new MgSiteConnection();
         $siteConn->Open($this->userInfo);
         $site = $siteConn->GetSite();
         try {
             $user = $site->GetUserForSession();
             //Hmmm. Should we allow Anonymous to discover its own roles?
             if ($user === "Anonymous" && $userName !== "Anonymous") {
                 $this->Unauthorized($this->GetMimeTypeForFormat($format));
             }
         } catch (MgException $ex) {
             //Could happen if we have non-anonymous credentials in the http authentication header
         }
         $content = $site->EnumerateRoles($userName);
         $mimeType = MgMimeType::Xml;
         if ($fmt === "json") {
             $mimeType = MgMimeType::Json;
         }
         $this->app->response->header("Content-Type", $mimeType);
         $this->OutputMgStringCollection($content, $mimeType);
     } catch (MgException $ex) {
         $this->OnException($ex, $this->GetMimeTypeForFormat($format));
     }
 }
Exemple #14
0
 function SetPassword($id, $password)
 {
     $encryptedPassword = crypt($password, SALT);
     $success = $this->db->queryExec('UPDATE users SET password = "******", resetkey = "" where userid = ' . $id);
     $user = $this->GetUser($id);
     if ($success) {
         $adminUser = new MgUserInformation(MG_ADMIN_USER, MG_ADMIN_PASSWD);
         $siteConnection = new MgSiteConnection();
         $siteConnection->Open($adminUser);
         $site = $siteConnection->GetSite();
         $site->UpdateUser($user->userName(), "", $user->userName(), $password, "");
     } else {
         echo "/* failed to update user password */";
     }
     return $success;
 }
//  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
//
$fusionMGpath = '../../layers/MapGuide/php/';
require_once $fusionMGpath . 'Common.php';
if (InitializationErrorOccurred()) {
    DisplayInitializationErrorText();
    exit;
}
require_once $fusionMGpath . 'Utilities.php';
require_once $fusionMGpath . 'JSON.php';
require_once 'classes/featureinfo.php';
$args = $_SERVER['REQUEST_METHOD'] == "POST" ? $_POST : $_GET;
try {
    $responseType = 'text/plain';
    $response = '';
    $site = new MgSiteConnection();
    $site->Open(new MgUserInformation($args['SESSION']));
    $resourceService = $site->CreateService(MgServiceType::ResourceService);
    $featureService = $site->CreateService(MgServiceType::FeatureService);
    $layerName = $args['LAYERNAME'];
    $mapName = $args['MAPNAME'];
    $map = new MgMap($site);
    $map->Open($mapName);
    $layer = $map->GetLayers()->GetItem($layerName);
    $className = $layer->GetFeatureClassName();
    $selection = new MgSelection($map);
    $selection->Open($resourceService, $mapName);
    $properties = new stdClass();
    if ($selection->Contains($layer, $className)) {
        $featureReader = $selection->GetSelectedFeatures($layer, $className, new MgStringCollection());
        /* Get the map SRS - we use this to convert distances */
 public function DestroySession($sessionId)
 {
     try {
         $siteConn = new MgSiteConnection();
         $userInfo = new MgUserInformation($sessionId);
         $userInfo->SetClientAgent("MapGuide REST Extension");
         $userInfo->SetClientIp($this->GetClientIp());
         $siteConn->Open($userInfo);
         $site = $siteConn->GetSite();
         $site->DestroySession($sessionId);
     } catch (MgException $ex) {
         $this->OnException($ex);
     }
 }
 public function MoveResource()
 {
     $resIdStr = $this->GetRequestParameter("source");
     $sessionId = $this->GetRequestParameter("session", "");
     $fmt = "json";
     $mimeType = MgMimeType::Json;
     $this->EnsureAuthenticationForSite($sessionId, false, $mimeType);
     $siteConn = new MgSiteConnection();
     $siteConn->Open($this->userInfo);
     $site = $siteConn->GetSite();
     $this->VerifyWhitelist($resIdStr, $mimeType, "MOVE  RESOURCE", $fmt, $site, $this->userName);
     $that = $this;
     $this->EnsureAuthenticationForHttp(function ($req, $param) use($that) {
         $param->AddParameter("OPERATION", "MOVERESOURCE");
         $param->AddParameter("VERSION", "2.2.0");
         $param->AddParameter("SOURCE", $that->GetRequestParameter("source"));
         $param->AddParameter("DESTINATION", $that->GetRequestParameter("destination"));
         //Default the depth to 1 if not specified (think of the MapGuide Server!)
         $param->AddParameter("OVERWRITE", $that->GetBooleanRequestParameter("overwrite", "0"));
         $param->AddParameter("OVERWRITE", $that->GetBooleanRequestParameter("cascade", "1"));
         $that->ExecuteHttpRequest($req);
     });
 }
 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);
     }
 }
Exemple #19
0
//  General Public License as published by the Free Software Foundation.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
//
require_once "../../../Web/src/PhpApi/Constants.php";
require_once "Utils.php";
try {
    Utils::MapAgentInit(WEBCONFIGINI);
    $site = new MgSiteConnection();
    $cred = new MgUserInformation();
    $cred->SetMgUsernamePassword("Administrator", "admin");
    $cred->SetLocale("en");
    $site->Open($cred);
    $svc = $site->CreateService(MgServiceType::FeatureService);
} catch (MgException $exc) {
    echo $exc->GetExceptionMessage() . "\n";
    echo $exc->GetDetails() . "\n";
    return;
}
echo "Created Services\n";
// Create class definition for new feature  class
$classDef = new MgClassDefinition();
$classDef->SetName("Buffer");
$classDef->SetDescription("Feature class for buffer layer");
Exemple #20
0
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);
}
 private function HandleMethodSingle($uriParts, $id, $extension, $method)
 {
     $uriPath = self::SanitizeUriPath(implode("/", $uriParts));
     $path = realpath($this->app->config("AppRootDir") . "/" . $this->app->config("GeoRest.ConfigPath") . "/{$uriPath}/restcfg.json");
     if ($path === false) {
         $this->NotFound($this->app->localizer->getText("E_NO_DATA_CONFIGURATION_FOR_URI", $uriPath), MgMimeType::Json);
     } else {
         $config = json_decode(file_get_contents($path), true);
         $result = $this->ValidateConfiguration($config, $extension, $method);
         if (!$this->app->container->has($result->adapterName)) {
             throw new Exception($this->app->localizer->getText("E_ADAPTER_NOT_REGISTERED", $result->adapterName));
         }
         $bAllowAnonymous = false;
         if (array_key_exists("AllowAnonymous", $result->config) && $result->config["AllowAnonymous"] == true) {
             $bAllowAnonymous = true;
         }
         try {
             $session = null;
             $extractorName = $result->adapterName . "SessionID";
             if ($this->app->container->has($extractorName)) {
                 $extractor = $this->app->container[$extractorName];
                 $session = $extractor->TryGetSessionId($this->app, $method);
             }
             if ($session == null) {
                 $session = $this->app->request->params("session");
             }
             $this->EnsureAuthenticationForSite($session, $bAllowAnonymous);
             $siteConn = new MgSiteConnection();
             $siteConn->Open($this->userInfo);
             if ($this->ValidateAcl($siteConn, $result->config)) {
                 $this->app->MgSiteConnection = $siteConn;
                 if (property_exists($result, "LayerDefinition")) {
                     $resSvc = $siteConn->CreateService(MgServiceType::ResourceService);
                     self::ApplyFeatureSource($resSvc, $this->app, $result->LayerDefinition);
                 } else {
                     $this->app->FeatureSource = $result->resId;
                     $this->app->FeatureClass = $result->className;
                 }
                 $this->app->AdapterConfig = $result->config;
                 $this->app->ConfigPath = dirname($path);
                 $this->app->IdentityProperty = $result->IdentityProperty;
                 $adapter = $this->app->container[$result->adapterName];
                 $adapter->SetFeatureId($id);
                 $adapter->HandleMethod($method, true);
             } else {
                 $this->Forbidden($this->app->localizer->getText("E_FORBIDDEN_ACCESS"), $this->GetMimeTypeForFormat($extension));
             }
         } catch (MgException $ex) {
             $this->OnException($ex, $this->GetMimeTypeForFormat($extension));
         }
     }
 }
Exemple #22
0
    <body>

        <?php 
$username = "******";
$password = "******";
try {
    $thisFile = __FILE__;
    $pos = strrpos($thisFile, '\\');
    if ($pos == false) {
        $pos = strrpos($thisFile, '/');
    }
    $configFilePath = substr($thisFile, 0, $pos + 1) . "../webconfig.ini";
    MgInitializeWebTier($configFilePath);
    $userInfo = new MgUserInformation($username, $password);
    $site = new MgSiteConnection();
    $site->Open($userInfo);
    $sessionId = $site->GetSite()->CreateSession();
} catch (MgException $e) {
    echo $e->GetExceptionMessage();
}
?>

        <h1><?php 
echo DisplayHeadings::MainHeading;
?>
</h1>

        <form action="describeschema.php" method="get">
            <?php 
echo FormText::InputResourceId;
Exemple #23
0
    </script>
</head>

<body>

<?php 
include '../utilityfunctions.php';
include 'findaddressfunctions.php';
$mgSessionId = $_SERVER['REQUEST_METHOD'] == "POST" ? $_POST['SESSION'] : $_GET['SESSION'];
$showPreviousResults = false;
try {
    // Initialize the Web Extensions and connect to the Server using
    // the Web Extensions session identifier stored in PHP session state.
    MgInitializeWebTier($configFilePath);
    $userInfo = new MgUserInformation($mgSessionId);
    $siteConnection = new MgSiteConnection();
    $siteConnection->Open($userInfo);
    // Create a ReserviceService object and use it to open the Map
    // object from the sessions repository. Use the Map object to
    // determine if the "AddressMarker" layer is visible.
    $resourceService = $siteConnection->CreateService(MgServiceType::ResourceService);
    $map = new MgMap();
    $map->Open($resourceService, 'Sheboygan');
    $addressLayer = GetLayerByName($map, 'AddressMarker');
    if ($addressLayer != null) {
        $showPreviousResults = $addressLayer->GetVisible();
    }
} catch (MgException $e) {
    echo $e->GetExceptionMessage();
    echo $e->GetDetails();
}
Exemple #24
0
        $wkt = new MgWktReaderWriter();
        $agf = new MgAgfReaderWriter();
        $geom = $wkt->Read("POLYGON ((20 20, 20 100, 120 100, 140 20, 20 20))");
        $geomReader = $agf->Write($geom);
        $geomProp = new MgGeometryProperty("GEOM", $geomReader);
        $props->Add($geomProp);
        $cmd = new MgInsertFeatures("StringKey", $props);
        return $cmd;
    }
    function ValidateFeature($key, $featureReader)
    {
    }
}
try {
    Utils::MapAgentInit(WEBCONFIGINI);
    $site = new MgSiteConnection();
    $cred = new MgUserInformation();
    $cred->SetMgUsernamePassword("Administrator", "admin");
    $cred->SetLocale("en");
    $site->Open($cred);
    $fsvc = $site->CreateService(MgServiceType::FeatureService);
    $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");
Exemple #25
0
     session_start();
     /* current user is re-authenticating or not? */
     if (isset($_REQUEST['username']) && isset($_REQUEST['password'])) {
         $user = new MgUserInformation($_REQUEST['username'], $_REQUEST['password']);
         $user->SetClientIp(GetClientIp());
         $user->SetClientAgent(GetClientAgent());
         $user->SetMgSessionId($sessionID);
     } else {
         $user = new MgUserInformation($sessionID);
         $user->SetClientIp(GetClientIp());
         $user->SetClientAgent(GetClientAgent());
     }
     /* open a connection to the site.  This will generate exceptions if the user
      * is set up properly - not found, invalid password etc
      */
     $siteConnection = new MgSiteConnection();
     $siteConnection->Open($user);
     /* MgUserInformation doesn't tell us who is logged in so we store it
      * in the php session for convenience
      */
     if (isset($_REQUEST['username']) && isset($_REQUEST['password'])) {
         $_SESSION['username'] = $_REQUEST['username'];
     }
     //echo "<current user: >".$_SESSION['username']. '</current>';
 }
 //common resource service to be used by all scripts
 $resourceService = $siteConnection->CreateService(MgServiceType::ResourceService);
 if (isset($_REQUEST['mapname'])) {
     $mapName = $_REQUEST['mapname'];
     $mapResourceID = new MgResourceIdentifier('Session:' . $sessionID . '//' . $mapName . '.MapDefinition');
     $mapStateID = new MgResourceIdentifier('Session:' . $sessionID . '//' . $mapName . '.' . MgResourceType::Map);
 public function GetLayerKml($resId, $format = "kml")
 {
     //Check for unsupported representations
     $fmt = $this->ValidateRepresentation($format, array("kml", "kmz"));
     $width = $this->GetRequestParameter("width", null);
     $height = $this->GetRequestParameter("height", null);
     $drawOrder = $this->GetRequestParameter("draworder", null);
     $dpi = $this->GetRequestParameter("dpi", 96);
     $bbox = $this->GetRequestParameter("bbox", null);
     $extents = null;
     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));
     } else {
         $parts = explode(",", $bbox);
         if (count($parts) == 4) {
             $extents = new MgEnvelope($parts[0], $parts[1], $parts[2], $parts[3]);
         }
     }
     $sessionId = "";
     if ($resId->GetRepositoryType() == MgRepositoryType::Session) {
         $sessionId = $resId->GetRepositoryName();
     } else {
         $sessionId = $this->GetRequestParameter("session", "");
     }
     $this->EnsureAuthenticationForSite($sessionId, true);
     $siteConn = new MgSiteConnection();
     if ($sessionId !== "") {
         $userInfo = new MgUserInformation($sessionId);
         $siteConn->Open($userInfo);
     } else {
         $siteConn->Open($this->userInfo);
         $site = $siteConn->GetSite();
         $sessionId = $site->CreateSession();
         $userInfo = new MgUserInformation($sessionId);
         $siteConn->Open($userInfo);
     }
     $csFactory = new MgCoordinateSystemFactory();
     $csObj = $csFactory->CreateFromCode("LL84");
     $scale = MgUtils::GetScale($extents, $csObj, $width, $height, $dpi);
     $writer = new MgSlimChunkWriter($this->app);
     $doc = new MgKmlDocument($writer);
     $resSvc = $siteConn->CreateService(MgServiceType::ResourceService);
     $featSvc = $siteConn->CreateService(MgServiceType::FeatureService);
     $ldfContent = $resSvc->GetResourceContent($resId);
     $xml = new DOMDocument();
     $xml->loadXML($ldfContent->ToString());
     $destExtent = self::GetLayerExtent($csFactory, $xml, $csObj, $featSvc, $resSvc);
     $doc->StartDocument();
     $doc->WriteString("<visibility>1</visibility>");
     if ($destExtent != null) {
         $widthMeters = $csObj->ConvertCoordinateSystemUnitsToMeters($destExtent->GetWidth());
         $heightMeters = $csObj->ConvertCoordinateSystemUnitsToMeters($destExtent->GetHeight());
         $dimension = sqrt($widthMeters * $heightMeters);
         $vlNodes = $xml->getElementsByTagName("VectorLayerDefinition");
         $glNodes = $xml->getElementsByTagName("GridLayerDefinition");
         $dlNodes = $xml->getElementsByTagName("DrawingLayerDefinition");
         if ($vlNodes->length == 1) {
             $scaleRangeNodes = $vlNodes->item(0)->getElementsByTagName("VectorScaleRange");
             for ($i = 0; $i < $scaleRangeNodes->length; $i++) {
                 $scaleRange = $scaleRangeNodes->item($i);
                 $minElt = $scaleRange->getElementsByTagName('MinScale');
                 $maxElt = $scaleRange->getElementsByTagName('MaxScale');
                 $minScale = "0";
                 $maxScale = 'infinity';
                 // as MDF's VectorScaleRange::MAX_MAP_SCALE
                 if ($minElt->length > 0) {
                     $minScale = $minElt->item(0)->nodeValue;
                 }
                 if ($maxElt->length > 0) {
                     $maxScale = $maxElt->item(0)->nodeValue;
                 }
                 if ($minScale != 'infinity') {
                     $minScale = intval($minScale);
                 }
                 if ($maxScale != 'infinity') {
                     $maxScale = intval($maxScale);
                 } else {
                     $maxScale = 1000000000000.0;
                 }
                 // as MDF's VectorScaleRange::MAX_MAP_SCALE
                 if ($scale > $minScale && $scale <= $maxScale) {
                     $this->AppendScaleRange($resId, $destExtent, $dimension, $minScale, $maxScale, $dpi, $drawOrder, $format, $sessionId, $doc);
                 }
             }
         } else {
             if ($glNodes->length == 1) {
             }
         }
     }
     $doc->EndDocument();
 }
 /**
  * Handles GET requests for this adapter. Overridable. Does nothing if not overridden.
  */
 public function HandleGet($single)
 {
     try {
         //Apply any overrides from query string
         $ovWidth = $this->app->request->get("width");
         $ovHeight = $this->app->request->get("height");
         $ovDpi = $this->app->request->get("dpi");
         $ovScale = $this->app->request->get("scale");
         if ($ovWidth != null) {
             $this->imgWidth = $ovWidth;
         }
         if ($ovHeight != null) {
             $this->imgHeight = $ovHeight;
         }
         if ($ovDpi != null) {
             $this->dpi = $ovDpi;
         }
         if ($ovScale != null) {
             $this->viewScale = intval($ovScale);
         }
         $site = $this->siteConn->GetSite();
         $this->sessionId = $site->GetCurrentSession();
         $bCreatedSession = false;
         if ($this->sessionId === "") {
             $this->sessionId = $site->CreateSession();
             $bCreatedSession = true;
         }
         $userInfo = new MgUserInformation($this->sessionId);
         $siteConn = new MgSiteConnection();
         $siteConn->Open($userInfo);
         $this->resSvc = $siteConn->CreateService(MgServiceType::ResourceService);
         $this->featSvc = $siteConn->CreateService(MgServiceType::FeatureService);
         $mapName = "MapImageAdapter";
         $this->map = new MgMap($siteConn);
         $this->map->Create($this->mapDefId, $mapName);
         $this->sel = new MgSelection($this->map);
         $mapId = new MgResourceIdentifier("Session:" . $this->sessionId . "//{$mapName}.Map");
         $this->map->Save($this->resSvc, $mapId);
         $layers = $this->map->GetLayers();
         $idx = $layers->IndexOf($this->selLayerName);
         if ($idx < 0) {
             throw new Exception($this->app->localizer->getText("E_LAYER_NOT_FOUND_IN_MAP", $this->selLayerName));
         }
         $layer = $layers->GetItem($idx);
         if ($layer->GetFeatureSourceId() !== $this->featureSourceId->ToString()) {
             throw new Exception($this->app->localizer->getText("E_LAYER_NOT_POINTING_TO_EXPECTED_FEATURE_SOURCE", $this->selLayerName, $this->featureSourceId->ToString(), $layer->GetFeatureSourceId()));
         }
         $this->selLayer = $layer;
         $query = $this->CreateQueryOptions($single);
         $reader = $this->featSvc->SelectFeatures($this->featureSourceId, $this->className, $query);
         $start = -1;
         $end = -1;
         $read = 0;
         $limit = $this->limit;
         $pageNo = $this->app->request->get("page");
         if ($pageNo == null) {
             $pageNo = 1;
         } else {
             $pageNo = intval($pageNo);
         }
         $bEndOfReader = false;
         if ($this->pageSize > 0) {
             if ($pageNo > 1) {
                 $skipThisMany = ($pageNo - 1) * $this->pageSize - 1;
                 //echo "skip this many: $skipThisMany<br/>";
                 $bEndOfReader = true;
                 while ($reader->ReadNext()) {
                     if ($read == $skipThisMany) {
                         $bEndOfReader = false;
                         $limit = min($skipThisMany + $this->pageSize, $this->limit - 1) - $read;
                         break;
                     }
                     $read++;
                 }
             } else {
                 //first page, set limit to page size
                 $limit = $this->pageSize;
             }
         }
         //echo "read: $read, limit: $limit, pageSize: ".$this->pageSize." result limit: ".$this->limit;
         //die;
         $this->sel->AddFeatures($this->selLayer, $reader, $limit);
         $reader->Close();
         $this->sel->Save($this->resSvc, $mapName);
         $extents = $this->sel->GetExtents($this->featSvc);
         $extLL = $extents->GetLowerLeftCoordinate();
         $extUR = $extents->GetUpperRightCoordinate();
         $x = ($extLL->GetX() + $extUR->GetX()) / 2.0;
         $y = ($extLL->GetY() + $extUR->GetY()) / 2.0;
         if ($this->viewScale === 0) {
             $csFactory = new MgCoordinateSystemFactory();
             $cs = $csFactory->Create($this->map->GetMapSRS());
             $metersPerUnit = $cs->ConvertCoordinateSystemUnitsToMeters(1.0);
             $mcsH = $extUR->GetY() - $extLL->GetY();
             $mcsW = $extUR->GetX() - $extLL->GetX();
             $mcsH = $mcsH * $this->zoomFactor;
             $mcsW = $mcsW * $this->zoomFactor;
             $metersPerPixel = 0.0254 / $this->dpi;
             if ($this->imgHeight * $mcsW > $this->imgWidth * $mcsH) {
                 $this->viewScale = $mcsW * $metersPerUnit / ($this->imgWidth * $metersPerPixel);
             } else {
                 $this->viewScale = $mcsH * $metersPerUnit / ($this->imgHeight * $metersPerPixel);
             }
             // height-limited
         }
         $req = new MgHttpRequest("");
         $param = $req->GetRequestParam();
         $param->AddParameter("OPERATION", "GETMAPIMAGE");
         $param->AddParameter("VERSION", "1.0.0");
         $param->AddParameter("SESSION", $this->sessionId);
         $param->AddParameter("LOCALE", $this->app->config("Locale"));
         $param->AddParameter("CLIENTAGENT", "MapGuide REST Extension");
         $param->AddParameter("CLIENTIP", $this->GetClientIp());
         $param->AddParameter("FORMAT", $this->imgFormat);
         $param->AddParameter("MAPNAME", $mapName);
         $param->AddParameter("KEEPSELECTION", "1");
         $param->AddParameter("SETDISPLAYWIDTH", $this->imgWidth);
         $param->AddParameter("SETDISPLAYHEIGHT", $this->imgHeight);
         $param->AddParameter("SETDISPLAYDPI", $this->dpi);
         $param->AddParameter("SETVIEWCENTERX", $x);
         $param->AddParameter("SETVIEWCENTERY", $y);
         $param->AddParameter("SETVIEWSCALE", $this->viewScale);
         $param->AddParameter("BEHAVIOR", 3);
         //Layers + Selection
         //Apply file download parameters if specified
         if ($this->app->request->params("download") === "1" || $this->app->request->params("download") === "true") {
             $param->AddParameter("X-DOWNLOAD-ATTACHMENT", "true");
             if ($this->app->request->params("downloadname")) {
                 $param->AddParameter("X-DOWNLOAD-ATTACHMENT-NAME", $this->app->request->params("downloadname"));
             }
         }
         $this->ExecuteHttpRequest($req);
         if ($bCreatedSession === true) {
             $conn2 = new MgSiteConnection();
             $user2 = new MgUserInformation($this->sessionId);
             $conn2->Open($user2);
             $site2 = $conn2->GetSite();
             $site2->DestroySession($this->sessionId);
         }
     } catch (MgException $ex) {
         $this->OnException($ex);
     }
 }
Exemple #28
0
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
//
require_once '../common/common.php';
$args = $_SERVER['REQUEST_METHOD'] == "POST" ? $_POST : $_GET;
$sessionId = $args['SESSION'];
$mapName = $args['MAPNAME'];
try {
    // Initialize the Web Extensions and connect to the server using
    // the Web Extensions session identifier stored in PHP session state.
    MgInitializeWebTier($webconfigFilePath);
    $userInfo = new MgUserInformation($sessionId);
    $siteConnection = new MgSiteConnection();
    $siteConnection->Open($userInfo);
    // Create an instance of ResourceService and use that to open the
    // current map instance stored in session state.
    $resourceService = $siteConnection->CreateService(MgServiceType::ResourceService);
    $map = new MgMap();
    $map->Open($resourceService, $mapName);
    $mappingService = $siteConnection->CreateService(MgServiceType::MappingService);
    $dwfVersion = new MgDwfVersion("6.01", "1.2");
    $plotSpec = new MgPlotSpecification(8.5, 11, MgPageUnitsType::Inches);
    $plotSpec->SetMargins(0.5, 0.5, 0.5, 0.5);
    $layoutRes = new MgResourceIdentifier("Library://Samples/Sheboygan/Layouts/SheboyganMap.PrintLayout");
    $layout = new MgLayout($layoutRes, "City of Sheboygan", MgPageUnitsType::Inches);
    $byteReader = $mappingService->GeneratePlot($map, $plotSpec, $layout, $dwfVersion);
    // Now output the resulting DWF.
    $outputBuffer = '';
<?php

include 'resizableadmin.php';
LoadSessionVars();
// Did the user logout?
CheckForLogout();
$mapDefiniton = $_GET["mapDefinition"];
$siteConn = new MgSiteConnection();
$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
Exemple #30
0
include 'common.php';
include 'constants.php';
$mapName = "";
$sessionId = "";
$inputSel = "";
$layers = null;
$dwf = 0;
GetRequestParameters();
try {
    InitializeWebTier();
    $cred = new MgUserInformation($sessionId);
    $cred->SetClientIp(GetClientIp());
    $cred->SetClientAgent(GetClientAgent());
    //connect to the site and get an instance of each service used in this script
    //
    $site = new MgSiteConnection();
    $site->Open($cred);
    $featureSrvc = $site->CreateService(MgServiceType::FeatureService);
    $renderingSrvc = $site->CreateService(MgServiceType::RenderingService);
    $resourceSrvc = $site->CreateService(MgServiceType::ResourceService);
    //load the map runtime state
    //
    $map = new MgMap();
    $map->Open($resourceSrvc, $mapName);
    $layers = explode(",", $layers);
    if (count($layers) > 0) {
        $layerNames = new MgStringCollection();
        for ($i = 0; $i < count($layers); $i++) {
            $layerNames->Add($layers[$i]);
        }
        // create a multi-polygon or a multi-geometry containing the input selected features