]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/XmlElement.php
Whitespace only
[SourceForge/phpwiki.git] / lib / XmlElement.php
1 <?php
2 /**
3  * Code for writing XML.
4  * @package Markup
5  * @author: Jeff Dairiki,
6  *          Reini Urban (php5 tricks)
7  *
8  * WARNING: This module is very php5 sensitive.
9  *          Fixed for 1.3.9, 1.3.11 and 1.3.13 (php-5.2).
10  *          With allow_call_time_pass_reference clean fixes.
11  */
12
13 /**
14  * A sequence of (zero or more) XmlElements (possibly interspersed with
15  * plain strings (CDATA).
16  */
17 class XmlContent
18 {
19     function XmlContent (/* ... */) {
20         $this->_content = array();
21         $this->_pushContent_array(func_get_args());
22     }
23
24     function pushContent ($arg /*, ...*/) {
25         if (func_num_args() > 1)
26             $this->_pushContent_array(func_get_args());
27         elseif (is_array($arg))
28             $this->_pushContent_array($arg);
29         else
30             $this->_pushContent($arg);
31     }
32
33     function _pushContent_array ($array) {
34         foreach ($array as $item) {
35             if (is_array($item))
36                 $this->_pushContent_array($item);
37             else
38                 $this->_pushContent($item);
39         }
40     }
41
42     function _pushContent ($item) {
43         if (is_object($item) && strtolower(get_class($item)) == 'xmlcontent')
44             array_splice($this->_content, count($this->_content), 0,
45                          $item->_content);
46         else
47             $this->_content[] = $item;
48     }
49
50     function unshiftContent ($arg /*, ...*/) {
51         if (func_num_args() > 1)
52             $this->_unshiftContent_array(func_get_args());
53         elseif (is_array($arg))
54             $this->_unshiftContent_array($arg);
55         else
56             $this->_unshiftContent($arg);
57     }
58
59     function _unshiftContent_array ($array) {
60         foreach (array_reverse($array) as $item) {
61             if (is_array($item))
62                 $this->_unshiftContent_array($item);
63             else
64                 $this->_unshiftContent($item);
65         }
66     }
67
68     function _unshiftContent ($item) {
69         if (strtolower(get_class($item)) == 'xmlcontent')
70             array_splice($this->_content, 0, 0, $item->_content);
71         else
72             array_unshift($this->_content, $item);
73     }
74
75     function getContent () {
76         return $this->_content;
77     }
78
79     function setContent ($arg /* , ... */) {
80         $this->_content = array();
81         $this->_pushContent_array(func_get_args());
82     }
83
84     function printXML () {
85         foreach ($this->_content as $item) {
86             if (is_object($item)) {
87                 if (method_exists($item, 'printXML'))
88                     $item->printXML();
89                 elseif (method_exists($item, 'asXML'))
90                     echo $item->asXML();
91                 elseif (method_exists($item, 'asString'))
92                     echo $this->_quote($item->asString());
93                 else
94                     printf("==Object(%s)==", get_class($item));
95             }
96             elseif (is_array($item)) {
97             // DEPRECATED:
98             // Use XmlContent objects instead of arrays for collections of XmlElements.
99             trigger_error("Passing arrays to printXML() is deprecated: (" . AsXML($item, true) . ")",
100                       E_USER_NOTICE);
101             foreach ($item as $x)
102                     $this->printXML($x);
103             } else {
104                 echo $this->_quote((string) $item);
105             }
106         }
107     }
108
109     function asXML () {
110         $xml = '';
111         foreach ($this->_content as $item) {
112             if (is_object($item)) {
113                 if (method_exists($item, 'asXML'))
114                     $xml .= $item->asXML();
115                 elseif (method_exists($item, 'asString'))
116                     $xml .= $this->_quote($item->asString());
117                 else
118                     $xml .= sprintf("==Object(%s)==", get_class($item));
119             }
120             elseif (is_array($item)) {
121             trigger_error("Passing arrays to ->asXML() is deprecated: (" . AsXML($item, true) . ")",
122                       E_USER_NOTICE);
123             foreach ($item as $x)
124                     $xml .= $this->asXML($x);
125             }
126             else
127                 $xml .= $this->_quote((string) $item);
128         }
129         return $xml;
130     }
131
132     function asPDF () {
133         $pdf = '';
134         foreach ($this->_content as $item) {
135             if (is_object($item)) {
136                 if (method_exists($item, 'asPDF'))
137                     $pdf .= $item->asPDF();
138                 elseif (method_exists($item, 'asString'))
139                     $pdf .= $this->_quote($item->asString());
140                 else
141                     $pdf .= sprintf("==Object(%s)==", get_class($item));
142             }
143             else
144                 $pdf .= $this->_quote((string) $item);
145         }
146         return $pdf;
147     }
148
149     /* php-5.2 magic */
150     function __toString () {
151         return $this->asString();
152     }
153
154     function asString () {
155         $val = '';
156         foreach ($this->_content as $item) {
157             if (is_object($item)) {
158                 if (method_exists($item, 'asString')) {
159                     $string = $item->asString();
160                 if (is_object($string)) {
161                     ; // ignore error so far: ImageLink labels
162                 } else {
163                         $val .= $this->_quote($item->asString());
164                 }
165                 } else {
166                     $val .= sprintf("==Object(%s)==", get_class($item));
167                 }
168             }
169             else
170                 $val .= (string) $item;
171         }
172         return trim($val);
173     }
174
175     /**
176      * See if element is empty.
177      *
178      * Empty means it has no content.
179      * @return bool True if empty.
180      */
181     function isEmpty () {
182         if (empty($this->_content))
183             return true;
184         foreach ($this->_content as $x) {
185             if (is_string($x) ? strlen($x) : !empty($x))
186                 return false;
187         }
188         return true;
189     }
190
191     function _quote ($string) {
192         if (!$string) return $string;
193     return htmlspecialchars($string, ENT_COMPAT, $GLOBALS['charset']);
194     }
195 };
196
197 /**
198  * An XML element.
199  *
200  * @param $tagname string Tag of html element.
201  */
202 class XmlElement extends XmlContent
203 {
204     function XmlElement ($tagname /* , $attr_or_content , ...*/) {
205         //FIXME: php5 incompatible
206         $this->XmlContent();
207         $this->_init(func_get_args());
208     }
209
210     function _init ($args) {
211         if (!is_array($args))
212             $args = func_get_args();
213
214         assert(count($args) >= 1);
215         //assert(is_string($args[0]));
216         $this->_tag = array_shift($args);
217
218         if ($args && is_array($args[0]))
219             $this->_attr = array_shift($args);
220         else {
221             $this->_attr = array();
222             if ($args && $args[0] === false)
223                 array_shift($args);
224         }
225
226         $this->setContent($args);
227     }
228
229     /** Methods only needed for XmlParser,
230      *  to be fully compatible to perl Html::Element
231      */
232     // doesn't yet work with php5 as __destruct()
233     function _destruct () {
234         if ($this->hasChildren()) {
235             foreach ($this->getChildren() as $node) {
236                 $node->_destruct();
237             }
238         }
239         unset($this->_tag);
240         unset($this->_attr);
241         unset($this->_content);
242     }
243
244     function getChildren () {
245         return $this->_children;
246     }
247
248     function hasChildren () {
249         return !empty($this->_children);
250     }
251     /* End XmlParser Methods
252      */
253
254     function getTag () {
255         return $this->_tag;
256     }
257
258     function setAttr ($attr, $value = false) {
259     if (is_array($attr)) {
260             assert($value === false);
261             foreach ($attr as $a => $v) {
262                 $this->_attr[strtolower($a)] = $v;
263         //$this->set($a, $v);
264             }
265             return;
266     }
267
268         assert(is_string($attr));
269
270         if ($value === false) {
271             unset($this->_attr[$attr]);
272         }
273         else {
274             if (is_bool($value))
275                 $value = $attr;
276             $this->_attr[$attr] = (string) $value;
277         }
278
279     if ($attr == 'class')
280         unset($this->_classes);
281     }
282
283     function getAttr ($attr) {
284     if ($attr == 'class')
285         $this->_setClasses();
286
287     if (isset($this->_attr[strtolower($attr)]))
288         return $this->_attr[strtolower($attr)];
289     else
290         return false;
291     }
292
293     function _getClasses() {
294     if (!isset($this->_classes)) {
295         $this->_classes = array();
296         if (isset($this->_attr['class'])) {
297         $classes = explode(' ', (string) $this->_attr['class']);
298         foreach ($classes as $class) {
299             $class = trim($class);
300             if ($class)
301             $this->_classes[$class] = $class;
302         }
303         }
304     }
305     return $this->_classes;
306     }
307
308     function _setClasses() {
309     if (isset($this->_classes)) {
310         if ($this->_classes)
311         $this->_attr['class'] = join(' ', $this->_classes);
312         else
313         unset($this->_attr['class']);
314     }
315     }
316
317     /**
318      * Manipulate the elements CSS class membership.
319      *
320      * This adds or remove an elements membership
321      * in a give CSS class.
322      *
323      * @param $class string
324      *
325      * @param $in_class bool
326      *   If true (the default) the element is added to class $class.
327      *   If false, the element is removed from the class.
328      */
329     function setInClass($class, $in_class=true) {
330     $this->_getClasses();
331     $class = trim($class);
332     if ($in_class)
333         $this->_classes[$class] = $class;
334     else
335         unset($this->_classes[$class]);
336     }
337
338     /**
339      * Is element in a given (CSS) class?
340      *
341      * This checks for the presence of a particular class in the
342      * elements 'class' attribute.
343      *
344      * @param $class string  The class to check for.
345      * @return bool True if the element is a member of $class.
346      */
347     function inClass($class) {
348     $this->_parseClasses();
349     return isset($this->_classes[trim($class)]);
350     }
351
352     function startTag() {
353         $start = "<" . $this->_tag;
354     $this->_setClasses();
355         foreach ($this->_attr as $attr => $val) {
356             if (is_bool($val)) {
357                 if (!$val)
358                     continue;
359                 $val = $attr;
360             }
361             $qval = str_replace("\"", '&quot;', $this->_quote((string)$val));
362             $start .= " $attr=\"$qval\"";
363         }
364         $start .= ">";
365         return $start;
366     }
367
368     function emptyTag() {
369         return substr($this->startTag(), 0, -1) . "/>";
370     }
371
372
373     function endTag() {
374         return "</$this->_tag>";
375     }
376
377
378     function printXML () {
379         if ($this->isEmpty())
380             echo $this->emptyTag();
381         else {
382             echo $this->startTag();
383             // FIXME: The next two lines could be removed for efficiency
384             if (!$this->hasInlineContent())
385                 echo "\n";
386             XmlContent::printXML();
387             echo "</$this->_tag>";
388         }
389         if (!$this->isInlineElement())
390             echo "\n";
391     }
392
393     function asXML () {
394         if ($this->isEmpty()) {
395             $xml = $this->emptyTag();
396         }
397         else {
398             $xml = $this->startTag();
399             // FIXME: The next two lines could be removed for efficiency
400             if (!$this->hasInlineContent())
401                 $xml .= "\n";
402             $xml .= XmlContent::asXML();
403             $xml .= "</$this->_tag>";
404         }
405         if (!$this->isInlineElement())
406             $xml .= "\n";
407         return $xml;
408     }
409
410     /**
411      * Can this element have inline content?
412      *
413      * This is a hack, but is probably the best one can do without
414      * knowledge of the DTD...
415      */
416     function hasInlineContent () {
417         // This is a hack.
418         if (empty($this->_content))
419             return true;
420         if (is_object($this->_content[0]))
421             return false;
422         return true;
423     }
424
425     /**
426      * Is this element part of inline content?
427      *
428      * This is a hack, but is probably the best one can do without
429      * knowledge of the DTD...
430      */
431     function isInlineElement () {
432         return false;
433     }
434
435 };
436
437 class RawXml {
438     function RawXml ($xml_text) {
439         $this->_xml = $xml_text;
440     }
441
442     function printXML () {
443         echo $this->_xml;
444     }
445
446     /* php-5.2 magic */
447     function __toString () {
448         return $this->_xml;
449     }
450
451     function asXML () {
452         return $this->_xml;
453     }
454
455     function asString () {
456         return $this->_xml;
457     }
458
459     function isEmpty () {
460         return empty($this->_xml);
461     }
462 }
463
464 class FormattedText {
465     function FormattedText ($fs /* , ... */) {
466         if ($fs !== false) {
467             $this->_init(func_get_args());
468         }
469     }
470
471     function _init ($args) {
472         $this->_fs = array_shift($args);
473
474         // PHP's sprintf doesn't support variable width specifiers,
475         // like sprintf("%*s", 10, "x"); --- so we won't either.
476         $m = array();
477         if (! preg_match_all('/(?<!%)%(\d+)\$/x', $this->_fs, $m)) {
478             $this->_args  = $args;
479         }
480         else {
481             // Format string has '%2$s' style argument reordering.
482             // PHP doesn't support this.
483             if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $this->_fs)) // $fmt
484                 // literal variable name substitution only to keep locale
485                 // strings uncluttered
486                 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
487                                       '%1\$s','%s'), E_USER_WARNING);
488
489             $this->_fs = preg_replace('/(?<!%)%\d+\$/x', '%', $this->_fs);
490
491             $this->_args = array();
492             foreach($m[1] as $argnum) {
493                 if ($argnum < 1 || $argnum > count($args))
494                     trigger_error(sprintf("%s: argument index out of range",
495                                           $argnum), E_USER_WARNING);
496                 $this->_args[] = $args[$argnum - 1];
497             }
498         }
499     }
500
501     function asXML () {
502         // Not all PHP's have vsprintf, so...
503         $args[] = XmlElement::_quote((string)$this->_fs);
504         foreach ($this->_args as $arg)
505             $args[] = AsXML($arg);
506         return call_user_func_array('sprintf', $args);
507     }
508
509     function printXML () {
510         // Not all PHP's have vsprintf, so...
511         $args[] = XmlElement::_quote((string)$this->_fs);
512         foreach ($this->_args as $arg)
513             $args[] = AsXML($arg);
514         call_user_func_array('printf', $args);
515     }
516
517     function asString() {
518         $args[] = $this->_fs;
519         foreach ($this->_args as $arg)
520             $args[] = AsString($arg);
521         return call_user_func_array('sprintf', $args);
522     }
523
524     /* php-5.2 magic */
525     function __toString () {
526         return $this->asString();
527     }
528 }
529
530 /**
531  * PHP5 compatibility
532  * Error[2048]: Non-static method XmlContent::_quote() should not be called statically
533  * Note: There's lot of room for performance increase if the right charset variant can
534  * be created on load-time.
535  */
536 function XmlContent_quote ($string) {
537     if (!$string) return $string;
538     if (isset($GLOBALS['charset'])
539         and (!defined('IGNORE_CHARSET_NOT_SUPPORTED_WARNING') or !IGNORE_CHARSET_NOT_SUPPORTED_WARNING))
540     {
541         return htmlspecialchars($string, ENT_COMPAT, $GLOBALS['charset']);
542     } else {
543         return htmlspecialchars($string);
544     }
545 }
546
547 function PrintXML ($val /* , ... */ ) {
548     if (func_num_args() > 1) {
549         foreach (func_get_args() as $arg)
550             PrintXML($arg);
551     }
552     elseif (is_object($val)) {
553         if (method_exists($val, 'printXML'))
554             $val->printXML();
555         elseif (method_exists($val, 'asXML')) {
556             echo $val->asXML();
557         }
558         elseif (method_exists($val, 'asString'))
559             echo XmlContent_quote($val->asString());
560         else
561             printf("==Object(%s)==", get_class($val));
562     }
563     elseif (is_array($val)) {
564         // DEPRECATED:
565         // Use XmlContent objects instead of arrays for collections of XmlElements.
566         trigger_error("Passing arrays to PrintXML() is deprecated: (" . AsXML($val, true) . ")",
567                       E_USER_NOTICE);
568         foreach ($val as $x)
569             PrintXML($x);
570     }
571     else
572         echo (string)XmlContent_quote((string)$val);
573 }
574
575 function AsXML ($val /* , ... */) {
576     static $nowarn;
577
578     if (func_num_args() > 1) {
579         $xml = '';
580         foreach (func_get_args() as $arg)
581             $xml .= AsXML($arg);
582         return $xml;
583     }
584     elseif (is_object($val)) {
585         if (method_exists($val, 'asXML'))
586             return $val->asXML();
587         elseif (method_exists($val, 'asString'))
588             return XmlContent_quote($val->asString());
589         else
590             return sprintf("==Object(%s)==", get_class($val));
591     }
592     elseif (is_array($val)) {
593         // DEPRECATED:
594         // Use XmlContent objects instead of arrays for collections of XmlElements.
595         if (empty($nowarn)) {
596             $nowarn = true;
597             trigger_error("Passing arrays to AsXML() is deprecated: (" . AsXML($val) . ")",
598                           E_USER_NOTICE);
599             unset($nowarn);
600         }
601         $xml = '';
602         foreach ($val as $x)
603             $xml .= AsXML($x);
604         return $xml;
605     }
606     else
607         return XmlContent_quote((string)$val);
608 }
609
610 function AsString ($val) {
611     if (func_num_args() > 1) {
612         $str = '';
613         foreach (func_get_args() as $arg)
614             $str .= AsString($arg);
615         return $str;
616     }
617     elseif (is_object($val)) {
618         if (method_exists($val, 'asString'))
619             return $val->asString();
620         else
621             return sprintf("==Object(%s)==", get_class($val));
622     }
623     elseif (is_array($val)) {
624         // DEPRECATED:
625         // Use XmlContent objects instead of arrays for collections of XmlElements.
626         trigger_error("Passing arrays to AsString() is deprecated", E_USER_NOTICE);
627         $str = '';
628         foreach ($val as $x)
629             $str .= AsString($x);
630         return $str;
631     }
632
633     return (string) $val;
634 }
635
636 function fmt ($fs /* , ... */) {
637     $s = new FormattedText(false);
638
639     $args = func_get_args();
640     $args[0] = _($args[0]);
641     $s->_init($args);
642     return $s;
643 }
644
645 // Local Variables:
646 // mode: php
647 // tab-width: 8
648 // c-basic-offset: 4
649 // c-hanging-comment-ender-p: nil
650 // indent-tabs-mode: nil
651 // End: