GisPolygon.php 19 KB

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