Update website

This commit is contained in:
Guilhem Lavaux 2024-11-23 20:45:29 +01:00
parent 41ce1aa076
commit ea0eb1c6e0
4222 changed files with 721797 additions and 14 deletions

View file

@ -0,0 +1,54 @@
<?php
/**
* Contains the factory class that handles the creation of geometric objects
*/
declare(strict_types=1);
namespace PhpMyAdmin\Gis;
use function strtoupper;
/**
* Factory class that handles the creation of geometric objects.
*/
class GisFactory
{
/**
* Returns the singleton instance of geometric class of the given type.
*
* @param string $type type of the geometric object
*
* @return GisGeometry|false the singleton instance of geometric class of the given type
*
* @static
*/
public static function factory($type)
{
switch (strtoupper($type)) {
case 'MULTIPOLYGON':
return GisMultiPolygon::singleton();
case 'POLYGON':
return GisPolygon::singleton();
case 'MULTIPOINT':
return GisMultiPoint::singleton();
case 'POINT':
return GisPoint::singleton();
case 'MULTILINESTRING':
return GisMultiLineString::singleton();
case 'LINESTRING':
return GisLineString::singleton();
case 'GEOMETRYCOLLECTION':
return GisGeometryCollection::singleton();
default:
return false;
}
}
}

View file

@ -0,0 +1,382 @@
<?php
/**
* Base class for all GIS data type classes
*/
declare(strict_types=1);
namespace PhpMyAdmin\Gis;
use PhpMyAdmin\Image\ImageWrapper;
use TCPDF;
use function explode;
use function floatval;
use function mb_strripos;
use function mb_substr;
use function mt_getrandmax;
use function preg_match;
use function random_int;
use function sprintf;
use function str_replace;
use function trim;
/**
* Base class for all GIS data type classes.
*/
abstract class GisGeometry
{
/**
* Prepares and returns the code related to a row in the GIS dataset as SVG.
*
* @param string $spatial GIS data object
* @param string $label label for the GIS data object
* @param string $color color for the GIS data object
* @param array $scale_data data related to scaling
*
* @return string the code related to a row in the GIS dataset
*/
abstract public function prepareRowAsSvg($spatial, $label, $color, array $scale_data);
/**
* Adds to the PNG image object, the data related to a row in the GIS dataset.
*
* @param string $spatial GIS POLYGON object
* @param string|null $label Label for the GIS POLYGON object
* @param string $color Color for the GIS POLYGON object
* @param array $scale_data Array containing data related to scaling
*/
abstract public function prepareRowAsPng(
$spatial,
?string $label,
$color,
array $scale_data,
ImageWrapper $image
): ImageWrapper;
/**
* Adds to the TCPDF instance, the data related to a row in the GIS dataset.
*
* @param string $spatial GIS data object
* @param string|null $label label for the GIS data object
* @param string $color color for the GIS data object
* @param array $scale_data array containing data related to scaling
* @param TCPDF $pdf TCPDF instance
*
* @return TCPDF the modified TCPDF instance
*/
abstract public function prepareRowAsPdf(
$spatial,
?string $label,
$color,
array $scale_data,
$pdf
);
/**
* Prepares the JavaScript related to a row in the GIS dataset
* to visualize it with OpenLayers.
*
* @param string $spatial GIS data object
* @param int $srid spatial reference ID
* @param string $label label for the GIS data object
* @param array $color color for the GIS data object
* @param array $scale_data array containing data related to scaling
*
* @return string the JavaScript related to a row in the GIS dataset
*/
abstract public function prepareRowAsOl(
$spatial,
int $srid,
$label,
$color,
array $scale_data
);
/**
* Scales each row.
*
* @param string $spatial spatial data of a row
*
* @return array array containing the min, max values for x and y coordinates
*/
abstract public function scaleRow($spatial);
/**
* Generates the WKT with the set of parameters passed by the GIS editor.
*
* @param array $gis_data GIS data
* @param int $index index into the parameter object
* @param string|null $empty value for empty points
*
* @return string WKT with the set of parameters passed by the GIS editor
*/
abstract public function generateWkt(array $gis_data, $index, $empty = '');
/**
* Returns OpenLayers.Bounds object that correspond to the bounds of GIS data.
*
* @param int $srid spatial reference ID
* @param array $scale_data data related to scaling
*
* @return string OpenLayers.Bounds object that
* correspond to the bounds of GIS data
*/
protected function getBoundsForOl(int $srid, array $scale_data)
{
return sprintf(
'var minLoc = [%s, %s];'
. 'var maxLoc = [%s, %s];'
. 'var ext = ol.extent.boundingExtent([minLoc, maxLoc]);'
. 'ext = ol.proj.transformExtent(ext, ol.proj.get("EPSG:%s"), ol.proj.get(\'EPSG:3857\'));'
. 'map.getView().fit(ext, map.getSize());',
$scale_data['minX'],
$scale_data['minY'],
$scale_data['maxX'],
$scale_data['maxY'],
$srid
);
}
/**
* Updates the min, max values with the given point set.
*
* @param string $point_set point set
* @param array $min_max existing min, max values
*
* @return array the updated min, max values
*/
protected function setMinMax($point_set, array $min_max)
{
// Separate each point
$points = explode(',', $point_set);
foreach ($points as $point) {
// Extract coordinates of the point
$cordinates = explode(' ', $point);
$x = (float) $cordinates[0];
if (! isset($min_max['maxX']) || $x > $min_max['maxX']) {
$min_max['maxX'] = $x;
}
if (! isset($min_max['minX']) || $x < $min_max['minX']) {
$min_max['minX'] = $x;
}
$y = (float) $cordinates[1];
if (! isset($min_max['maxY']) || $y > $min_max['maxY']) {
$min_max['maxY'] = $y;
}
if (isset($min_max['minY']) && $y >= $min_max['minY']) {
continue;
}
$min_max['minY'] = $y;
}
return $min_max;
}
/**
* Generates parameters for the GIS data editor from the value of the GIS column.
* This method performs common work.
* More specific work is performed by each of the geom classes.
*
* @param string $value value of the GIS column
*
* @return array parameters for the GIS editor from the value of the GIS column
*/
public function generateParams($value)
{
$geom_types = '(POINT|MULTIPOINT|LINESTRING|MULTILINESTRING|POLYGON|MULTIPOLYGON|GEOMETRYCOLLECTION)';
$srid = 0;
$wkt = '';
if (preg_match("/^'" . $geom_types . "\(.*\)',[0-9]*$/i", $value)) {
$last_comma = mb_strripos($value, ',');
$srid = (int) trim(mb_substr($value, $last_comma + 1));
$wkt = trim(mb_substr($value, 1, $last_comma - 2));
} elseif (preg_match('/^' . $geom_types . '\(.*\)$/i', $value)) {
$wkt = $value;
}
return [
'srid' => $srid,
'wkt' => $wkt,
];
}
/**
* Extracts points, scales and returns them as an array.
*
* @param string $point_set string of comma separated points
* @param array|null $scale_data data related to scaling
* @param bool $linear if true, as a 1D array, else as a 2D array
*
* @return array scaled points
*/
protected function extractPoints($point_set, $scale_data, $linear = false): array
{
$points_arr = [];
// Separate each point
$points = explode(',', $point_set);
foreach ($points as $point) {
$point = str_replace(['(', ')'], '', $point);
// Extract coordinates of the point
$coordinates = explode(' ', $point);
if (isset($coordinates[0], $coordinates[1]) && trim($coordinates[0]) != '' && trim($coordinates[1]) != '') {
if ($scale_data != null) {
$x = ($coordinates[0] - $scale_data['x']) * $scale_data['scale'];
$y = $scale_data['height']
- ($coordinates[1] - $scale_data['y']) * $scale_data['scale'];
} else {
$x = floatval(trim($coordinates[0]));
$y = floatval(trim($coordinates[1]));
}
} else {
$x = 0;
$y = 0;
}
if (! $linear) {
$points_arr[] = [
$x,
$y,
];
} else {
$points_arr[] = $x;
$points_arr[] = $y;
}
}
return $points_arr;
}
/**
* Generates JavaScript for adding an array of polygons to OpenLayers.
*
* @param array $polygons x and y coordinates for each polygon
* @param int $srid spatial reference id
*
* @return string JavaScript for adding an array of polygons to OpenLayers
*/
protected function getPolygonArrayForOpenLayers(array $polygons, int $srid)
{
$ol_array = 'var polygonArray = [];';
foreach ($polygons as $polygon) {
$rings = explode('),(', $polygon);
$ol_array .= $this->getPolygonForOpenLayers($rings, $srid);
$ol_array .= 'polygonArray.push(polygon);';
}
return $ol_array;
}
/**
* Generates JavaScript for adding points for OpenLayers polygon.
*
* @param array $polygon x and y coordinates for each line
* @param int $srid spatial reference id
*
* @return string JavaScript for adding points for OpenLayers polygon
*/
protected function getPolygonForOpenLayers(array $polygon, int $srid)
{
return $this->getLineArrayForOpenLayers($polygon, $srid, false)
. 'var polygon = new ol.geom.Polygon(arr);';
}
/**
* Generates JavaScript for adding an array of LineString
* or LineRing to OpenLayers.
*
* @param array $lines x and y coordinates for each line
* @param int $srid spatial reference id
* @param bool $is_line_string whether it's an array of LineString
*
* @return string JavaScript for adding an array of LineString
* or LineRing to OpenLayers
*/
protected function getLineArrayForOpenLayers(
array $lines,
int $srid,
$is_line_string = true
) {
$ol_array = 'var arr = [];';
foreach ($lines as $line) {
$ol_array .= 'var lineArr = [];';
$points_arr = $this->extractPoints($line, null);
$ol_array .= 'var line = ' . $this->getLineForOpenLayers($points_arr, $srid, $is_line_string) . ';';
$ol_array .= 'var coord = line.getCoordinates();';
$ol_array .= 'for (var i = 0; i < coord.length; i++) lineArr.push(coord[i]);';
$ol_array .= 'arr.push(lineArr);';
}
return $ol_array;
}
/**
* Generates JavaScript for adding a LineString or LineRing to OpenLayers.
*
* @param array $points_arr x and y coordinates for each point
* @param int $srid spatial reference id
* @param bool $is_line_string whether it's a LineString
*
* @return string JavaScript for adding a LineString or LineRing to OpenLayers
*/
protected function getLineForOpenLayers(
array $points_arr,
int $srid,
$is_line_string = true
) {
return 'new ol.geom.'
. ($is_line_string ? 'LineString' : 'LinearRing') . '('
. $this->getPointsArrayForOpenLayers($points_arr, $srid)
. ')';
}
/**
* Generates JavaScript for adding an array of points to OpenLayers.
*
* @param array $points_arr x and y coordinates for each point
* @param int $srid spatial reference id
*
* @return string JavaScript for adding an array of points to OpenLayers
*/
protected function getPointsArrayForOpenLayers(array $points_arr, int $srid)
{
$ol_array = 'new Array(';
foreach ($points_arr as $point) {
$ol_array .= $this->getPointForOpenLayers($point, $srid) . '.getCoordinates(), ';
}
$ol_array = mb_substr($ol_array, 0, -2);
return $ol_array . ')';
}
/**
* Generates JavaScript for adding a point to OpenLayers.
*
* @param array $point array containing the x and y coordinates of the point
* @param int $srid spatial reference id
*
* @return string JavaScript for adding points to OpenLayers
*/
protected function getPointForOpenLayers(array $point, int $srid)
{
return '(new ol.geom.Point([' . $point[0] . ',' . $point[1] . '])'
. '.transform(ol.proj.get("EPSG:' . $srid . '")'
. ', ol.proj.get(\'EPSG:3857\')))';
}
protected function getRandomId(): int
{
return random_int(0, mt_getrandmax());
}
}

View file

@ -0,0 +1,367 @@
<?php
/**
* Handles actions related to GIS GEOMETRYCOLLECTION objects
*/
declare(strict_types=1);
namespace PhpMyAdmin\Gis;
use PhpMyAdmin\Image\ImageWrapper;
use TCPDF;
use function array_merge;
use function count;
use function mb_strpos;
use function mb_substr;
use function str_split;
/**
* Handles actions related to GIS GEOMETRYCOLLECTION objects
*/
class GisGeometryCollection extends GisGeometry
{
/** @var self */
private static $instance;
/**
* A private constructor; prevents direct creation of object.
*/
private function __construct()
{
}
/**
* Returns the singleton.
*
* @return GisGeometryCollection the singleton
*/
public static function singleton()
{
if (! isset(self::$instance)) {
self::$instance = new GisGeometryCollection();
}
return self::$instance;
}
/**
* Scales each row.
*
* @param string $spatial spatial data of a row
*
* @return array array containing the min, max values for x and y coordinates
*/
public function scaleRow($spatial)
{
$min_max = [];
// Trim to remove leading 'GEOMETRYCOLLECTION(' and trailing ')'
$goem_col = mb_substr($spatial, 19, -1);
// Split the geometry collection object to get its constituents.
$sub_parts = $this->explodeGeomCol($goem_col);
foreach ($sub_parts as $sub_part) {
$type_pos = mb_strpos($sub_part, '(');
if ($type_pos === false) {
continue;
}
$type = mb_substr($sub_part, 0, $type_pos);
$gis_obj = GisFactory::factory($type);
if (! $gis_obj) {
continue;
}
$scale_data = $gis_obj->scaleRow($sub_part);
// Update minimum/maximum values for x and y coordinates.
$c_maxX = (float) $scale_data['maxX'];
if (! isset($min_max['maxX']) || $c_maxX > $min_max['maxX']) {
$min_max['maxX'] = $c_maxX;
}
$c_minX = (float) $scale_data['minX'];
if (! isset($min_max['minX']) || $c_minX < $min_max['minX']) {
$min_max['minX'] = $c_minX;
}
$c_maxY = (float) $scale_data['maxY'];
if (! isset($min_max['maxY']) || $c_maxY > $min_max['maxY']) {
$min_max['maxY'] = $c_maxY;
}
$c_minY = (float) $scale_data['minY'];
if (isset($min_max['minY']) && $c_minY >= $min_max['minY']) {
continue;
}
$min_max['minY'] = $c_minY;
}
return $min_max;
}
/**
* Adds to the PNG image object, the data related to a row in the GIS dataset.
*
* @param string $spatial GIS POLYGON object
* @param string|null $label Label for the GIS POLYGON object
* @param string $color Color for the GIS POLYGON object
* @param array $scale_data Array containing data related to scaling
*/
public function prepareRowAsPng(
$spatial,
?string $label,
$color,
array $scale_data,
ImageWrapper $image
): ImageWrapper {
// Trim to remove leading 'GEOMETRYCOLLECTION(' and trailing ')'
$goem_col = mb_substr($spatial, 19, -1);
// Split the geometry collection object to get its constituents.
$sub_parts = $this->explodeGeomCol($goem_col);
foreach ($sub_parts as $sub_part) {
$type_pos = mb_strpos($sub_part, '(');
if ($type_pos === false) {
continue;
}
$type = mb_substr($sub_part, 0, $type_pos);
$gis_obj = GisFactory::factory($type);
if (! $gis_obj) {
continue;
}
$image = $gis_obj->prepareRowAsPng($sub_part, $label, $color, $scale_data, $image);
}
return $image;
}
/**
* Adds to the TCPDF instance, the data related to a row in the GIS dataset.
*
* @param string $spatial GIS GEOMETRYCOLLECTION object
* @param string|null $label label for the GIS GEOMETRYCOLLECTION object
* @param string $color color for the GIS GEOMETRYCOLLECTION object
* @param array $scale_data array containing data related to scaling
* @param TCPDF $pdf TCPDF instance
*
* @return TCPDF the modified TCPDF instance
*/
public function prepareRowAsPdf($spatial, ?string $label, $color, array $scale_data, $pdf)
{
// Trim to remove leading 'GEOMETRYCOLLECTION(' and trailing ')'
$goem_col = mb_substr($spatial, 19, -1);
// Split the geometry collection object to get its constituents.
$sub_parts = $this->explodeGeomCol($goem_col);
foreach ($sub_parts as $sub_part) {
$type_pos = mb_strpos($sub_part, '(');
if ($type_pos === false) {
continue;
}
$type = mb_substr($sub_part, 0, $type_pos);
$gis_obj = GisFactory::factory($type);
if (! $gis_obj) {
continue;
}
$pdf = $gis_obj->prepareRowAsPdf($sub_part, $label, $color, $scale_data, $pdf);
}
return $pdf;
}
/**
* Prepares and returns the code related to a row in the GIS dataset as SVG.
*
* @param string $spatial GIS GEOMETRYCOLLECTION object
* @param string $label label for the GIS GEOMETRYCOLLECTION object
* @param string $color color for the GIS GEOMETRYCOLLECTION object
* @param array $scale_data array containing data related to scaling
*
* @return string the code related to a row in the GIS dataset
*/
public function prepareRowAsSvg($spatial, $label, $color, array $scale_data)
{
$row = '';
// Trim to remove leading 'GEOMETRYCOLLECTION(' and trailing ')'
$goem_col = mb_substr($spatial, 19, -1);
// Split the geometry collection object to get its constituents.
$sub_parts = $this->explodeGeomCol($goem_col);
foreach ($sub_parts as $sub_part) {
$type_pos = mb_strpos($sub_part, '(');
if ($type_pos === false) {
continue;
}
$type = mb_substr($sub_part, 0, $type_pos);
$gis_obj = GisFactory::factory($type);
if (! $gis_obj) {
continue;
}
$row .= $gis_obj->prepareRowAsSvg($sub_part, $label, $color, $scale_data);
}
return $row;
}
/**
* Prepares JavaScript related to a row in the GIS dataset
* to visualize it with OpenLayers.
*
* @param string $spatial GIS GEOMETRYCOLLECTION object
* @param int $srid spatial reference ID
* @param string $label label for the GIS GEOMETRYCOLLECTION object
* @param array $color color for the GIS GEOMETRYCOLLECTION object
* @param array $scale_data array containing data related to scaling
*
* @return string JavaScript related to a row in the GIS dataset
*/
public function prepareRowAsOl($spatial, int $srid, $label, $color, array $scale_data)
{
$row = '';
// Trim to remove leading 'GEOMETRYCOLLECTION(' and trailing ')'
$goem_col = mb_substr($spatial, 19, -1);
// Split the geometry collection object to get its constituents.
$sub_parts = $this->explodeGeomCol($goem_col);
foreach ($sub_parts as $sub_part) {
$type_pos = mb_strpos($sub_part, '(');
if ($type_pos === false) {
continue;
}
$type = mb_substr($sub_part, 0, $type_pos);
$gis_obj = GisFactory::factory($type);
if (! $gis_obj) {
continue;
}
$row .= $gis_obj->prepareRowAsOl($sub_part, $srid, $label, $color, $scale_data);
}
return $row;
}
/**
* Splits the GEOMETRYCOLLECTION object and get its constituents.
*
* @param string $geom_col geometry collection string
*
* @return array the constituents of the geometry collection object
*/
private function explodeGeomCol($geom_col)
{
$sub_parts = [];
$br_count = 0;
$start = 0;
$count = 0;
foreach (str_split($geom_col) as $char) {
if ($char === '(') {
$br_count++;
} elseif ($char === ')') {
$br_count--;
if ($br_count == 0) {
$sub_parts[] = mb_substr($geom_col, $start, $count + 1 - $start);
$start = $count + 2;
}
}
$count++;
}
return $sub_parts;
}
/**
* Generates the WKT with the set of parameters passed by the GIS editor.
*
* @param array $gis_data GIS data
* @param int $index index into the parameter object
* @param string|null $empty value for empty points
*
* @return string WKT with the set of parameters passed by the GIS editor
*/
public function generateWkt(array $gis_data, $index, $empty = '')
{
$geom_count = $gis_data['GEOMETRYCOLLECTION']['geom_count'] ?? 1;
$wkt = 'GEOMETRYCOLLECTION(';
for ($i = 0; $i < $geom_count; $i++) {
if (! isset($gis_data[$i]['gis_type'])) {
continue;
}
$type = $gis_data[$i]['gis_type'];
$gis_obj = GisFactory::factory($type);
if (! $gis_obj) {
continue;
}
$wkt .= $gis_obj->generateWkt($gis_data, $i, $empty) . ',';
}
if (isset($gis_data[0]['gis_type'])) {
$wkt = mb_substr($wkt, 0, -1);
}
return $wkt . ')';
}
/**
* Generates parameters for the GIS data editor from the value of the GIS column.
*
* @param string $value of the GIS column
*
* @return array parameters for the GIS editor from the value of the GIS column
*/
public function generateParams($value)
{
$params = [];
$data = GisGeometry::generateParams($value);
$params['srid'] = $data['srid'];
$wkt = $data['wkt'];
// Trim to remove leading 'GEOMETRYCOLLECTION(' and trailing ')'
$goem_col = mb_substr($wkt, 19, -1);
// Split the geometry collection object to get its constituents.
$sub_parts = $this->explodeGeomCol($goem_col);
$params['GEOMETRYCOLLECTION']['geom_count'] = count($sub_parts);
$i = 0;
foreach ($sub_parts as $sub_part) {
$type_pos = mb_strpos($sub_part, '(');
if ($type_pos === false) {
continue;
}
$type = mb_substr($sub_part, 0, $type_pos);
/**
* @var GisMultiPolygon|GisPolygon|GisMultiPoint|GisPoint|GisMultiLineString|GisLineString $gis_obj
*/
$gis_obj = GisFactory::factory($type);
if (! $gis_obj) {
continue;
}
$params = array_merge($params, $gis_obj->generateParams($sub_part, $i));
$i++;
}
return $params;
}
}

View file

@ -0,0 +1,321 @@
<?php
/**
* Handles actions related to GIS LINESTRING objects
*/
declare(strict_types=1);
namespace PhpMyAdmin\Gis;
use PhpMyAdmin\Image\ImageWrapper;
use TCPDF;
use function count;
use function hexdec;
use function json_encode;
use function mb_substr;
use function round;
use function trim;
/**
* Handles actions related to GIS LINESTRING objects
*/
class GisLineString extends GisGeometry
{
/** @var self */
private static $instance;
/**
* A private constructor; prevents direct creation of object.
*/
private function __construct()
{
}
/**
* Returns the singleton.
*
* @return GisLineString the singleton
*/
public static function singleton()
{
if (! isset(self::$instance)) {
self::$instance = new GisLineString();
}
return self::$instance;
}
/**
* Scales each row.
*
* @param string $spatial spatial data of a row
*
* @return array an array containing the min, max values for x and y coordinates
*/
public function scaleRow($spatial)
{
// Trim to remove leading 'LINESTRING(' and trailing ')'
$linestring = mb_substr($spatial, 11, -1);
return $this->setMinMax($linestring, []);
}
/**
* Adds to the PNG image object, the data related to a row in the GIS dataset.
*
* @param string $spatial GIS POLYGON object
* @param string|null $label Label for the GIS POLYGON object
* @param string $line_color Color for the GIS POLYGON object
* @param array $scale_data Array containing data related to scaling
*/
public function prepareRowAsPng(
$spatial,
?string $label,
$line_color,
array $scale_data,
ImageWrapper $image
): ImageWrapper {
// allocate colors
$black = $image->colorAllocate(0, 0, 0);
$red = (int) hexdec(mb_substr($line_color, 1, 2));
$green = (int) hexdec(mb_substr($line_color, 3, 2));
$blue = (int) hexdec(mb_substr($line_color, 4, 2));
$color = $image->colorAllocate($red, $green, $blue);
$label = trim($label ?? '');
// Trim to remove leading 'LINESTRING(' and trailing ')'
$lineString = mb_substr($spatial, 11, -1);
$points_arr = $this->extractPoints($lineString, $scale_data);
foreach ($points_arr as $point) {
if (isset($temp_point)) {
// draw line section
$image->line(
(int) round($temp_point[0]),
(int) round($temp_point[1]),
(int) round($point[0]),
(int) round($point[1]),
$color
);
}
$temp_point = $point;
}
// print label if applicable
if ($label !== '') {
$image->string(
1,
(int) round($points_arr[1][0]),
(int) round($points_arr[1][1]),
$label,
$black
);
}
return $image;
}
/**
* Adds to the TCPDF instance, the data related to a row in the GIS dataset.
*
* @param string $spatial GIS LINESTRING object
* @param string|null $label Label for the GIS LINESTRING object
* @param string $line_color Color for the GIS LINESTRING object
* @param array $scale_data Array containing data related to scaling
* @param TCPDF $pdf TCPDF instance
*
* @return TCPDF the modified TCPDF instance
*/
public function prepareRowAsPdf($spatial, ?string $label, $line_color, array $scale_data, $pdf)
{
// allocate colors
$red = hexdec(mb_substr($line_color, 1, 2));
$green = hexdec(mb_substr($line_color, 3, 2));
$blue = hexdec(mb_substr($line_color, 4, 2));
$line = [
'width' => 1.5,
'color' => [
$red,
$green,
$blue,
],
];
$label = trim($label ?? '');
// Trim to remove leading 'LINESTRING(' and trailing ')'
$linesrting = mb_substr($spatial, 11, -1);
$points_arr = $this->extractPoints($linesrting, $scale_data);
foreach ($points_arr as $point) {
if (isset($temp_point)) {
// draw line section
$pdf->Line($temp_point[0], $temp_point[1], $point[0], $point[1], $line);
}
$temp_point = $point;
}
// print label
if ($label !== '') {
$pdf->setXY($points_arr[1][0], $points_arr[1][1]);
$pdf->setFontSize(5);
$pdf->Cell(0, 0, $label);
}
return $pdf;
}
/**
* Prepares and returns the code related to a row in the GIS dataset as SVG.
*
* @param string $spatial GIS LINESTRING object
* @param string $label Label for the GIS LINESTRING object
* @param string $line_color Color for the GIS LINESTRING object
* @param array $scale_data Array containing data related to scaling
*
* @return string the code related to a row in the GIS dataset
*/
public function prepareRowAsSvg($spatial, $label, $line_color, array $scale_data)
{
$line_options = [
'name' => $label,
'id' => $label . $this->getRandomId(),
'class' => 'linestring vector',
'fill' => 'none',
'stroke' => $line_color,
'stroke-width' => 2,
];
// Trim to remove leading 'LINESTRING(' and trailing ')'
$linesrting = mb_substr($spatial, 11, -1);
$points_arr = $this->extractPoints($linesrting, $scale_data);
$row = '<polyline points="';
foreach ($points_arr as $point) {
$row .= $point[0] . ',' . $point[1] . ' ';
}
$row .= '"';
foreach ($line_options as $option => $val) {
$row .= ' ' . $option . '="' . trim((string) $val) . '"';
}
$row .= '/>';
return $row;
}
/**
* Prepares JavaScript related to a row in the GIS dataset
* to visualize it with OpenLayers.
*
* @param string $spatial GIS LINESTRING object
* @param int $srid Spatial reference ID
* @param string $label Label for the GIS LINESTRING object
* @param array $line_color Color for the GIS LINESTRING object
* @param array $scale_data Array containing data related to scaling
*
* @return string JavaScript related to a row in the GIS dataset
*/
public function prepareRowAsOl($spatial, int $srid, $label, $line_color, array $scale_data)
{
$stroke_style = [
'color' => $line_color,
'width' => 2,
];
$result = 'var style = new ol.style.Style({'
. 'stroke: new ol.style.Stroke(' . json_encode($stroke_style) . ')';
if (trim($label) !== '') {
$text_style = ['text' => trim($label)];
$result .= ', text: new ol.style.Text(' . json_encode($text_style) . ')';
}
$result .= '});';
if ($srid === 0) {
$srid = 4326;
}
$result .= $this->getBoundsForOl($srid, $scale_data);
// Trim to remove leading 'LINESTRING(' and trailing ')'
$linesrting = mb_substr($spatial, 11, -1);
$points_arr = $this->extractPoints($linesrting, null);
return $result . 'var line = new ol.Feature({geometry: '
. $this->getLineForOpenLayers($points_arr, $srid) . '});'
. 'line.setStyle(style);'
. 'vectorLayer.addFeature(line);';
}
/**
* Generate the WKT with the set of parameters passed by the GIS editor.
*
* @param array $gis_data GIS data
* @param int $index Index into the parameter object
* @param string|null $empty Value for empty points
*
* @return string WKT with the set of parameters passed by the GIS editor
*/
public function generateWkt(array $gis_data, $index, $empty = '')
{
$no_of_points = $gis_data[$index]['LINESTRING']['no_of_points'] ?? 2;
if ($no_of_points < 2) {
$no_of_points = 2;
}
$wkt = 'LINESTRING(';
for ($i = 0; $i < $no_of_points; $i++) {
$wkt .= (isset($gis_data[$index]['LINESTRING'][$i]['x'])
&& trim((string) $gis_data[$index]['LINESTRING'][$i]['x']) != ''
? $gis_data[$index]['LINESTRING'][$i]['x'] : $empty)
. ' ' . (isset($gis_data[$index]['LINESTRING'][$i]['y'])
&& trim((string) $gis_data[$index]['LINESTRING'][$i]['y']) != ''
? $gis_data[$index]['LINESTRING'][$i]['y'] : $empty) . ',';
}
$wkt = mb_substr($wkt, 0, -1);
return $wkt . ')';
}
/**
* Generate parameters for the GIS data editor from the value of the GIS column.
*
* @param string $value of the GIS column
* @param int $index of the geometry
*
* @return array params for the GIS data editor from the value of the GIS column
*/
public function generateParams($value, $index = -1)
{
$params = [];
if ($index == -1) {
$index = 0;
$data = GisGeometry::generateParams($value);
$params['srid'] = $data['srid'];
$wkt = $data['wkt'];
} else {
$params[$index]['gis_type'] = 'LINESTRING';
$wkt = $value;
}
// Trim to remove leading 'LINESTRING(' and trailing ')'
$linestring = mb_substr($wkt, 11, -1);
$points_arr = $this->extractPoints($linestring, null);
$no_of_points = count($points_arr);
$params[$index]['LINESTRING']['no_of_points'] = $no_of_points;
for ($i = 0; $i < $no_of_points; $i++) {
$params[$index]['LINESTRING'][$i]['x'] = $points_arr[$i][0];
$params[$index]['LINESTRING'][$i]['y'] = $points_arr[$i][1];
}
return $params;
}
}

View file

@ -0,0 +1,400 @@
<?php
/**
* Handles actions related to GIS MULTILINESTRING objects
*/
declare(strict_types=1);
namespace PhpMyAdmin\Gis;
use PhpMyAdmin\Image\ImageWrapper;
use TCPDF;
use function count;
use function explode;
use function hexdec;
use function json_encode;
use function mb_substr;
use function round;
use function trim;
/**
* Handles actions related to GIS MULTILINESTRING objects
*/
class GisMultiLineString extends GisGeometry
{
/** @var self */
private static $instance;
/**
* A private constructor; prevents direct creation of object.
*/
private function __construct()
{
}
/**
* Returns the singleton.
*
* @return GisMultiLineString the singleton
*/
public static function singleton()
{
if (! isset(self::$instance)) {
self::$instance = new GisMultiLineString();
}
return self::$instance;
}
/**
* Scales each row.
*
* @param string $spatial spatial data of a row
*
* @return array an array containing the min, max values for x and y coordinates
*/
public function scaleRow($spatial)
{
$min_max = [];
// Trim to remove leading 'MULTILINESTRING((' and trailing '))'
$multilinestirng = mb_substr($spatial, 17, -2);
// Separate each linestring
$linestirngs = explode('),(', $multilinestirng);
foreach ($linestirngs as $linestring) {
$min_max = $this->setMinMax($linestring, $min_max);
}
return $min_max;
}
/**
* Adds to the PNG image object, the data related to a row in the GIS dataset.
*
* @param string $spatial GIS POLYGON object
* @param string|null $label Label for the GIS POLYGON object
* @param string $line_color Color for the GIS POLYGON object
* @param array $scale_data Array containing data related to scaling
*/
public function prepareRowAsPng(
$spatial,
?string $label,
$line_color,
array $scale_data,
ImageWrapper $image
): ImageWrapper {
// allocate colors
$black = $image->colorAllocate(0, 0, 0);
$red = (int) hexdec(mb_substr($line_color, 1, 2));
$green = (int) hexdec(mb_substr($line_color, 3, 2));
$blue = (int) hexdec(mb_substr($line_color, 4, 2));
$color = $image->colorAllocate($red, $green, $blue);
$label = trim($label ?? '');
// Trim to remove leading 'MULTILINESTRING((' and trailing '))'
$multilinestirng = mb_substr($spatial, 17, -2);
// Separate each linestring
$linestirngs = explode('),(', $multilinestirng);
$first_line = true;
foreach ($linestirngs as $linestring) {
$points_arr = $this->extractPoints($linestring, $scale_data);
foreach ($points_arr as $point) {
if (isset($temp_point)) {
// draw line section
$image->line(
(int) round($temp_point[0]),
(int) round($temp_point[1]),
(int) round($point[0]),
(int) round($point[1]),
$color
);
}
$temp_point = $point;
}
unset($temp_point);
// print label if applicable
if ($label !== '' && $first_line) {
$image->string(
1,
(int) round($points_arr[1][0]),
(int) round($points_arr[1][1]),
$label,
$black
);
}
$first_line = false;
}
return $image;
}
/**
* Adds to the TCPDF instance, the data related to a row in the GIS dataset.
*
* @param string $spatial GIS MULTILINESTRING object
* @param string|null $label Label for the GIS MULTILINESTRING object
* @param string $line_color Color for the GIS MULTILINESTRING object
* @param array $scale_data Array containing data related to scaling
* @param TCPDF $pdf TCPDF instance
*
* @return TCPDF the modified TCPDF instance
*/
public function prepareRowAsPdf($spatial, ?string $label, $line_color, array $scale_data, $pdf)
{
// allocate colors
$red = hexdec(mb_substr($line_color, 1, 2));
$green = hexdec(mb_substr($line_color, 3, 2));
$blue = hexdec(mb_substr($line_color, 4, 2));
$line = [
'width' => 1.5,
'color' => [
$red,
$green,
$blue,
],
];
$label = trim($label ?? '');
// Trim to remove leading 'MULTILINESTRING((' and trailing '))'
$multilinestirng = mb_substr($spatial, 17, -2);
// Separate each linestring
$linestirngs = explode('),(', $multilinestirng);
$first_line = true;
foreach ($linestirngs as $linestring) {
$points_arr = $this->extractPoints($linestring, $scale_data);
foreach ($points_arr as $point) {
if (isset($temp_point)) {
// draw line section
$pdf->Line($temp_point[0], $temp_point[1], $point[0], $point[1], $line);
}
$temp_point = $point;
}
unset($temp_point);
// print label
if ($label !== '' && $first_line) {
$pdf->setXY($points_arr[1][0], $points_arr[1][1]);
$pdf->setFontSize(5);
$pdf->Cell(0, 0, $label);
}
$first_line = false;
}
return $pdf;
}
/**
* Prepares and returns the code related to a row in the GIS dataset as SVG.
*
* @param string $spatial GIS MULTILINESTRING object
* @param string $label Label for the GIS MULTILINESTRING object
* @param string $line_color Color for the GIS MULTILINESTRING object
* @param array $scale_data Array containing data related to scaling
*
* @return string the code related to a row in the GIS dataset
*/
public function prepareRowAsSvg($spatial, $label, $line_color, array $scale_data)
{
$line_options = [
'name' => $label,
'class' => 'linestring vector',
'fill' => 'none',
'stroke' => $line_color,
'stroke-width' => 2,
];
// Trim to remove leading 'MULTILINESTRING((' and trailing '))'
$multilinestirng = mb_substr($spatial, 17, -2);
// Separate each linestring
$linestirngs = explode('),(', $multilinestirng);
$row = '';
foreach ($linestirngs as $linestring) {
$points_arr = $this->extractPoints($linestring, $scale_data);
$row .= '<polyline points="';
foreach ($points_arr as $point) {
$row .= $point[0] . ',' . $point[1] . ' ';
}
$row .= '"';
$line_options['id'] = $label . $this->getRandomId();
foreach ($line_options as $option => $val) {
$row .= ' ' . $option . '="' . trim((string) $val) . '"';
}
$row .= '/>';
}
return $row;
}
/**
* Prepares JavaScript related to a row in the GIS dataset
* to visualize it with OpenLayers.
*
* @param string $spatial GIS MULTILINESTRING object
* @param int $srid Spatial reference ID
* @param string $label Label for the GIS MULTILINESTRING object
* @param array $line_color Color for the GIS MULTILINESTRING object
* @param array $scale_data Array containing data related to scaling
*
* @return string JavaScript related to a row in the GIS dataset
*/
public function prepareRowAsOl($spatial, int $srid, $label, $line_color, array $scale_data)
{
$stroke_style = [
'color' => $line_color,
'width' => 2,
];
$row = 'var style = new ol.style.Style({'
. 'stroke: new ol.style.Stroke(' . json_encode($stroke_style) . ')';
if (trim($label) !== '') {
$text_style = ['text' => trim($label)];
$row .= ', text: new ol.style.Text(' . json_encode($text_style) . ')';
}
$row .= '});';
if ($srid === 0) {
$srid = 4326;
}
$row .= $this->getBoundsForOl($srid, $scale_data);
// Trim to remove leading 'MULTILINESTRING((' and trailing '))'
$multilinestirng = mb_substr($spatial, 17, -2);
// Separate each linestring
$linestirngs = explode('),(', $multilinestirng);
return $row . $this->getLineArrayForOpenLayers($linestirngs, $srid)
. 'var multiLineString = new ol.geom.MultiLineString(arr);'
. 'var feature = new ol.Feature({geometry: multiLineString});'
. 'feature.setStyle(style);'
. 'vectorLayer.addFeature(feature);';
}
/**
* Generate the WKT with the set of parameters passed by the GIS editor.
*
* @param array $gis_data GIS data
* @param int $index Index into the parameter object
* @param string|null $empty Value for empty points
*
* @return string WKT with the set of parameters passed by the GIS editor
*/
public function generateWkt(array $gis_data, $index, $empty = '')
{
$data_row = $gis_data[$index]['MULTILINESTRING'];
$no_of_lines = $data_row['no_of_lines'] ?? 1;
if ($no_of_lines < 1) {
$no_of_lines = 1;
}
$wkt = 'MULTILINESTRING(';
for ($i = 0; $i < $no_of_lines; $i++) {
$no_of_points = $data_row[$i]['no_of_points'] ?? 2;
if ($no_of_points < 2) {
$no_of_points = 2;
}
$wkt .= '(';
for ($j = 0; $j < $no_of_points; $j++) {
$wkt .= (isset($data_row[$i][$j]['x'])
&& trim((string) $data_row[$i][$j]['x']) != ''
? $data_row[$i][$j]['x'] : $empty)
. ' ' . (isset($data_row[$i][$j]['y'])
&& trim((string) $data_row[$i][$j]['y']) != ''
? $data_row[$i][$j]['y'] : $empty) . ',';
}
$wkt = mb_substr($wkt, 0, -1);
$wkt .= '),';
}
$wkt = mb_substr($wkt, 0, -1);
return $wkt . ')';
}
/**
* Generate the WKT for the data from ESRI shape files.
*
* @param array $row_data GIS data
*
* @return string the WKT for the data from ESRI shape files
*/
public function getShape(array $row_data)
{
$wkt = 'MULTILINESTRING(';
for ($i = 0; $i < $row_data['numparts']; $i++) {
$wkt .= '(';
foreach ($row_data['parts'][$i]['points'] as $point) {
$wkt .= $point['x'] . ' ' . $point['y'] . ',';
}
$wkt = mb_substr($wkt, 0, -1);
$wkt .= '),';
}
$wkt = mb_substr($wkt, 0, -1);
return $wkt . ')';
}
/**
* Generate parameters for the GIS data editor from the value of the GIS column.
*
* @param string $value Value of the GIS column
* @param int $index Index of the geometry
*
* @return array params for the GIS data editor from the value of the GIS column
*/
public function generateParams($value, $index = -1)
{
$params = [];
if ($index == -1) {
$index = 0;
$data = GisGeometry::generateParams($value);
$params['srid'] = $data['srid'];
$wkt = $data['wkt'];
} else {
$params[$index]['gis_type'] = 'MULTILINESTRING';
$wkt = $value;
}
// Trim to remove leading 'MULTILINESTRING((' and trailing '))'
$multilinestirng = mb_substr($wkt, 17, -2);
// Separate each linestring
$linestirngs = explode('),(', $multilinestirng);
$params[$index]['MULTILINESTRING']['no_of_lines'] = count($linestirngs);
$j = 0;
foreach ($linestirngs as $linestring) {
$points_arr = $this->extractPoints($linestring, null);
$no_of_points = count($points_arr);
$params[$index]['MULTILINESTRING'][$j]['no_of_points'] = $no_of_points;
for ($i = 0; $i < $no_of_points; $i++) {
$params[$index]['MULTILINESTRING'][$j][$i]['x'] = $points_arr[$i][0];
$params[$index]['MULTILINESTRING'][$j][$i]['y'] = $points_arr[$i][1];
}
$j++;
}
return $params;
}
}

View file

@ -0,0 +1,392 @@
<?php
/**
* Handles actions related to GIS MULTIPOINT objects
*/
declare(strict_types=1);
namespace PhpMyAdmin\Gis;
use PhpMyAdmin\Image\ImageWrapper;
use TCPDF;
use function count;
use function hexdec;
use function json_encode;
use function mb_substr;
use function round;
use function trim;
/**
* Handles actions related to GIS MULTIPOINT objects
*/
class GisMultiPoint extends GisGeometry
{
/** @var self */
private static $instance;
/**
* A private constructor; prevents direct creation of object.
*/
private function __construct()
{
}
/**
* Returns the singleton.
*
* @return GisMultiPoint the singleton
*/
public static function singleton()
{
if (! isset(self::$instance)) {
self::$instance = new GisMultiPoint();
}
return self::$instance;
}
/**
* Scales each row.
*
* @param string $spatial spatial data of a row
*
* @return array an array containing the min, max values for x and y coordinates
*/
public function scaleRow($spatial)
{
// Trim to remove leading 'MULTIPOINT(' and trailing ')'
$multipoint = mb_substr($spatial, 11, -1);
return $this->setMinMax($multipoint, []);
}
/**
* Adds to the PNG image object, the data related to a row in the GIS dataset.
*
* @param string $spatial GIS POLYGON object
* @param string|null $label Label for the GIS POLYGON object
* @param string $point_color Color for the GIS POLYGON object
* @param array $scale_data Array containing data related to scaling
*/
public function prepareRowAsPng(
$spatial,
?string $label,
$point_color,
array $scale_data,
ImageWrapper $image
): ImageWrapper {
// allocate colors
$black = $image->colorAllocate(0, 0, 0);
$red = (int) hexdec(mb_substr($point_color, 1, 2));
$green = (int) hexdec(mb_substr($point_color, 3, 2));
$blue = (int) hexdec(mb_substr($point_color, 4, 2));
$color = $image->colorAllocate($red, $green, $blue);
// Trim to remove leading 'MULTIPOINT(' and trailing ')'
$multipoint = mb_substr($spatial, 11, -1);
$points_arr = $this->extractPoints($multipoint, $scale_data);
foreach ($points_arr as $point) {
// draw a small circle to mark the point
if ($point[0] == '' || $point[1] == '') {
continue;
}
$image->arc(
(int) round($point[0]),
(int) round($point[1]),
7,
7,
0,
360,
$color
);
}
// print label for each point
if ((isset($label) && trim($label) != '') && ($points_arr[0][0] != '' && $points_arr[0][1] != '')) {
$image->string(
1,
(int) round($points_arr[0][0]),
(int) round($points_arr[0][1]),
trim($label),
$black
);
}
return $image;
}
/**
* Adds to the TCPDF instance, the data related to a row in the GIS dataset.
*
* @param string $spatial GIS MULTIPOINT object
* @param string|null $label Label for the GIS MULTIPOINT object
* @param string $point_color Color for the GIS MULTIPOINT object
* @param array $scale_data Array containing data related to scaling
* @param TCPDF $pdf TCPDF instance
*
* @return TCPDF the modified TCPDF instance
*/
public function prepareRowAsPdf(
$spatial,
?string $label,
$point_color,
array $scale_data,
$pdf
) {
// allocate colors
$red = hexdec(mb_substr($point_color, 1, 2));
$green = hexdec(mb_substr($point_color, 3, 2));
$blue = hexdec(mb_substr($point_color, 4, 2));
$line = [
'width' => 1.25,
'color' => [
$red,
$green,
$blue,
],
];
// Trim to remove leading 'MULTIPOINT(' and trailing ')'
$multipoint = mb_substr($spatial, 11, -1);
$points_arr = $this->extractPoints($multipoint, $scale_data);
foreach ($points_arr as $point) {
// draw a small circle to mark the point
if ($point[0] == '' || $point[1] == '') {
continue;
}
$pdf->Circle($point[0], $point[1], 2, 0, 360, 'D', $line);
}
// print label for each point
if ((isset($label) && trim($label) != '') && ($points_arr[0][0] != '' && $points_arr[0][1] != '')) {
$pdf->setXY($points_arr[0][0], $points_arr[0][1]);
$pdf->setFontSize(5);
$pdf->Cell(0, 0, trim($label));
}
return $pdf;
}
/**
* Prepares and returns the code related to a row in the GIS dataset as SVG.
*
* @param string $spatial GIS MULTIPOINT object
* @param string $label Label for the GIS MULTIPOINT object
* @param string $point_color Color for the GIS MULTIPOINT object
* @param array $scale_data Array containing data related to scaling
*
* @return string the code related to a row in the GIS dataset
*/
public function prepareRowAsSvg($spatial, $label, $point_color, array $scale_data)
{
$point_options = [
'name' => $label,
'class' => 'multipoint vector',
'fill' => 'white',
'stroke' => $point_color,
'stroke-width' => 2,
];
// Trim to remove leading 'MULTIPOINT(' and trailing ')'
$multipoint = mb_substr($spatial, 11, -1);
$points_arr = $this->extractPoints($multipoint, $scale_data);
$row = '';
foreach ($points_arr as $point) {
if (((float) $point[0]) === 0.0 || ((float) $point[1]) === 0.0) {
continue;
}
$row .= '<circle cx="' . $point[0] . '" cy="'
. $point[1] . '" r="3"';
$point_options['id'] = $label . $this->getRandomId();
foreach ($point_options as $option => $val) {
$row .= ' ' . $option . '="' . trim((string) $val) . '"';
}
$row .= '/>';
}
return $row;
}
/**
* Prepares JavaScript related to a row in the GIS dataset
* to visualize it with OpenLayers.
*
* @param string $spatial GIS MULTIPOINT object
* @param int $srid Spatial reference ID
* @param string $label Label for the GIS MULTIPOINT object
* @param array $point_color Color for the GIS MULTIPOINT object
* @param array $scale_data Array containing data related to scaling
*
* @return string JavaScript related to a row in the GIS dataset
*/
public function prepareRowAsOl(
$spatial,
int $srid,
$label,
$point_color,
array $scale_data
) {
$fill_style = ['color' => 'white'];
$stroke_style = [
'color' => $point_color,
'width' => 2,
];
$result = 'var fill = new ol.style.Fill(' . json_encode($fill_style) . ');'
. 'var stroke = new ol.style.Stroke(' . json_encode($stroke_style) . ');'
. 'var style = new ol.style.Style({'
. 'image: new ol.style.Circle({'
. 'fill: fill,'
. 'stroke: stroke,'
. 'radius: 3'
. '}),'
. 'fill: fill,'
. 'stroke: stroke';
if (trim($label) !== '') {
$text_style = [
'text' => trim($label),
'offsetY' => -9,
];
$result .= ',text: new ol.style.Text(' . json_encode($text_style) . ')';
}
$result .= '});';
if ($srid === 0) {
$srid = 4326;
}
$result .= $this->getBoundsForOl($srid, $scale_data);
// Trim to remove leading 'MULTIPOINT(' and trailing ')'
$multipoint = mb_substr($spatial, 11, -1);
$points_arr = $this->extractPoints($multipoint, null);
return $result . 'var multiPoint = new ol.geom.MultiPoint('
. $this->getPointsArrayForOpenLayers($points_arr, $srid) . ');'
. 'var feature = new ol.Feature({geometry: multiPoint});'
. 'feature.setStyle(style);'
. 'vectorLayer.addFeature(feature);';
}
/**
* Generate the WKT with the set of parameters passed by the GIS editor.
*
* @param array $gis_data GIS data
* @param int $index Index into the parameter object
* @param string|null $empty Multipoint does not adhere to this
*
* @return string WKT with the set of parameters passed by the GIS editor
*/
public function generateWkt(array $gis_data, $index, $empty = '')
{
$no_of_points = $gis_data[$index]['MULTIPOINT']['no_of_points'] ?? 1;
if ($no_of_points < 1) {
$no_of_points = 1;
}
$wkt = 'MULTIPOINT(';
for ($i = 0; $i < $no_of_points; $i++) {
$wkt .= (isset($gis_data[$index]['MULTIPOINT'][$i]['x'])
&& trim((string) $gis_data[$index]['MULTIPOINT'][$i]['x']) != ''
? $gis_data[$index]['MULTIPOINT'][$i]['x'] : '')
. ' ' . (isset($gis_data[$index]['MULTIPOINT'][$i]['y'])
&& trim((string) $gis_data[$index]['MULTIPOINT'][$i]['y']) != ''
? $gis_data[$index]['MULTIPOINT'][$i]['y'] : '') . ',';
}
$wkt = mb_substr($wkt, 0, -1);
return $wkt . ')';
}
/**
* Generate the WKT for the data from ESRI shape files.
*
* @param array $row_data GIS data
*
* @return string the WKT for the data from ESRI shape files
*/
public function getShape(array $row_data)
{
$wkt = 'MULTIPOINT(';
for ($i = 0; $i < $row_data['numpoints']; $i++) {
$wkt .= $row_data['points'][$i]['x'] . ' '
. $row_data['points'][$i]['y'] . ',';
}
$wkt = mb_substr($wkt, 0, -1);
return $wkt . ')';
}
/**
* Generate parameters for the GIS data editor from the value of the GIS column.
*
* @param string $value Value of the GIS column
* @param int $index Index of the geometry
*
* @return array params for the GIS data editor from the value of the GIS column
*/
public function generateParams($value, $index = -1)
{
$params = [];
if ($index == -1) {
$index = 0;
$data = GisGeometry::generateParams($value);
$params['srid'] = $data['srid'];
$wkt = $data['wkt'];
} else {
$params[$index]['gis_type'] = 'MULTIPOINT';
$wkt = $value;
}
// Trim to remove leading 'MULTIPOINT(' and trailing ')'
$points = mb_substr($wkt, 11, -1);
$points_arr = $this->extractPoints($points, null);
$no_of_points = count($points_arr);
$params[$index]['MULTIPOINT']['no_of_points'] = $no_of_points;
for ($i = 0; $i < $no_of_points; $i++) {
$params[$index]['MULTIPOINT'][$i]['x'] = $points_arr[$i][0];
$params[$index]['MULTIPOINT'][$i]['y'] = $points_arr[$i][1];
}
return $params;
}
/**
* Overridden to make sure that only the points having valid values
* for x and y coordinates are added.
*
* @param array $points_arr x and y coordinates for each point
* @param int $srid spatial reference id
*
* @return string JavaScript for adding an array of points to OpenLayers
*/
protected function getPointsArrayForOpenLayers(array $points_arr, int $srid)
{
$ol_array = 'new Array(';
foreach ($points_arr as $point) {
if ($point[0] == '' || $point[1] == '') {
continue;
}
$ol_array .= $this->getPointForOpenLayers($point, $srid) . '.getCoordinates(), ';
}
if (mb_substr($ol_array, -2) === ', ') {
$ol_array = mb_substr($ol_array, 0, -2);
}
return $ol_array . ')';
}
}

View file

@ -0,0 +1,575 @@
<?php
/**
* Handles actions related to GIS MULTIPOLYGON objects
*/
declare(strict_types=1);
namespace PhpMyAdmin\Gis;
use PhpMyAdmin\Image\ImageWrapper;
use TCPDF;
use function array_merge;
use function array_slice;
use function count;
use function explode;
use function hexdec;
use function json_encode;
use function mb_substr;
use function round;
use function str_contains;
use function trim;
/**
* Handles actions related to GIS MULTIPOLYGON objects
*/
class GisMultiPolygon extends GisGeometry
{
/** @var self */
private static $instance;
/**
* A private constructor; prevents direct creation of object.
*/
private function __construct()
{
}
/**
* Returns the singleton.
*
* @return GisMultiPolygon the singleton
*/
public static function singleton()
{
if (! isset(self::$instance)) {
self::$instance = new GisMultiPolygon();
}
return self::$instance;
}
/**
* Scales each row.
*
* @param string $spatial spatial data of a row
*
* @return array an array containing the min, max values for x and y coordinates
*/
public function scaleRow($spatial)
{
$min_max = [];
// Trim to remove leading 'MULTIPOLYGON(((' and trailing ')))'
$multipolygon = mb_substr($spatial, 15, -3);
// Separate each polygon
$polygons = explode(')),((', $multipolygon);
foreach ($polygons as $polygon) {
// If the polygon doesn't have an inner ring, use polygon itself
if (! str_contains($polygon, '),(')) {
$ring = $polygon;
} else {
// Separate outer ring and use it to determine min-max
$parts = explode('),(', $polygon);
$ring = $parts[0];
}
$min_max = $this->setMinMax($ring, $min_max);
}
return $min_max;
}
/**
* Adds to the PNG image object, the data related to a row in the GIS dataset.
*
* @param string $spatial GIS POLYGON object
* @param string|null $label Label for the GIS POLYGON object
* @param string $fill_color Color for the GIS POLYGON object
* @param array $scale_data Array containing data related to scaling
*/
public function prepareRowAsPng(
$spatial,
?string $label,
$fill_color,
array $scale_data,
ImageWrapper $image
): ImageWrapper {
// allocate colors
$black = $image->colorAllocate(0, 0, 0);
$red = (int) hexdec(mb_substr($fill_color, 1, 2));
$green = (int) hexdec(mb_substr($fill_color, 3, 2));
$blue = (int) hexdec(mb_substr($fill_color, 4, 2));
$color = $image->colorAllocate($red, $green, $blue);
$label = trim($label ?? '');
// Trim to remove leading 'MULTIPOLYGON(((' and trailing ')))'
$multipolygon = mb_substr($spatial, 15, -3);
// Separate each polygon
$polygons = explode(')),((', $multipolygon);
$first_poly = true;
foreach ($polygons as $polygon) {
// If the polygon doesn't have an inner polygon
if (! str_contains($polygon, '),(')) {
$points_arr = $this->extractPoints($polygon, $scale_data, true);
} else {
// Separate outer and inner polygons
$parts = explode('),(', $polygon);
$outer = $parts[0];
$inner = array_slice($parts, 1);
$points_arr = $this->extractPoints($outer, $scale_data, true);
foreach ($inner as $inner_poly) {
$points_arr = array_merge(
$points_arr,
$this->extractPoints($inner_poly, $scale_data, true)
);
}
}
// draw polygon
$image->filledPolygon($points_arr, $color);
// mark label point if applicable
if ($label !== '' && $first_poly) {
$label_point = [
$points_arr[2],
$points_arr[3],
];
}
$first_poly = false;
}
// print label if applicable
if (isset($label_point)) {
$image->string(
1,
(int) round($label_point[0]),
(int) round($label_point[1]),
$label,
$black
);
}
return $image;
}
/**
* Adds to the TCPDF instance, the data related to a row in the GIS dataset.
*
* @param string $spatial GIS MULTIPOLYGON object
* @param string|null $label Label for the GIS MULTIPOLYGON object
* @param string $fill_color Color for the GIS MULTIPOLYGON object
* @param array $scale_data Array containing data related to scaling
* @param TCPDF $pdf TCPDF instance
*
* @return TCPDF the modified TCPDF instance
*/
public function prepareRowAsPdf($spatial, ?string $label, $fill_color, array $scale_data, $pdf)
{
// allocate colors
$red = hexdec(mb_substr($fill_color, 1, 2));
$green = hexdec(mb_substr($fill_color, 3, 2));
$blue = hexdec(mb_substr($fill_color, 4, 2));
$color = [
$red,
$green,
$blue,
];
$label = trim($label ?? '');
// Trim to remove leading 'MULTIPOLYGON(((' and trailing ')))'
$multipolygon = mb_substr($spatial, 15, -3);
// Separate each polygon
$polygons = explode(')),((', $multipolygon);
$first_poly = true;
foreach ($polygons as $polygon) {
// If the polygon doesn't have an inner polygon
if (! str_contains($polygon, '),(')) {
$points_arr = $this->extractPoints($polygon, $scale_data, true);
} else {
// Separate outer and inner polygons
$parts = explode('),(', $polygon);
$outer = $parts[0];
$inner = array_slice($parts, 1);
$points_arr = $this->extractPoints($outer, $scale_data, true);
foreach ($inner as $inner_poly) {
$points_arr = array_merge(
$points_arr,
$this->extractPoints($inner_poly, $scale_data, true)
);
}
}
// draw polygon
$pdf->Polygon($points_arr, 'F*', [], $color, true);
// mark label point if applicable
if ($label !== '' && $first_poly) {
$label_point = [
$points_arr[2],
$points_arr[3],
];
}
$first_poly = false;
}
// print label if applicable
if (isset($label_point)) {
$pdf->setXY($label_point[0], $label_point[1]);
$pdf->setFontSize(5);
$pdf->Cell(0, 0, $label);
}
return $pdf;
}
/**
* Prepares and returns the code related to a row in the GIS dataset as SVG.
*
* @param string $spatial GIS MULTIPOLYGON object
* @param string $label Label for the GIS MULTIPOLYGON object
* @param string $fill_color Color for the GIS MULTIPOLYGON object
* @param array $scale_data Array containing data related to scaling
*
* @return string the code related to a row in the GIS dataset
*/
public function prepareRowAsSvg($spatial, $label, $fill_color, array $scale_data)
{
$polygon_options = [
'name' => $label,
'class' => 'multipolygon vector',
'stroke' => 'black',
'stroke-width' => 0.5,
'fill' => $fill_color,
'fill-rule' => 'evenodd',
'fill-opacity' => 0.8,
];
$row = '';
// Trim to remove leading 'MULTIPOLYGON(((' and trailing ')))'
$multipolygon = mb_substr($spatial, 15, -3);
// Separate each polygon
$polygons = explode(')),((', $multipolygon);
foreach ($polygons as $polygon) {
$row .= '<path d="';
// If the polygon doesn't have an inner polygon
if (! str_contains($polygon, '),(')) {
$row .= $this->drawPath($polygon, $scale_data);
} else {
// Separate outer and inner polygons
$parts = explode('),(', $polygon);
$outer = $parts[0];
$inner = array_slice($parts, 1);
$row .= $this->drawPath($outer, $scale_data);
foreach ($inner as $inner_poly) {
$row .= $this->drawPath($inner_poly, $scale_data);
}
}
$polygon_options['id'] = $label . $this->getRandomId();
$row .= '"';
foreach ($polygon_options as $option => $val) {
$row .= ' ' . $option . '="' . trim((string) $val) . '"';
}
$row .= '/>';
}
return $row;
}
/**
* Prepares JavaScript related to a row in the GIS dataset
* to visualize it with OpenLayers.
*
* @param string $spatial GIS MULTIPOLYGON object
* @param int $srid Spatial reference ID
* @param string $label Label for the GIS MULTIPOLYGON object
* @param array $fill_color Color for the GIS MULTIPOLYGON object
* @param array $scale_data Array containing data related to scaling
*
* @return string JavaScript related to a row in the GIS dataset
*/
public function prepareRowAsOl($spatial, int $srid, $label, $fill_color, array $scale_data)
{
$fill_color[] = 0.8;
$fill_style = ['color' => $fill_color];
$stroke_style = [
'color' => [0,0,0],
'width' => 0.5,
];
$row = 'var style = new ol.style.Style({'
. 'fill: new ol.style.Fill(' . json_encode($fill_style) . '),'
. 'stroke: new ol.style.Stroke(' . json_encode($stroke_style) . ')';
if (trim($label) !== '') {
$text_style = ['text' => trim($label)];
$row .= ',text: new ol.style.Text(' . json_encode($text_style) . ')';
}
$row .= '});';
if ($srid === 0) {
$srid = 4326;
}
$row .= $this->getBoundsForOl($srid, $scale_data);
// Trim to remove leading 'MULTIPOLYGON(((' and trailing ')))'
$multipolygon = mb_substr($spatial, 15, -3);
// Separate each polygon
$polygons = explode(')),((', $multipolygon);
return $row . $this->getPolygonArrayForOpenLayers($polygons, $srid)
. 'var multiPolygon = new ol.geom.MultiPolygon(polygonArray);'
. 'var feature = new ol.Feature(multiPolygon);'
. 'feature.setStyle(style);'
. 'vectorLayer.addFeature(feature);';
}
/**
* Draws a ring of the polygon using SVG path element.
*
* @param string $polygon The ring
* @param array $scale_data Array containing data related to scaling
*
* @return string the code to draw the ring
*/
private function drawPath($polygon, array $scale_data)
{
$points_arr = $this->extractPoints($polygon, $scale_data);
$row = ' M ' . $points_arr[0][0] . ', ' . $points_arr[0][1];
$other_points = array_slice($points_arr, 1, count($points_arr) - 2);
foreach ($other_points as $point) {
$row .= ' L ' . $point[0] . ', ' . $point[1];
}
$row .= ' Z ';
return $row;
}
/**
* Generate the WKT with the set of parameters passed by the GIS editor.
*
* @param array $gis_data GIS data
* @param int $index Index into the parameter object
* @param string|null $empty Value for empty points
*
* @return string WKT with the set of parameters passed by the GIS editor
*/
public function generateWkt(array $gis_data, $index, $empty = '')
{
$data_row = $gis_data[$index]['MULTIPOLYGON'];
$no_of_polygons = $data_row['no_of_polygons'] ?? 1;
if ($no_of_polygons < 1) {
$no_of_polygons = 1;
}
$wkt = 'MULTIPOLYGON(';
for ($k = 0; $k < $no_of_polygons; $k++) {
$no_of_lines = $data_row[$k]['no_of_lines'] ?? 1;
if ($no_of_lines < 1) {
$no_of_lines = 1;
}
$wkt .= '(';
for ($i = 0; $i < $no_of_lines; $i++) {
$no_of_points = $data_row[$k][$i]['no_of_points'] ?? 4;
if ($no_of_points < 4) {
$no_of_points = 4;
}
$wkt .= '(';
for ($j = 0; $j < $no_of_points; $j++) {
$wkt .= (isset($data_row[$k][$i][$j]['x'])
&& trim((string) $data_row[$k][$i][$j]['x']) != ''
? $data_row[$k][$i][$j]['x'] : $empty)
. ' ' . (isset($data_row[$k][$i][$j]['y'])
&& trim((string) $data_row[$k][$i][$j]['y']) != ''
? $data_row[$k][$i][$j]['y'] : $empty) . ',';
}
$wkt = mb_substr($wkt, 0, -1);
$wkt .= '),';
}
$wkt = mb_substr($wkt, 0, -1);
$wkt .= '),';
}
$wkt = mb_substr($wkt, 0, -1);
return $wkt . ')';
}
/**
* Generate the WKT for the data from ESRI shape files.
*
* @param array $row_data GIS data
*
* @return string the WKT for the data from ESRI shape files
*/
public function getShape(array $row_data)
{
// Determines whether each line ring is an inner ring or an outer ring.
// If it's an inner ring get a point on the surface which can be used to
// correctly classify inner rings to their respective outer rings.
foreach ($row_data['parts'] as $i => $ring) {
$row_data['parts'][$i]['isOuter'] = GisPolygon::isOuterRing($ring['points']);
}
// Find points on surface for inner rings
foreach ($row_data['parts'] as $i => $ring) {
if ($ring['isOuter']) {
continue;
}
$row_data['parts'][$i]['pointOnSurface'] = GisPolygon::getPointOnSurface($ring['points']);
}
// Classify inner rings to their respective outer rings.
foreach ($row_data['parts'] as $j => $ring1) {
if ($ring1['isOuter']) {
continue;
}
foreach ($row_data['parts'] as $k => $ring2) {
if (! $ring2['isOuter']) {
continue;
}
// If the pointOnSurface of the inner ring
// is also inside the outer ring
if (! GisPolygon::isPointInsidePolygon($ring1['pointOnSurface'], $ring2['points'])) {
continue;
}
if (! isset($ring2['inner'])) {
$row_data['parts'][$k]['inner'] = [];
}
$row_data['parts'][$k]['inner'][] = $j;
}
}
$wkt = 'MULTIPOLYGON(';
// for each polygon
foreach ($row_data['parts'] as $ring) {
if (! $ring['isOuter']) {
continue;
}
$wkt .= '('; // start of polygon
$wkt .= '('; // start of outer ring
foreach ($ring['points'] as $point) {
$wkt .= $point['x'] . ' ' . $point['y'] . ',';
}
$wkt = mb_substr($wkt, 0, -1);
$wkt .= ')'; // end of outer ring
// inner rings if any
if (isset($ring['inner'])) {
foreach ($ring['inner'] as $j) {
$wkt .= ',('; // start of inner ring
foreach ($row_data['parts'][$j]['points'] as $innerPoint) {
$wkt .= $innerPoint['x'] . ' ' . $innerPoint['y'] . ',';
}
$wkt = mb_substr($wkt, 0, -1);
$wkt .= ')'; // end of inner ring
}
}
$wkt .= '),'; // end of polygon
}
$wkt = mb_substr($wkt, 0, -1);
return $wkt . ')';
}
/**
* Generate parameters for the GIS data editor from the value of the GIS column.
*
* @param string $value Value of the GIS column
* @param int $index Index of the geometry
*
* @return array params for the GIS data editor from the value of the GIS column
*/
public function generateParams($value, $index = -1)
{
$params = [];
if ($index == -1) {
$index = 0;
$data = GisGeometry::generateParams($value);
$params['srid'] = $data['srid'];
$wkt = $data['wkt'];
} else {
$params[$index]['gis_type'] = 'MULTIPOLYGON';
$wkt = $value;
}
// Trim to remove leading 'MULTIPOLYGON(((' and trailing ')))'
$multipolygon = mb_substr($wkt, 15, -3);
// Separate each polygon
$polygons = explode(')),((', $multipolygon);
$param_row =& $params[$index]['MULTIPOLYGON'];
$param_row['no_of_polygons'] = count($polygons);
$k = 0;
foreach ($polygons as $polygon) {
// If the polygon doesn't have an inner polygon
if (! str_contains($polygon, '),(')) {
$param_row[$k]['no_of_lines'] = 1;
$points_arr = $this->extractPoints($polygon, null);
$no_of_points = count($points_arr);
$param_row[$k][0]['no_of_points'] = $no_of_points;
for ($i = 0; $i < $no_of_points; $i++) {
$param_row[$k][0][$i]['x'] = $points_arr[$i][0];
$param_row[$k][0][$i]['y'] = $points_arr[$i][1];
}
} else {
// Separate outer and inner polygons
$parts = explode('),(', $polygon);
$param_row[$k]['no_of_lines'] = count($parts);
$j = 0;
foreach ($parts as $ring) {
$points_arr = $this->extractPoints($ring, null);
$no_of_points = count($points_arr);
$param_row[$k][$j]['no_of_points'] = $no_of_points;
for ($i = 0; $i < $no_of_points; $i++) {
$param_row[$k][$j][$i]['x'] = $points_arr[$i][0];
$param_row[$k][$j][$i]['y'] = $points_arr[$i][1];
}
$j++;
}
}
$k++;
}
return $params;
}
}

View file

@ -0,0 +1,336 @@
<?php
/**
* Handles actions related to GIS POINT objects
*/
declare(strict_types=1);
namespace PhpMyAdmin\Gis;
use PhpMyAdmin\Image\ImageWrapper;
use TCPDF;
use function hexdec;
use function json_encode;
use function mb_substr;
use function round;
use function trim;
/**
* Handles actions related to GIS POINT objects
*/
class GisPoint extends GisGeometry
{
/** @var self */
private static $instance;
/**
* A private constructor; prevents direct creation of object.
*/
private function __construct()
{
}
/**
* Returns the singleton.
*
* @return GisPoint the singleton
*/
public static function singleton()
{
if (! isset(self::$instance)) {
self::$instance = new GisPoint();
}
return self::$instance;
}
/**
* Scales each row.
*
* @param string $spatial spatial data of a row
*
* @return array an array containing the min, max values for x and y coordinates
*/
public function scaleRow($spatial)
{
// Trim to remove leading 'POINT(' and trailing ')'
$point = mb_substr($spatial, 6, -1);
return $this->setMinMax($point, []);
}
/**
* Adds to the PNG image object, the data related to a row in the GIS dataset.
*
* @param string $spatial GIS POLYGON object
* @param string|null $label Label for the GIS POLYGON object
* @param string $point_color Color for the GIS POLYGON object
* @param array $scale_data Array containing data related to scaling
*/
public function prepareRowAsPng(
$spatial,
?string $label,
$point_color,
array $scale_data,
ImageWrapper $image
): ImageWrapper {
// allocate colors
$black = $image->colorAllocate(0, 0, 0);
$red = (int) hexdec(mb_substr($point_color, 1, 2));
$green = (int) hexdec(mb_substr($point_color, 3, 2));
$blue = (int) hexdec(mb_substr($point_color, 4, 2));
$color = $image->colorAllocate($red, $green, $blue);
$label = trim($label ?? '');
// Trim to remove leading 'POINT(' and trailing ')'
$point = mb_substr($spatial, 6, -1);
$points_arr = $this->extractPoints($point, $scale_data);
// draw a small circle to mark the point
if ($points_arr[0][0] != '' && $points_arr[0][1] != '') {
$image->arc(
(int) round($points_arr[0][0]),
(int) round($points_arr[0][1]),
7,
7,
0,
360,
$color
);
// print label if applicable
if ($label !== '') {
$image->string(
1,
(int) round($points_arr[0][0]),
(int) round($points_arr[0][1]),
$label,
$black
);
}
}
return $image;
}
/**
* Adds to the TCPDF instance, the data related to a row in the GIS dataset.
*
* @param string $spatial GIS POINT object
* @param string|null $label Label for the GIS POINT object
* @param string $point_color Color for the GIS POINT object
* @param array $scale_data Array containing data related to scaling
* @param TCPDF $pdf TCPDF instance
*
* @return TCPDF the modified TCPDF instance
*/
public function prepareRowAsPdf(
$spatial,
?string $label,
$point_color,
array $scale_data,
$pdf
) {
// allocate colors
$red = hexdec(mb_substr($point_color, 1, 2));
$green = hexdec(mb_substr($point_color, 3, 2));
$blue = hexdec(mb_substr($point_color, 4, 2));
$line = [
'width' => 1.25,
'color' => [
$red,
$green,
$blue,
],
];
$label = trim($label ?? '');
// Trim to remove leading 'POINT(' and trailing ')'
$point = mb_substr($spatial, 6, -1);
$points_arr = $this->extractPoints($point, $scale_data);
// draw a small circle to mark the point
if ($points_arr[0][0] != '' && $points_arr[0][1] != '') {
$pdf->Circle($points_arr[0][0], $points_arr[0][1], 2, 0, 360, 'D', $line);
// print label if applicable
if ($label !== '') {
$pdf->setXY($points_arr[0][0], $points_arr[0][1]);
$pdf->setFontSize(5);
$pdf->Cell(0, 0, $label);
}
}
return $pdf;
}
/**
* Prepares and returns the code related to a row in the GIS dataset as SVG.
*
* @param string $spatial GIS POINT object
* @param string $label Label for the GIS POINT object
* @param string $point_color Color for the GIS POINT object
* @param array $scale_data Array containing data related to scaling
*
* @return string the code related to a row in the GIS dataset
*/
public function prepareRowAsSvg($spatial, $label, $point_color, array $scale_data)
{
$point_options = [
'name' => $label,
'id' => $label . $this->getRandomId(),
'class' => 'point vector',
'fill' => 'white',
'stroke' => $point_color,
'stroke-width' => 2,
];
// Trim to remove leading 'POINT(' and trailing ')'
$point = mb_substr($spatial, 6, -1);
$points_arr = $this->extractPoints($point, $scale_data);
$row = '';
if (((float) $points_arr[0][0]) !== 0.0 && ((float) $points_arr[0][1]) !== 0.0) {
$row .= '<circle cx="' . $points_arr[0][0]
. '" cy="' . $points_arr[0][1] . '" r="3"';
foreach ($point_options as $option => $val) {
$row .= ' ' . $option . '="' . trim((string) $val) . '"';
}
$row .= '/>';
}
return $row;
}
/**
* Prepares JavaScript related to a row in the GIS dataset
* to visualize it with OpenLayers.
*
* @param string $spatial GIS POINT object
* @param int $srid Spatial reference ID
* @param string $label Label for the GIS POINT object
* @param array $point_color Color for the GIS POINT object
* @param array $scale_data Array containing data related to scaling
*
* @return string JavaScript related to a row in the GIS dataset
*/
public function prepareRowAsOl(
$spatial,
int $srid,
$label,
$point_color,
array $scale_data
) {
$fill_style = ['color' => 'white'];
$stroke_style = [
'color' => $point_color,
'width' => 2,
];
$result = 'var fill = new ol.style.Fill(' . json_encode($fill_style) . ');'
. 'var stroke = new ol.style.Stroke(' . json_encode($stroke_style) . ');'
. 'var style = new ol.style.Style({'
. 'image: new ol.style.Circle({'
. 'fill: fill,'
. 'stroke: stroke,'
. 'radius: 3'
. '}),'
. 'fill: fill,'
. 'stroke: stroke';
if (trim($label) !== '') {
$text_style = [
'text' => trim($label),
'offsetY' => -9,
];
$result .= ',text: new ol.style.Text(' . json_encode($text_style) . ')';
}
$result .= '});';
if ($srid === 0) {
$srid = 4326;
}
$result .= $this->getBoundsForOl($srid, $scale_data);
// Trim to remove leading 'POINT(' and trailing ')'
$point = mb_substr($spatial, 6, -1);
$points_arr = $this->extractPoints($point, null);
if ($points_arr[0][0] != '' && $points_arr[0][1] != '') {
$result .= 'var point = new ol.Feature({geometry: '
. $this->getPointForOpenLayers($points_arr[0], $srid) . '});'
. 'point.setStyle(style);'
. 'vectorLayer.addFeature(point);';
}
return $result;
}
/**
* Generate the WKT with the set of parameters passed by the GIS editor.
*
* @param array $gis_data GIS data
* @param int $index Index into the parameter object
* @param string|null $empty Point does not adhere to this parameter
*
* @return string WKT with the set of parameters passed by the GIS editor
*/
public function generateWkt(array $gis_data, $index, $empty = '')
{
return 'POINT('
. (isset($gis_data[$index]['POINT']['x'])
&& trim((string) $gis_data[$index]['POINT']['x']) != ''
? $gis_data[$index]['POINT']['x'] : '')
. ' '
. (isset($gis_data[$index]['POINT']['y'])
&& trim((string) $gis_data[$index]['POINT']['y']) != ''
? $gis_data[$index]['POINT']['y'] : '') . ')';
}
/**
* Generate the WKT for the data from ESRI shape files.
*
* @param array $row_data GIS data
*
* @return string the WKT for the data from ESRI shape files
*/
public function getShape(array $row_data)
{
return 'POINT(' . ($row_data['x'] ?? '')
. ' ' . ($row_data['y'] ?? '') . ')';
}
/**
* Generate parameters for the GIS data editor from the value of the GIS column.
*
* @param string $value of the GIS column
* @param int $index of the geometry
*
* @return array params for the GIS data editor from the value of the GIS column
*/
public function generateParams($value, $index = -1)
{
$params = [];
if ($index == -1) {
$index = 0;
$data = GisGeometry::generateParams($value);
$params['srid'] = $data['srid'];
$wkt = $data['wkt'];
} else {
$params[$index]['gis_type'] = 'POINT';
$wkt = $value;
}
// Trim to remove leading 'POINT(' and trailing ')'
$point = mb_substr($wkt, 6, -1);
$points_arr = $this->extractPoints($point, null);
$params[$index]['POINT']['x'] = $points_arr[0][0];
$params[$index]['POINT']['y'] = $points_arr[0][1];
return $params;
}
}

View file

@ -0,0 +1,580 @@
<?php
/**
* Handles actions related to GIS POLYGON objects
*/
declare(strict_types=1);
namespace PhpMyAdmin\Gis;
use PhpMyAdmin\Image\ImageWrapper;
use TCPDF;
use function array_merge;
use function array_slice;
use function count;
use function explode;
use function hexdec;
use function json_encode;
use function max;
use function mb_substr;
use function min;
use function round;
use function sqrt;
use function str_contains;
use function trim;
/**
* Handles actions related to GIS POLYGON objects
*/
class GisPolygon extends GisGeometry
{
/** @var self */
private static $instance;
/**
* A private constructor; prevents direct creation of object.
*/
private function __construct()
{
}
/**
* Returns the singleton.
*
* @return GisPolygon the singleton
*/
public static function singleton()
{
if (! isset(self::$instance)) {
self::$instance = new GisPolygon();
}
return self::$instance;
}
/**
* Scales each row.
*
* @param string $spatial spatial data of a row
*
* @return array an array containing the min, max values for x and y coordinates
*/
public function scaleRow($spatial)
{
// Trim to remove leading 'POLYGON((' and trailing '))'
$polygon = mb_substr($spatial, 9, -2);
// If the polygon doesn't have an inner ring, use polygon itself
if (! str_contains($polygon, '),(')) {
$ring = $polygon;
} else {
// Separate outer ring and use it to determine min-max
$parts = explode('),(', $polygon);
$ring = $parts[0];
}
return $this->setMinMax($ring, []);
}
/**
* Adds to the PNG image object, the data related to a row in the GIS dataset.
*
* @param string $spatial GIS POLYGON object
* @param string|null $label Label for the GIS POLYGON object
* @param string $fill_color Color for the GIS POLYGON object
* @param array $scale_data Array containing data related to scaling
*/
public function prepareRowAsPng(
$spatial,
?string $label,
$fill_color,
array $scale_data,
ImageWrapper $image
): ImageWrapper {
// allocate colors
$black = $image->colorAllocate(0, 0, 0);
$red = (int) hexdec(mb_substr($fill_color, 1, 2));
$green = (int) hexdec(mb_substr($fill_color, 3, 2));
$blue = (int) hexdec(mb_substr($fill_color, 4, 2));
$color = $image->colorAllocate($red, $green, $blue);
$label = trim($label ?? '');
// Trim to remove leading 'POLYGON((' and trailing '))'
$polygon = mb_substr($spatial, 9, -2);
// If the polygon doesn't have an inner polygon
if (! str_contains($polygon, '),(')) {
$points_arr = $this->extractPoints($polygon, $scale_data, true);
} else {
// Separate outer and inner polygons
$parts = explode('),(', $polygon);
$outer = $parts[0];
$inner = array_slice($parts, 1);
$points_arr = $this->extractPoints($outer, $scale_data, true);
foreach ($inner as $inner_poly) {
$points_arr = array_merge(
$points_arr,
$this->extractPoints($inner_poly, $scale_data, true)
);
}
}
// draw polygon
$image->filledPolygon($points_arr, $color);
// print label if applicable
if ($label !== '') {
$image->string(
1,
(int) round($points_arr[2]),
(int) round($points_arr[3]),
$label,
$black
);
}
return $image;
}
/**
* Adds to the TCPDF instance, the data related to a row in the GIS dataset.
*
* @param string $spatial GIS POLYGON object
* @param string|null $label Label for the GIS POLYGON object
* @param string $fill_color Color for the GIS POLYGON object
* @param array $scale_data Array containing data related to scaling
* @param TCPDF $pdf TCPDF instance
*
* @return TCPDF the modified TCPDF instance
*/
public function prepareRowAsPdf($spatial, ?string $label, $fill_color, array $scale_data, $pdf)
{
// allocate colors
$red = hexdec(mb_substr($fill_color, 1, 2));
$green = hexdec(mb_substr($fill_color, 3, 2));
$blue = hexdec(mb_substr($fill_color, 4, 2));
$color = [
$red,
$green,
$blue,
];
$label = trim($label ?? '');
// Trim to remove leading 'POLYGON((' and trailing '))'
$polygon = mb_substr($spatial, 9, -2);
// If the polygon doesn't have an inner polygon
if (! str_contains($polygon, '),(')) {
$points_arr = $this->extractPoints($polygon, $scale_data, true);
} else {
// Separate outer and inner polygons
$parts = explode('),(', $polygon);
$outer = $parts[0];
$inner = array_slice($parts, 1);
$points_arr = $this->extractPoints($outer, $scale_data, true);
foreach ($inner as $inner_poly) {
$points_arr = array_merge(
$points_arr,
$this->extractPoints($inner_poly, $scale_data, true)
);
}
}
// draw polygon
$pdf->Polygon($points_arr, 'F*', [], $color, true);
// print label if applicable
if ($label !== '') {
$pdf->setXY($points_arr[2], $points_arr[3]);
$pdf->setFontSize(5);
$pdf->Cell(0, 0, $label);
}
return $pdf;
}
/**
* Prepares and returns the code related to a row in the GIS dataset as SVG.
*
* @param string $spatial GIS POLYGON object
* @param string $label Label for the GIS POLYGON object
* @param string $fill_color Color for the GIS POLYGON object
* @param array $scale_data Array containing data related to scaling
*
* @return string the code related to a row in the GIS dataset
*/
public function prepareRowAsSvg($spatial, $label, $fill_color, array $scale_data)
{
$polygon_options = [
'name' => $label,
'id' => $label . $this->getRandomId(),
'class' => 'polygon vector',
'stroke' => 'black',
'stroke-width' => 0.5,
'fill' => $fill_color,
'fill-rule' => 'evenodd',
'fill-opacity' => 0.8,
];
// Trim to remove leading 'POLYGON((' and trailing '))'
$polygon = mb_substr($spatial, 9, -2);
$row = '<path d="';
// If the polygon doesn't have an inner polygon
if (! str_contains($polygon, '),(')) {
$row .= $this->drawPath($polygon, $scale_data);
} else {
// Separate outer and inner polygons
$parts = explode('),(', $polygon);
$outer = $parts[0];
$inner = array_slice($parts, 1);
$row .= $this->drawPath($outer, $scale_data);
foreach ($inner as $inner_poly) {
$row .= $this->drawPath($inner_poly, $scale_data);
}
}
$row .= '"';
foreach ($polygon_options as $option => $val) {
$row .= ' ' . $option . '="' . trim((string) $val) . '"';
}
$row .= '/>';
return $row;
}
/**
* Prepares JavaScript related to a row in the GIS dataset
* to visualize it with OpenLayers.
*
* @param string $spatial GIS POLYGON object
* @param int $srid Spatial reference ID
* @param string $label Label for the GIS POLYGON object
* @param array $fill_color Color for the GIS POLYGON object
* @param array $scale_data Array containing data related to scaling
*
* @return string JavaScript related to a row in the GIS dataset
*/
public function prepareRowAsOl($spatial, int $srid, $label, $fill_color, array $scale_data)
{
$fill_color[] = 0.8;
$fill_style = ['color' => $fill_color];
$stroke_style = [
'color' => [0,0,0],
'width' => 0.5,
];
$row = 'var style = new ol.style.Style({'
. 'fill: new ol.style.Fill(' . json_encode($fill_style) . '),'
. 'stroke: new ol.style.Stroke(' . json_encode($stroke_style) . ')';
if (trim($label) !== '') {
$text_style = ['text' => trim($label)];
$row .= ',text: new ol.style.Text(' . json_encode($text_style) . ')';
}
$row .= '});';
if ($srid === 0) {
$srid = 4326;
}
$row .= $this->getBoundsForOl($srid, $scale_data);
// Trim to remove leading 'POLYGON((' and trailing '))'
$polygon = mb_substr($spatial, 9, -2);
// Separate outer and inner polygons
$parts = explode('),(', $polygon);
return $row . $this->getPolygonForOpenLayers($parts, $srid)
. 'var feature = new ol.Feature({geometry: polygon});'
. 'feature.setStyle(style);'
. 'vectorLayer.addFeature(feature);';
}
/**
* Draws a ring of the polygon using SVG path element.
*
* @param string $polygon The ring
* @param array $scale_data Array containing data related to scaling
*
* @return string the code to draw the ring
*/
private function drawPath($polygon, array $scale_data)
{
$points_arr = $this->extractPoints($polygon, $scale_data);
$row = ' M ' . $points_arr[0][0] . ', ' . $points_arr[0][1];
$other_points = array_slice($points_arr, 1, count($points_arr) - 2);
foreach ($other_points as $point) {
$row .= ' L ' . $point[0] . ', ' . $point[1];
}
$row .= ' Z ';
return $row;
}
/**
* Generate the WKT with the set of parameters passed by the GIS editor.
*
* @param array $gis_data GIS data
* @param int $index Index into the parameter object
* @param string|null $empty Value for empty points
*
* @return string WKT with the set of parameters passed by the GIS editor
*/
public function generateWkt(array $gis_data, $index, $empty = '')
{
$no_of_lines = $gis_data[$index]['POLYGON']['no_of_lines'] ?? 1;
if ($no_of_lines < 1) {
$no_of_lines = 1;
}
$wkt = 'POLYGON(';
for ($i = 0; $i < $no_of_lines; $i++) {
$no_of_points = $gis_data[$index]['POLYGON'][$i]['no_of_points'] ?? 4;
if ($no_of_points < 4) {
$no_of_points = 4;
}
$wkt .= '(';
for ($j = 0; $j < $no_of_points; $j++) {
$wkt .= (isset($gis_data[$index]['POLYGON'][$i][$j]['x'])
&& trim((string) $gis_data[$index]['POLYGON'][$i][$j]['x']) != ''
? $gis_data[$index]['POLYGON'][$i][$j]['x'] : $empty)
. ' ' . (isset($gis_data[$index]['POLYGON'][$i][$j]['y'])
&& trim((string) $gis_data[$index]['POLYGON'][$i][$j]['y']) != ''
? $gis_data[$index]['POLYGON'][$i][$j]['y'] : $empty) . ',';
}
$wkt = mb_substr($wkt, 0, -1);
$wkt .= '),';
}
$wkt = mb_substr($wkt, 0, -1);
return $wkt . ')';
}
/**
* Calculates the area of a closed simple polygon.
*
* @param array $ring array of points forming the ring
*
* @return float the area of a closed simple polygon
*
* @static
*/
public static function area(array $ring)
{
$no_of_points = count($ring);
// If the last point is same as the first point ignore it
$last = count($ring) - 1;
if (($ring[0]['x'] == $ring[$last]['x']) && ($ring[0]['y'] == $ring[$last]['y'])) {
$no_of_points--;
}
// _n-1
// A = _1_ \ (X(i) * Y(i+1)) - (Y(i) * X(i+1))
// 2 /__
// i=0
$area = 0;
for ($i = 0; $i < $no_of_points; $i++) {
$j = ($i + 1) % $no_of_points;
$area += $ring[$i]['x'] * $ring[$j]['y'];
$area -= $ring[$i]['y'] * $ring[$j]['x'];
}
$area /= 2.0;
return $area;
}
/**
* Determines whether a set of points represents an outer ring.
* If points are in clockwise orientation then, they form an outer ring.
*
* @param array $ring array of points forming the ring
*
* @static
*/
public static function isOuterRing(array $ring): bool
{
// If area is negative then it's in clockwise orientation,
// i.e. it's an outer ring
return self::area($ring) < 0;
}
/**
* Determines whether a given point is inside a given polygon.
*
* @param array $point x, y coordinates of the point
* @param array $polygon array of points forming the ring
*
* @static
*/
public static function isPointInsidePolygon(array $point, array $polygon): bool
{
// If first point is repeated at the end remove it
$last = count($polygon) - 1;
if (($polygon[0]['x'] == $polygon[$last]['x']) && ($polygon[0]['y'] == $polygon[$last]['y'])) {
$polygon = array_slice($polygon, 0, $last);
}
$no_of_points = count($polygon);
$counter = 0;
// Use ray casting algorithm
$p1 = $polygon[0];
for ($i = 1; $i <= $no_of_points; $i++) {
$p2 = $polygon[$i % $no_of_points];
if ($point['y'] <= min([$p1['y'], $p2['y']])) {
$p1 = $p2;
continue;
}
if ($point['y'] > max([$p1['y'], $p2['y']])) {
$p1 = $p2;
continue;
}
if ($point['x'] > max([$p1['x'], $p2['x']])) {
$p1 = $p2;
continue;
}
if ($p1['y'] != $p2['y']) {
$xinters = ($point['y'] - $p1['y'])
* ($p2['x'] - $p1['x'])
/ ($p2['y'] - $p1['y']) + $p1['x'];
if ($p1['x'] == $p2['x'] || $point['x'] <= $xinters) {
$counter++;
}
}
$p1 = $p2;
}
return $counter % 2 != 0;
}
/**
* Returns a point that is guaranteed to be on the surface of the ring.
* (for simple closed rings)
*
* @param array $ring array of points forming the ring
*
* @return array|false a point on the surface of the ring
*/
public static function getPointOnSurface(array $ring)
{
$x0 = null;
$x1 = null;
$y0 = null;
$y1 = null;
// Find two consecutive distinct points.
for ($i = 0, $nb = count($ring) - 1; $i < $nb; $i++) {
if ($ring[$i]['y'] != $ring[$i + 1]['y']) {
$x0 = $ring[$i]['x'];
$x1 = $ring[$i + 1]['x'];
$y0 = $ring[$i]['y'];
$y1 = $ring[$i + 1]['y'];
break;
}
}
if (! isset($x0)) {
return false;
}
// Find the mid point
$x2 = ($x0 + $x1) / 2;
$y2 = ($y0 + $y1) / 2;
// Always keep $epsilon < 1 to go with the reduction logic down here
$epsilon = 0.1;
$denominator = sqrt(($y1 - $y0) ** 2 + ($x0 - $x1) ** 2);
$pointA = [];
$pointB = [];
while (true) {
// Get the points on either sides of the line
// with a distance of epsilon to the mid point
$pointA['x'] = $x2 + ($epsilon * ($y1 - $y0)) / $denominator;
$pointA['y'] = $y2 + ($pointA['x'] - $x2) * ($x0 - $x1) / ($y1 - $y0);
$pointB['x'] = $x2 + ($epsilon * ($y1 - $y0)) / (0 - $denominator);
$pointB['y'] = $y2 + ($pointB['x'] - $x2) * ($x0 - $x1) / ($y1 - $y0);
// One of the points should be inside the polygon,
// unless epsilon chosen is too large
if (self::isPointInsidePolygon($pointA, $ring)) {
return $pointA;
}
if (self::isPointInsidePolygon($pointB, $ring)) {
return $pointB;
}
//If both are outside the polygon reduce the epsilon and
//recalculate the points(reduce exponentially for faster convergence)
$epsilon **= 2;
if ($epsilon == 0) {
return false;
}
}
}
/**
* Generate parameters for the GIS data editor from the value of the GIS column.
*
* @param string $value Value of the GIS column
* @param int $index Index of the geometry
*
* @return array params for the GIS data editor from the value of the GIS column
*/
public function generateParams($value, $index = -1)
{
$params = [];
if ($index == -1) {
$index = 0;
$data = GisGeometry::generateParams($value);
$params['srid'] = $data['srid'];
$wkt = $data['wkt'];
} else {
$params[$index]['gis_type'] = 'POLYGON';
$wkt = $value;
}
// Trim to remove leading 'POLYGON((' and trailing '))'
$polygon = mb_substr($wkt, 9, -2);
// Separate each linestring
$linerings = explode('),(', $polygon);
$params[$index]['POLYGON']['no_of_lines'] = count($linerings);
$j = 0;
foreach ($linerings as $linering) {
$points_arr = $this->extractPoints($linering, null);
$no_of_points = count($points_arr);
$params[$index]['POLYGON'][$j]['no_of_points'] = $no_of_points;
for ($i = 0; $i < $no_of_points; $i++) {
$params[$index]['POLYGON'][$j][$i]['x'] = $points_arr[$i][0];
$params[$index]['POLYGON'][$j][$i]['y'] = $points_arr[$i][1];
}
$j++;
}
return $params;
}
}

View file

@ -0,0 +1,719 @@
<?php
/**
* Handles visualization of GIS data
*/
declare(strict_types=1);
namespace PhpMyAdmin\Gis;
use PhpMyAdmin\Core;
use PhpMyAdmin\Image\ImageWrapper;
use PhpMyAdmin\Sanitize;
use PhpMyAdmin\Util;
use TCPDF;
use function array_merge;
use function base64_encode;
use function count;
use function intval;
use function is_numeric;
use function is_string;
use function mb_strlen;
use function mb_strpos;
use function mb_strtolower;
use function mb_substr;
use function ob_get_clean;
use function ob_start;
use function rtrim;
use const PNG_ALL_FILTERS;
/**
* Handles visualization of GIS data
*/
class GisVisualization
{
/** @var array Raw data for the visualization */
private $data;
/** @var string */
private $modifiedSql;
/** @var array Set of default settings values are here. */
private $settings = [
// Array of colors to be used for GIS visualizations.
'colors' => [
'#B02EE0',
'#E0642E',
'#E0D62E',
'#2E97E0',
'#BCE02E',
'#E02E75',
'#5CE02E',
'#E0B02E',
'#0022E0',
'#726CB1',
'#481A36',
'#BAC658',
'#127224',
'#825119',
'#238C74',
'#4C489B',
'#87C9BF',
],
// Hex values for abovementioned colours
'colors_hex' => [
[176, 46, 224],
[224, 100, 46],
[224, 214, 46],
[46, 151, 224],
[188, 224, 46],
[224, 46, 117],
[92, 224, 46],
[224, 176, 46],
[0, 34, 224],
[114, 108, 177],
[72, 26, 54],
[186, 198, 88],
[18, 114, 36],
[130, 81, 25],
[35, 140, 116],
[76, 72, 155],
[135, 201, 191],
],
// The width of the GIS visualization.
'width' => 600,
// The height of the GIS visualization.
'height' => 450,
];
/** @var array Options that the user has specified. */
private $userSpecifiedSettings = null;
/**
* Returns the settings array
*
* @return array the settings array
*/
public function getSettings()
{
return $this->settings;
}
/**
* Factory
*
* @param string $sql_query SQL to fetch raw data for visualization
* @param array $options Users specified options
* @param int $row number of rows
* @param int $pos start position
*
* @return GisVisualization
*/
public static function get($sql_query, array $options, $row, $pos)
{
return new GisVisualization($sql_query, $options, $row, $pos);
}
/**
* Get visualization
*
* @param array $data Raw data, if set, parameters other than $options will be
* ignored
* @param array $options Users specified options
*
* @return GisVisualization
*/
public static function getByData(array $data, array $options)
{
return new GisVisualization(null, $options, null, null, $data);
}
/**
* Check if data has SRID
*/
public function hasSrid(): bool
{
foreach ($this->data as $row) {
if ($row['srid'] != 0) {
return true;
}
}
return false;
}
/**
* Stores user specified options.
*
* @param string $sql_query SQL to fetch raw data for visualization
* @param array $options Users specified options
* @param int $row number of rows
* @param int $pos start position
* @param array|null $data raw data. If set, parameters other than $options
* will be ignored
*/
private function __construct($sql_query, array $options, $row, $pos, $data = null)
{
$this->userSpecifiedSettings = $options;
if (isset($data)) {
$this->data = $data;
} else {
$this->modifiedSql = $this->modifySqlQuery($sql_query, $row, $pos);
$this->data = $this->fetchRawData();
}
}
/**
* All the variable initialization, options handling has to be done here.
*/
protected function init(): void
{
$this->handleOptions();
}
/**
* Returns sql for fetching raw data
*
* @param string $sql_query The SQL to modify.
* @param int $rows Number of rows.
* @param int $pos Start position.
*
* @return string the modified sql query.
*/
private function modifySqlQuery($sql_query, $rows, $pos)
{
$isMariaDb = $this->userSpecifiedSettings['isMariaDB'] === true;
$modified_query = 'SELECT ';
$spatialAsText = 'ASTEXT';
$spatialSrid = 'SRID';
$axisOrder = '';
if ($this->userSpecifiedSettings['mysqlVersion'] >= 50600) {
$spatialAsText = 'ST_ASTEXT';
$spatialSrid = 'ST_SRID';
}
// If MYSQL version >= 8.0.1 override default axis order
if ($this->userSpecifiedSettings['mysqlVersion'] >= 80001 && ! $isMariaDb) {
$axisOrder = ', \'axis-order=long-lat\'';
}
// If label column is chosen add it to the query
if (! empty($this->userSpecifiedSettings['labelColumn'])) {
$modified_query .= Util::backquote($this->userSpecifiedSettings['labelColumn'])
. ', ';
}
// Wrap the spatial column with 'ST_ASTEXT()' function and add it
$modified_query .= $spatialAsText . '('
. Util::backquote($this->userSpecifiedSettings['spatialColumn'])
. $axisOrder . ') AS ' . Util::backquote($this->userSpecifiedSettings['spatialColumn'])
. ', ';
// Get the SRID
$modified_query .= $spatialSrid . '('
. Util::backquote($this->userSpecifiedSettings['spatialColumn'])
. ') AS ' . Util::backquote('srid') . ' ';
// Append the original query as the inner query
$modified_query .= 'FROM (' . rtrim($sql_query, ';') . ') AS '
. Util::backquote('temp_gis');
// LIMIT clause
if (is_numeric($rows) && $rows > 0) {
$modified_query .= ' LIMIT ';
if (is_numeric($pos) && $pos >= 0) {
$modified_query .= $pos . ', ' . $rows;
} else {
$modified_query .= $rows;
}
}
return $modified_query;
}
/**
* Returns raw data for GIS visualization.
*
* @return array the raw data.
*/
private function fetchRawData(): array
{
global $dbi;
$modified_result = $dbi->tryQuery($this->modifiedSql);
if ($modified_result === false) {
return [];
}
return $modified_result->fetchAllAssoc();
}
/**
* A function which handles passed parameters. Useful if desired
* chart needs to be a little bit different from the default one.
*/
private function handleOptions(): void
{
if ($this->userSpecifiedSettings === null) {
return;
}
$this->settings = array_merge($this->settings, $this->userSpecifiedSettings);
}
/**
* Sanitizes the file name.
*
* @param string $file_name file name
* @param string $ext extension of the file
*
* @return string the sanitized file name
*/
private function sanitizeName($file_name, $ext)
{
$file_name = Sanitize::sanitizeFilename($file_name);
// Check if the user already added extension;
// get the substring where the extension would be if it was included
$required_extension = '.' . $ext;
$extension_length = mb_strlen($required_extension);
$user_extension = mb_substr($file_name, -$extension_length);
if (mb_strtolower($user_extension) != $required_extension) {
$file_name .= $required_extension;
}
return $file_name;
}
/**
* Handles common tasks of writing the visualization to file for various formats.
*
* @param string $file_name file name
* @param string $type mime type
* @param string $ext extension of the file
*/
private function writeToFile($file_name, $type, $ext): void
{
$file_name = $this->sanitizeName($file_name, $ext);
Core::downloadHeader($file_name, $type);
}
/**
* Generate the visualization in SVG format.
*
* @return string the generated image resource
*/
private function svg()
{
$this->init();
$output = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>'
. "\n"
. '<svg version="1.1" xmlns:svg="http://www.w3.org/2000/svg"'
. ' xmlns="http://www.w3.org/2000/svg"'
. ' width="' . intval($this->settings['width']) . '"'
. ' height="' . intval($this->settings['height']) . '">'
. '<g id="groupPanel">';
$scale_data = $this->scaleDataSet($this->data);
$output .= $this->prepareDataSet($this->data, $scale_data, 'svg', '');
$output .= '</g></svg>';
return $output;
}
/**
* Get the visualization as a SVG.
*
* @return string the visualization as a SVG
*/
public function asSVG()
{
return $this->svg();
}
/**
* Saves as a SVG image to a file.
*
* @param string $file_name File name
*/
public function toFileAsSvg($file_name): void
{
$img = $this->svg();
$this->writeToFile($file_name, 'image/svg+xml', 'svg');
echo $img;
}
/**
* Generate the visualization in PNG format.
*
* @return ImageWrapper|null the generated image resource
*/
private function png(): ?ImageWrapper
{
$this->init();
$image = ImageWrapper::create(
$this->settings['width'],
$this->settings['height'],
['red' => 229, 'green' => 229, 'blue' => 229]
);
if ($image === null) {
return null;
}
$scale_data = $this->scaleDataSet($this->data);
/** @var ImageWrapper $image */
$image = $this->prepareDataSet($this->data, $scale_data, 'png', $image);
return $image;
}
/**
* Get the visualization as a PNG.
*
* @return string the visualization as a PNG
*/
public function asPng()
{
$image = $this->png();
if ($image === null) {
return '';
}
// render and save it to variable
ob_start();
$image->png(null, 9, PNG_ALL_FILTERS);
$image->destroy();
$output = ob_get_clean();
// base64 encode
$encoded = base64_encode((string) $output);
return '<img src="data:image/png;base64,' . $encoded . '">';
}
/**
* Saves as a PNG image to a file.
*
* @param string $file_name File name
*/
public function toFileAsPng($file_name): void
{
$image = $this->png();
if ($image === null) {
return;
}
$this->writeToFile($file_name, 'image/png', 'png');
$image->png(null, 9, PNG_ALL_FILTERS);
$image->destroy();
}
/**
* Get the code for visualization with OpenLayers.
*
* @return string the code for visualization with OpenLayers
*
* @todo Should return JSON to avoid eval() in gis_data_editor.js
*/
public function asOl()
{
$this->init();
$scale_data = $this->scaleDataSet($this->data);
$output = 'function drawOpenLayers() {'
. 'if (typeof ol !== "undefined") {'
. 'var olCss = "js/vendor/openlayers/theme/ol.css";'
. '$(\'head\').append(\'<link rel="stylesheet" type="text/css" href=\'+olCss+\'>\');'
. 'var vectorLayer = new ol.source.Vector({});'
. 'var map = new ol.Map({'
. 'target: \'openlayersmap\','
. 'layers: ['
. 'new ol.layer.Tile({'
. 'source: new ol.source.OSM()'
. '}),'
. 'new ol.layer.Vector({'
. 'source: vectorLayer'
. '})'
. '],'
. 'view: new ol.View({'
. 'center: ol.proj.fromLonLat([37.41, 8.82]),'
. 'zoom: 4'
. '}),'
. 'controls: [new ol.control.MousePosition({'
. 'coordinateFormat: ol.coordinate.createStringXY(4),'
. 'projection: \'EPSG:4326\'}),'
. 'new ol.control.Zoom,'
. 'new ol.control.Attribution]'
. '});';
$output .= $this->prepareDataSet($this->data, $scale_data, 'ol', '')
. 'return map;'
. '}'
. 'return undefined;'
. '}';
return $output;
}
/**
* Saves as a PDF to a file.
*
* @param string $file_name File name
*/
public function toFileAsPdf($file_name): void
{
$this->init();
// create pdf
$pdf = new TCPDF('', 'pt', $GLOBALS['cfg']['PDFDefaultPageSize'], true, 'UTF-8', false);
// disable header and footer
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
//set auto page breaks
$pdf->setAutoPageBreak(false);
// add a page
$pdf->AddPage();
$scale_data = $this->scaleDataSet($this->data);
$pdf = $this->prepareDataSet($this->data, $scale_data, 'pdf', $pdf);
// sanitize file name
$file_name = $this->sanitizeName($file_name, 'pdf');
$pdf->Output($file_name, 'D');
}
/**
* Convert file to image
*
* @param string $format Output format
*
* @return string File
*/
public function toImage($format)
{
if ($format === 'svg') {
return $this->asSVG();
}
if ($format === 'png') {
return $this->asPng();
}
if ($format === 'ol') {
return $this->asOl();
}
return '';
}
/**
* Convert file to given format
*
* @param string $filename Filename
* @param string $format Output format
*/
public function toFile($filename, $format): void
{
if ($format === 'svg') {
$this->toFileAsSvg($filename);
} elseif ($format === 'png') {
$this->toFileAsPng($filename);
} elseif ($format === 'pdf') {
$this->toFileAsPdf($filename);
}
}
/**
* Calculates the scale, horizontal and vertical offset that should be used.
*
* @param array $data Row data
*
* @return array an array containing the scale, x and y offsets
*/
private function scaleDataSet(array $data)
{
$min_max = [
'maxX' => 0.0,
'maxY' => 0.0,
'minX' => 0.0,
'minY' => 0.0,
];
$border = 15;
// effective width and height of the plot
$plot_width = $this->settings['width'] - 2 * $border;
$plot_height = $this->settings['height'] - 2 * $border;
foreach ($data as $row) {
// Figure out the data type
$ref_data = $row[$this->settings['spatialColumn']];
if (! is_string($ref_data)) {
continue;
}
$type_pos = mb_strpos($ref_data, '(');
if ($type_pos === false) {
continue;
}
$type = mb_substr($ref_data, 0, $type_pos);
$gis_obj = GisFactory::factory($type);
if (! $gis_obj) {
continue;
}
$scale_data = $gis_obj->scaleRow($row[$this->settings['spatialColumn']]);
// Update minimum/maximum values for x and y coordinates.
$c_maxX = (float) $scale_data['maxX'];
if ($min_max['maxX'] === 0.0 || $c_maxX > $min_max['maxX']) {
$min_max['maxX'] = $c_maxX;
}
$c_minX = (float) $scale_data['minX'];
if ($min_max['minX'] === 0.0 || $c_minX < $min_max['minX']) {
$min_max['minX'] = $c_minX;
}
$c_maxY = (float) $scale_data['maxY'];
if ($min_max['maxY'] === 0.0 || $c_maxY > $min_max['maxY']) {
$min_max['maxY'] = $c_maxY;
}
$c_minY = (float) $scale_data['minY'];
if ($min_max['minY'] !== 0.0 && $c_minY >= $min_max['minY']) {
continue;
}
$min_max['minY'] = $c_minY;
}
// scale the visualization
$x_ratio = ($min_max['maxX'] - $min_max['minX']) / $plot_width;
$y_ratio = ($min_max['maxY'] - $min_max['minY']) / $plot_height;
$ratio = $x_ratio > $y_ratio ? $x_ratio : $y_ratio;
$scale = $ratio != 0 ? 1 / $ratio : 1;
// Center plot
$x = $ratio == 0 || $x_ratio < $y_ratio
? ($min_max['maxX'] + $min_max['minX'] - $this->settings['width'] / $scale) / 2
: $min_max['minX'] - ($border / $scale);
$y = $ratio == 0 || $x_ratio >= $y_ratio
? ($min_max['maxY'] + $min_max['minY'] - $this->settings['height'] / $scale) / 2
: $min_max['minY'] - ($border / $scale);
return [
'scale' => $scale,
'x' => $x,
'y' => $y,
'minX' => $min_max['minX'],
'maxX' => $min_max['maxX'],
'minY' => $min_max['minY'],
'maxY' => $min_max['maxY'],
'height' => $this->settings['height'],
];
}
/**
* Prepares and return the dataset as needed by the visualization.
*
* @param array $data Raw data
* @param array $scale_data Data related to scaling
* @param string $format Format of the visualization
* @param ImageWrapper|TCPDF|string|false $results Image object in the case of png
* TCPDF object in the case of pdf
*
* @return mixed the formatted array of data
*/
private function prepareDataSet(array $data, array $scale_data, $format, $results)
{
$color_number = 0;
// loop through the rows
foreach ($data as $row) {
$index = $color_number % count($this->settings['colors']);
// Figure out the data type
$ref_data = $row[$this->settings['spatialColumn']];
if (! is_string($ref_data)) {
continue;
}
$type_pos = mb_strpos($ref_data, '(');
if ($type_pos === false) {
continue;
}
$type = mb_substr($ref_data, 0, $type_pos);
$gis_obj = GisFactory::factory($type);
if (! $gis_obj) {
continue;
}
$label = '';
if (isset($this->settings['labelColumn'], $row[$this->settings['labelColumn']])) {
$label = $row[$this->settings['labelColumn']];
}
if ($format === 'svg') {
$results .= $gis_obj->prepareRowAsSvg(
$row[$this->settings['spatialColumn']],
$label,
$this->settings['colors'][$index],
$scale_data
);
} elseif ($format === 'png') {
$results = $gis_obj->prepareRowAsPng(
$row[$this->settings['spatialColumn']],
$label,
$this->settings['colors'][$index],
$scale_data,
$results
);
} elseif ($format === 'pdf' && $results instanceof TCPDF) {
$results = $gis_obj->prepareRowAsPdf(
$row[$this->settings['spatialColumn']],
$label,
$this->settings['colors'][$index],
$scale_data,
$results
);
} elseif ($format === 'ol') {
$results .= $gis_obj->prepareRowAsOl(
$row[$this->settings['spatialColumn']],
(int) $row['srid'],
$label,
$this->settings['colors_hex'][$index],
$scale_data
);
}
$color_number++;
}
return $results;
}
/**
* Set user specified settings
*
* @param array $userSpecifiedSettings User specified settings
*/
public function setUserSpecifiedSettings(array $userSpecifiedSettings): void
{
$this->userSpecifiedSettings = $userSpecifiedSettings;
}
}