GisPolygon.php 19 KB

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