Subversion-Projekte lars-tiefland.cakephp

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
1 lars 1
<?php
2
/* SVN FILE: $Id: xml.php 7945 2008-12-19 02:16:01Z gwoo $ */
3
/**
4
 * XML handling for Cake.
5
 *
6
 * The methods in these classes enable the datasources that use XML to work.
7
 *
8
 * PHP versions 4 and 5
9
 *
10
 * CakePHP(tm) :  Rapid Development Framework (http://www.cakephp.org)
11
 * Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
12
 *
13
 * Licensed under The MIT License
14
 * Redistributions of files must retain the above copyright notice.
15
 *
16
 * @filesource
17
 * @copyright     Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
18
 * @link          http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
19
 * @package       cake
20
 * @subpackage    cake.cake.libs
21
 * @since         CakePHP v .0.10.3.1400
22
 * @version       $Revision: 7945 $
23
 * @modifiedby    $LastChangedBy: gwoo $
24
 * @lastmodified  $Date: 2008-12-18 18:16:01 -0800 (Thu, 18 Dec 2008) $
25
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
26
 */
27
App::import('Core', 'Set');
28
/**
29
 * XML node.
30
 *
31
 * Single XML node in an XML tree.
32
 *
33
 * @package       cake
34
 * @subpackage    cake.cake.libs
35
 * @since         CakePHP v .0.10.3.1400
36
 */
37
class XmlNode extends Object {
38
/**
39
 * Name of node
40
 *
41
 * @var string
42
 * @access public
43
 */
44
	var $name = null;
45
/**
46
 * Node namespace
47
 *
48
 * @var string
49
 * @access public
50
 */
51
	var $namespace = null;
52
/**
53
 * Namespaces defined for this node and all child nodes
54
 *
55
 * @var array
56
 * @access public
57
 */
58
	var $namespaces = array();
59
/**
60
 * Value of node
61
 *
62
 * @var string
63
 * @access public
64
 */
65
	var $value;
66
/**
67
 * Attributes on this node
68
 *
69
 * @var array
70
 * @access public
71
 */
72
	var $attributes = array();
73
/**
74
 * This node's children
75
 *
76
 * @var array
77
 * @access public
78
 */
79
	var $children = array();
80
/**
81
 * Reference to parent node.
82
 *
83
 * @var XmlNode
84
 * @access private
85
 */
86
	var $__parent = null;
87
/**
88
 * Constructor.
89
 *
90
 * @param string $name Node name
91
 * @param array $attributes Node attributes
92
 * @param mixed $value Node contents (text)
93
 * @param array $children Node children
94
 */
95
	function __construct($name = null, $value = null, $namespace = null) {
96
		if (strpos($name, ':') !== false) {
97
			list($prefix, $name) = explode(':', $name);
98
			if (!$namespace) {
99
				$namespace = $prefix;
100
			}
101
		}
102
		$this->name = $name;
103
		if ($namespace) {
104
			$this->namespace = $namespace;
105
		}
106
 
107
		if (is_array($value) || is_object($value)) {
108
			$this->normalize($value);
109
		} elseif (!empty($value) || $value === 0 || $value === '0') {
110
			$this->createTextNode($value);
111
		}
112
	}
113
 
114
/**
115
 * Adds a namespace to the current node
116
 *
117
 * @param string $prefix The namespace prefix
118
 * @param string $url The namespace DTD URL
119
 * @return void
120
 */
121
	function addNamespace($prefix, $url) {
122
		if ($ns = Xml::addGlobalNs($prefix, $url)) {
123
			$this->namespaces = array_merge($this->namespaces, $ns);
124
			return true;
125
		}
126
		return false;
127
	}
128
/**
129
 * Adds a namespace to the current node
130
 *
131
 * @param string $prefix The namespace prefix
132
 * @param string $url The namespace DTD URL
133
 * @return void
134
 */
135
	function removeNamespace($prefix) {
136
		if (Xml::removeGlobalNs($prefix)) {
137
			return true;
138
		}
139
		return false;
140
	}
141
/**
142
 * Creates an XmlNode object that can be appended to this document or a node in it
143
 *
144
 * @param string $name Node name
145
 * @param string $value Node value
146
 * @param string $namespace Node namespace
147
 * @return object XmlNode
148
 */
149
	function &createNode($name = null, $value = null, $namespace = false) {
150
		$node =& new XmlNode($name, $value, $namespace);
151
		$node->setParent($this);
152
		return $node;
153
	}
154
/**
155
 * Creates an XmlElement object that can be appended to this document or a node in it
156
 *
157
 * @param string $name Element name
158
 * @param string $value Element value
159
 * @param array $attributes Element attributes
160
 * @param string $namespace Node namespace
161
 * @return object XmlElement
162
 */
163
	function &createElement($name = null, $value = null, $attributes = array(), $namespace = false) {
164
		$element =& new XmlElement($name, $value, $attributes, $namespace);
165
		$element->setParent($this);
166
		return $element;
167
	}
168
/**
169
 * Creates an XmlTextNode object that can be appended to this document or a node in it
170
 *
171
 * @param string $value Node value
172
 * @return object XmlTextNode
173
 */
174
	function &createTextNode($value = null) {
175
		$node = new XmlTextNode($value);
176
		$node->setParent($this);
177
		return $node;
178
	}
179
/**
180
 * Gets the XML element properties from an object.
181
 *
182
 * @param object $object Object to get properties from
183
 * @return array Properties from object
184
 * @access public
185
 */
186
	function normalize($object, $keyName = null, $options = array()) {
187
		if (is_a($object, 'XmlNode')) {
188
			return $object;
189
		}
190
		$name = null;
191
		$options = array_merge(array('format' => 'attributes'), $options);
192
 
193
		if ($keyName !== null && !is_numeric($keyName)) {
194
			$name = $keyName;
195
		} elseif (!empty($object->_name_)) {
196
			$name = $object->_name_;
197
		} elseif (isset($object->name)) {
198
			$name = $object->name;
199
		} elseif ($options['format'] == 'attributes') {
200
			$name = get_class($object);
201
		}
202
 
203
		$tagOpts = $this->__tagOptions($name);
204
		if ($tagOpts === false) {
205
			return;
206
		}
207
 
208
		if (isset($tagOpts['name'])) {
209
			$name = $tagOpts['name'];
210
		} elseif ($name != strtolower($name)) {
211
			$name = Inflector::slug(Inflector::underscore($name));
212
		}
213
 
214
		if (!empty($name)) {
215
			$node =& $this->createElement($name);
216
		} else {
217
			$node =& $this;
218
		}
219
 
220
		$namespace = array();
221
		$attributes = array();
222
		$children = array();
223
		$chldObjs = array();
224
		$document =& $this->document();
225
 
226
		if (is_object($object)) {
227
			$chldObjs = get_object_vars($object);
228
		} elseif (is_array($object)) {
229
			$chldObjs = $object;
230
		} elseif (!empty($object) || $object === 0) {
231
			$node->createTextNode($object);
232
		}
233
		$attr = array();
234
 
235
		if (isset($tagOpts['attributes'])) {
236
			$attr = $tagOpts['attributes'];
237
		}
238
		if (isset($tagOpts['value']) && isset($chldObjs[$tagOpts['value']])) {
239
			$node->createTextNode($chldObjs[$tagOpts['value']]);
240
			unset($chldObjs[$tagOpts['value']]);
241
		}
242
		unset($chldObjs['_name_']);
243
		$c = 0;
244
 
245
		foreach ($chldObjs as $key => $val) {
246
			if (in_array($key, $attr) && !is_object($val) && !is_array($val)) {
247
				$attributes[$key] = $val;
248
			} else {
249
				if (!isset($tagOpts['children']) || $tagOpts['children'] === array() || (is_array($tagOpts['children']) && in_array($key, $tagOpts['children']))) {
250
					$n = $key;
251
 
252
					if (is_numeric($n)) {
253
						$n = $name;
254
					}
255
					if (is_array($val)) {
256
						foreach ($val as $i => $obj2) {
257
							$n2 = $i;
258
							if (is_numeric($n2)) {
259
								$n2 = $n;
260
							}
261
							$node->normalize($obj2, $n2, $options);
262
						}
263
					} else {
264
						if (is_object($val)) {
265
							$node->normalize($val, $n, $options);
266
						} elseif ($options['format'] == 'tags' && $this->__tagOptions($key) !== false) {
267
							$tmp =& $node->createElement($key);
268
							if (!empty($val) || $val === 0) {
269
								$tmp->createTextNode($val);
270
							}
271
						} elseif ($options['format'] == 'attributes') {
272
							$node->addAttribute($key, $val);
273
						}
274
					}
275
				}
276
			}
277
			$c++;
278
		}
279
		if (!empty($name)) {
280
			return $node;
281
		}
282
		return $children;
283
	}
284
/**
285
 * Gets the tag-specific options for the given node name
286
 *
287
 * @param string $name XML tag name
288
 * @param string $option The specific option to query.  Omit for all options
289
 * @return mixed A specific option value if $option is specified, otherwise an array of all options
290
 * @access private
291
 */
292
	function __tagOptions($name, $option = null) {
293
		if (isset($this->__tags[$name])) {
294
			$tagOpts = $this->__tags[$name];
295
		} elseif (isset($this->__tags[strtolower($name)])) {
296
			$tagOpts = $this->__tags[strtolower($name)];
297
		} else {
298
			return null;
299
		}
300
		if ($tagOpts === false) {
301
			return false;
302
		}
303
		if (empty($option)) {
304
			return $tagOpts;
305
		}
306
		if (isset($tagOpts[$option])) {
307
			return $tagOpts[$option];
308
		}
309
		return null;
310
	}
311
/**
312
 * Returns the fully-qualified XML node name, with namespace
313
 *
314
 * @access public
315
 */
316
	function name() {
317
		if (!empty($this->namespace)) {
318
			$_this =& XmlManager::getInstance();
319
			if (!isset($_this->options['verifyNs']) || !$_this->options['verifyNs'] || in_array($this->namespace, array_keys($_this->namespaces))) {
320
				return $this->namespace . ':' . $this->name;
321
			}
322
		}
323
		return $this->name;
324
	}
325
/**
326
 * Sets the parent node of this XmlNode.
327
 *
328
 * @access public
329
 */
330
	function setParent(&$parent) {
331
		if (strtolower(get_class($this)) == 'xml') {
332
			return;
333
		}
334
		if (isset($this->__parent) && is_object($this->__parent)) {
335
			if ($this->__parent->compare($parent)) {
336
				return;
337
			}
338
			foreach ($this->__parent->children as $i => $child) {
339
				if ($this->compare($child)) {
340
					array_splice($this->__parent->children, $i, 1);
341
					break;
342
				}
343
			}
344
		}
345
		if ($parent == null) {
346
			unset($this->__parent);
347
		} else {
348
			$parent->children[] =& $this;
349
			$this->__parent =& $parent;
350
		}
351
	}
352
/**
353
 * Returns a copy of self.
354
 *
355
 * @return object Cloned instance
356
 * @access public
357
 */
358
	function cloneNode() {
359
		return clone($this);
360
	}
361
/**
362
 * Compares $node to this XmlNode object
363
 *
364
 * @param object An XmlNode or subclass instance
365
 * @return boolean True if the nodes match, false otherwise
366
 * @access public
367
 */
368
	function compare($node) {
369
		$keys = array(get_object_vars($this), get_object_vars($node));
370
		return ($keys[0] === $keys[1]);
371
	}
372
/**
373
 * Append given node as a child.
374
 *
375
 * @param object $child XmlNode with appended child
376
 * @param array $options XML generator options for objects and arrays
377
 * @return object A reference to the appended child node
378
 * @access public
379
 */
380
	function &append(&$child, $options = array()) {
381
		if (empty($child)) {
382
			$return = false;
383
			return $return;
384
		}
385
 
386
		if (is_object($child)) {
387
			if ($this->compare($child)) {
388
				trigger_error('Cannot append a node to itself.');
389
				$return = false;
390
				return $return;
391
			}
392
		} else if (is_array($child)) {
393
			$child = Set::map($child);
394
			if (is_array($child)) {
395
				if (!is_a(current($child), 'XmlNode')) {
396
					foreach ($child as $i => $childNode) {
397
						$child[$i] = $this->normalize($childNode, null, $options);
398
					}
399
				} else {
400
					foreach ($child as $childNode) {
401
						$this->append($childNode, $options);
402
					}
403
				}
404
				return $child;
405
			}
406
		} else {
407
			$attributes = array();
408
			if (func_num_args() >= 2) {
409
				$attributes = func_get_arg(1);
410
			}
411
			$child =& $this->createNode($child, null, $attributes);
412
		}
413
 
414
		$child = $this->normalize($child, null, $options);
415
 
416
		if (empty($child->namespace) && !empty($this->namespace)) {
417
			$child->namespace = $this->namespace;
418
		}
419
 
420
		if (is_a($child, 'XmlNode')) {
421
			$child->setParent($this);
422
		}
423
 
424
		return $child;
425
	}
426
/**
427
 * Returns first child node, or null if empty.
428
 *
429
 * @return object First XmlNode
430
 * @access public
431
 */
432
	function &first() {
433
		if (isset($this->children[0])) {
434
			return $this->children[0];
435
		} else {
436
			$return = null;
437
			return $return;
438
		}
439
	}
440
/**
441
 * Returns last child node, or null if empty.
442
 *
443
 * @return object Last XmlNode
444
 * @access public
445
 */
446
	function &last() {
447
		if (count($this->children) > 0) {
448
			return $this->children[count($this->children) - 1];
449
		} else {
450
			$return = null;
451
			return $return;
452
		}
453
	}
454
/**
455
 * Returns child node with given ID.
456
 *
457
 * @param string $id Name of child node
458
 * @return object Child XmlNode
459
 * @access public
460
 */
461
	function &child($id) {
462
		$null = null;
463
 
464
		if (is_int($id)) {
465
			if (isset($this->children[$id])) {
466
				return $this->children[$id];
467
			} else {
468
				return null;
469
			}
470
		} elseif (is_string($id)) {
471
			for ($i = 0; $i < count($this->children); $i++) {
472
				if ($this->children[$i]->name == $id) {
473
					return $this->children[$i];
474
				}
475
			}
476
		}
477
		return $null;
478
	}
479
/**
480
 * Gets a list of childnodes with the given tag name.
481
 *
482
 * @param string $name Tag name of child nodes
483
 * @return array An array of XmlNodes with the given tag name
484
 * @access public
485
 */
486
	function children($name) {
487
		$nodes = array();
488
		$count = count($this->children);
489
		for ($i = 0; $i < $count; $i++) {
490
			if ($this->children[$i]->name == $name) {
491
				$nodes[] =& $this->children[$i];
492
			}
493
		}
494
		return $nodes;
495
	}
496
/**
497
 * Gets a reference to the next child node in the list of this node's parent.
498
 *
499
 * @return object A reference to the XmlNode object
500
 * @access public
501
 */
502
	function &nextSibling() {
503
		$null = null;
504
		$count = count($this->__parent->children);
505
		for ($i = 0; $i < $count; $i++) {
506
			if ($this->__parent->children[$i] == $this) {
507
				if ($i >= $count - 1 || !isset($this->__parent->children[$i + 1])) {
508
					return $null;
509
				}
510
				return $this->__parent->children[$i + 1];
511
			}
512
		}
513
		return $null;
514
	}
515
/**
516
 * Gets a reference to the previous child node in the list of this node's parent.
517
 *
518
 * @return object A reference to the XmlNode object
519
 * @access public
520
 */
521
	function &previousSibling() {
522
		$null = null;
523
		$count = count($this->__parent->children);
524
		for ($i = 0; $i < $count; $i++) {
525
			if ($this->__parent->children[$i] == $this) {
526
				if ($i == 0 || !isset($this->__parent->children[$i - 1])) {
527
					return $null;
528
				}
529
				return $this->__parent->children[$i - 1];
530
			}
531
		}
532
		return $null;
533
	}
534
/**
535
 * Returns parent node.
536
 *
537
 * @return object Parent XmlNode
538
 * @access public
539
 */
540
	function &parent() {
541
		return $this->__parent;
542
	}
543
/**
544
 * Returns the XML document to which this node belongs
545
 *
546
 * @return object Parent XML object
547
 * @access public
548
 */
549
	function &document() {
550
		$document =& $this;
551
		while (true) {
552
			if (get_class($document) == 'Xml' || $document == null) {
553
				break;
554
			}
555
			$document =& $document->parent();
556
		}
557
		return $document;
558
	}
559
/**
560
 * Returns true if this structure has child nodes.
561
 *
562
 * @return bool
563
 * @access public
564
 */
565
	function hasChildren() {
566
		if (is_array($this->children) && count($this->children) > 0) {
567
			return true;
568
		}
569
		return false;
570
	}
571
/**
572
 * Returns this XML structure as a string.
573
 *
574
 * @return string String representation of the XML structure.
575
 * @access public
576
 */
577
	function toString($options = array(), $depth = 0) {
578
		if (is_int($options)) {
579
			$depth = $options;
580
			$options = array();
581
		}
582
		$defaults = array('cdata' => true, 'whitespace' => false, 'convertEntities' => false, 'showEmpty' => true, 'leaveOpen' => false);
583
		$options = array_merge($defaults, Xml::options(), $options);
584
		$tag = !(strpos($this->name, '#') === 0);
585
		$d = '';
586
 
587
		if ($tag) {
588
			if ($options['whitespace']) {
589
				$d .= str_repeat("\t", $depth);
590
			}
591
 
592
			$d .= '<' . $this->name();
593
			if (count($this->namespaces) > 0) {
594
				foreach ($this->namespaces as $key => $val) {
595
					$val = str_replace('"', '\"', $val);
596
					$d .= ' xmlns:' . $key . '="' . $val . '"';
597
				}
598
			}
599
 
600
			$parent =& $this->parent();
601
			if ($parent->name === '#document' && count($parent->namespaces) > 0) {
602
				foreach ($parent->namespaces as $key => $val) {
603
					$val = str_replace('"', '\"', $val);
604
					$d .= ' xmlns:' . $key . '="' . $val . '"';
605
				}
606
			}
607
 
608
			if (is_array($this->attributes) && count($this->attributes) > 0) {
609
				foreach ($this->attributes as $key => $val) {
610
					$d .= ' ' . $key . '="' . htmlspecialchars($val, ENT_QUOTES, Configure::read('App.encoding')) . '"';
611
				}
612
			}
613
		}
614
 
615
		if (!$this->hasChildren() && empty($this->value) && $this->value !== 0 && $tag) {
616
			if (!$options['leaveOpen']) {
617
				$d .= ' />';
618
			}
619
			if ($options['whitespace']) {
620
				$d .= "\n";
621
			}
622
		} elseif ($tag || $this->hasChildren()) {
623
			if ($tag) {
624
				$d .= '>';
625
			}
626
			if ($this->hasChildren()) {
627
				if ($options['whitespace']) {
628
					$d .= "\n";
629
				}
630
 
631
				$count = count($this->children);
632
				$cDepth = $depth + 1;
633
				for ($i = 0; $i < $count; $i++) {
634
					$d .= $this->children[$i]->toString($options, $cDepth);
635
				}
636
				if ($tag) {
637
					if ($options['whitespace'] && $tag) {
638
						$d .= str_repeat("\t", $depth);
639
					}
640
					if (!$options['leaveOpen']) {
641
						$d .= '</' . $this->name() . '>';
642
					}
643
					if ($options['whitespace']) {
644
						$d .= "\n";
645
					}
646
				}
647
			}
648
		}
649
		return $d;
650
	}
651
/**
652
 * Return array representation of current object.
653
 *
654
 * @param boolean $camelize true will camelize child nodes, false will not alter node names
655
 * @return array Array representation
656
 * @access public
657
 */
658
	function toArray($camelize = true) {
659
		$out = $this->attributes;
660
		$multi = null;
661
 
662
		foreach ($this->children as $child) {
663
			$key = $camelize ? Inflector::camelize($child->name) : $child->name;
664
 
665
			if (is_a($child, 'XmlTextNode')) {
666
				$out['value'] = $child->value;
667
				continue;
668
			} elseif (isset($child->children[0]) && is_a($child->children[0], 'XmlTextNode')) {
669
				$value = $child->children[0]->value;
670
 
671
				if ($child->attributes) {
672
					$value = array_merge(array('value' => $value), $child->attributes);
673
				}
674
 
675
				if (isset($out[$child->name]) || isset($multi[$key])) {
676
					if (!isset($multi[$key])) {
677
						$multi[$key] = array($out[$child->name]);
678
						unset($out[$child->name]);
679
					}
680
					$multi[$key][] = $value;
681
				} else {
682
					$out[$child->name] = $value;
683
				}
684
				continue;
685
			} else {
686
				$value = $child->toArray($camelize);
687
			}
688
 
689
			if (!isset($out[$key])) {
690
				$out[$key] = $value;
691
			} else {
692
				if (!is_array($out[$key]) || !isset($out[$key][0])) {
693
					$out[$key] = array($out[$key]);
694
				}
695
				$out[$key][] = $value;
696
			}
697
		}
698
 
699
		if (isset($multi)) {
700
			$out = array_merge($out, $multi);
701
		}
702
		return $out;
703
	}
704
/**
705
 * Returns data from toString when this object is converted to a string.
706
 *
707
 * @return string String representation of this structure.
708
 * @access private
709
 */
710
	function __toString() {
711
		return $this->toString();
712
	}
713
/**
714
 * Debug method. Deletes the parent. Also deletes this node's children,
715
 * if given the $recursive parameter.
716
 *
717
 * @param boolean $recursive Recursively delete elements.
718
 * @access private
719
 */
720
	function __killParent($recursive = true) {
721
		unset($this->__parent, $this->_log);
722
		if ($recursive && $this->hasChildren()) {
723
			for ($i = 0; $i < count($this->children); $i++) {
724
				$this->children[$i]->__killParent(true);
725
			}
726
		}
727
	}
728
}
729
 
730
/**
731
 * Main XML class.
732
 *
733
 * Parses and stores XML data, representing the root of an XML document
734
 *
735
 * @package       cake
736
 * @subpackage    cake.cake.libs
737
 * @since         CakePHP v .0.10.3.1400
738
 */
739
class Xml extends XmlNode {
740
 
741
/**
742
 * Resource handle to XML parser.
743
 *
744
 * @var resource
745
 * @access private
746
 */
747
	var $__parser;
748
/**
749
 * File handle to XML indata file.
750
 *
751
 * @var resource
752
 * @access private
753
 */
754
	var $__file;
755
/**
756
 * Raw XML string data (for loading purposes)
757
 *
758
 * @var string
759
 * @access private
760
 */
761
	var $__rawData = null;
762
 
763
/**
764
 * XML document header
765
 *
766
 * @var string
767
 * @access private
768
 */
769
	var $__header = null;
770
 
771
/**
772
 * Default array keys/object properties to use as tag names when converting objects or array structures to XML.
773
 * Set by passing $options['tags'] to this object's constructor.
774
 *
775
 * @var array
776
 * @access private
777
 */
778
	var $__tags = array();
779
 
780
/**
781
 * XML document version
782
 *
783
 * @var string
784
 * @access private
785
 */
786
	var $version = '1.0';
787
 
788
/**
789
 * XML document encoding
790
 *
791
 * @var string
792
 * @access private
793
 */
794
	var $encoding = 'UTF-8';
795
 
796
/**
797
 * Constructor.  Sets up the XML parser with options, gives it this object as
798
 * its XML object, and sets some variables.
799
 *
800
 * @param string $input What should be used to set up
801
 * @param array $options Options to set up with
802
 */
803
	function __construct($input = null, $options = array()) {
804
		$defaults = array(
805
			'root' => '#document', 'tags' => array(), 'namespaces' => array(),
806
			'version' => '1.0', 'encoding' => 'UTF-8', 'format' => 'attributes'
807
		);
808
		$options = array_merge($defaults, Xml::options(), $options);
809
 
810
		foreach (array('version', 'encoding', 'namespaces') as $key) {
811
			$this->{$key} = $options[$key];
812
		}
813
		$this->__tags = $options['tags'];
814
		parent::__construct($options['root']);
815
 
816
		if (!empty($input)) {
817
			if (is_string($input)) {
818
				$this->load($input);
819
			} elseif (is_array($input) || is_object($input)) {
820
				$this->append($input, $options);
821
			}
822
		}
823
 
824
		// if (Configure::read('App.encoding') !== null) {
825
		// 	$this->encoding = Configure::read('App.encoding');
826
		// }
827
	}
828
/**
829
 * Initialize XML object from a given XML string. Returns false on error.
830
 *
831
 * @param string $input XML string, a path to a file, or an HTTP resource to load
832
 * @return boolean Success
833
 * @access public
834
 */
835
	function load($input) {
836
		if (!is_string($input)) {
837
			return false;
838
		}
839
		$this->__rawData = null;
840
		$this->__header = null;
841
 
842
		if (strstr($input, "<")) {
843
			$this->__rawData = $input;
844
		} elseif (strpos($input, 'http://') === 0 || strpos($input, 'https://') === 0) {
845
			App::import('Core', 'HttpSocket');
846
			$socket = new HttpSocket();
847
			$this->__rawData = $socket->get($input);
848
		} elseif (file_exists($input)) {
849
			$this->__rawData = file_get_contents($input);
850
		} else {
851
			trigger_error('XML cannot be read');
852
			return false;
853
		}
854
		return $this->parse();
855
	}
856
/**
857
 * Parses and creates XML nodes from the __rawData property.
858
 *
859
 * @return boolean Success
860
 * @access public
861
 * @see Xml::load()
862
 * @todo figure out how to link attributes and namespaces
863
 */
864
	function parse() {
865
		$this->__initParser();
866
		$this->__header = trim(str_replace(a('<' . '?', '?' . '>'), a('', ''), substr(trim($this->__rawData), 0, strpos($this->__rawData, "\n"))));
867
 
868
		xml_parse_into_struct($this->__parser, $this->__rawData, $vals);
869
		$xml =& $this;
870
		$count = count($vals);
871
 
872
		for ($i = 0; $i < $count; $i++) {
873
			$data = $vals[$i];
874
			$data = array_merge(array('tag' => null, 'value' => null, 'attributes' => array()), $data);
875
			switch ($data['type']) {
876
				case "open" :
877
					$xml =& $xml->createElement($data['tag'], $data['value'], $data['attributes']);
878
				break;
879
				case "close" :
880
					$xml =& $xml->parent();
881
				break;
882
				case "complete" :
883
					$xml->createElement($data['tag'], $data['value'], $data['attributes']);
884
				break;
885
				case 'cdata':
886
					$xml->createTextNode($data['value']);
887
				break;
888
			}
889
		}
890
		return true;
891
	}
892
/**
893
 * Initializes the XML parser resource
894
 *
895
 * @return void
896
 * @access private
897
 */
898
	function __initParser() {
899
		if (empty($this->__parser)) {
900
			$this->__parser = xml_parser_create();
901
			xml_set_object($this->__parser, $this);
902
			xml_parser_set_option($this->__parser, XML_OPTION_CASE_FOLDING, 0);
903
			xml_parser_set_option($this->__parser, XML_OPTION_SKIP_WHITE, 1);
904
		}
905
	}
906
/**
907
 * Returns a string representation of the XML object
908
 *
909
 * @param mixed $options If boolean: whether to include the XML header with the document (defaults to true); if array:
910
 *						 overrides the default XML generation options
911
 * @return string XML data
912
 * @access public
913
 * @deprecated
914
 * @see Xml::toString()
915
 */
916
	function compose($options = array()) {
917
		return $this->toString($options);
918
	}
919
/**
920
 * If debug mode is on, this method echoes an error message.
921
 *
922
 * @param string $msg Error message
923
 * @param integer $code Error code
924
 * @param integer $line Line in file
925
 * @access public
926
 */
927
	function error($msg, $code = 0, $line = 0) {
928
		if (Configure::read('debug')) {
929
			echo $msg . " " . $code . " " . $line;
930
		}
931
	}
932
/**
933
 * Returns a string with a textual description of the error code, or FALSE if no description was found.
934
 *
935
 * @param integer $code Error code
936
 * @return string Error message
937
 * @access public
938
 */
939
	function getError($code) {
940
		$r = @xml_error_string($code);
941
		return $r;
942
	}
943
 
944
// Overridden functions from superclass
945
 
946
/**
947
 * Get next element. NOT implemented.
948
 *
949
 * @return object
950
 * @access public
951
 */
952
	function &next() {
953
		$return = null;
954
		return $return;
955
	}
956
/**
957
 * Get previous element. NOT implemented.
958
 *
959
 * @return object
960
 * @access public
961
 */
962
	function &previous() {
963
		$return = null;
964
		return $return;
965
	}
966
/**
967
 * Get parent element. NOT implemented.
968
 *
969
 * @return object
970
 * @access public
971
 */
972
	function &parent() {
973
		$return = null;
974
		return $return;
975
	}
976
/**
977
 * Adds a namespace to the current document
978
 *
979
 * @param string $prefix The namespace prefix
980
 * @param string $url The namespace DTD URL
981
 * @return void
982
 */
983
	function addNamespace($prefix, $url) {
984
		if ($count = count($this->children)) {
985
			for ($i = 0; $i < $count; $i++) {
986
				$this->children[$i]->addNamespace($prefix, $url);
987
			}
988
			return true;
989
		}
990
		return parent::addNamespace($prefix, $url);
991
	}
992
/**
993
 * Removes a namespace to the current document
994
 *
995
 * @param string $prefix The namespace prefix
996
 * @return void
997
 */
998
	function removeNamespace($prefix) {
999
		if ($count = count($this->children)) {
1000
			for ($i = 0; $i < $count; $i++) {
1001
				$this->children[$i]->removeNamespace($prefix);
1002
			}
1003
			return true;
1004
		}
1005
		return parent::removeNamespace($prefix);
1006
	}
1007
/**
1008
 * Return string representation of current object.
1009
 *
1010
 * @return string String representation
1011
 * @access public
1012
 */
1013
	function toString($options = array()) {
1014
		if (is_bool($options)) {
1015
			$options = array('header' => $options);
1016
		}
1017
 
1018
		$defaults = array('header' => false, 'encoding' => $this->encoding);
1019
		$options = array_merge($defaults, Xml::options(), $options);
1020
		$data = parent::toString($options, 0);
1021
 
1022
		if ($options['header']) {
1023
			if (!empty($this->__header)) {
1024
				return $this->header($this->__header)  . "\n" . $data;
1025
			}
1026
			return $this->header()  . "\n" . $data;
1027
		}
1028
 
1029
		return $data;
1030
	}
1031
/**
1032
 * Return a header used on the first line of the xml file
1033
 *
1034
 * @param  mixed  $attrib attributes of the header element
1035
 * @return string formated header
1036
 */
1037
	function header($attrib = array()) {
1038
		$header = 'xml';
1039
		if (is_string($attrib)) {
1040
			$header = $attrib;
1041
		} else {
1042
 
1043
			$attrib = array_merge(array('version' => $this->version, 'encoding' => $this->encoding), $attrib);
1044
			foreach ($attrib as $key=>$val) {
1045
				$header .= ' ' . $key . '="' . $val . '"';
1046
			}
1047
		}
1048
		return '<' . '?' . $header . ' ?' . '>';
1049
	}
1050
 
1051
/**
1052
 * Destructor, used to free resources.
1053
 *
1054
 * @access private
1055
 */
1056
	function __destruct() {
1057
		if (is_resource($this->__parser)) {
1058
			xml_parser_free($this->__parser);
1059
		}
1060
	}
1061
/**
1062
 * Adds a namespace to any XML documents generated or parsed
1063
 *
1064
 * @param  string  $name The namespace name
1065
 * @param  string  $url  The namespace URI; can be empty if in the default namespace map
1066
 * @return boolean False if no URL is specified, and the namespace does not exist
1067
 *                 default namespace map, otherwise true
1068
 * @access public
1069
 * @static
1070
 */
1071
	function addGlobalNs($name, $url = null) {
1072
		$_this =& XmlManager::getInstance();
1073
		if ($ns = Xml::resolveNamespace($name, $url)) {
1074
			$_this->namespaces = array_merge($_this->namespaces, $ns);
1075
			return $ns;
1076
		}
1077
		return false;
1078
	}
1079
/**
1080
 * Resolves current namespace
1081
 *
1082
 * @param  string  $name
1083
 * @param  string  $url
1084
 * @return array
1085
 */
1086
	function resolveNamespace($name, $url) {
1087
		$_this =& XmlManager::getInstance();
1088
		if ($url == null && isset($_this->defaultNamespaceMap[$name])) {
1089
			$url = $_this->defaultNamespaceMap[$name];
1090
		} elseif ($url == null) {
1091
			return false;
1092
		}
1093
 
1094
		if (!strpos($url, '://') && isset($_this->defaultNamespaceMap[$name])) {
1095
			$_url = $_this->defaultNamespaceMap[$name];
1096
			$name = $url;
1097
			$url = $_url;
1098
		}
1099
		return array($name => $url);
1100
	}
1101
/**
1102
 * Alias to Xml::addNs
1103
 *
1104
 * @access public
1105
 * @static
1106
 */
1107
	function addGlobalNamespace($name, $url = null) {
1108
		return Xml::addGlobalNs($name, $url);
1109
	}
1110
/**
1111
 * Removes a namespace added in addNs()
1112
 *
1113
 * @param  string  $name The namespace name or URI
1114
 * @access public
1115
 * @static
1116
 */
1117
	function removeGlobalNs($name) {
1118
		$_this =& XmlManager::getInstance();
1119
		if (isset($_this->namespaces[$name])) {
1120
			unset($_this->namespaces[$name]);
1121
			unset($this->namespaces[$name]);
1122
			return true;
1123
		} elseif (in_array($name, $_this->namespaces)) {
1124
			$keys = array_keys($_this->namespaces);
1125
			$count = count($keys);
1126
			for ($i = 0; $i < $count; $i++) {
1127
				if ($_this->namespaces[$keys[$i]] == $name) {
1128
					unset($_this->namespaces[$keys[$i]]);
1129
					unset($this->namespaces[$keys[$i]]);
1130
					return true;
1131
				}
1132
			}
1133
		}
1134
		return false;
1135
	}
1136
/**
1137
 * Alias to Xml::removeNs
1138
 *
1139
 * @access public
1140
 * @static
1141
 */
1142
	function removeGlobalNamespace($name) {
1143
		return Xml::removeGlobalNs($name);
1144
	}
1145
/**
1146
 * Sets/gets global XML options
1147
 *
1148
 * @param array $options
1149
 * @return array
1150
 * @access public
1151
 * @static
1152
 */
1153
	function options($options = array()) {
1154
		$_this =& XmlManager::getInstance();
1155
		$_this->options = array_merge($_this->options, $options);
1156
		return $_this->options;
1157
	}
1158
}
1159
/**
1160
 * The XML Element
1161
 *
1162
 */
1163
class XmlElement extends XmlNode {
1164
/**
1165
 * Construct an Xml element
1166
 *
1167
 * @param  string  $name name of the node
1168
 * @param  string  $value value of the node
1169
 * @param  array  $attributes
1170
 * @param  string  $namespace
1171
 * @return string A copy of $data in XML format
1172
 */
1173
	function __construct($name = null, $value = null, $attributes = array(), $namespace = false) {
1174
		parent::__construct($name, $value, $namespace);
1175
		$this->addAttribute($attributes);
1176
	}
1177
/**
1178
 * Get all the attributes for this element
1179
 *
1180
 * @return array
1181
 */
1182
	function attributes() {
1183
		return $this->attributes;
1184
	}
1185
/**
1186
 * Add attributes to this element
1187
 *
1188
 * @param  string  $name name of the node
1189
 * @param  string  $value value of the node
1190
 * @return boolean
1191
 */
1192
	function addAttribute($name, $val = null) {
1193
		if (is_object($name)) {
1194
			$name = get_object_vars($name);
1195
		}
1196
		if (is_array($name)) {
1197
			foreach ($name as $key => $val) {
1198
				$this->addAttribute($key, $val);
1199
			}
1200
			return true;
1201
		}
1202
		if (is_numeric($name)) {
1203
			$name = $val;
1204
			$val = null;
1205
		}
1206
		if (!empty($name)) {
1207
			if (strpos($name, 'xmlns') === 0) {
1208
				if ($name == 'xmlns') {
1209
					$this->namespace = $val;
1210
				} else {
1211
					list($pre, $prefix) = explode(':', $name);
1212
					$this->addNamespace($prefix, $val);
1213
					return true;
1214
				}
1215
			}
1216
			$this->attributes[$name] = $val;
1217
			return true;
1218
		}
1219
		return false;
1220
	}
1221
/**
1222
 * Remove attributes to this element
1223
 *
1224
 * @param  string  $name name of the node
1225
 * @return boolean
1226
 */
1227
	function removeAttribute($attr) {
1228
		if (array_key_exists($attr, $this->attributes)) {
1229
			unset($this->attributes[$attr]);
1230
			return true;
1231
		}
1232
		return false;
1233
	}
1234
}
1235
 
1236
/**
1237
 * XML text or CDATA node
1238
 *
1239
 * Stores XML text data according to the encoding of the parent document
1240
 *
1241
 * @package       cake
1242
 * @subpackage    cake.cake.libs
1243
 * @since         CakePHP v .1.2.6000
1244
 */
1245
class XmlTextNode extends XmlNode {
1246
/**
1247
 * Harcoded XML node name, represents this object as a text node
1248
 *
1249
 * @var string
1250
 */
1251
	var $name = '#text';
1252
/**
1253
 * The text/data value which this node contains
1254
 *
1255
 * @var string
1256
 */
1257
	var $value = null;
1258
/**
1259
 * Construct text node with the given parent object and data
1260
 *
1261
 * @param object $parent Parent XmlNode/XmlElement object
1262
 * @param mixed $value Node value
1263
 */
1264
	function __construct($value = null) {
1265
		$this->value = $value;
1266
	}
1267
/**
1268
 * Looks for child nodes in this element
1269
 *
1270
 * @return boolean False - not supported
1271
 */
1272
	function hasChildren() {
1273
		return false;
1274
	}
1275
/**
1276
 * Append an XML node: XmlTextNode does not support this operation
1277
 *
1278
 * @return boolean False - not supported
1279
 * @todo make convertEntities work without mb support, convert entities to number entities
1280
 */
1281
	function append() {
1282
		return false;
1283
	}
1284
/**
1285
 * Return string representation of current text node object.
1286
 *
1287
 * @return string String representation
1288
 * @access public
1289
 */
1290
	function toString($options = array(), $depth = 0) {
1291
		if (is_int($options)) {
1292
			$depth = $options;
1293
			$options = array();
1294
		}
1295
 
1296
		$defaults = array('cdata' => true, 'whitespace' => false, 'convertEntities'	=> false);
1297
		$options = array_merge($defaults, Xml::options(), $options);
1298
		$val = $this->value;
1299
 
1300
		if ($options['convertEntities'] && function_exists('mb_convert_encoding')) {
1301
			$val = mb_convert_encoding($val,'UTF-8', 'HTML-ENTITIES');
1302
		}
1303
 
1304
		if ($options['cdata'] === true && !is_numeric($val)) {
1305
			$val = '<![CDATA[' . $val . ']]>';
1306
		}
1307
 
1308
		if ($options['whitespace']) {
1309
			return str_repeat("\t", $depth) . $val . "\n";
1310
		}
1311
		return $val;
1312
	}
1313
}
1314
/**
1315
 * Manages application-wide namespaces and XML parsing/generation settings.
1316
 * Private class, used exclusively within scope of XML class.
1317
 *
1318
 * @access private
1319
 */
1320
class XmlManager {
1321
 
1322
/**
1323
 * Global XML namespaces.  Used in all XML documents processed by this application
1324
 *
1325
 * @var array
1326
 * @access public
1327
 */
1328
	var $namespaces = array();
1329
/**
1330
 * Global XML document parsing/generation settings.
1331
 *
1332
 * @var array
1333
 * @access public
1334
 */
1335
	var $options = array();
1336
/**
1337
 * Map of common namespace URIs
1338
 *
1339
 * @access private
1340
 * @var array
1341
 */
1342
	var $defaultNamespaceMap = array(
1343
		'dc'     => 'http://purl.org/dc/elements/1.1/',					// Dublin Core
1344
		'dct'    => 'http://purl.org/dc/terms/',						// Dublin Core Terms
1345
		'g'			=> 'http://base.google.com/ns/1.0',					// Google Base
1346
		'rc'		=> 'http://purl.org/rss/1.0/modules/content/',		// RSS 1.0 Content Module
1347
		'wf'		=> 'http://wellformedweb.org/CommentAPI/',			// Well-Formed Web Comment API
1348
		'fb'		=> 'http://rssnamespace.org/feedburner/ext/1.0',	// FeedBurner extensions
1349
		'lj'		=> 'http://www.livejournal.org/rss/lj/1.0/',		// Live Journal
1350
		'itunes'	=> 'http://www.itunes.com/dtds/podcast-1.0.dtd',	// iTunes
1351
		'xhtml'		=> 'http://www.w3.org/1999/xhtml',					// XHTML,
1352
		'atom'	 	=> 'http://www.w3.org/2005/Atom'					// Atom
1353
	);
1354
/**
1355
 * Returns a reference to the global XML object that manages app-wide XML settings
1356
 *
1357
 * @return object
1358
 * @access public
1359
 */
1360
	function &getInstance() {
1361
		static $instance = array();
1362
 
1363
		if (!$instance) {
1364
			$instance[0] =& new XmlManager();
1365
		}
1366
		return $instance[0];
1367
	}
1368
}
1369
?>