GisPolygon.php 19 KB

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