GisPolygon.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. <?php
  2. /**
  3. * Handles actions related to GIS POLYGON objects
  4. */
  5. declare(strict_types=1);
  6. namespace PhpMyAdmin\Gis;
  7. use PhpMyAdmin\Image\ImageWrapper;
  8. use TCPDF;
  9. use function array_merge;
  10. use function array_slice;
  11. use function count;
  12. use function explode;
  13. use function hexdec;
  14. use function json_encode;
  15. use function max;
  16. use function mb_substr;
  17. use function min;
  18. use function round;
  19. use function sqrt;
  20. use function str_contains;
  21. use function trim;
  22. /**
  23. * Handles actions related to GIS POLYGON objects
  24. */
  25. class GisPolygon extends GisGeometry
  26. {
  27. /** @var self */
  28. private static $instance;
  29. /**
  30. * A private constructor; prevents direct creation of object.
  31. */
  32. private function __construct()
  33. {
  34. }
  35. /**
  36. * Returns the singleton.
  37. *
  38. * @return GisPolygon the singleton
  39. */
  40. public static function singleton()
  41. {
  42. if (! isset(self::$instance)) {
  43. self::$instance = new GisPolygon();
  44. }
  45. return self::$instance;
  46. }
  47. /**
  48. * Scales each row.
  49. *
  50. * @param string $spatial spatial data of a row
  51. *
  52. * @return array an array containing the min, max values for x and y coordinates
  53. * @psalm-return array{minX:float,minY:float,maxX:float,maxY:float}
  54. */
  55. public function scaleRow($spatial)
  56. {
  57. // Trim to remove leading 'POLYGON((' and trailing '))'
  58. $polygon = mb_substr($spatial, 9, -2);
  59. // If the polygon doesn't have an inner ring, use polygon itself
  60. if (! str_contains($polygon, '),(')) {
  61. $ring = $polygon;
  62. } else {
  63. // Separate outer ring and use it to determine min-max
  64. $parts = explode('),(', $polygon);
  65. $ring = $parts[0];
  66. }
  67. return $this->setMinMax($ring, GisGeometry::EMPTY_EXTENT);
  68. }
  69. /**
  70. * Adds to the PNG image object, the data related to a row in the GIS dataset.
  71. *
  72. * @param string $spatial GIS POLYGON object
  73. * @param string|null $label Label for the GIS POLYGON object
  74. * @param string $fill_color Color for the GIS POLYGON object
  75. * @param array $scale_data Array containing data related to scaling
  76. */
  77. public function prepareRowAsPng(
  78. $spatial,
  79. ?string $label,
  80. $fill_color,
  81. array $scale_data,
  82. ImageWrapper $image
  83. ): ImageWrapper {
  84. // allocate colors
  85. $black = $image->colorAllocate(0, 0, 0);
  86. $red = (int) hexdec(mb_substr($fill_color, 1, 2));
  87. $green = (int) hexdec(mb_substr($fill_color, 3, 2));
  88. $blue = (int) hexdec(mb_substr($fill_color, 4, 2));
  89. $color = $image->colorAllocate($red, $green, $blue);
  90. $label = trim($label ?? '');
  91. // Trim to remove leading 'POLYGON((' and trailing '))'
  92. $polygon = mb_substr($spatial, 9, -2);
  93. // If the polygon doesn't have an inner polygon
  94. if (! str_contains($polygon, '),(')) {
  95. $points_arr = $this->extractPoints($polygon, $scale_data, true);
  96. } else {
  97. // Separate outer and inner polygons
  98. $parts = explode('),(', $polygon);
  99. $outer = $parts[0];
  100. $inner = array_slice($parts, 1);
  101. $points_arr = $this->extractPoints($outer, $scale_data, true);
  102. foreach ($inner as $inner_poly) {
  103. $points_arr = array_merge(
  104. $points_arr,
  105. $this->extractPoints($inner_poly, $scale_data, true)
  106. );
  107. }
  108. }
  109. // draw polygon
  110. $image->filledPolygon($points_arr, $color);
  111. // print label if applicable
  112. if ($label !== '') {
  113. $image->string(
  114. 1,
  115. (int) round($points_arr[2]),
  116. (int) round($points_arr[3]),
  117. $label,
  118. $black
  119. );
  120. }
  121. return $image;
  122. }
  123. /**
  124. * Adds to the TCPDF instance, the data related to a row in the GIS dataset.
  125. *
  126. * @param string $spatial GIS POLYGON object
  127. * @param string|null $label Label for the GIS POLYGON object
  128. * @param string $fill_color Color for the GIS POLYGON object
  129. * @param array $scale_data Array containing data related to scaling
  130. * @param TCPDF $pdf TCPDF instance
  131. *
  132. * @return TCPDF the modified TCPDF instance
  133. */
  134. public function prepareRowAsPdf($spatial, ?string $label, $fill_color, array $scale_data, $pdf)
  135. {
  136. // allocate colors
  137. $red = hexdec(mb_substr($fill_color, 1, 2));
  138. $green = hexdec(mb_substr($fill_color, 3, 2));
  139. $blue = hexdec(mb_substr($fill_color, 4, 2));
  140. $color = [
  141. $red,
  142. $green,
  143. $blue,
  144. ];
  145. $label = trim($label ?? '');
  146. // Trim to remove leading 'POLYGON((' and trailing '))'
  147. $polygon = mb_substr($spatial, 9, -2);
  148. // If the polygon doesn't have an inner polygon
  149. if (! str_contains($polygon, '),(')) {
  150. $points_arr = $this->extractPoints($polygon, $scale_data, true);
  151. } else {
  152. // Separate outer and inner polygons
  153. $parts = explode('),(', $polygon);
  154. $outer = $parts[0];
  155. $inner = array_slice($parts, 1);
  156. $points_arr = $this->extractPoints($outer, $scale_data, true);
  157. foreach ($inner as $inner_poly) {
  158. $points_arr = array_merge(
  159. $points_arr,
  160. $this->extractPoints($inner_poly, $scale_data, true)
  161. );
  162. }
  163. }
  164. // draw polygon
  165. $pdf->Polygon($points_arr, 'F*', [], $color, true);
  166. // print label if applicable
  167. if ($label !== '') {
  168. $pdf->setXY($points_arr[2], $points_arr[3]);
  169. $pdf->setFontSize(5);
  170. $pdf->Cell(0, 0, $label);
  171. }
  172. return $pdf;
  173. }
  174. /**
  175. * Prepares and returns the code related to a row in the GIS dataset as SVG.
  176. *
  177. * @param string $spatial GIS POLYGON object
  178. * @param string $label Label for the GIS POLYGON object
  179. * @param string $fill_color Color for the GIS POLYGON object
  180. * @param array $scale_data Array containing data related to scaling
  181. *
  182. * @return string the code related to a row in the GIS dataset
  183. */
  184. public function prepareRowAsSvg($spatial, $label, $fill_color, array $scale_data)
  185. {
  186. $polygon_options = [
  187. 'data-label' => $label,
  188. 'id' => $label . $this->getRandomId(),
  189. 'class' => 'polygon vector',
  190. 'stroke' => 'black',
  191. 'stroke-width' => 0.5,
  192. 'fill' => $fill_color,
  193. 'fill-rule' => 'evenodd',
  194. 'fill-opacity' => 0.8,
  195. ];
  196. // Trim to remove leading 'POLYGON((' and trailing '))'
  197. $polygon = mb_substr($spatial, 9, -2);
  198. $row = '<path d="';
  199. // If the polygon doesn't have an inner polygon
  200. if (! str_contains($polygon, '),(')) {
  201. $row .= $this->drawPath($polygon, $scale_data);
  202. } else {
  203. // Separate outer and inner polygons
  204. $parts = explode('),(', $polygon);
  205. $outer = $parts[0];
  206. $inner = array_slice($parts, 1);
  207. $row .= $this->drawPath($outer, $scale_data);
  208. foreach ($inner as $inner_poly) {
  209. $row .= $this->drawPath($inner_poly, $scale_data);
  210. }
  211. }
  212. $row .= '"';
  213. foreach ($polygon_options as $option => $val) {
  214. $row .= ' ' . $option . '="' . trim((string) $val) . '"';
  215. }
  216. $row .= '/>';
  217. return $row;
  218. }
  219. /**
  220. * Prepares JavaScript related to a row in the GIS dataset
  221. * to visualize it with OpenLayers.
  222. *
  223. * @param string $spatial GIS POLYGON object
  224. * @param int $srid Spatial reference ID
  225. * @param string $label Label for the GIS POLYGON object
  226. * @param array $fill_color Color for the GIS POLYGON object
  227. * @param array $scale_data Array containing data related to scaling
  228. *
  229. * @return string JavaScript related to a row in the GIS dataset
  230. */
  231. public function prepareRowAsOl($spatial, int $srid, $label, $fill_color, array $scale_data)
  232. {
  233. $fill_color[] = 0.8;
  234. $fill_style = ['color' => $fill_color];
  235. $stroke_style = [
  236. 'color' => [0,0,0],
  237. 'width' => 0.5,
  238. ];
  239. $row = 'var style = new ol.style.Style({'
  240. . 'fill: new ol.style.Fill(' . json_encode($fill_style) . '),'
  241. . 'stroke: new ol.style.Stroke(' . json_encode($stroke_style) . ')';
  242. if (trim($label) !== '') {
  243. $text_style = ['text' => trim($label)];
  244. $row .= ',text: new ol.style.Text(' . json_encode($text_style) . ')';
  245. }
  246. $row .= '});';
  247. if ($srid === 0) {
  248. $srid = 4326;
  249. }
  250. $row .= $this->getBoundsForOl($srid, $scale_data);
  251. // Trim to remove leading 'POLYGON((' and trailing '))'
  252. $polygon = mb_substr($spatial, 9, -2);
  253. // Separate outer and inner polygons
  254. $parts = explode('),(', $polygon);
  255. return $row . $this->getPolygonForOpenLayers($parts, $srid)
  256. . 'var feature = new ol.Feature({geometry: polygon});'
  257. . 'feature.setStyle(style);'
  258. . 'vectorLayer.addFeature(feature);';
  259. }
  260. /**
  261. * Draws a ring of the polygon using SVG path element.
  262. *
  263. * @param string $polygon The ring
  264. * @param array $scale_data Array containing data related to scaling
  265. *
  266. * @return string the code to draw the ring
  267. */
  268. private function drawPath($polygon, array $scale_data)
  269. {
  270. $points_arr = $this->extractPoints($polygon, $scale_data);
  271. $row = ' M ' . $points_arr[0][0] . ', ' . $points_arr[0][1];
  272. $other_points = array_slice($points_arr, 1, count($points_arr) - 2);
  273. foreach ($other_points as $point) {
  274. $row .= ' L ' . $point[0] . ', ' . $point[1];
  275. }
  276. $row .= ' Z ';
  277. return $row;
  278. }
  279. /**
  280. * Generate the WKT with the set of parameters passed by the GIS editor.
  281. *
  282. * @param array $gis_data GIS data
  283. * @param int $index Index into the parameter object
  284. * @param string|null $empty Value for empty points
  285. *
  286. * @return string WKT with the set of parameters passed by the GIS editor
  287. */
  288. public function generateWkt(array $gis_data, $index, $empty = '')
  289. {
  290. $no_of_lines = $gis_data[$index]['POLYGON']['no_of_lines'] ?? 1;
  291. if ($no_of_lines < 1) {
  292. $no_of_lines = 1;
  293. }
  294. $wkt = 'POLYGON(';
  295. for ($i = 0; $i < $no_of_lines; $i++) {
  296. $no_of_points = $gis_data[$index]['POLYGON'][$i]['no_of_points'] ?? 4;
  297. if ($no_of_points < 4) {
  298. $no_of_points = 4;
  299. }
  300. $wkt .= '(';
  301. for ($j = 0; $j < $no_of_points; $j++) {
  302. $wkt .= (isset($gis_data[$index]['POLYGON'][$i][$j]['x'])
  303. && trim((string) $gis_data[$index]['POLYGON'][$i][$j]['x']) != ''
  304. ? $gis_data[$index]['POLYGON'][$i][$j]['x'] : $empty)
  305. . ' ' . (isset($gis_data[$index]['POLYGON'][$i][$j]['y'])
  306. && trim((string) $gis_data[$index]['POLYGON'][$i][$j]['y']) != ''
  307. ? $gis_data[$index]['POLYGON'][$i][$j]['y'] : $empty) . ',';
  308. }
  309. $wkt = mb_substr($wkt, 0, -1);
  310. $wkt .= '),';
  311. }
  312. $wkt = mb_substr($wkt, 0, -1);
  313. return $wkt . ')';
  314. }
  315. /**
  316. * Calculates the area of a closed simple polygon.
  317. *
  318. * @param array $ring array of points forming the ring
  319. *
  320. * @return float the area of a closed simple polygon
  321. *
  322. * @static
  323. */
  324. public static function area(array $ring)
  325. {
  326. $no_of_points = count($ring);
  327. // If the last point is same as the first point ignore it
  328. $last = count($ring) - 1;
  329. if (($ring[0]['x'] == $ring[$last]['x']) && ($ring[0]['y'] == $ring[$last]['y'])) {
  330. $no_of_points--;
  331. }
  332. // _n-1
  333. // A = _1_ \ (X(i) * Y(i+1)) - (Y(i) * X(i+1))
  334. // 2 /__
  335. // i=0
  336. $area = 0;
  337. for ($i = 0; $i < $no_of_points; $i++) {
  338. $j = ($i + 1) % $no_of_points;
  339. $area += $ring[$i]['x'] * $ring[$j]['y'];
  340. $area -= $ring[$i]['y'] * $ring[$j]['x'];
  341. }
  342. $area /= 2.0;
  343. return $area;
  344. }
  345. /**
  346. * Determines whether a set of points represents an outer ring.
  347. * If points are in clockwise orientation then, they form an outer ring.
  348. *
  349. * @param array $ring array of points forming the ring
  350. *
  351. * @static
  352. */
  353. public static function isOuterRing(array $ring): bool
  354. {
  355. // If area is negative then it's in clockwise orientation,
  356. // i.e. it's an outer ring
  357. return self::area($ring) < 0;
  358. }
  359. /**
  360. * Determines whether a given point is inside a given polygon.
  361. *
  362. * @param array $point x, y coordinates of the point
  363. * @param array $polygon array of points forming the ring
  364. *
  365. * @static
  366. */
  367. public static function isPointInsidePolygon(array $point, array $polygon): bool
  368. {
  369. // If first point is repeated at the end remove it
  370. $last = count($polygon) - 1;
  371. if (($polygon[0]['x'] == $polygon[$last]['x']) && ($polygon[0]['y'] == $polygon[$last]['y'])) {
  372. $polygon = array_slice($polygon, 0, $last);
  373. }
  374. $no_of_points = count($polygon);
  375. $counter = 0;
  376. // Use ray casting algorithm
  377. $p1 = $polygon[0];
  378. for ($i = 1; $i <= $no_of_points; $i++) {
  379. $p2 = $polygon[$i % $no_of_points];
  380. if ($point['y'] <= min([$p1['y'], $p2['y']])) {
  381. $p1 = $p2;
  382. continue;
  383. }
  384. if ($point['y'] > max([$p1['y'], $p2['y']])) {
  385. $p1 = $p2;
  386. continue;
  387. }
  388. if ($point['x'] > max([$p1['x'], $p2['x']])) {
  389. $p1 = $p2;
  390. continue;
  391. }
  392. if ($p1['y'] != $p2['y']) {
  393. $xinters = ($point['y'] - $p1['y'])
  394. * ($p2['x'] - $p1['x'])
  395. / ($p2['y'] - $p1['y']) + $p1['x'];
  396. if ($p1['x'] == $p2['x'] || $point['x'] <= $xinters) {
  397. $counter++;
  398. }
  399. }
  400. $p1 = $p2;
  401. }
  402. return $counter % 2 != 0;
  403. }
  404. /**
  405. * Returns a point that is guaranteed to be on the surface of the ring.
  406. * (for simple closed rings)
  407. *
  408. * @param array $ring array of points forming the ring
  409. *
  410. * @return array|false a point on the surface of the ring
  411. */
  412. public static function getPointOnSurface(array $ring)
  413. {
  414. $x0 = null;
  415. $x1 = null;
  416. $y0 = null;
  417. $y1 = null;
  418. // Find two consecutive distinct points.
  419. for ($i = 0, $nb = count($ring) - 1; $i < $nb; $i++) {
  420. if ($ring[$i]['y'] != $ring[$i + 1]['y']) {
  421. $x0 = $ring[$i]['x'];
  422. $x1 = $ring[$i + 1]['x'];
  423. $y0 = $ring[$i]['y'];
  424. $y1 = $ring[$i + 1]['y'];
  425. break;
  426. }
  427. }
  428. if (! isset($x0)) {
  429. return false;
  430. }
  431. // Find the mid point
  432. $x2 = ($x0 + $x1) / 2;
  433. $y2 = ($y0 + $y1) / 2;
  434. // Always keep $epsilon < 1 to go with the reduction logic down here
  435. $epsilon = 0.1;
  436. $denominator = sqrt(($y1 - $y0) ** 2 + ($x0 - $x1) ** 2);
  437. $pointA = [];
  438. $pointB = [];
  439. while (true) {
  440. // Get the points on either sides of the line
  441. // with a distance of epsilon to the mid point
  442. $pointA['x'] = $x2 + ($epsilon * ($y1 - $y0)) / $denominator;
  443. $pointA['y'] = $y2 + ($pointA['x'] - $x2) * ($x0 - $x1) / ($y1 - $y0);
  444. $pointB['x'] = $x2 + ($epsilon * ($y1 - $y0)) / (0 - $denominator);
  445. $pointB['y'] = $y2 + ($pointB['x'] - $x2) * ($x0 - $x1) / ($y1 - $y0);
  446. // One of the points should be inside the polygon,
  447. // unless epsilon chosen is too large
  448. if (self::isPointInsidePolygon($pointA, $ring)) {
  449. return $pointA;
  450. }
  451. if (self::isPointInsidePolygon($pointB, $ring)) {
  452. return $pointB;
  453. }
  454. //If both are outside the polygon reduce the epsilon and
  455. //recalculate the points(reduce exponentially for faster convergence)
  456. $epsilon **= 2;
  457. if ($epsilon == 0) {
  458. return false;
  459. }
  460. }
  461. }
  462. /**
  463. * Generate parameters for the GIS data editor from the value of the GIS column.
  464. *
  465. * @param string $value Value of the GIS column
  466. * @param int $index Index of the geometry
  467. *
  468. * @return array params for the GIS data editor from the value of the GIS column
  469. */
  470. public function generateParams($value, $index = -1)
  471. {
  472. $params = [];
  473. if ($index == -1) {
  474. $index = 0;
  475. $data = GisGeometry::generateParams($value);
  476. $params['srid'] = $data['srid'];
  477. $wkt = $data['wkt'];
  478. } else {
  479. $params[$index]['gis_type'] = 'POLYGON';
  480. $wkt = $value;
  481. }
  482. // Trim to remove leading 'POLYGON((' and trailing '))'
  483. $polygon = mb_substr($wkt, 9, -2);
  484. // Separate each linestring
  485. $linerings = explode('),(', $polygon);
  486. $params[$index]['POLYGON']['no_of_lines'] = count($linerings);
  487. $j = 0;
  488. foreach ($linerings as $linering) {
  489. $points_arr = $this->extractPoints($linering, null);
  490. $no_of_points = count($points_arr);
  491. $params[$index]['POLYGON'][$j]['no_of_points'] = $no_of_points;
  492. for ($i = 0; $i < $no_of_points; $i++) {
  493. $params[$index]['POLYGON'][$j][$i]['x'] = $points_arr[$i][0];
  494. $params[$index]['POLYGON'][$j][$i]['y'] = $points_arr[$i][1];
  495. }
  496. $j++;
  497. }
  498. return $params;
  499. }
  500. }