]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/XmlElement.php
Harmonize file footer
[SourceForge/phpwiki.git] / lib / XmlElement.php
1 <?php // rcs_id('$Id$');
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     /**
177      * See if element is empty.
178      *
179      * Empty means it has no content.
180      * @return bool True if empty.
181      */
182     function isEmpty () {
183         if (empty($this->_content))
184             return true;
185         foreach ($this->_content as $x) {
186             if (is_string($x) ? strlen($x) : !empty($x))
187                 return false;
188         }
189         return true;
190     }
191   
192     function _quote ($string) {
193         if (!$string) return $string;
194         return htmlspecialchars($string, ENT_COMPAT, $GLOBALS['charset']);
195     }
196 };
197
198 /**
199  * An XML element.
200  *
201  * @param $tagname string Tag of html element.
202  */
203 class XmlElement extends XmlContent
204 {
205     function XmlElement ($tagname /* , $attr_or_content , ...*/) {
206         //FIXME: php5 incompatible
207         $this->XmlContent();
208         $this->_init(func_get_args());
209     }
210
211     function _init ($args) {
212         if (!is_array($args))
213             $args = func_get_args();
214
215         assert(count($args) >= 1);
216         //assert(is_string($args[0]));
217         $this->_tag = array_shift($args);
218       
219         if ($args && is_array($args[0]))
220             $this->_attr = array_shift($args);
221         else {
222             $this->_attr = array();
223             if ($args && $args[0] === false)
224                 array_shift($args);
225         }
226
227         $this->setContent($args);
228     }
229   
230     /** Methods only needed for XmlParser,
231      *  to be fully compatible to perl Html::Element
232      */
233     // doesn't yet work with php5 as __destruct()
234     function _destruct () {
235         if ($this->hasChildren()) {
236             foreach ($this->getChildren() as $node) {
237                 $node->_destruct();
238             }
239         }
240         unset($this->_tag);
241         unset($this->_attr);
242         unset($this->_content);
243     }
244   
245     function getChildren () {
246         return $this->_children;
247     }
248
249     function hasChildren () {
250         return !empty($this->_children);
251     }
252     /* End XmlParser Methods
253      */
254
255     function getTag () {
256         return $this->_tag;
257     }
258   
259     function setAttr ($attr, $value = false) {
260         if (is_array($attr)) {
261             assert($value === false);
262             foreach ($attr as $a => $v) {
263                 $this->_attr[strtolower($a)] = $v;
264                 //$this->set($a, $v);
265             }
266             return;
267         }
268
269         assert(is_string($attr));
270           
271         if ($value === false) {
272             unset($this->_attr[$attr]);
273         }
274         else {
275             if (is_bool($value))
276                 $value = $attr;
277             $this->_attr[$attr] = (string) $value;
278         }
279
280         if ($attr == 'class')
281             unset($this->_classes);
282     }
283
284     function getAttr ($attr) {
285         if ($attr == 'class')
286             $this->_setClasses();
287
288         if (isset($this->_attr[strtolower($attr)]))
289             return $this->_attr[strtolower($attr)];
290         else
291             return false;
292     }
293
294     function _getClasses() {
295         if (!isset($this->_classes)) {
296             $this->_classes = array();
297             if (isset($this->_attr['class'])) {
298                 $classes = explode(' ', (string) $this->_attr['class']);
299                 foreach ($classes as $class) {
300                     $class = trim($class);
301                     if ($class)
302                         $this->_classes[$class] = $class;
303                 }
304             }
305         }
306         return $this->_classes;
307     }
308
309     function _setClasses() {
310         if (isset($this->_classes)) {
311             if ($this->_classes)
312                 $this->_attr['class'] = join(' ', $this->_classes);
313             else
314                 unset($this->_attr['class']);
315         }
316     }
317
318     /**
319      * Manipulate the elements CSS class membership.
320      *
321      * This adds or remove an elements membership
322      * in a give CSS class.
323      *
324      * @param $class string
325      *
326      * @param $in_class bool
327      *   If true (the default) the element is added to class $class.
328      *   If false, the element is removed from the class.
329      */
330     function setInClass($class, $in_class=true) {
331         $this->_getClasses();
332         $class = trim($class);
333         if ($in_class)
334             $this->_classes[$class] = $class;
335         else
336             unset($this->_classes[$class]);
337     }
338
339     /**
340      * Is element in a given (CSS) class?
341      *
342      * This checks for the presence of a particular class in the
343      * elements 'class' attribute.
344      *
345      * @param $class string  The class to check for.
346      * @return bool True if the element is a member of $class.
347      */
348     function inClass($class) {
349         $this->_parseClasses();
350         return isset($this->_classes[trim($class)]);
351     }
352
353     function startTag() {
354         $start = "<" . $this->_tag;
355         $this->_setClasses();
356         foreach ($this->_attr as $attr => $val) {
357             if (is_bool($val)) {
358                 if (!$val)
359                     continue;
360                 $val = $attr;
361             }
362             $qval = str_replace("\"", '&quot;', $this->_quote((string)$val));
363             $start .= " $attr=\"$qval\"";
364         }
365         $start .= ">";
366         return $start;
367     }
368
369     function emptyTag() {
370         return substr($this->startTag(), 0, -1) . "/>";
371     }
372
373   
374     function endTag() {
375         return "</$this->_tag>";
376     }
377   
378       
379     function printXML () {
380         if ($this->isEmpty())
381             echo $this->emptyTag();
382         else {
383             echo $this->startTag();
384             // FIXME: The next two lines could be removed for efficiency
385             if (!$this->hasInlineContent())
386                 echo "\n";
387             XmlContent::printXML();
388             echo "</$this->_tag>";
389         }
390         if (!$this->isInlineElement())
391             echo "\n";
392     }
393
394     function asXML () {
395         if ($this->isEmpty()) {
396             $xml = $this->emptyTag();
397         }
398         else {
399             $xml = $this->startTag();
400             // FIXME: The next two lines could be removed for efficiency
401             if (!$this->hasInlineContent())
402                 $xml .= "\n";
403             $xml .= XmlContent::asXML();
404             $xml .= "</$this->_tag>";
405         }
406         if (!$this->isInlineElement())
407             $xml .= "\n";
408         return $xml;
409     }
410
411     /**
412      * Can this element have inline content?
413      *
414      * This is a hack, but is probably the best one can do without
415      * knowledge of the DTD...
416      */
417     function hasInlineContent () {
418         // This is a hack.
419         if (empty($this->_content))
420             return true;
421         if (is_object($this->_content[0]))
422             return false;
423         return true;
424     }
425   
426     /**
427      * Is this element part of inline content?
428      *
429      * This is a hack, but is probably the best one can do without
430      * knowledge of the DTD...
431      */
432     function isInlineElement () {
433         return false;
434     }
435   
436 };
437
438 class RawXml {
439     function RawXml ($xml_text) {
440         $this->_xml = $xml_text;
441     }
442
443     function printXML () {
444         echo $this->_xml;
445     }
446
447     /* php-5.2 magic */
448     function __toString () {
449         return $this->_xml;
450     }
451
452     function asXML () {
453         return $this->_xml;
454     }
455   
456     function asString () {
457         return $this->_xml;
458     }
459
460     function isEmpty () {
461         return empty($this->_xml);
462     }
463 }
464
465 class FormattedText {
466     function FormattedText ($fs /* , ... */) {
467         if ($fs !== false) {
468             $this->_init(func_get_args());
469         }
470     }
471
472     function _init ($args) {
473         $this->_fs = array_shift($args);
474
475         // PHP's sprintf doesn't support variable width specifiers,
476         // like sprintf("%*s", 10, "x"); --- so we won't either.
477         $m = array();
478         if (! preg_match_all('/(?<!%)%(\d+)\$/x', $this->_fs, $m)) {
479             $this->_args  = $args;
480         }
481         else {
482             // Format string has '%2$s' style argument reordering.
483             // PHP doesn't support this.
484             if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $this->_fs)) // $fmt
485                 // literal variable name substitution only to keep locale
486                 // strings uncluttered
487                 trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
488                                       '%1\$s','%s'), E_USER_WARNING);
489       
490             $this->_fs = preg_replace('/(?<!%)%\d+\$/x', '%', $this->_fs);
491
492             $this->_args = array();
493             foreach($m[1] as $argnum) {
494                 if ($argnum < 1 || $argnum > count($args))
495                     trigger_error(sprintf("%s: argument index out of range",
496                                           $argnum), E_USER_WARNING);
497                 $this->_args[] = $args[$argnum - 1];
498             }
499         }
500     }
501
502     function asXML () {
503         // Not all PHP's have vsprintf, so...
504         $args[] = XmlElement::_quote((string)$this->_fs);
505         foreach ($this->_args as $arg)
506             $args[] = AsXML($arg);
507         return call_user_func_array('sprintf', $args);
508     }
509
510     function printXML () {
511         // Not all PHP's have vsprintf, so...
512         $args[] = XmlElement::_quote((string)$this->_fs);
513         foreach ($this->_args as $arg)
514             $args[] = AsXML($arg);
515         call_user_func_array('printf', $args);
516     }
517
518     function asString() {
519         $args[] = $this->_fs;
520         foreach ($this->_args as $arg)
521             $args[] = AsString($arg);
522         return call_user_func_array('sprintf', $args);
523     }
524
525     /* php-5.2 magic */
526     function __toString () {
527         return $this->asString();
528     }
529 }
530
531 /**
532  * PHP5 compatibility
533  * Error[2048]: Non-static method XmlContent::_quote() should not be called statically
534  * Note: There's lot of room for performance increase if the right charset variant can
535  * be created on load-time.
536  */
537 function XmlContent_quote ($string) {
538     if (!$string) return $string;
539     if (isset($GLOBALS['charset'])
540         and (!defined('IGNORE_CHARSET_NOT_SUPPORTED_WARNING') or !IGNORE_CHARSET_NOT_SUPPORTED_WARNING))
541     {
542         return htmlspecialchars($string, ENT_COMPAT, $GLOBALS['charset']);
543     } else {
544         return htmlspecialchars($string);
545     }
546 }
547
548 function PrintXML ($val /* , ... */ ) {
549     if (func_num_args() > 1) {
550         foreach (func_get_args() as $arg)
551             PrintXML($arg);
552     }
553     elseif (is_object($val)) {
554         if (method_exists($val, 'printXML'))
555             $val->printXML();
556         elseif (method_exists($val, 'asXML')) {
557             echo $val->asXML();
558         }
559         elseif (method_exists($val, 'asString'))
560             echo XmlContent_quote($val->asString());
561         else
562             printf("==Object(%s)==", get_class($val));
563     }
564     elseif (is_array($val)) {
565         // DEPRECATED:
566         // Use XmlContent objects instead of arrays for collections of XmlElements.
567         trigger_error("Passing arrays to PrintXML() is deprecated: (" . AsXML($val, true) . ")",
568                       E_USER_NOTICE);
569         foreach ($val as $x)
570             PrintXML($x);
571     }
572     else
573         echo (string)XmlContent_quote((string)$val);
574 }
575
576 function AsXML ($val /* , ... */) {
577     static $nowarn;
578
579     if (func_num_args() > 1) {
580         $xml = '';
581         foreach (func_get_args() as $arg)
582             $xml .= AsXML($arg);
583         return $xml;
584     }
585     elseif (is_object($val)) {
586         if (method_exists($val, 'asXML'))
587             return $val->asXML();
588         elseif (method_exists($val, 'asString'))
589             return XmlContent_quote($val->asString());
590         else
591             return sprintf("==Object(%s)==", get_class($val));
592     }
593     elseif (is_array($val)) {
594         // DEPRECATED:
595         // Use XmlContent objects instead of arrays for collections of XmlElements.
596         if (empty($nowarn)) {
597             $nowarn = true;
598             trigger_error("Passing arrays to AsXML() is deprecated: (" . AsXML($val) . ")",
599                           E_USER_NOTICE);
600             unset($nowarn);
601         }
602         $xml = '';
603         foreach ($val as $x)
604             $xml .= AsXML($x);
605         return $xml;
606     }
607     else
608         return XmlContent_quote((string)$val);
609 }
610
611 function AsString ($val) {
612     if (func_num_args() > 1) {
613         $str = '';
614         foreach (func_get_args() as $arg)
615             $str .= AsString($arg);
616         return $str;
617     }
618     elseif (is_object($val)) {
619         if (method_exists($val, 'asString'))
620             return $val->asString();
621         else
622             return sprintf("==Object(%s)==", get_class($val));
623     }
624     elseif (is_array($val)) {
625         // DEPRECATED:
626         // Use XmlContent objects instead of arrays for collections of XmlElements.
627         trigger_error("Passing arrays to AsString() is deprecated", E_USER_NOTICE);
628         $str = '';
629         foreach ($val as $x)
630             $str .= AsString($x);
631         return $str;
632     }
633   
634     return (string) $val;
635 }
636
637 function fmt ($fs /* , ... */) {
638     $s = new FormattedText(false);
639
640     $args = func_get_args();
641     $args[0] = _($args[0]);
642     $s->_init($args);
643     return $s;
644 }
645
646 // Local Variables:
647 // mode: php
648 // tab-width: 8
649 // c-basic-offset: 4
650 // c-hanging-comment-ender-p: nil
651 // indent-tabs-mode: nil
652 // End: 
653 ?>