ShapeFile.php
17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
<?php
/**
* phpMyAdmin ShapeFile library
* <https://github.com/phpmyadmin/shapefile/>.
*
* Copyright 2006-2007 Ovidio <ovidio AT users.sourceforge.net>
* Copyright 2016 - 2017 Michal Čihař <michal@cihar.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, you can download one from
* https://www.gnu.org/copyleft/gpl.html.
*/
namespace PhpMyAdmin\ShapeFile;
/**
* ShapeFile class.
*/
class ShapeFile
{
const MAGIC = 0x270a;
public $FileName;
private $SHPFile = null;
private $SHXFile = null;
private $DBFFile = null;
private $DBFHeader;
public $lastError = '';
public $boundingBox = array('xmin' => 0.0, 'ymin' => 0.0, 'xmax' => 0.0, 'ymax' => 0.0);
private $fileLength = 0;
public $shapeType = 0;
public $records = array();
/**
* Checks whether dbase manipuations are supported.
*
* @return bool
*/
public static function supports_dbase()
{
return extension_loaded('dbase');
}
/**
* @param int $shapeType File shape type, should be same as all records
* @param array $boundingBox File bounding box
* @param null|mixed $FileName File name
*/
public function __construct($shapeType, $boundingBox = array('xmin' => 0.0, 'ymin' => 0.0, 'xmax' => 0.0, 'ymax' => 0.0), $FileName = null)
{
$this->shapeType = $shapeType;
$this->boundingBox = $boundingBox;
$this->FileName = $FileName;
$this->fileLength = 50; // The value for file length is the total length of the file in 16-bit words (including the fifty 16-bit words that make up the header).
}
/**
* Loads shapefile and dbase (if supported).
*
* @param string $FileName File mask to load (eg. example.*)
*/
public function loadFromFile($FileName)
{
if (!empty($FileName)) {
$this->FileName = $FileName;
$result = $this->_openSHPFile();
} else {
/* We operate on buffer emulated by readSHP / eofSHP */
$result = true;
}
if ($result && ($this->_openDBFFile())) {
if (!$this->_loadHeaders()) {
$this->_closeSHPFile();
$this->_closeDBFFile();
return false;
}
if (!$this->_loadRecords()) {
$this->_closeSHPFile();
$this->_closeDBFFile();
return false;
}
$this->_closeSHPFile();
$this->_closeDBFFile();
return true;
}
return false;
}
/**
* Saves shapefile.
*
* @param string|null $FileName Name of file, otherwise existing is used
*/
public function saveToFile($FileName = null)
{
if (!is_null($FileName)) {
$this->FileName = $FileName;
}
if (($this->_openSHPFile(true)) && ($this->_openSHXFile(true)) && ($this->_createDBFFile())) {
$this->_saveHeaders();
$this->_saveRecords();
$this->_closeSHPFile();
$this->_closeSHXFile();
$this->_closeDBFFile();
} else {
return false;
}
}
/**
* Generates filename with given extension.
*
* @param string $extension Extension to use (including dot)
*
* @return string
*/
private function _getFilename($extension)
{
return str_replace('.*', $extension, $this->FileName);
}
/**
* Updates bounding box based on SHPData.
*
* @param string $type Type of box
* @param array $data ShapeRecord SHPData
*/
private function updateBBox($type, $data)
{
$min = $type . 'min';
$max = $type . 'max';
if (!isset($this->boundingBox[$min]) || $this->boundingBox[$min] == 0.0 || ($this->boundingBox[$min] > $data[$min])) {
$this->boundingBox[$min] = $data[$min];
}
if (!isset($this->boundingBox[$max]) || $this->boundingBox[$max] == 0.0 || ($this->boundingBox[$max] < $data[$max])) {
$this->boundingBox[$max] = $data[$max];
}
}
/**
* Adds record to shape file.
*
* @param ShapeRecord $record
*
* @return int Number of added record
*/
public function addRecord($record)
{
if ((isset($this->DBFHeader)) && (is_array($this->DBFHeader))) {
$record->updateDBFInfo($this->DBFHeader);
}
$this->fileLength += ($record->getContentLength() + 4);
$this->records[] = $record;
$this->records[count($this->records) - 1]->recordNumber = count($this->records);
$this->updateBBox('x', $record->SHPData);
$this->updateBBox('y', $record->SHPData);
if (in_array($this->shapeType, array(11, 13, 15, 18, 21, 23, 25, 28))) {
$this->updateBBox('m', $record->SHPData);
}
if (in_array($this->shapeType, array(11, 13, 15, 18))) {
$this->updateBBox('z', $record->SHPData);
}
return count($this->records) - 1;
}
/**
* Deletes record from shapefile.
*
* @param int $index
*/
public function deleteRecord($index)
{
if (isset($this->records[$index])) {
$this->fileLength -= ($this->records[$index]->getContentLength() + 4);
$count = count($this->records) - 1;
for ($i = $index; $i < $count; ++$i) {
$this->records[$i] = $this->records[$i + 1];
}
unset($this->records[count($this->records) - 1]);
$this->_deleteRecordFromDBF($index);
}
}
/**
* Returns array defining fields in DBF file.
*
* @return array see setDBFHeader for more information
*/
public function getDBFHeader()
{
return $this->DBFHeader;
}
/**
* Changes array defining fields in DBF file, used in dbase_create call.
*
* @param array $header An array of arrays, each array describing the
* format of one field of the database. Each
* field consists of a name, a character indicating
* the field type, and optionally, a length,
* a precision and a nullable flag.
*/
public function setDBFHeader($header)
{
$this->DBFHeader = $header;
$count = count($this->records);
for ($i = 0; $i < $count; ++$i) {
$this->records[$i]->updateDBFInfo($header);
}
}
/**
* Lookups value in the DBF file and returs index.
*
* @param string $field Field to match
* @param mixed $value Value to match
*
* @return int
*/
public function getIndexFromDBFData($field, $value)
{
foreach ($this->records as $index => $record) {
if (isset($record->DBFData[$field]) &&
(trim(strtoupper($record->DBFData[$field])) == strtoupper($value))
) {
return $index;
}
}
return -1;
}
/**
* Loads DBF metadata.
*/
private function _loadDBFHeader()
{
$DBFFile = fopen($this->_getFilename('.dbf'), 'r');
$result = array();
$i = 1;
$inHeader = true;
while ($inHeader) {
if (!feof($DBFFile)) {
$buff32 = fread($DBFFile, 32);
if ($i > 1) {
if (substr($buff32, 0, 1) == chr(13)) {
$inHeader = false;
} else {
$pos = strpos(substr($buff32, 0, 10), chr(0));
$pos = ($pos == 0 ? 10 : $pos);
$fieldName = substr($buff32, 0, $pos);
$fieldType = substr($buff32, 11, 1);
$fieldLen = ord(substr($buff32, 16, 1));
$fieldDec = ord(substr($buff32, 17, 1));
array_push($result, array($fieldName, $fieldType, $fieldLen, $fieldDec));
}
}
++$i;
} else {
$inHeader = false;
}
}
fclose($DBFFile);
return $result;
}
/**
* Deletes record from the DBF file.
*
* @param int $index
*/
private function _deleteRecordFromDBF($index)
{
if (@dbase_delete_record($this->DBFFile, $index)) {
dbase_pack($this->DBFFile);
}
}
/**
* Loads SHP file metadata.
*
* @return bool
*/
private function _loadHeaders()
{
if (Util::loadData('N', $this->readSHP(4)) != self::MAGIC) {
$this->setError('Not a SHP file (file code mismatch)');
return false;
}
/* Skip 20 unused bytes */
$this->readSHP(20);
$this->fileLength = Util::loadData('N', $this->readSHP(4));
/* We currently ignore version */
$this->readSHP(4);
$this->shapeType = Util::loadData('V', $this->readSHP(4));
$this->boundingBox = array();
$this->boundingBox['xmin'] = Util::loadData('d', $this->readSHP(8));
$this->boundingBox['ymin'] = Util::loadData('d', $this->readSHP(8));
$this->boundingBox['xmax'] = Util::loadData('d', $this->readSHP(8));
$this->boundingBox['ymax'] = Util::loadData('d', $this->readSHP(8));
$this->boundingBox['zmin'] = Util::loadData('d', $this->readSHP(8));
$this->boundingBox['zmax'] = Util::loadData('d', $this->readSHP(8));
$this->boundingBox['mmin'] = Util::loadData('d', $this->readSHP(8));
$this->boundingBox['mmax'] = Util::loadData('d', $this->readSHP(8));
if (self::supports_dbase()) {
$this->DBFHeader = $this->_loadDBFHeader();
}
return true;
}
/**
* Saves bounding box record, possibly using 0 instead of not set values.
*
* @param file $file File object
* @param string $type Bounding box dimension (eg. xmax, mmin...)
*/
private function _saveBBoxRecord($file, $type)
{
fwrite($file, Util::packDouble(
isset($this->boundingBox[$type]) ? $this->boundingBox[$type] : 0)
);
}
/**
* Saves bounding box to a file.
*
* @param file $file File object
*/
private function _saveBBox($file)
{
$this->_saveBBoxRecord($file, 'xmin');
$this->_saveBBoxRecord($file, 'ymin');
$this->_saveBBoxRecord($file, 'xmax');
$this->_saveBBoxRecord($file, 'ymax');
$this->_saveBBoxRecord($file, 'zmin');
$this->_saveBBoxRecord($file, 'zmax');
$this->_saveBBoxRecord($file, 'mmin');
$this->_saveBBoxRecord($file, 'mmax');
}
/**
* Saves SHP and SHX file metadata.
*/
private function _saveHeaders()
{
fwrite($this->SHPFile, pack('NNNNNN', self::MAGIC, 0, 0, 0, 0, 0));
fwrite($this->SHPFile, pack('N', $this->fileLength));
fwrite($this->SHPFile, pack('V', 1000));
fwrite($this->SHPFile, pack('V', $this->shapeType));
$this->_saveBBox($this->SHPFile);
fwrite($this->SHXFile, pack('NNNNNN', self::MAGIC, 0, 0, 0, 0, 0));
fwrite($this->SHXFile, pack('N', 50 + 4 * count($this->records)));
fwrite($this->SHXFile, pack('V', 1000));
fwrite($this->SHXFile, pack('V', $this->shapeType));
$this->_saveBBox($this->SHXFile);
}
/**
* Loads records from SHP file (and DBF).
*
* @return bool
*/
private function _loadRecords()
{
/* Need to start at offset 100 */
while (!$this->eofSHP()) {
$record = new ShapeRecord(-1);
$record->loadFromFile($this, $this->SHPFile, $this->DBFFile);
if ($record->lastError != '') {
$this->setError($record->lastError);
return false;
}
if (($record->shapeType === false || $record->shapeType === '') && $this->eofSHP()) {
break;
}
$this->records[] = $record;
}
return true;
}
/**
* Saves records to SHP and SHX files.
*/
private function _saveRecords()
{
$offset = 50;
if (is_array($this->records) && (count($this->records) > 0)) {
foreach ($this->records as $index => $record) {
//Save the record to the .shp file
$record->saveToFile($this->SHPFile, $this->DBFFile, $index + 1);
//Save the record to the .shx file
fwrite($this->SHXFile, pack('N', $offset));
fwrite($this->SHXFile, pack('N', $record->getContentLength()));
$offset += (4 + $record->getContentLength());
}
}
}
/**
* Generic interface to open files.
*
* @param bool $toWrite Whether file should be opened for writing
* @param string $extension File extension
* @param string $name Verbose file name to report errors
*
* @return file|false File handle
*/
private function _openFile($toWrite, $extension, $name)
{
$shp_name = $this->_getFilename($extension);
$result = @fopen($shp_name, ($toWrite ? 'wb+' : 'rb'));
if (!$result) {
$this->setError(sprintf('It wasn\'t possible to open the %s file "%s"', $name, $shp_name));
return false;
}
return $result;
}
/**
* Opens SHP file.
*
* @param bool $toWrite Whether file should be opened for writing
*
* @return bool
*/
private function _openSHPFile($toWrite = false)
{
$this->SHPFile = $this->_openFile($toWrite, '.shp', 'Shape');
if (!$this->SHPFile) {
return false;
}
return true;
}
/**
* Closes SHP file.
*/
private function _closeSHPFile()
{
if ($this->SHPFile) {
fclose($this->SHPFile);
$this->SHPFile = null;
}
}
/**
* Opens SHX file.
*
* @param bool $toWrite Whether file should be opened for writing
*
* @return bool
*/
private function _openSHXFile($toWrite = false)
{
$this->SHXFile = $this->_openFile($toWrite, '.shx', 'Index');
if (!$this->SHXFile) {
return false;
}
return true;
}
/**
* Closes SHX file.
*/
private function _closeSHXFile()
{
if ($this->SHXFile) {
fclose($this->SHXFile);
$this->SHXFile = null;
}
}
/**
* Creates DBF file.
*
* @return bool
*/
private function _createDBFFile()
{
if (!self::supports_dbase() || !is_array($this->DBFHeader) || count($this->DBFHeader) == 0) {
$this->DBFFile = null;
return true;
}
$dbf_name = $this->_getFilename('.dbf');
/* Unlink existing file */
if (file_exists($dbf_name)) {
unlink($dbf_name);
}
/* Create new file */
$this->DBFFile = @dbase_create($dbf_name, $this->DBFHeader);
if ($this->DBFFile === false) {
$this->setError(sprintf('It wasn\'t possible to create the DBase file "%s"', $dbf_name));
return false;
}
return true;
}
/**
* Loads DBF file if supported.
*
* @return bool
*/
private function _openDBFFile()
{
if (!self::supports_dbase()) {
$this->DBFFile = null;
return true;
}
$dbf_name = $this->_getFilename('.dbf');
if (is_readable($dbf_name)) {
$this->DBFFile = @dbase_open($dbf_name, 0);
if (!$this->DBFFile) {
$this->setError(sprintf('It wasn\'t possible to open the DBase file "%s"', $dbf_name));
return false;
}
} else {
$this->setError(sprintf('It wasn\'t possible to find the DBase file "%s"', $dbf_name));
return false;
}
return true;
}
/**
* Closes DBF file.
*/
private function _closeDBFFile()
{
if ($this->DBFFile) {
dbase_close($this->DBFFile);
$this->DBFFile = null;
}
}
/**
* Sets error message.
*
* @param string $error
*/
public function setError($error)
{
$this->lastError = $error;
}
/**
* Reads given number of bytes from SHP file.
*
* @param int $bytes
*
* @return string
*/
public function readSHP($bytes)
{
return fread($this->SHPFile, $bytes);
}
/**
* Checks whether file is at EOF.
*
* @return bool
*/
public function eofSHP()
{
return feof($this->SHPFile);
}
/**
* Returns shape name.
*
* @return string
*/
public function getShapeName()
{
return Util::nameShape($this->shapeType);
}
/**
* Check whether file contains measure data.
*
* For some reason this is distinguished by zero bounding box in the
* specification.
*
* @return bool
*/
public function hasMeasure()
{
return $this->boundingBox['mmin'] != 0 || $this->boundingBox['mmax'] != 0;
}
}