-
Notifications
You must be signed in to change notification settings - Fork 269
Expand file tree
/
Copy pathXmlArray.php
More file actions
776 lines (648 loc) · 18.8 KB
/
Copy pathXmlArray.php
File metadata and controls
776 lines (648 loc) · 18.8 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
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
<?php
/**
* The XmlArray class is an XML parser.
*
* Simple Machines Forum (SMF)
*
* @package SMF
* @author Simple Machines https://www.simplemachines.org
* @copyright 2026 Simple Machines and individual contributors
* @license https://www.simplemachines.org/about/smf/license.php BSD
*
* @version 3.0 Alpha 4
*/
namespace SMF\PackageManager;
use SMF\Lang;
/**
* Class XmlArray
* Represents an XML array
*/
final class XmlArray
{
/*******************
* Public properties
*******************/
/**
* @var array Holds parsed XML results
*/
public $array;
/**
* @var int The debugging level
*/
public $debug_level;
/**
* holds trim level textual data
*
* @var bool Holds trim level textual data
*/
public $trim;
/****************
* Public methods
****************/
/**
* Constructor for the xml parser.
* Example use:
* $xml = new XmlArray(file('data.xml'));
*
* @param string|array $data The xml data or an array of, unless is_clone is true.
* @param bool $auto_trim Used to automatically trim textual data.
* @param int|null $level The debug level. Specifies whether notices should be generated for missing elements and attributes.
* @param bool $is_clone default false. If is_clone is true, the XmlArray is cloned from another - used internally only.
*/
public function __construct(string|array $data, bool $auto_trim = false, ?int $level = null, bool $is_clone = false)
{
// Set the debug level.
$this->debug_level = $level !== null ? $level : error_reporting();
$this->trim = $auto_trim;
// Is the data already parsed?
if ($is_clone) {
$this->array = $data;
return;
}
// Is the input an array? (ie. passed from file()?)
if (\is_array($data)) {
$data = implode('', $data);
}
// Remove any xml declaration or doctype, and parse out comments and CDATA.
$data = preg_replace('/<!--.*?-->/s', '', $this->_to_cdata(preg_replace(['/^<\?xml.+?\?' . '>/is', '/<!DOCTYPE[^>]+?' . '>/s'], '', $data)));
// Now parse the xml!
$this->array = $this->_parse($data);
}
/**
* Get the root element's name.
* Example use:
* echo $element->name();
*
* @return string The root element's name
*/
public function name(): string
{
return $this->array['name'] ?? '';
}
/**
* Get a specified element's value or attribute by path.
* Children are parsed for text, but only textual data is returned
* unless get_elements is true.
* Example use:
* $data = $xml->fetch('html/head/title');
*
* @param string $path The path to the element to fetch
* @param bool $get_elements Whether to include elements
* @return string|bool The value or attribute of the specified element
*/
public function fetch(string $path, bool $get_elements = false): string|bool
{
// Get the element, in array form.
$array = $this->path($path);
if ($array === false) {
return false;
}
// Getting elements into this is a bit complicated...
if ($get_elements && !\is_string($array)) {
$temp = '';
// Use the _xml() function to get the xml data.
foreach ($array->array as $val) {
// Skip the name and any attributes.
if (\is_array($val)) {
$temp .= $this->_xml($val, null);
}
}
// Just get the XML data and then take out the CDATAs.
return $this->_to_cdata($temp);
}
// Return the value - taking care to pick out all the text values.
return \is_string($array) ? $array : $this->_fetch($array->array);
}
/** Get an element, returns a new XmlArray.
* It finds any elements that match the path specified.
* It will always return a set if there is more than one of the element
* or return_set is true.
* Example use:
* $element = $xml->path('html/body');
*
* @param string $path The path to the element to get
* @param bool $return_full Whether to return the full result set
* @return XmlArray|string|bool a new XmlArray. False if we can not find an attribute
*/
public function path(string $path, bool $return_full = false): XmlArray|string|false
{
// Split up the path.
$path = explode('/', $path);
// Start with a base array.
$array = $this->array;
// For each element in the path.
foreach ($path as $el) {
$pos = strpos($el, '[');
// Deal with sets....
if ($pos !== false) {
$lvl = (int) substr($el, $pos + 1);
$el = substr($el, 0, $pos);
}
// Find an attribute.
elseif ($el[0] === '@') {
// It simplifies things if the attribute is already there ;).
if (isset($array[$el])) {
return $array[$el];
}
if ($this->debug_level & E_NOTICE) {
$trace = debug_backtrace();
$i = 0;
while ($i < \count($trace) && isset($trace[$i]['class']) && $trace[$i]['class'] == self::class) {
$i++;
}
$debug = ' (from ' . $trace[$i - 1]['file'] . ' on line ' . $trace[$i - 1]['line'] . ')';
// Cause an error.
trigger_error(Lang::getTxt('undefined_xml_attribute', [substr($el, 1) . $debug], file: 'Errors'), E_USER_NOTICE);
}
return false;
} else {
$lvl = null;
}
// Find this element.
$array = $this->_path($array, $el, $lvl);
}
// Clean up after $lvl, for $return_full.
if ($return_full && (!isset($array['name']) || substr($array['name'], -1) != ']')) {
$array = ['name' => $el . '[]', $array];
}
// Return a new XmlArray for the result.
return $array === false ? false : new self($array, $this->trim, $this->debug_level, true);
}
/**
* Check if an element exists.
* Example use,
* echo $xml->exists('html/body') ? 'y' : 'n';
*
* @param string $path The path to the element to get.
* @return bool Whether the specified path exists
*/
public function exists(string $path): bool
{
// Split up the path.
$path = explode('/', $path);
// Start with a base array.
$array = $this->array;
// For each element in the path.
foreach ($path as $el) {
$pos = strpos($el, '[');
// Deal with sets....
if ($pos !== false) {
$lvl = (int) substr($el, $pos + 1);
$el = substr($el, 0, $pos);
}
// Find an attribute.
elseif ($el[0] === '@') {
return isset($array[$el]);
} else {
$lvl = null;
}
// Nothing found, nothing exists.
if (empty($array)) {
return false;
}
// Find this element.
$array = $this->_path($array, $el, $lvl, true);
}
return !empty($array);
}
/**
* Count the number of occurrences of a path.
* Example use:
* echo $xml->count('html/head/meta');
*
* @param string $path The path to search for.
* @return int The number of elements the path matches.
*/
public function count(string $path): int
{
// Get the element, always returning a full set.
$temp = $this->path($path, true);
// Start at zero, then count up all the numeric keys.
$i = 0;
foreach ($temp->array as $item) {
if (\is_array($item)) {
$i++;
}
}
return $i;
}
/**
* Get an array of XmlArray's matching the specified path.
* This differs from ->path(path, true) in that instead of an XmlArray
* of elements, an array of XmlArray's is returned for use with foreach.
* Example use:
* foreach ($xml->set('html/body/p') as $p)
*
* @param string $path The path to search for.
* @return XmlArray[] An array of XmlArray objects
*/
public function set(string $path): array
{
// None as yet, just get the path.
$array = [];
$xml = $this->path($path, true);
foreach ($xml->array as $val) {
// Skip these, they aren't elements.
if (!\is_array($val) || $val['name'] == '!') {
continue;
}
// Create a new XmlArray and stick it in the array.
$array[] = new self($val, $this->trim, $this->debug_level, true);
}
return $array;
}
/**
* Create an xml file from an XmlArray, the specified path if any.
* Example use:
* echo $this->create_xml();
*
* @param string|null $path The path to the element. (optional)
* @return string Xml-formatted string.
*/
public function create_xml(?string $path = null): string
{
// Was a path specified? If so, use that array.
if ($path !== null) {
$path = $this->path($path);
// The path was not found
if ($path === false) {
return false;
}
$path = $path->array;
}
// Just use the current array.
else {
$path = $this->array;
}
// Add the xml declaration to the front.
return '<?xml version="1.0"?' . '>' . $this->_xml($path, 0);
}
/**
* Output the xml in an array form.
* Example use:
* print_r($xml->to_array());
*
* @param string|null $path The path to output.
* @return array An array of XML data
*/
public function to_array(?string $path = null): array
{
// Are we doing a specific path?
if ($path !== null) {
$path = $this->path($path);
// The path was not found
if ($path === false) {
return [];
}
$path = $path->array;
}
// No, so just use the current array.
else {
$path = $this->array;
}
return $this->_array($path);
}
/**
* Parse out CDATA tags. (htmlspecialchars them...)
*
* @param string $data The data with CDATA tags included
* @return string The data contained within CDATA tags
*/
public function _to_cdata(string $data): string
{
// Quickly check for either comments or CDATA tags.
if (strpos($data, '<!') === false) {
return $data;
}
$in_cdata = $in_comment = false;
$output = '';
$parts = preg_split('~(<!\[CDATA\[|\]\]>|<!--|-->)~', $data, -1, PREG_SPLIT_DELIM_CAPTURE);
foreach ($parts as $part) {
// Handle XML comments.
if (!$in_cdata && $part === '<!--') {
$in_comment = true;
}
if ($in_comment && $part === '-->') {
$in_comment = false;
} elseif ($in_comment) {
continue;
}
// Handle CDATA blocks.
elseif (!$in_comment && $part === '<![CDATA[') {
$in_cdata = true;
} elseif ($in_cdata && $part === ']]>') {
$in_cdata = false;
} elseif ($in_cdata) {
$output .= htmlentities($part, ENT_QUOTES);
}
// Everything else is kept as is.
else {
$output .= $part;
}
}
return $output;
}
/******************
* Internal methods
******************/
/**
* Parse data into an array. (privately used...)
*
* @param string $data The data to parse
* @return array The parsed array
*/
protected function _parse(string $data): array
{
// Start with an 'empty' array with no data.
$current = [];
$len = \strlen($data);
$offset = 0;
while ($offset < $len) {
preg_match('/\G<([\w\-:]+)((?:\s+[\s\S]+?)?)([\s]?\/)?>/', $data, $match, 0, $offset);
if (isset($match[0])) {
$offset += \strlen($match[0]);
}
// Didn't find a tag? Keep looping....
if (!isset($match[1]) || $match[1] == '') {
$pos = strpos($data, '<', $offset);
// If there's no <, the rest is data.
if ($pos === false) {
$text_value = $this->_from_cdata(substr($data, $offset));
$offset = $len;
if ($text_value != '') {
$current[] = [
'name' => '!',
'value' => $text_value,
];
}
}
// If the < isn't immediately next to the current position... more data.
elseif ($pos > $offset) {
$text_value = $this->_from_cdata(substr($data, $offset, $pos - $offset));
$offset = $pos;
if ($text_value != '') {
$current[] = [
'name' => '!',
'value' => $text_value,
];
}
}
// If we're looking at a </something> with no start, kill it.
elseif ($pos === $offset) {
$pos1 = strpos($data, '<', $offset + 1);
if ($pos1 !== false) {
$text_value = $this->_from_cdata(substr($data, $offset, $pos1 - $offset));
$offset = $pos1;
if ($text_value != '') {
$current[] = [
'name' => '!',
'value' => $text_value,
];
}
} else {
$text_value = $this->_from_cdata(substr($data, $offset));
$offset = $len;
if ($text_value != '') {
$current[] = [
'name' => '!',
'value' => $text_value,
];
}
}
}
// Wait for an actual occurrence of an element.
continue;
}
// Create a new element in the array.
$el = &$current[];
$el['name'] = $match[1];
// If this ISN'T empty, remove the close tag and parse the inner data.
if ((!isset($match[3]) || trim($match[3]) != '/') && (!isset($match[2]) || trim($match[2]) != '/')) {
$tag_start = '<' . $match[1];
$tag_end = '</' . $match[1] . '>';
$last_tag_end = strpos($data, $tag_end, $offset);
if ($last_tag_end === false) {
continue;
}
$inner_offset = $offset;
while (true) {
// Where is the next start tag?
$next_tag_start = strpos($data, $tag_start, $inner_offset);
// If the next start tag is after the last end tag then we've found the right close.
if ($next_tag_start === false || $next_tag_start > $last_tag_end) {
break;
}
// If not then find the next ending tag.
$next_tag_end = strpos($data, $tag_end, $inner_offset);
// Didn't find one? Then just use the last and sod it.
if ($next_tag_end === false) {
break;
}
$last_tag_end = $next_tag_end;
$inner_offset = $next_tag_start + 1;
}
// Parse the insides.
$inner_match = substr($data, $offset, $last_tag_end - $offset);
// Data now starts from where this section ends.
$offset = $last_tag_end + \strlen($tag_end);
if (!empty($inner_match)) {
// Parse the inner data.
if (str_contains($inner_match, '<')) {
$el += $this->_parse($inner_match);
} elseif (trim($inner_match) != '') {
$text_value = $this->_from_cdata($inner_match);
if ($text_value != '') {
$el[] = [
'name' => '!',
'value' => $text_value,
];
}
}
}
}
// If we're dealing with attributes as well, parse them out.
if (isset($match[2]) && $match[2] != '') {
// Find all the attribute pairs in the string.
preg_match_all('/([\w:]+)="(.+?)"/', $match[2], $attr, PREG_SET_ORDER);
// Set them as @attribute-name.
foreach ($attr as $match_attr) {
$el['@' . $match_attr[1]] = $match_attr[2];
}
}
}
// Return the parsed array.
return $current;
}
/**
* Get a specific element's xml. (privately used...)
*
* @param array $array An array of element data
* @param null|int $indent How many levels to indent the elements (null = no indent)
* @return string The formatted XML
*/
protected function _xml(array $array, ?int $indent): string
{
$indentation = $indent !== null ? '
' . str_repeat(' ', $indent) : '';
// This is a set of elements, with no name...
if (\is_array($array) && !isset($array['name'])) {
$temp = '';
foreach ($array as $val) {
$temp .= $this->_xml($val, $indent);
}
return $temp;
}
// This is just text!
if ($array['name'] === '!') {
return $indentation . '<![CDATA[' . $array['value'] . ']]>';
}
if (str_ends_with($array['name'], '[]')) {
$array['name'] = substr($array['name'], 0, -2);
}
// Start the element.
$output = $indentation . '<' . $array['name'];
$inside_elements = false;
$output_el = '';
// Run through and recursively output all the elements or attributes inside this.
foreach ($array as $k => $v) {
if (str_starts_with($k, '@')) {
$output .= ' ' . substr($k, 1) . '="' . $v . '"';
} elseif (\is_array($v)) {
$output_el .= $this->_xml($v, $indent === null ? null : $indent + 1);
$inside_elements = true;
}
}
// Indent, if necessary.... then close the tag.
if ($inside_elements) {
$output .= '>' . $output_el . $indentation . '</' . $array['name'] . '>';
} else {
$output .= ' />';
}
return $output;
}
/**
* Return an element as an array
*
* @param array $array An array of data
* @return string|array A string with the element's value or an array of element data
*/
protected function _array(array $array): string|array
{
$return = [];
$text = '';
foreach ($array as $value) {
if (!\is_array($value) || !isset($value['name'])) {
continue;
}
if ($value['name'] === '!') {
$text .= $value['value'];
} else {
$return[$value['name']] = $this->_array($value);
}
}
if (empty($return)) {
return $text;
}
return $return;
}
/**
* Turn the CDATAs back to normal text.
*
* @param string $data The data with CDATA tags
* @return string The transformed data
*/
protected function _from_cdata(string $data): string
{
if (str_contains($data, '&')) {
$data = html_entity_decode($data, ENT_QUOTES | ENT_XML1, 'UTF-8');
}
return $this->trim ? trim($data) : $data;
}
/**
* Given an array, return the text from that array. (recursive and privately used.)
*
* @param null|array|string $array An array of data
* @return string The text from the array
*/
protected function _fetch(array|string|null $array): string
{
// Don't return anything if this is just a string.
if (\is_string($array)) {
return '';
}
$temp = '';
foreach ((array) $array as $text) {
// This means it's most likely an attribute or the name itself.
if (!isset($text['name'])) {
continue;
}
// This is text!
if ($text['name'] == '!') {
$temp .= $text['value'];
}
// Another element - dive in ;).
else {
$temp .= $this->_fetch($text);
}
}
// Return all the bits and pieces we've put together.
return $temp;
}
/**
* Get a specific array by path, one level down. (privately used...)
*
* @param array $array An array of data
* @param string $path The path
* @param null|int $level How far deep into the array we should go
* @param bool $no_error Whether or not to ignore errors
* @return string|array The specified array (or the contents of said array if there's only one result)
*/
protected function _path(array $array, string $path, ?int $level, bool $no_error = false): string|array
{
// Is $array even an array? It might be false!
if (!\is_array($array)) {
return false;
}
// Asking for *no* path?
if ($path == '' || $path == '.') {
return $array;
}
$paths = explode('|', $path);
// A * means all elements of any name.
$path_map = array_flip($paths);
$show_all = isset($path_map['*']);
$results = [];
// Check each element.
foreach ($array as $value) {
if (!\is_array($value) || $value['name'] === '!') {
continue;
}
if ($show_all || isset($path_map[$value['name']])) {
// Skip elements before "the one".
if ($level !== null && $level > 0) {
$level--;
} else {
$results[] = $value;
}
}
}
// No results found...
if (empty($results) && $this->debug_level & E_NOTICE && !$no_error) {
$trace = debug_backtrace();
$i = 0;
while ($i < \count($trace) && isset($trace[$i]['class']) && $trace[$i]['class'] == self::class) {
$i++;
}
$debug = ' from ' . $trace[$i - 1]['file'] . ' on line ' . $trace[$i - 1]['line'];
// Cause an error.
trigger_error(Lang::getTxt('undefined_xml_element', [$path . $debug], file: 'Errors'), E_USER_NOTICE);
return false;
}
// Only one result.
if (\count($results) == 1 || $level !== null) {
return $results[0];
}
// Return the result set.
return $results + ['name' => $path . '[]'];
}
}