PageRenderTime 5ms CodeModel.GetById 20ms app.highlight 23ms RepoModel.GetById 4ms app.codeStats 0ms

/common/libraries/plugin/pear/XML/Util.php

https://bitbucket.org/cbenelug/chamilo
PHP | 929 lines | 342 code | 54 blank | 533 comment | 63 complexity | 7d542849c83b53c50b670ffdcd8a7297 MD5 | raw file
  1<?php
  2
  3/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  4
  5/**
  6 * XML_Util
  7 *
  8 * XML Utilities package
  9 * 
 10 * PHP versions 4 and 5
 11 *
 12 * LICENSE:
 13 *
 14 * Copyright (c) 2003-2008 Stephan Schmidt <schst@php.net>
 15 * All rights reserved.
 16 *
 17 * Redistribution and use in source and binary forms, with or without
 18 * modification, are permitted provided that the following conditions
 19 * are met:
 20 *
 21 * * Redistributions of source code must retain the above copyright
 22 * notice, this list of conditions and the following disclaimer.
 23 * * Redistributions in binary form must reproduce the above copyright
 24 * notice, this list of conditions and the following disclaimer in the
 25 * documentation and/or other materials provided with the distribution.
 26 * * The name of the author may not be used to endorse or promote products
 27 * derived from this software without specific prior written permission.
 28 *
 29 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 30 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 31 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 32 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 33 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 34 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 35 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 36 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 37 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 38 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 39 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 40 *
 41 * @category  XML
 42 * @package   XML_Util
 43 * @author    Stephan Schmidt <schst@php.net>
 44 * @copyright 2003-2008 Stephan Schmidt <schst@php.net>
 45 * @license   http://opensource.org/licenses/bsd-license New BSD License
 46 * @version   CVS: $Id: Util.php 137 2009-11-09 13:24:37Z vanpouckesven $
 47 * @link      http://pear.php.net/package/XML_Util
 48 */
 49
 50/**
 51 * error code for invalid chars in XML name
 52 */
 53define('XML_UTIL_ERROR_INVALID_CHARS', 51);
 54
 55/**
 56 * error code for invalid chars in XML name
 57 */
 58define('XML_UTIL_ERROR_INVALID_START', 52);
 59
 60/**
 61 * error code for non-scalar tag content
 62 */
 63define('XML_UTIL_ERROR_NON_SCALAR_CONTENT', 60);
 64
 65/**
 66 * error code for missing tag name
 67 */
 68define('XML_UTIL_ERROR_NO_TAG_NAME', 61);
 69
 70/**
 71 * replace XML entities
 72 */
 73define('XML_UTIL_REPLACE_ENTITIES', 1);
 74
 75/**
 76 * embedd content in a CData Section
 77 */
 78define('XML_UTIL_CDATA_SECTION', 5);
 79
 80/**
 81 * do not replace entitites
 82 */
 83define('XML_UTIL_ENTITIES_NONE', 0);
 84
 85/**
 86 * replace all XML entitites
 87 * This setting will replace <, >, ", ' and &
 88 */
 89define('XML_UTIL_ENTITIES_XML', 1);
 90
 91/**
 92 * replace only required XML entitites
 93 * This setting will replace <, " and &
 94 */
 95define('XML_UTIL_ENTITIES_XML_REQUIRED', 2);
 96
 97/**
 98 * replace HTML entitites
 99 * @link http://www.php.net/htmlentities
100 */
101define('XML_UTIL_ENTITIES_HTML', 3);
102
103/**
104 * Collapse all empty tags.
105 */
106define('XML_UTIL_COLLAPSE_ALL', 1);
107
108/**
109 * Collapse only empty XHTML tags that have no end tag.
110 */
111define('XML_UTIL_COLLAPSE_XHTML_ONLY', 2);
112
113/**
114 * utility class for working with XML documents
115 *
116
117 * @category  XML
118 * @package   XML_Util
119 * @author    Stephan Schmidt <schst@php.net>
120 * @copyright 2003-2008 Stephan Schmidt <schst@php.net>
121 * @license   http://opensource.org/licenses/bsd-license New BSD License
122 * @version   Release: 1.2.1
123 * @link      http://pear.php.net/package/XML_Util
124 */
125class XML_Util
126{
127
128    /**
129     * return API version
130     *
131     * @return string $version API version
132     * @access public
133     * @static
134     */
135    function apiVersion()
136    {
137        return '1.1';
138    }
139
140    /**
141     * replace XML entities
142     *
143     * With the optional second parameter, you may select, which
144     * entities should be replaced.
145     *
146     * <code>
147     * require_once 'XML/Util.php';
148     *
149     * // replace XML entites:
150     * $string = XML_Util::replaceEntities('This string contains < & >.');
151     * </code>
152     *
153     * With the optional third parameter, you may pass the character encoding
154     * <code>
155     * require_once 'XML/Util.php';
156     *
157     * // replace XML entites in UTF-8:
158     * $string = XML_Util::replaceEntities(
159     * 'This string contains < & > as well as ä, ö, ß, à and ê',
160     * XML_UTIL_ENTITIES_HTML,
161     * 'UTF-8'
162     * );
163     * </code>
164     *
165     * @param string $string          string where XML special chars 
166     * should be replaced
167     * @param int    $replaceEntities setting for entities in attribute values 
168     * (one of XML_UTIL_ENTITIES_XML, 
169     * XML_UTIL_ENTITIES_XML_REQUIRED, 
170     * XML_UTIL_ENTITIES_HTML)
171     * @param string $encoding        encoding value (if any)...
172     * must be a valid encoding as determined
173     * by the htmlentities() function
174     *
175     * @return string string with replaced chars
176     * @access public
177     * @static
178     * @see reverseEntities()
179     */
180    function replaceEntities($string, $replaceEntities = XML_UTIL_ENTITIES_XML, $encoding = 'ISO-8859-1')
181    {
182        switch ($replaceEntities)
183        {
184            case XML_UTIL_ENTITIES_XML :
185                return strtr($string, array('&' => '&amp;', '>' => '&gt;', '<' => '&lt;', '"' => '&quot;', 
186                        '\'' => '&apos;'));
187                break;
188            case XML_UTIL_ENTITIES_XML_REQUIRED :
189                return strtr($string, array('&' => '&amp;', '<' => '&lt;', '"' => '&quot;'));
190                break;
191            case XML_UTIL_ENTITIES_HTML :
192                return htmlentities($string, ENT_COMPAT, $encoding);
193                break;
194        }
195        return $string;
196    }
197
198    /**
199     * reverse XML entities
200     *
201     * With the optional second parameter, you may select, which
202     * entities should be reversed.
203     *
204     * <code>
205     * require_once 'XML/Util.php';
206     *
207     * // reverse XML entites:
208     * $string = XML_Util::reverseEntities('This string contains &lt; &amp; &gt;.');
209     * </code>
210     *
211     * With the optional third parameter, you may pass the character encoding
212     * <code>
213     * require_once 'XML/Util.php';
214     *
215     * // reverse XML entites in UTF-8:
216     * $string = XML_Util::reverseEntities(
217     * 'This string contains &lt; &amp; &gt; as well as'
218     * . ' &auml;, &ouml;, &szlig;, &agrave; and &ecirc;',
219     * XML_UTIL_ENTITIES_HTML,
220     * 'UTF-8'
221     * );
222     * </code>
223     *
224     * @param string $string          string where XML special chars 
225     * should be replaced
226     * @param int    $replaceEntities setting for entities in attribute values 
227     * (one of XML_UTIL_ENTITIES_XML, 
228     * XML_UTIL_ENTITIES_XML_REQUIRED, 
229     * XML_UTIL_ENTITIES_HTML)
230     * @param string $encoding        encoding value (if any)...
231     * must be a valid encoding as determined
232     * by the html_entity_decode() function
233     *
234     * @return string string with replaced chars
235     * @access public
236     * @static
237     * @see replaceEntities()
238     */
239    function reverseEntities($string, $replaceEntities = XML_UTIL_ENTITIES_XML, $encoding = 'ISO-8859-1')
240    {
241        switch ($replaceEntities)
242        {
243            case XML_UTIL_ENTITIES_XML :
244                return strtr($string, array('&amp;' => '&', '&gt;' => '>', '&lt;' => '<', '&quot;' => '"', 
245                        '&apos;' => '\''));
246                break;
247            case XML_UTIL_ENTITIES_XML_REQUIRED :
248                return strtr($string, array('&amp;' => '&', '&lt;' => '<', '&quot;' => '"'));
249                break;
250            case XML_UTIL_ENTITIES_HTML :
251                return html_entity_decode($string, ENT_COMPAT, $encoding);
252                break;
253        }
254        return $string;
255    }
256
257    /**
258     * build an xml declaration
259     *
260     * <code>
261     * require_once 'XML/Util.php';
262     *
263     * // get an XML declaration:
264     * $xmlDecl = XML_Util::getXMLDeclaration('1.0', 'UTF-8', true);
265     * </code>
266     *
267     * @param string $version    xml version
268     * @param string $encoding   character encoding
269     * @param bool   $standalone document is standalone (or not)
270     *
271     * @return string xml declaration
272     * @access public
273     * @static
274     * @uses attributesToString() to serialize the attributes of the XML declaration
275     */
276    function getXMLDeclaration($version = '1.0', $encoding = null, $standalone = null)
277    {
278        $attributes = array('version' => $version);
279        // add encoding
280        if ($encoding !== null)
281        {
282            $attributes['encoding'] = $encoding;
283        }
284        // add standalone, if specified
285        if ($standalone !== null)
286        {
287            $attributes['standalone'] = $standalone ? 'yes' : 'no';
288        }
289        
290        return sprintf('<?xml%s?>', XML_Util :: attributesToString($attributes, false));
291    }
292
293    /**
294     * build a document type declaration
295     *
296     * <code>
297     * require_once 'XML/Util.php';
298     *
299     * // get a doctype declaration:
300     * $xmlDecl = XML_Util::getDocTypeDeclaration('rootTag','myDocType.dtd');
301     * </code>
302     *
303     * @param string $root        name of the root tag
304     * @param string $uri         uri of the doctype definition 
305     * (or array with uri and public id)
306     * @param string $internalDtd internal dtd entries
307     *
308     * @return string doctype declaration
309     * @access public
310     * @static
311     * @since 0.2
312     */
313    function getDocTypeDeclaration($root, $uri = null, $internalDtd = null)
314    {
315        if (is_array($uri))
316        {
317            $ref = sprintf(' PUBLIC "%s" "%s"', $uri['id'], $uri['uri']);
318        }
319        elseif (! empty($uri))
320        {
321            $ref = sprintf(' SYSTEM "%s"', $uri);
322        }
323        else
324        {
325            $ref = '';
326        }
327        
328        if (empty($internalDtd))
329        {
330            return sprintf('<!DOCTYPE %s%s>', $root, $ref);
331        }
332        else
333        {
334            return sprintf("<!DOCTYPE %s%s [\n%s\n]>", $root, $ref, $internalDtd);
335        }
336    }
337
338    /**
339     * create string representation of an attribute list
340     *
341     * <code>
342     * require_once 'XML/Util.php';
343     *
344     * // build an attribute string
345     * $att = array(
346     * 'foo'   =>  'bar',
347     * 'argh'  =>  'tomato'
348     * );
349     *
350     * $attList = XML_Util::attributesToString($att);
351     * </code>
352     *
353     * @param array      $attributes attribute array
354     * @param bool|array $sort       sort attribute list alphabetically, 
355     * may also be an assoc array containing 
356     * the keys 'sort', 'multiline', 'indent', 
357     * 'linebreak' and 'entities'
358     * @param bool       $multiline  use linebreaks, if more than 
359     * one attribute is given
360     * @param string     $indent     string used for indentation of 
361     * multiline attributes
362     * @param string     $linebreak  string used for linebreaks of 
363     * multiline attributes
364     * @param int        $entities   setting for entities in attribute values 
365     * (one of XML_UTIL_ENTITIES_NONE, 
366     * XML_UTIL_ENTITIES_XML, 
367     * XML_UTIL_ENTITIES_XML_REQUIRED, 
368     * XML_UTIL_ENTITIES_HTML)
369     *
370     * @return string string representation of the attributes
371     * @access public
372     * @static
373     * @uses replaceEntities() to replace XML entities in attribute values
374     * @todo allow sort also to be an options array
375     */
376    function attributesToString($attributes, $sort = true, $multiline = false, $indent = '    ', $linebreak = "\n", $entities = XML_UTIL_ENTITIES_XML)
377    {
378        /*
379         * second parameter may be an array
380         */
381        if (is_array($sort))
382        {
383            if (isset($sort['multiline']))
384            {
385                $multiline = $sort['multiline'];
386            }
387            if (isset($sort['indent']))
388            {
389                $indent = $sort['indent'];
390            }
391            if (isset($sort['linebreak']))
392            {
393                $multiline = $sort['linebreak'];
394            }
395            if (isset($sort['entities']))
396            {
397                $entities = $sort['entities'];
398            }
399            if (isset($sort['sort']))
400            {
401                $sort = $sort['sort'];
402            }
403            else
404            {
405                $sort = true;
406            }
407        }
408        $string = '';
409        if (is_array($attributes) && ! empty($attributes))
410        {
411            if ($sort)
412            {
413                ksort($attributes);
414            }
415            if (! $multiline || count($attributes) == 1)
416            {
417                foreach ($attributes as $key => $value)
418                {
419                    if ($entities != XML_UTIL_ENTITIES_NONE)
420                    {
421                        if ($entities === XML_UTIL_CDATA_SECTION)
422                        {
423                            $entities = XML_UTIL_ENTITIES_XML;
424                        }
425                        $value = XML_Util :: replaceEntities($value, $entities);
426                    }
427                    $string .= ' ' . $key . '="' . $value . '"';
428                }
429            }
430            else
431            {
432                $first = true;
433                foreach ($attributes as $key => $value)
434                {
435                    if ($entities != XML_UTIL_ENTITIES_NONE)
436                    {
437                        $value = XML_Util :: replaceEntities($value, $entities);
438                    }
439                    if ($first)
440                    {
441                        $string .= ' ' . $key . '="' . $value . '"';
442                        $first = false;
443                    }
444                    else
445                    {
446                        $string .= $linebreak . $indent . $key . '="' . $value . '"';
447                    }
448                }
449            }
450        }
451        return $string;
452    }
453
454    /**
455     * Collapses empty tags.
456     *
457     * @param string $xml  XML
458     * @param int    $mode Whether to collapse all empty tags (XML_UTIL_COLLAPSE_ALL)
459     * or only XHTML (XML_UTIL_COLLAPSE_XHTML_ONLY) ones.
460     *
461     * @return string XML
462     * @access public
463     * @static
464     * @todo PEAR CS - unable to avoid "space after open parens" error
465     * in the IF branch
466     */
467    function collapseEmptyTags($xml, $mode = XML_UTIL_COLLAPSE_ALL)
468    {
469        if ($mode == XML_UTIL_COLLAPSE_XHTML_ONLY)
470        {
471            return preg_replace('/<(area|base(?:font)?|br|col|frame|hr|img|input|isindex|link|meta|' . 'param)([^>]*)><\/\\1>/s', '<\\1\\2 />', $xml);
472        }
473        else
474        {
475            return preg_replace('/<(\w+)([^>]*)><\/\\1>/s', '<\\1\\2 />', $xml);
476        }
477    }
478
479    /**
480     * create a tag
481     *
482     * This method will call XML_Util::createTagFromArray(), which
483     * is more flexible.
484     *
485     * <code>
486     * require_once 'XML/Util.php';
487     *
488     * // create an XML tag:
489     * $tag = XML_Util::createTag('myNs:myTag', 
490     * array('foo' => 'bar'), 
491     * 'This is inside the tag', 
492     * 'http://www.w3c.org/myNs#');
493     * </code>
494     *
495     * @param string $qname           qualified tagname (including namespace)
496     * @param array  $attributes      array containg attributes
497     * @param mixed  $content         the content
498     * @param string $namespaceUri    URI of the namespace
499     * @param int    $replaceEntities whether to replace XML special chars in 
500     * content, embedd it in a CData section 
501     * or none of both
502     * @param bool   $multiline       whether to create a multiline tag where 
503     * each attribute gets written to a single line
504     * @param string $indent          string used to indent attributes 
505     * (_auto indents attributes so they start 
506     * at the same column)
507     * @param string $linebreak       string used for linebreaks
508     * @param bool   $sortAttributes  Whether to sort the attributes or not
509     *
510     * @return string XML tag
511     * @access public
512     * @static
513     * @see createTagFromArray()
514     * @uses createTagFromArray() to create the tag
515     */
516    function createTag($qname, $attributes = array(), $content = null, $namespaceUri = null, $replaceEntities = XML_UTIL_REPLACE_ENTITIES, $multiline = false, $indent = '_auto', $linebreak = "\n", $sortAttributes = true)
517    {
518        $tag = array('qname' => $qname, 'attributes' => $attributes);
519        
520        // add tag content
521        if ($content !== null)
522        {
523            $tag['content'] = $content;
524        }
525        
526        // add namespace Uri
527        if ($namespaceUri !== null)
528        {
529            $tag['namespaceUri'] = $namespaceUri;
530        }
531        
532        return XML_Util :: createTagFromArray($tag, $replaceEntities, $multiline, $indent, $linebreak, $sortAttributes);
533    }
534
535    /**
536     * create a tag from an array
537     * this method awaits an array in the following format
538     * <pre>
539     * array(
540     * // qualified name of the tag
541     * 'qname' => $qname        
542     *
543     * // namespace prefix (optional, if qname is specified or no namespace)
544     * 'namespace' => $namespace    
545     *
546     * // local part of the tagname (optional, if qname is specified)
547     * 'localpart' => $localpart,   
548     *
549     * // array containing all attributes (optional)
550     * 'attributes' => array(),      
551     *
552     * // tag content (optional)
553     * 'content' => $content,     
554     *
555     * // namespaceUri for the given namespace (optional)
556     * 'namespaceUri' => $namespaceUri 
557     * )
558     * </pre>
559     *
560     * <code>
561     * require_once 'XML/Util.php';
562     *
563     * $tag = array(
564     * 'qname'        => 'foo:bar',
565     * 'namespaceUri' => 'http://foo.com',
566     * 'attributes'   => array('key' => 'value', 'argh' => 'fruit&vegetable'),
567     * 'content'      => 'I\'m inside the tag',
568     * );
569     * // creating a tag with qualified name and namespaceUri
570     * $string = XML_Util::createTagFromArray($tag);
571     * </code>
572     *
573     * @param array  $tag             tag definition
574     * @param int    $replaceEntities whether to replace XML special chars in 
575     * content, embedd it in a CData section 
576     * or none of both
577     * @param bool   $multiline       whether to create a multiline tag where each 
578     * attribute gets written to a single line
579     * @param string $indent          string used to indent attributes 
580     * (_auto indents attributes so they start 
581     * at the same column)
582     * @param string $linebreak       string used for linebreaks
583     * @param bool   $sortAttributes  Whether to sort the attributes or not
584     *
585     * @return string XML tag
586     * @access public
587     * @static
588     * @see createTag()
589     * @uses attributesToString() to serialize the attributes of the tag
590     * @uses splitQualifiedName() to get local part and namespace of a qualified name
591     * @uses createCDataSection()
592     * @uses raiseError()
593     */
594    function createTagFromArray($tag, $replaceEntities = XML_UTIL_REPLACE_ENTITIES, $multiline = false, $indent = '_auto', $linebreak = "\n", $sortAttributes = true)
595    {
596        if (isset($tag['content']) && ! is_scalar($tag['content']))
597        {
598            return XML_Util :: raiseError('Supplied non-scalar value as tag content', XML_UTIL_ERROR_NON_SCALAR_CONTENT);
599        }
600        
601        if (! isset($tag['qname']) && ! isset($tag['localPart']))
602        {
603            return XML_Util :: raiseError('You must either supply a qualified name ' . '(qname) or local tag name (localPart).', XML_UTIL_ERROR_NO_TAG_NAME);
604        }
605        
606        // if no attributes hav been set, use empty attributes
607        if (! isset($tag['attributes']) || ! is_array($tag['attributes']))
608        {
609            $tag['attributes'] = array();
610        }
611        
612        if (isset($tag['namespaces']))
613        {
614            foreach ($tag['namespaces'] as $ns => $uri)
615            {
616                $tag['attributes']['xmlns:' . $ns] = $uri;
617            }
618        }
619        
620        if (! isset($tag['qname']))
621        {
622            // qualified name is not given
623            
624
625            // check for namespace
626            if (isset($tag['namespace']) && ! empty($tag['namespace']))
627            {
628                $tag['qname'] = $tag['namespace'] . ':' . $tag['localPart'];
629            }
630            else
631            {
632                $tag['qname'] = $tag['localPart'];
633            }
634        }
635        elseif (isset($tag['namespaceUri']) && ! isset($tag['namespace']))
636        {
637            // namespace URI is set, but no namespace
638            
639
640            $parts = XML_Util :: splitQualifiedName($tag['qname']);
641            
642            $tag['localPart'] = $parts['localPart'];
643            if (isset($parts['namespace']))
644            {
645                $tag['namespace'] = $parts['namespace'];
646            }
647        }
648        
649        if (isset($tag['namespaceUri']) && ! empty($tag['namespaceUri']))
650        {
651            // is a namespace given
652            if (isset($tag['namespace']) && ! empty($tag['namespace']))
653            {
654                $tag['attributes']['xmlns:' . $tag['namespace']] = $tag['namespaceUri'];
655            }
656            else
657            {
658                // define this Uri as the default namespace
659                $tag['attributes']['xmlns'] = $tag['namespaceUri'];
660            }
661        }
662        
663        // check for multiline attributes
664        if ($multiline === true)
665        {
666            if ($indent === '_auto')
667            {
668                $indent = str_repeat(' ', (strlen($tag['qname']) + 2));
669            }
670        }
671        
672        // create attribute list
673        $attList = XML_Util :: attributesToString($tag['attributes'], $sortAttributes, $multiline, $indent, $linebreak, $replaceEntities);
674        if (! isset($tag['content']) || (string) $tag['content'] == '')
675        {
676            $tag = sprintf('<%s%s />', $tag['qname'], $attList);
677        }
678        else
679        {
680            switch ($replaceEntities)
681            {
682                case XML_UTIL_ENTITIES_NONE :
683                    break;
684                case XML_UTIL_CDATA_SECTION :
685                    $tag['content'] = XML_Util :: createCDataSection($tag['content']);
686                    break;
687                default :
688                    $tag['content'] = XML_Util :: replaceEntities($tag['content'], $replaceEntities);
689                    break;
690            }
691            $tag = sprintf('<%s%s>%s</%s>', $tag['qname'], $attList, $tag['content'], $tag['qname']);
692        }
693        return $tag;
694    }
695
696    /**
697     * create a start element
698     *
699     * <code>
700     * require_once 'XML/Util.php';
701     *
702     * // create an XML start element:
703     * $tag = XML_Util::createStartElement('myNs:myTag', 
704     * array('foo' => 'bar') ,'http://www.w3c.org/myNs#');
705     * </code>
706     *
707     * @param string $qname          qualified tagname (including namespace)
708     * @param array  $attributes     array containg attributes
709     * @param string $namespaceUri   URI of the namespace
710     * @param bool   $multiline      whether to create a multiline tag where each 
711     * attribute gets written to a single line
712     * @param string $indent         string used to indent attributes (_auto indents
713     * attributes so they start at the same column)
714     * @param string $linebreak      string used for linebreaks
715     * @param bool   $sortAttributes Whether to sort the attributes or not
716     *
717     * @return string XML start element
718     * @access public
719     * @static
720     * @see createEndElement(), createTag()
721     */
722    function createStartElement($qname, $attributes = array(), $namespaceUri = null, $multiline = false, $indent = '_auto', $linebreak = "\n", $sortAttributes = true)
723    {
724        // if no attributes hav been set, use empty attributes
725        if (! isset($attributes) || ! is_array($attributes))
726        {
727            $attributes = array();
728        }
729        
730        if ($namespaceUri != null)
731        {
732            $parts = XML_Util :: splitQualifiedName($qname);
733        }
734        
735        // check for multiline attributes
736        if ($multiline === true)
737        {
738            if ($indent === '_auto')
739            {
740                $indent = str_repeat(' ', (strlen($qname) + 2));
741            }
742        }
743        
744        if ($namespaceUri != null)
745        {
746            // is a namespace given
747            if (isset($parts['namespace']) && ! empty($parts['namespace']))
748            {
749                $attributes['xmlns:' . $parts['namespace']] = $namespaceUri;
750            }
751            else
752            {
753                // define this Uri as the default namespace
754                $attributes['xmlns'] = $namespaceUri;
755            }
756        }
757        
758        // create attribute list
759        $attList = XML_Util :: attributesToString($attributes, $sortAttributes, $multiline, $indent, $linebreak);
760        $element = sprintf('<%s%s>', $qname, $attList);
761        return $element;
762    }
763
764    /**
765     * create an end element
766     *
767     * <code>
768     * require_once 'XML/Util.php';
769     *
770     * // create an XML start element:
771     * $tag = XML_Util::createEndElement('myNs:myTag');
772     * </code>
773     *
774     * @param string $qname qualified tagname (including namespace)
775     *
776     * @return string XML end element
777     * @access public
778     * @static
779     * @see createStartElement(), createTag()
780     */
781    function createEndElement($qname)
782    {
783        $element = sprintf('</%s>', $qname);
784        return $element;
785    }
786
787    /**
788     * create an XML comment
789     *
790     * <code>
791     * require_once 'XML/Util.php';
792     *
793     * // create an XML start element:
794     * $tag = XML_Util::createComment('I am a comment');
795     * </code>
796     *
797     * @param string $content content of the comment
798     *
799     * @return string XML comment
800     * @access public
801     * @static
802     */
803    function createComment($content)
804    {
805        $comment = sprintf('<!-- %s -->', $content);
806        return $comment;
807    }
808
809    /**
810     * create a CData section
811     *
812     * <code>
813     * require_once 'XML/Util.php';
814     *
815     * // create a CData section
816     * $tag = XML_Util::createCDataSection('I am content.');
817     * </code>
818     *
819     * @param string $data data of the CData section
820     *
821     * @return string CData section with content
822     * @access public
823     * @static
824     */
825    function createCDataSection($data)
826    {
827        return sprintf('<![CDATA[%s]]>', preg_replace('/\]\]>/', ']]]]><![CDATA[>', strval($data)));
828    
829    }
830
831    /**
832     * split qualified name and return namespace and local part
833     *
834     * <code>
835     * require_once 'XML/Util.php';
836     *
837     * // split qualified tag
838     * $parts = XML_Util::splitQualifiedName('xslt:stylesheet');
839     * </code>
840     * the returned array will contain two elements:
841     * <pre>
842     * array(
843     * 'namespace' => 'xslt',
844     * 'localPart' => 'stylesheet'
845     * );
846     * </pre>
847     *
848     * @param string $qname     qualified tag name
849     * @param string $defaultNs default namespace (optional)
850     *
851     * @return array array containing namespace and local part
852     * @access public
853     * @static
854     */
855    function splitQualifiedName($qname, $defaultNs = null)
856    {
857        if (strstr($qname, ':'))
858        {
859            $tmp = explode(':', $qname);
860            return array('namespace' => $tmp[0], 'localPart' => $tmp[1]);
861        }
862        return array('namespace' => $defaultNs, 'localPart' => $qname);
863    }
864
865    /**
866     * check, whether string is valid XML name
867     *
868     * <p>XML names are used for tagname, attribute names and various
869     * other, lesser known entities.</p>
870     * <p>An XML name may only consist of alphanumeric characters,
871     * dashes, undescores and periods, and has to start with a letter
872     * or an underscore.</p>
873     *
874     * <code>
875     * require_once 'XML/Util.php';
876     *
877     * // verify tag name
878     * $result = XML_Util::isValidName('invalidTag?');
879     * if (is_a($result, 'PEAR_Error')) {
880     * print 'Invalid XML name: ' . $result->getMessage();
881     * }
882     * </code>
883     *
884     * @param string $string string that should be checked
885     *
886     * @return mixed true, if string is a valid XML name, PEAR error otherwise
887     * @access public
888     * @static
889     * @todo support for other charsets
890     * @todo PEAR CS - unable to avoid 85-char limit on second preg_match
891     */
892    function isValidName($string)
893    {
894        // check for invalid chars
895        if (! preg_match('/^[[:alpha:]_]$/', $string{0}))
896        {
897            return XML_Util :: raiseError('XML names may only start with letter ' . 'or underscore', XML_UTIL_ERROR_INVALID_START);
898        }
899        
900        // check for invalid chars
901        if (! preg_match('/^([[:alpha:]_]([[:alnum:]\-\.]*)?:)?[[:alpha:]_]([[:alnum:]\_\-\.]+)?$/', $string))
902        {
903            return XML_Util :: raiseError('XML names may only contain alphanumeric ' . 'chars, period, hyphen, colon and underscores', XML_UTIL_ERROR_INVALID_CHARS);
904        }
905        // XML name is valid
906        return true;
907    }
908
909    /**
910     * replacement for XML_Util::raiseError
911     *
912     * Avoids the necessity to always require
913     * PEAR.php
914     *
915     * @param string $msg  error message
916     * @param int    $code error code
917     *
918     * @return PEAR_Error
919     * @access public
920     * @static
921     * @todo PEAR CS - should this use include_once instead?
922     */
923    function raiseError($msg, $code)
924    {
925        require_once 'PEAR.php';
926        return PEAR :: raiseError($msg, $code);
927    }
928}
929?>