<commit_before><?php

//
//  Copyright (C) 2014 by <NAME>
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of version 2.1 of the GNU Lesser
//  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 "controller.php";

class MgTileServiceController extends MgBaseController {
    public function __construct($app) {
        parent::__construct($app);
    }

    private static function GetFolderName($prefix, $index, $tilesPerFolder = 30) {
        $folder = "";
        $folderIndex = floor($index / $tilesPerFolder);
        $firstTileIndex = floor($folderIndex * $tilesPerFolder);
        if ($index < 0 && $firstTileIndex === 0) {
            $folder = "-0";
        } else {
            $folder = "$firstTileIndex";
        }
        return $prefix.$folder;
    }

    private static function GetTileIndexString($index, $tilesPerFolder = 30) {
        $name = "";
        $tnIndex = $index % $tilesPerFolder;
        if ($index < 0 && $tnIndex === 0) {
            $name = "-0";
        } else {
            $name = "$tnIndex";
        }
        return $name;
    }

    public function GetTileModificationDate($mapDefIdStr, $groupName, $scaleIndex, $row, $col) {
        $tileCacheName = str_replace("Library://", "", $mapDefIdStr);
        $tileCacheName = str_replace(".MapDefinition", "", $tileCacheName);
        $tileCacheName = str_replace("/", "_", $tileCacheName);
        $path = sprintf("%s/%s/S%s/%s/%s/%s/%s_%s.%s",
                        $this->app->config("MapGuide.PhysicalTilePath"),
                        $tileCacheName,
                        $scaleIndex,
                        $groupName,
                        MgTileServiceController::GetFolderName("R", $row),
                        MgTileServiceController::GetFolderName("C", $col),
                        MgTileServiceController::GetTileIndexString($row),
                        MgTileServiceController::GetTileIndexString($col),
                        $this->app->config("MapGuide.TileImageFormat"));
        //var_dump($path);
        //die;
        $path = str_replace("/", DIRECTORY_SEPARATOR, $path);
        if (file_exists($path)) {
            return filemtime($path);
        } else {
            //$this->app->response->header("X-Debug-Message", "Could not fetch mtime of $path. File does not exist");
            return false;
        }
    }

    private function GetTileImage($resId, $groupName, $scaleIndex, $row, $col) {
        $resIdStr = $resId->ToString();
        $that = $this;
        $app = $this->app;
        $sessionId = "";
        if ($resId->GetRepositoryType() === MgRepositoryType::Session && $this->app->request->get("session") == null) {
            $sessionId = $resId->GetRepositoryName();
        }

        $this->EnsureAuthenticationForHttp(function($req, $param) use ($app, $that, $resIdStr, $groupName, $scaleIndex, $row, $col) {

            $tmd = $that->GetTileModificationDate($resIdStr, $groupName, $scaleIndex, $row, $col);
            if ($tmd !== FALSE) {
                $app->lastModified($tmd);
            }

            $param->AddParameter("OPERATION", "GETTILEIMAGE");
            $param->AddParameter("VERSION", "1.2.0");
            $param->AddParameter("MAPDEFINITION", $resIdStr);
            $param->AddParameter("BASEMAPLAYERGROUPNAME", $groupName);
            $param->AddParameter("SCALEINDEX", $scaleIndex);
            $param->AddParameter("TILEROW", $row);
            $param->AddParameter("TILECOL", $col);
            $that->ExecuteHttpRequest($req);

            $tmd = $that->GetTileModificationDate($resIdStr, $groupName, $scaleIndex, $row, $col);
            if ($tmd !== FALSE) {
                $app->lastModified($tmd);
            }
            $app->expires("+6 months");
            $app->response->header("Cache-Control", "max-age=31536000, must-revalidate");
        }, 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
    }

    private static function GetTransform($featSvc, $featureSourceId, $clsDef, $targetWkt, $factory) {
        $transform = null;
        //Has a designated geometry property, use it's spatial context
        if ($clsDef->GetDefaultGeometryPropertyName() !== "") {
            $props = $clsDef->GetProperties();
            $idx = $props->IndexOf($clsDef->GetDefaultGeometryPropertyName());
            if ($idx >= 0) {
                $geomProp = $props->GetItem($idx);
                $scName = $geomProp->GetSpatialContextAssociation();
                $scReader = $featSvc->GetSpatialContexts($featureSourceId, false);
                while ($scReader->ReadNext()) {
                    if ($scReader->GetName() === $scName) {
                        if ($scReader->GetCoordinateSystemWkt() !== $targetWkt) {
                            $targetCs = $factory->Create($targetWkt);
                            $sourceCs = $factory->Create($scReader->GetCoordinateSystemWkt());
                            $transform = $factory->GetTransform($sourceCs, $targetCs);
                            break;
                        }
                    }
                }
                $scReader->Close();
            }
        }
        return $transform;
    }

    private static function IsLayerVisibleAtScale($layer, $resSvc, $scale) {
        $ldfId = $layer->GetLayerDefinition();
        $layerContent = $resSvc->GetResourceContent($ldfId);
        $doc = new DOMDocument();
        $doc->loadXML($layerContent->ToString());
        $scaleRangeNodes = $doc->getElementsByTagName("VectorScaleRange");
        for ($i = 0; $i < $scaleRangeNodes->length; $i++) {
            $scaleRangeNode = $scaleRangeNodes->item($i);

            $minEl = $scaleRangeNode->getElementsByTagName("MinScale");
            $maxEl = $scaleRangeNode->getElementsByTagName("MaxScale");

            $minScale = 0;
            $maxScale = 1000000000000.0; //MdfModel::ScaleRange::MAX_MAP_SCALE
            if ($minEl->length > 0)
                $minScale = floatval($minEl->item(0)->nodeValue);
            if ($maxEl->length > 0)
                $maxScale = floatval($maxEl->item(0)->nodeValue);

            if ($scale >= $minScale && $scale < $maxScale)
                return true;
        }
        return false;
    }

    private static function GetTilePath($app, $resId, $groupName, $z, $x, $y, $type) {
        $relPath = "/".$resId->GetPath()."/".$resId->GetName()."/$groupName/$z/$x/$y.$type";
        $path = $app->config("AppRootDir")."/".$app->config("Cache.RootDir")."/tile.$type".$relPath;
        return $path;
    }

    private static function GetScaleFromBounds($map, $devW, $devH, $metersPerUnit, $boundsMinX, $boundsMinY, $boundsMaxX, $boundsMaxY) {
        $mcsW = $boundsMaxX - $boundsMinX;
        $mcsH = $boundsMaxY - $boundsMinY;
        $metersPerPixel = 0.0254 / $map->GetDisplayDpi();
        if ($devH * $mcsW > $devW * $mcsH)
            return $mcsW * $metersPerUnit / ($devW * $metersPerPixel); // width-limited
        else
            return $mcsH * $metersPerUnit / ($devH * $metersPerPixel); // height-limited
    }

    private function PutVectorTileXYZ($map, $groupName, $siteConn, $metersPerUnit, $csFactory, $path, $boundsMinx, $boundsMinY, $boundsMaxX, $boundsMaxY) {
        $wktRw = new MgWktReaderWriter();
        $agfRw = new MgAgfReaderWriter();

        $resSvc = $siteConn->CreateService(MgServiceType::ResourceService);
        $featSvc = $siteConn->CreateService(MgServiceType::FeatureService);
        $mapCsWkt = $map->GetMapSRS();
        $layers = $map->GetLayers();
        $groups = $map->GetLayerGroups();
        $baseGroup = $groups->GetItem($groupName);
        $layerCount = $layers->GetCount();
        $firstFeature = true;
<commit_msg>When generating PNG8 tiles, use a .png extension.<commit_after><?php

//
//  Copyright (C) 2014 by <NAME>
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of version 2.1 of the GNU Lesser
//  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 "controller.php";

class MgTileServiceController extends MgBaseController {
    public function __construct($app) {
        parent::__construct($app);
    }

    private static function GetFolderName($prefix, $index, $tilesPerFolder = 30) {
        $folder = "";
        $folderIndex = floor($index / $tilesPerFolder);
        $firstTileIndex = floor($folderIndex * $tilesPerFolder);
        if ($index < 0 && $firstTileIndex === 0) {
            $folder = "-0";
        } else {
            $folder = "$firstTileIndex";
        }
        return $prefix.$folder;
    }

    private static function GetTileIndexString($index, $tilesPerFolder = 30) {
        $name = "";
        $tnIndex = $index % $tilesPerFolder;
        if ($index < 0 && $tnIndex === 0) {
            $name = "-0";
        } else {
            $name = "$tnIndex";
        }
        return $name;
    }

    public function GetTileModificationDate($mapDefIdStr, $groupName, $scaleIndex, $row, $col) {
        $tileCacheName = str_replace("Library://", "", $mapDefIdStr);
        $tileCacheName = str_replace(".MapDefinition", "", $tileCacheName);
        $tileCacheName = str_replace("/", "_", $tileCacheName);
        $path = sprintf("%s/%s/S%s/%s/%s/%s/%s_%s.%s",
                        $this->app->config("MapGuide.PhysicalTilePath"),
                        $tileCacheName,
                        $scaleIndex,
                        $groupName,
                        MgTileServiceController::GetFolderName("R", $row),
                        MgTileServiceController::GetFolderName("C", $col),
                        MgTileServiceController::GetTileIndexString($row),
                        MgTileServiceController::GetTileIndexString($col),
                        $this->app->config("MapGuide.TileImageFormat"));
        //var_dump($path);
        //die;
        $path = str_replace("/", DIRECTORY_SEPARATOR, $path);
        if (file_exists($path)) {
            return filemtime($path);
        } else {
            //$this->app->response->header("X-Debug-Message", "Could not fetch mtime of $path. File does not exist");
            return false;
        }
    }

    private function GetTileImage($resId, $groupName, $scaleIndex, $row, $col) {
        $resIdStr = $resId->ToString();
        $that = $this;
        $app = $this->app;
        $sessionId = "";
        if ($resId->GetRepositoryType() === MgRepositoryType::Session && $this->app->request->get("session") == null) {
            $sessionId = $resId->GetRepositoryName();
        }

        $this->EnsureAuthenticationForHttp(function($req, $param) use ($app, $that, $resIdStr, $groupName, $scaleIndex, $row, $col) {

            $tmd = $that->GetTileModificationDate($resIdStr, $groupName, $scaleIndex, $row, $col);
            if ($tmd !== FALSE) {
                $app->lastModified($tmd);
            }

            $param->AddParameter("OPERATION", "GETTILEIMAGE");
            $param->AddParameter("VERSION", "1.2.0");
            $param->AddParameter("MAPDEFINITION", $resIdStr);
            $param->AddParameter("BASEMAPLAYERGROUPNAME", $groupName);
            $param->AddParameter("SCALEINDEX", $scaleIndex);
            $param->AddParameter("TILEROW", $row);
            $param->AddParameter("TILECOL", $col);
            $that->ExecuteHttpRequest($req);

            $tmd = $that->GetTileModificationDate($resIdStr, $groupName, $scaleIndex, $row, $col);
            if ($tmd !== FALSE) {
                $app->lastModified($tmd);
            }
            $app->expires("+6 months");
            $app->response->header("Cache-Control", "max-age=31536000, must-revalidate");
        }, 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
    }

    private static function GetTransform($featSvc, $featureSourceId, $clsDef, $targetWkt, $factory) {
        $transform = null;
        //Has a designated geometry property, use it's spatial context
        if ($clsDef->GetDefaultGeometryPropertyName() !== "") {
            $props = $clsDef->GetProperties();
            $idx = $props->IndexOf($clsDef->GetDefaultGeometryPropertyName());
            if ($idx >= 0) {
                $geomProp = $props->GetItem($idx);
                $scName = $geomProp->GetSpatialContextAssociation();
                $scReader = $featSvc->GetSpatialContexts($featureSourceId, false);
                while ($scReader->ReadNext()) {
                    if ($scReader->GetName() === $scName) {
                        if ($scReader->GetCoordinateSystemWkt() !== $targetWkt) {
                            $targetCs = $factory->Create($targetWkt);
                            $sourceCs = $factory->Create($scReader->GetCoordinateSystemWkt());
                            $transform = $factory->GetTransform($sourceCs, $targetCs);
                            break;
                        }
                    }
                }
                $scReader->Close();
            }
        }
        return $transform;
    }

    private static function IsLayerVisibleAtScale($layer, $resSvc, $scale) {
        $ldfId = $layer->GetLayerDefinition();
        $layerContent = $resSvc->GetResourceContent($ldfId);
        $doc = new DOMDocument();
        $doc->loadXML($layerContent->ToString());
        $scaleRangeNodes = $doc->getElementsByTagName("VectorScaleRange");
        for ($i = 0; $i < $scaleRangeNodes->length; $i++) {
            $scaleRangeNode = $scaleRangeNodes->item($i);

            $minEl = $scaleRangeNode->getElementsByTagName("MinScale");
            $maxEl = $scaleRangeNode->getElementsByTagName("MaxScale");

            $minScale = 0;
            $maxScale = 1000000000000.0; //MdfModel::ScaleRange::MAX_MAP_SCALE
            if ($minEl->length > 0)
                $minScale = floatval($minEl->item(0)->nodeValue);
            if ($maxEl->length > 0)
                $maxScale = floatval($maxEl->item(0)->nodeValue);

            if ($scale >= $minScale && $scale < $maxScale)
                return true;
        }
        return false;
    }

    private static function GetTilePath($app, $resId, $groupName, $z, $x, $y, $type) {
        $ext = $type;
        if (strtolower($type) == "png8")
            $ext = substr($type, 0, 3); //png8 -> png
        $relPath = "/".$resId->GetPath()."/".$resId->GetName()."/$groupName/$z/$x/$y.$ext";
        $path = $app->config("AppRootDir")."/".$app->config("Cache.RootDir")."/tile.$type".$relPath;
        return $path;
    }

    private static function GetScaleFromBounds($map, $devW, $devH, $metersPerUnit, $boundsMinX, $boundsMinY, $boundsMaxX, $boundsMaxY) {
        $mcsW = $boundsMaxX - $boundsMinX;
        $mcsH = $boundsMaxY - $boundsMinY;
        $metersPerPixel = 0.0254 / $map->GetDisplayDpi();
        if ($devH * $mcsW > $devW * $mcsH)
            return $mcsW * $metersPerUnit / ($devW * $metersPerPixel); // width-limited
        else
            return $mcsH * $metersPerUnit / ($devH * $metersPerPixel); // height-limited
    }

    private function PutVectorTileXYZ($map, $groupName, $siteConn, $metersPerUnit, $csFactory, $path, $boundsMinx, $boundsMinY, $boundsMaxX, $boundsMaxY) {
        $wktRw = new MgWktReaderWriter();
        $agfRw = new MgAgfReaderWriter();

        $resSvc = $siteConn->CreateService(MgServiceType::ResourceService);
        $featSvc = $siteConn->CreateService(MgServiceType::FeatureService);
        $mapCsWkt = $map->GetMapSRS();
        $layers = $map->GetLayers();
        $groups = $map->GetLayerGroups();
        $baseGroup = $groups->GetItem($groupName);
        $layerCount = $layers->GetCount();
        $firstFeature = true;

{'fraction_non_alphanumeric': 0.14819191680453794, 'fraction_numerical': 0.007976837627038526, 'mean_word_length': 2.2992202729044835, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 160, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 2, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1069804', 'n_tokens_mistral': 5028, 'n_tokens_neox': 4813, 'n_words': 1054}