-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMapFileWorkshop.php
1877 lines (1579 loc) · 63.7 KB
/
MapFileWorkshop.php
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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* MapFileWorkshop is a PHP library for reading, searching, editing and creating MapFiles for MapServer version 5 to 7 and higher.
* It's peculiarity is that no regular expression is used. The MapFile is read with respect to
* the MapServer syntax, but without understanding the meaning. The dictionary of special keyswords
* is stored into a Synopsis class. The Synopsis class can be updated if needed in futur MapServer versions.
*
* The MapFileWorkshop library is also a nice tool to find syntax errors in an existing MapFile.
*
* This library is case insensitive for reading a source file.
* But when using a MapFileObject, all MapServer keywords must be specified UPPERCASE.
*
* @author Skrol29
* @date 2018-12-05
* @version 0.30-beta-2019-06-11
*
* @example #1
*
* $map = new MapFileObject::getFromFile('my_source_file.map');
* $layer = $map->getChild('LAYER', 'my_sweet_layer');
* echo $layer->getProp('DATA'); // reading a property
* echo $layer->asString(); // get the MapServer definition
*
* @example #2
*
* $map = new MapFileObject::getFromFile('my_source_file.map', 'MAP/LAYER:my_sweet_layer');
*
* -------------------
* class MapFileObject
* -------------------
* Represents a MapFile object, with its properties and children objects.
*
* Synopsis:
*
* new MapFileObject($type) Create a new object of the given type with no properties and no child.
*
* ::getFromString($str, $path) Return the object from a string source, or false if not supported.
* ::getFromFile($file, $path) Return the object from a file source, or false if not supported.
* ::checkError($str) Return the error message when parsing the source, or empty string ('') if no error.
*
* ->innerValues (read/write) List of the inner values in a single row.
* Inner values are attached to the object without any property's name.
* Example : CONFIG, PROJECTION, SYMBOL, METADA,...
* ->children (read only) An indexed array of all MapFileObject children.
* ->props (read only) An associative array or properties => values.
* ->setComment($comment) Set a comment to the current object.
* ->setProp($prop, $value, $strDelim=false, $check=false)
* Set a property to the current object.
* A property is a tag with a single value which is not an object (numer, string, MapServer expression, MapServer regexp)
* $value must be set wihtout escaping or string delimited.
* Put $strDelim to true if the value has to be string delimited for this property (such as an URL, or a file name).
* ->getProp($prop, $default = false) Get a property of the current object, or $default if missing.
* ->countChildren($type) Return the number of children of the given type.
* ->getChild($type, $nameOrIndex = 1, $nameProp = 'NAME') Return the object corresponding to the criterias.
* ->getChildren($type) Return an array of all children object of the given type.
* ->deleteChildrenByType($type) Delete all child of the given type.
* ->addChildren($arr) Add one child or an array of children to the current object.
* ->asString() Return the MapFile source for this object, including and its children.
* ->getSrcPosition() Return the position of the object in the source where it comes from.
* ->saveInFile($file) Save the object in the file.
*
* ->escapeString($txt) Escape a string. Do not use it for setProp()
* ::colorHex2Ms() Convert a '#hhhhhh' color into 'r g b'. Note that MapServer supports format '#hhhhhh'.
* ::colorMs2Hex() Convert a 'r g b' color into '#hhhhhh'. Note that MapServer supports format '#hhhhhh'.
*
* ---------------------
* class MapFileSynopsis
* ---------------------
*
* It's a core classe for parsing a file.
*
* ---------------------
* class MapFileSynopsis
* ---------------------
* It's a core class that contains the dictionary of MapFile special keyswords.
* Keywords that are not in the synopsis are supposed to be simple MapFile properties (a keyword with a single value).
*
*
*/
/**
* A MapFile Object is any block in the MapFile that has a END tag.
* Other tags in the MapFile are considered as Properties of an object.
* Most of Objects have properties and child Objects.
* But some Objects may have inner values, thus no properties nor child objects (PROJECTION, METADATA, ...).
* Despite reading a MapFile is case insensitive, properties an objects names are all converted uppercase so
* they must be managed uppercase.
*/
class MapFileObject {
public $type = '';
public $supported = false;
public $warnings = false; // warnings coming from the reader
public $innerValues = array();
public $innerValCols = 0;
public $children = array();
public $props = array(); // The only prop wich is multi is CONFIG
public $delimProps = array(); // Names of the properties to be ouput with string delimitors
public $parent = false;
public $hasEnd = true;
public $srcPosBeg = false;
public $srcPosEnd = false;
public $srcPosBottom = false;
public $srcLineBeg = false;
public $srcLineEnd = false;
private $_comment = '';
/**
* Return the object corresponding to string.
* @param string $txt The string to parse.
* @param string $str_path (optional) the search path. Examples : 'MAP/LAYER:my_layer'. By default return the first object which is usually MAP.
* @return {MapFileObject|false}
*/
public static function getFromString($txt, $str_path = false) {
$map = new MapFileWorkshop(false, false);
$map->setSearchPath($str_path);
return $map->readContent($txt);
}
/**
* Return the object corresponding to file content.
* @param string $file The file to parse.
* @param string $str_path (optional) the search path. Examples : 'MAP/LAYER:my_layer'. By default return the first object which is usually MAP.
* @return {MapFileObject|false}
*/
public static function getFromFile($file, $str_path = false) {
$map = new MapFileWorkshop($file, false);
$map->setSearchPath($str_path);
return $map->readFile();
}
/**
* Return the error message when parsing the content, or empty string ('') if no error.
* @return {string} $content The content to parse.
* @param {string} $sep (optional) The separator in case they are several errors. Default is a line-break.
*/
public static function checkError($content, $sep = "\n") {
$map = new MapFileWorkshop(false, false);
$map->errorAsWarning = true;
$map->readContent($content);
return implode($sep, $map->warnings);
}
/**
* Constructor
* @param string $type The type of the object (cas sensitive).
* @param string $chk_parent_type (optional) Check if $type is valid for the given parent type. Useful for a type that can be either a block or a property, like 'SYMBOL'.
*
* If the type is unkowed in the synopsis, then property « supported » is set to false.
*/
public function __construct($type, $chk_parent_type = false) {
$this->type = $type;
if ($syno = MapFileSynopsis::getSyno($type, $chk_parent_type)) {
$this->innerValCols = $syno['innerValCols'];
$this->hasEnd = $syno['hasEnd'];
$this->supported = true;
} else {
$this->supported = false;
}
}
/**
* Apply a comment ot the object. This comment is is displayed only when using ->asString().
*/
public function setComment($comment) {
$comment = (string) $comment;
$comment = str_replace("\r", '', $comment);
$comment = str_replace("\n", '', $comment);
$this->_comment = $comment;
}
/**
* Save the property.
* @param string @prop The name of the property (case insensitive).
* @param string|false @value The value to set. false or null values make the property to be deleted.
* @param string|boolean @strDelim The string delimitor to use, or true to use the default delimitor (")
* @param boolean @check (optional) Set to true if you want the function to return whereas the property was previously defined or not.
* @return boolean Return true is $check is set to true and the property already existed before.
*/
public function setProp($prop, $value, $strDelim=false, $check=false) {
$prop = strtoupper($prop);
if ($check) {
$check = isset($this->props[$prop]);
}
if (($value === false) || (is_null($value)) ) {
unset($this->props[$prop]);
} else {
$this->props[$prop] = $value;
}
// String delimitor
if ($strDelim === true) {
$strDelim = '"';
} elseif ($strDelim === false) {
$strDelim = '';
}
if ($strDelim === '') {
unset($this->delimProps[$prop]);
} else {
$this->delimProps[$prop] = $strDelim;
}
return $check;
}
/**
* Read the property.
* @param string @prop The name of the property (case insensitive).
* @param mixed @default The value to return if the property is not set.
* @return mixed The existing property's value or the default value.
*/
public function getProp($prop, $default = false) {
$prop = strtoupper($prop);
if (isset($this->props[$prop])) {
return $this->props[$prop];
} else {
return $default;
}
}
/**
* Escape and delimit a string.
*/
public function escapeString($str, $strDelim) {
return str_replace($strDelim, '\\'.$strDelim, $str);
}
private function _delim_string($str, $strDelim) {
return $strDelim . $this->escapeString($str, $strDelim) . $strDelim;
}
/**
* Count the number of child for a given type.
* @param string $type Type of the objet (case insensitive).
* @return integer
*/
public function countChildren($type) {
$type = strtoupper($type);
$n = 0;
foreach($this->children as $obj) {
if ($obj->type == $type) {
$n++;
}
}
return $n;
}
/**
* Find a child object.
* @param string $type Type of the objet (case insensitive)
* @param string|integer $nameOrIndex (optional, default is 1) Name of the object (case sensitive) or the index (first is 1) for this type of object.
* @param string $nameProp (optional, default is 'NAME') Property for searching the name of the object.
*/
public function getChild($type, $nameOrIndex = 1, $nameProp = 'NAME') {
$type = strtoupper($type);
$i = 0;
$byName = is_string($nameOrIndex);
foreach($this->children as $obj) {
if ($obj->type == $type) {
$i++;
if ($byName) {
if ($obj->getProp($nameProp) == $nameOrIndex) {
return $obj;
}
} else {
if ($i == $nameOrIndex) {
return $obj;
}
}
}
}
return false;
}
/**
* Return the array of children for a given type.
* @param string $type The type to child to return (case sentitive).
* @param false|string $prop (optional) The property to return (case sentitive), or false to return the MapfileObject.
* @return array
*/
public function getChildren($type, $return_prop = false) {
$res = array();
foreach ($this->children as $obj) {
if ($obj->type == $type) {
if ($return_prop) {
$res[] = $obj->getProp($return_prop);
} else {
$res[] = $obj;
}
}
}
return $res;
}
/**
* Delete all children of a give type.
* @param string $type The type to search (case sentitive).
* @return integer The number of deleted children.
*/
public function deleteChildrenByType($type) {
$n = 0;
for ($i = count($this->children) -1; $i >= 0 ; $i--) {
$obj = $this->children[$i];
if ($obj->type == $type) {
$obj->parent = false;
array_splice($this->children, $i, 1);
$n++;
}
}
return $n;
}
/**
* Delete all children.
* @return integer The number of deleted children.
*/
public function deleteAllChildren() {
foreach ($this->children as &$c) {
$c->parent = false;
}
$n = count($this->children);
$this->children = array();
return $n;
}
/**
* Add a new child or an array of children.
* @param MapFileObject|array $arr
* @return integer The number of added children.
*/
public function addChildren($arr) {
$n = 0;
if (is_object($arr)) {
$arr = array($arr);
}
if (is_array($arr)) {
foreach ($arr as $obj) {
$obj->parent = $this;
$this->children[] = $obj;
$n++;
}
}
return $n;
}
/**
* If the object is the result of a search, then return an array containing the start en end positions
* of the object in the source.
* Otherwise return false.
*/
public function getSrcPosition() {
if ($this->srcPosBeg !== false) {
return array($this->srcPosBeg, $this->srcPosEnd);
} else {
return false;
}
}
/**
* If the object is the result of a search, then return the bottom position
* of the object in the source. That is the position just before the END word.
* Otherwise return false.
*/
public function getSrcBottom() {
return $this->srcPosBottom;
}
/**
* Return the MapServer definition of the object as a string.
* @param integer $indent (optional) The number of text indentations.
*/
public function asString($indent = false) {
static $nl = "\n";
static $step = ' ';
if ($indent === false) {
$indent = 0;
}
$incr = str_repeat($step, $indent);
$end = $this->hasEnd;
// Type
$str = $incr . $this->type;
// Comment
if ($this->_comment !== '') {
$str .= $nl . $incr . $step . '# ' . $this->_comment;
}
// Inner values
$col = 1;
foreach ($this->innerValues as $val) {
// Inner values can be numerical (example: PATTERN)
if (!is_numeric($val)) {
$val = $this->_delim_string($val, '"');
}
if ( ($col == 1) && $end ) {
$str .= $nl . $incr . $step;
} else {
$str .= ' ';
}
$str .= $val;
$col++;
if ($col > $this->innerValCols) {
$col = 1;
}
}
$hasKids = (count($this->children) > 0);
$hasProp = (count($this->props) > 0);
// Properties
if ($hasProp) {
if ($hasKids) $str .= $nl;
foreach ($this->props as $prop => $val) {
if (isset($this->delimProps[$prop])) {
$val = $this->_delim_string($val, $this->delimProps[$prop]);
}
$str .= $nl . $incr . $step. $prop . ' ' . $val;
}
}
// Child objects
$children = $this->_orderder_children(); // increase the time output by 30%
foreach ($children as $obj) {
// Just like MapScript, we add a line-break before each object of the MAP (level = 1)
if ($hasKids && $obj->hasEnd) {
$str .= $nl;
}
$str .= $nl . $obj->asString($indent + 1);
}
// End
if ($end) {
if ($hasKids) $str .= $nl;
$str .= $nl . $incr . 'END # ' . $this->type;
}
return $str;
}
/**
* Save the object in the file.
* return true.
*/
public function saveInFile($file) {
$str = $this->asString();
file_put_contents($file, $str);
return true;
}
/**
* Return a short descr of the current object.
*/
private function _short_descr() {
$name = $this->getProp('NAME', '');
$num = $this->_get_child_num();
$x = $this->type;
if ($num !== false) $x .= '(#' . $num . ')';
if ($name != '') $x .= '[' . $name . ']';
return $x;
}
/**
* Return the ordre numer of current object in the parent's child of the same type.
* First child is number 1.
* Return false if no parent or current object not found.
*/
private function _get_child_num() {
if ($this->parent) {
$num = 0;
foreach ($this->parent->children as $c) {
if ($this->type == $c->type) {
$num++;
}
if ($this === $c) {
return $num;
}
}
}
return false;
}
/**
* Return the list of child ordered by type.
* More numerous types are ordered at the end, then it is ordered by type name.
* In a same type, children are nor re-ordered because custom CLASS and STYLE orders actually matter.
*/
private function _orderder_children() {
// build the type list
$t_nb = array();
$t_ch = array();
foreach ($this->children as $idx => $c) {
$t = $c->type;
if (!isset($t_nb[$t])) {
$t_nb[$t] = 0;
$t_ch[$t] = array();
}
$t_nb[$t]++;
$t_ch[$t][] = $c;
}
// Sort the type list by number of items
ksort($t_nb);
asort($t_nb);
// Cuild the child list sorted by type
$result = array();
foreach($t_nb as $t => $nb) {
foreach ($t_ch[$t] as $c) {
$result[] = $c;
}
}
return $result;
}
/**
* Return a breadcrumb of the current object in its parent hierarchy.
* @return {string}
*/
public function getBreadcrumb() {
$sep = '/';
$obj = $this;
$h = array();
do {
if ($obj->type != ':SNIPPET:') {
$h[] = $obj->_short_descr();
}
$obj = $obj->parent;
} while ($obj);
$x = implode($sep, array_reverse($h));
return $x;
}
/**
* For debug only.
* Use this method to return a var_export() on the current object. This will avoid « Fatal error: Nesting level too deep ».
*/
public function varExport() {
$this->_unsetParent();
$x = var_export($this, true);
$this->_setParent();
return $x;
}
private function _unsetParent() {
$this->parent = false;
foreach ($this->children as $c) {
$c->_unsetParent();
}
}
private function _setParent() {
$this->parent = false;
foreach ($this->children as $c) {
$c->_setParent();
}
}
/**
* Convert an hexa color number into a MapServer (RGB) color number.
* Empty values are returned as is.
* @param string $hex The color number as hexa, with or without the '#' symbole.
* @return string The MapServer color number.
*/
public static function colorHex2Ms($hex) {
// Check empty value
$hex = trim($hex);
if ($hex == '') return '';
$hex = str_replace('#', '', $hex);
if(strlen($hex) == 3) {
$r = hexdec(substr($hex,0,1).substr($hex,0,1));
$g = hexdec(substr($hex,1,1).substr($hex,1,1));
$b = hexdec(substr($hex,2,1).substr($hex,2,1));
} else {
$r = hexdec(substr($hex,0,2));
$g = hexdec(substr($hex,2,2));
$b = hexdec(substr($hex,4,2));
}
$rgb = $r . ' ' . $g . ' ' . $b;
return $rgb;
}
/**
* Convert a MapServer (RGB) color number into an hexa color number.
* Empty values are returned as is.
* @param string $rgb The color number as MapServer (RGB separated with with spaces).
* @return string The Hexa color number, without '#'.
*/
public static function colorMs2Hex($rgb) {
$rgb = str_replace("\r", ' ', $rgb);
$rgb = str_replace("\n", ' ', $rgb);
$rgb = str_replace("\t", ' ', $rgb);
while (strpos($rgb, ' ') !== false) {
$rgb = str_replace(' ', ' ', $rgb);
}
// Check empty value
$rgb = trim($rgb);
if ($rgb == '') return '';
// Ensure last items
$rgb .= ' 0 0 0';
$rgb = trim($rgb);
$rgb = explode(' ', $rgb);
$hex = '';
$hex .= str_pad(dechex($rgb[0]), 2, '0', STR_PAD_LEFT);
$hex .= str_pad(dechex($rgb[1]), 2, '0', STR_PAD_LEFT);
$hex .= str_pad(dechex($rgb[2]), 2, '0', STR_PAD_LEFT);
return $hex;
}
}
/*
* The MapFileSynopsis class manages the dictionary of special keywords in MapFiles and their corresponding properties needed to read them.
*
* For this library, a « simple » MapServer keyword is a keyword that is expected to be followed by a single value (according to the MapFile syntax).
* For this library, a « special » keyword is any keyword that is not a simple keyword.
* The dictionary of special keywords and their properties is listed above.
*
*/
class MapFileSynopsis {
/**
* Default properties for all special keywords.
*/
private static $_default = array(
'hasEnd' => true, // false means the keyword has no END tag. Thus the end of the object is determined using property innerValCols.
'innerValCols' => 0, // The number of values expected for this keyword. 0 means the object has no inner value (it contains keywords).
'onlyForParents' => false, // List of keyworks for whom this one is special. For other parents, this one is considered has a simple keyword (a keyword with a single value).
'onlyIfNoParent' => false, // True means that this keyword is special only if it has no parent (as root or as a free object).
'several' => false, // True means that they may be several of this object type in the same parent.
);
/**
* List of special keywords and their properties.
*/
private static $_special_kw = array(
'CLASS' => array( // children: LABEL, LEADER, STYLE, VALIDATION
'several' => true,
),
'CLUSTER' => array(),
'COLORRANGE' => array(
'hasEnd' => false,
'innerValCols' => 2, // supports only hexadecimal strings for now, (r g b) values not supported yet
'several' => true,
),
'COMPOSITE' => array(),
'CONFIG' => array(
'hasEnd' => false,
'innerValCols' => 2,
'several' => true,
),
'FEATURE' => array(), // children: POINTS
'GRID' => array(),
'JOIN' => array(),
'LABEL' => array(), // children: STYLE
'LAYER' => array( // children: CLUSTER, COMPOSITE, FEATURE, PROCESSING, GRID, JOIN, PROJECTION, VALIDATION, CLASS
'several' => true,
),
'LEADER' => array(), // children: STYLE
'LEGEND' => array(), // children: LABEL
'MAP' => array(), // children: CONFIG, OUTPUTFORMAT, PROJECTION, LEGEND, QUERYMAP, REFERENCE, SCALEBAR, SYMBOL, WEB, LAYER
'METADATA' => array(
'innerValCols' => 2,
),
'OUTPUTFORMAT' => array(),
'PATTERN' => array(
'innerValCols' => 1,
),
'POINTS' => array(
'innerValCols' => 2,
),
'PROCESSING' => array(
'hasEnd' => false,
'innerValCols' => 1,
'several' => true,
),
'PROJECTION' => array(
'innerValCols' => 1,
),
'QUERYMAP' => array(),
'REFERENCE' => array(),
'SCALEBAR' => array(), // children: LABEL
'STYLE' => array( // children: PATTERN, COLORRANGE
'several' => true,
),
'SYMBOL' => array( // children: POINTS
'onlyForParents' => array(
'MAP',
'SYMBOLSET',
),
'several' => true,
),
'SYMBOLSET' => array( // children: SYMBOL
'onlyIfNoParent' => true,
),
'VALIDATION' => array(
'innerValCols' => 2,
),
'WEB' => array(), // children: METADATA
);
// Indicates if the dictionary has to be prepared.
static $to_prepare = true;
/**
* Returns the configuration of an object or false if the tag name is not a knowed object (but may be a valid property).
*
* @param string $name The name of a tag.
* @param string $chk_parent_type (optional) Check if $type is valid for the given parent type. Useful for a type that can be either a block or a property, like 'SYMBOL'.
*
* @return array|boolean
*/
static public function getSyno($name, $chk_parent_type = false) {
if (isset(self::$_special_kw[$name])) {
$syno = self::$_special_kw[$name];
// Check if the item is an object only for the given parent type
if ($chk_parent_type !== false) {
if ($syno['onlyForParents']) {
if (!in_array($chk_parent_type, $syno['onlyForParents'], true)) {
return false;
}
} elseif ($syno['onlyIfNoParent']) {
if ($chk_parent_type != ':SNIPPET:') {
return false;
}
}
}
return $syno;
} else {
return false;
}
}
/**
* Return true if the tag is the one for ending blocks.
* @param string @name
* @return boolean
*/
static public function isEnd($name) {
return ($name === 'END');
}
/**
* Return true if the tag name is valid.
* @param string @name
* @return boolean
*/
static public function isValidName($name) {
if ($name == '') return false;
// For now we check only the first char. TODO : check MapServer keywords naming.
$x = strtoupper($name[0]);
$o = ord($x);
// ord('A')=65, ord('Z')=90
if ($o < 65) return false;
if ($o > 90) return false;
return true;
}
/**
* Prepare the dictionary if it has not been done before.
* Preparing the dictionary consists in setting all default preperties and check for coherence.
*/
static public function prepare() {
if (self::$to_prepare) {
foreach (self::$_special_kw as $k => $def) {
$def = array_merge(self::$_default, $def);
self::$_special_kw[$k] = $def;
// Check 'hasEnd'
if (!$def['hasEnd']) {
if ($def['innerValCols'] <= 0) {
self::_raiseError("Synopsis ERROR: item '$k' has 'hasEnd' set to false wihtout a positive 'innerValCols'. You have to fix the Synopsis configuration.");
}
}
}
self::$to_prepare = false;
}
}
static private function _raiseError($msg) {
throw new Exception(__CLASS__ . " ERROR : " . $msg);
return false;
}
}
/**
* This is a core classe for parsing a Mapfile content.
* Do not use directly. Use MapFileObject instead.
*/
class MapFileWorkshop {
const NL = "\n"; // New line
const CR = "\r"; // Carriage Return
const SP = ' '; // Space
const TAB = "\t"; // Tab
const COMMENT = '#'; // Comment
const DEBUG_NO = 0;
const DEBUG_NORMAL = 1;
const DEBUG_DETAILED = 2;
const DEBUG_DEEP = 3;
const STR1 = '"'; // String delimiter #1
const STR2 = "'"; // String delimiter #2
const ESC = '\\'; // String escaper
// Debug level
public static $debug = 0;
// Last loaded file
public $file = false;
// Warning messages collected during the parsing
public $warnings = array();
// Variables for couting lines
private $_line_num = 0; // current line number
private $_npos = -1; // « position + 1 » of the last line-break
private $_fchar = ''; // first char of the last line-break
private $_continue = false;
// Buffer variables for converting strings to objects
private $_currObj = false;
private $_currProp = false;
private $_currPropSD = ''; // String delimitor for the property
private $_currValues = array();
// Contain the hierachy of objects that has not been complety read. They are not yet attached to their parent.
private $_currPath = false;
private $_currIdx = false;
// Search variables
private $_srchPath = false;
private $_srchLastIdx = false;
private $_srchFound = false;
private $_srchFirstObj = false;
/**
* If debug mode is activated then informations is displayed concerning the parsing.
*/
public $debug_n = 0;
public $debug_max = 40000;
/**
* Use this property to catch the errors into $this->warnings instead of raising an Exception.
*/
public $errorAsWarning = false;
/**
* Set the debug level.
* @param {integer} $debug_level
*/
static function setDebug($debug_level) {
self::$debug = $debug_level;
}
/**
* Constructor
* @param {string} $sourceFile (optional) The source file path to work with. Will not be loaded now.
* @param {string} $targetFile (optional) The target file where to save modifications. By default it is $sourceFile.
*/
public function __construct($sourceFile = false, $targetFile = false) {
MapFileSynopsis::prepare();
$this->sourceFile = $sourceFile;
$this->targetFile = $targetFile;
if (!$this->targetFile) {
$this->targetFile = $this->sourceFile;
}
}
/**
* Set the search path.
*
* @param string $str_path (optional) Path for the search.
* - false (default value) means it will return the first object in the snippet (typically a MAP object)
* - ':SNIPPET:' means it will return the virtual snippet object. Thta is an object that contains all the objects in the file.
* - a string like : 'MAP/LAYER:my_layer'
* The target object must be defined with its hierarchy.
* Each item can be :
* - a simple type (examples : 'MAP', 'LAYER', ...)
* - a type with a child numerical index - first index is 1 - ( examples : 'LAYER:1', 'CLASS:1', ...)
* - a type with a name (example : 'LAYER:my_layer')
*/
public function setSearchPath($str_path) {
$this->_srchFirstObj = ($str_path === false);
$this->_srchPath = $this->_get_search_path($str_path);
$this->_srchLastIdx = count($this->_srchPath) - 1;
$this->_srchFound = false;
}
/**
* Replace a part of the source and save the result in the target file (can be the same file).
*
* @param array $srcPos Array of the two positions of replacement in the source file: array($pos_start, $pos_end)
* It is typically given by a MapFileObject using method ->getPosition()
* @param MapFileObject|string $newDef The new definition to write in the target file.
* It can be a string or a MapFileObject.
* @param boolean $protect (optional) protect the snippet to insert from beeing mixed with surrounding words or comments.
*
* @return boolean True if the definition is replaced in the file.
*/
public function replaceDef($srcPos, $newDef, $protect = true) {
// check source file
if ($this->sourceFile === false) {
return $this->raiseError("Cannot replace object if no source file is defined.", __METHOD__);
}
// check target file
if ($this->targetFile === false) {
return $this->raiseError("Cannot replace object if no target file is defined.", __METHOD__);
}
$txt = file_get_contents($this->sourceFile);
// Get the new object definition
if (is_object($newDef)) {
$str = $newDef->asString();
$protect = true;
} else {
$str = $newDef;
}
// Positions
if (is_array($srcPos) && isset($srcPos[0]) && isset($srcPos[1])) {
$beg = $srcPos[0];
$end = $srcPos[1];
} elseif (is_numeric($srcPos)) {
$beg = $srcPos;
$end = $srcPos - 1; // in order to have a replace length = 0
} else {
return $this->raiseError("First argument is not a position. Array or Integer expected", __METHOD__);
}