home *** CD-ROM | disk | FTP | other *** search
/ Cricao de Sites - 650 Layouts Prontos / WebMasters.iso / Servidores / xampp-win32-1.6.7-installer.exe / php / tmp / PEAR-1.7.1 / PEAR / PackageFile / Generator / v2.php < prev   
Encoding:
PHP Script  |  2008-02-15  |  59.3 KB  |  1,529 lines

  1. <?php
  2. /**
  3.  * package.xml generation class, package.xml version 2.0
  4.  *
  5.  * PHP versions 4 and 5
  6.  *
  7.  * LICENSE: This source file is subject to version 3.0 of the PHP license
  8.  * that is available through the world-wide-web at the following URI:
  9.  * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
  10.  * the PHP License and are unable to obtain it through the web, please
  11.  * send a note to license@php.net so we can mail you a copy immediately.
  12.  *
  13.  * @category   pear
  14.  * @package    PEAR
  15.  * @author     Greg Beaver <cellog@php.net>
  16.  * @author     Stephan Schmidt (original XML_Serializer code)
  17.  * @copyright  1997-2008 The PHP Group
  18.  * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
  19.  * @version    CVS: $Id: v2.php,v 1.38 2008/01/03 20:26:37 cellog Exp $
  20.  * @link       http://pear.php.net/package/PEAR
  21.  * @since      File available since Release 1.4.0a1
  22.  */
  23. /**
  24.  * file/dir manipulation routines
  25.  */
  26. require_once 'System.php';
  27. /**
  28.  * This class converts a PEAR_PackageFile_v2 object into any output format.
  29.  *
  30.  * Supported output formats include array, XML string (using S. Schmidt's
  31.  * XML_Serializer, slightly customized)
  32.  * @category   pear
  33.  * @package    PEAR
  34.  * @author     Greg Beaver <cellog@php.net>
  35.  * @author     Stephan Schmidt (original XML_Serializer code)
  36.  * @copyright  1997-2008 The PHP Group
  37.  * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
  38.  * @version    Release: 1.7.1
  39.  * @link       http://pear.php.net/package/PEAR
  40.  * @since      Class available since Release 1.4.0a1
  41.  */
  42. class PEAR_PackageFile_Generator_v2
  43. {
  44.    /**
  45.     * default options for the serialization
  46.     * @access private
  47.     * @var array $_defaultOptions
  48.     */
  49.     var $_defaultOptions = array(
  50.                          'indent'             => ' ',                    // string used for indentation
  51.                          'linebreak'          => "\n",                  // string used for newlines
  52.                          'typeHints'          => false,                 // automatically add type hin attributes
  53.                          'addDecl'            => true,                 // add an XML declaration
  54.                          'defaultTagName'     => 'XML_Serializer_Tag',  // tag used for indexed arrays or invalid names
  55.                          'classAsTagName'     => false,                 // use classname for objects in indexed arrays
  56.                          'keyAttribute'       => '_originalKey',        // attribute where original key is stored
  57.                          'typeAttribute'      => '_type',               // attribute for type (only if typeHints => true)
  58.                          'classAttribute'     => '_class',              // attribute for class of objects (only if typeHints => true)
  59.                          'scalarAsAttributes' => false,                 // scalar values (strings, ints,..) will be serialized as attribute
  60.                          'prependAttributes'  => '',                    // prepend string for attributes
  61.                          'indentAttributes'   => false,                 // indent the attributes, if set to '_auto', it will indent attributes so they all start at the same column
  62.                          'mode'               => 'simplexml',             // use 'simplexml' to use parent name as tagname if transforming an indexed array
  63.                          'addDoctype'         => false,                 // add a doctype declaration
  64.                          'doctype'            => null,                  // supply a string or an array with id and uri ({@see PEAR_PackageFile_Generator_v2_PEAR_PackageFile_Generator_v2_XML_Util::getDoctypeDeclaration()}
  65.                          'rootName'           => 'package',                  // name of the root tag
  66.                          'rootAttributes'     => array(
  67.                              'version' => '2.0',
  68.                              'xmlns' => 'http://pear.php.net/dtd/package-2.0',
  69.                              'xmlns:tasks' => 'http://pear.php.net/dtd/tasks-1.0',
  70.                              'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
  71.                              'xsi:schemaLocation' => 'http://pear.php.net/dtd/tasks-1.0
  72. http://pear.php.net/dtd/tasks-1.0.xsd
  73. http://pear.php.net/dtd/package-2.0
  74. http://pear.php.net/dtd/package-2.0.xsd',
  75.                          ),               // attributes of the root tag
  76.                          'attributesArray'    => 'attribs',                  // all values in this key will be treated as attributes
  77.                          'contentName'        => '_content',                   // this value will be used directly as content, instead of creating a new tag, may only be used in conjuction with attributesArray
  78.                          'beautifyFilelist'   => false,
  79.                          'encoding' => 'UTF-8',
  80.                         );
  81.  
  82.    /**
  83.     * options for the serialization
  84.     * @access private
  85.     * @var array $options
  86.     */
  87.     var $options = array();
  88.  
  89.    /**
  90.     * current tag depth
  91.     * @var integer $_tagDepth
  92.     */
  93.     var $_tagDepth = 0;
  94.  
  95.    /**
  96.     * serilialized representation of the data
  97.     * @var string $_serializedData
  98.     */
  99.     var $_serializedData = null;
  100.     /**
  101.      * @var PEAR_PackageFile_v2
  102.      */
  103.     var $_packagefile;
  104.     /**
  105.      * @param PEAR_PackageFile_v2
  106.      */
  107.     function PEAR_PackageFile_Generator_v2(&$packagefile)
  108.     {
  109.         $this->_packagefile = &$packagefile;
  110.     }
  111.  
  112.     /**
  113.      * @return string
  114.      */
  115.     function getPackagerVersion()
  116.     {
  117.         return '1.7.1';
  118.     }
  119.  
  120.     /**
  121.      * @param PEAR_Packager
  122.      * @param bool generate a .tgz or a .tar
  123.      * @param string|null temporary directory to package in
  124.      */
  125.     function toTgz(&$packager, $compress = true, $where = null)
  126.     {
  127.         $a = null;
  128.         return $this->toTgz2($packager, $a, $compress, $where);
  129.     }
  130.  
  131.     /**
  132.      * Package up both a package.xml and package2.xml for the same release
  133.      * @param PEAR_Packager
  134.      * @param PEAR_PackageFile_v1
  135.      * @param bool generate a .tgz or a .tar
  136.      * @param string|null temporary directory to package in
  137.      */
  138.     function toTgz2(&$packager, &$pf1, $compress = true, $where = null)
  139.     {
  140.         require_once 'Archive/Tar.php';
  141.         if (!$this->_packagefile->isEquivalent($pf1)) {
  142.             return PEAR::raiseError('PEAR_Packagefile_v2::toTgz: "' .
  143.                 basename($pf1->getPackageFile()) .
  144.                 '" is not equivalent to "' . basename($this->_packagefile->getPackageFile())
  145.                 . '"');
  146.         }
  147.         if ($where === null) {
  148.             if (!($where = System::mktemp(array('-d')))) {
  149.                 return PEAR::raiseError('PEAR_Packagefile_v2::toTgz: mktemp failed');
  150.             }
  151.         } elseif (!@System::mkDir(array('-p', $where))) {
  152.             return PEAR::raiseError('PEAR_Packagefile_v2::toTgz: "' . $where . '" could' .
  153.                 ' not be created');
  154.         }
  155.         if (file_exists($where . DIRECTORY_SEPARATOR . 'package.xml') &&
  156.               !is_file($where . DIRECTORY_SEPARATOR . 'package.xml')) {
  157.             return PEAR::raiseError('PEAR_Packagefile_v2::toTgz: unable to save package.xml as' .
  158.                 ' "' . $where . DIRECTORY_SEPARATOR . 'package.xml"');
  159.         }
  160.         if (!$this->_packagefile->validate(PEAR_VALIDATE_PACKAGING)) {
  161.             return PEAR::raiseError('PEAR_Packagefile_v2::toTgz: invalid package.xml');
  162.         }
  163.         $ext = $compress ? '.tgz' : '.tar';
  164.         $pkgver = $this->_packagefile->getPackage() . '-' . $this->_packagefile->getVersion();
  165.         $dest_package = getcwd() . DIRECTORY_SEPARATOR . $pkgver . $ext;
  166.         if (file_exists(getcwd() . DIRECTORY_SEPARATOR . $pkgver . $ext) &&
  167.               !is_file(getcwd() . DIRECTORY_SEPARATOR . $pkgver . $ext)) {
  168.             return PEAR::raiseError('PEAR_Packagefile_v2::toTgz: cannot create tgz file "' .
  169.                 getcwd() . DIRECTORY_SEPARATOR . $pkgver . $ext . '"');
  170.         }
  171.         if ($pkgfile = $this->_packagefile->getPackageFile()) {
  172.             $pkgdir = dirname(realpath($pkgfile));
  173.             $pkgfile = basename($pkgfile);
  174.         } else {
  175.             return PEAR::raiseError('PEAR_Packagefile_v2::toTgz: package file object must ' .
  176.                 'be created from a real file');
  177.         }
  178.         // {{{ Create the package file list
  179.         $filelist = array();
  180.         $i = 0;
  181.         $this->_packagefile->flattenFilelist();
  182.         $contents = $this->_packagefile->getContents();
  183.         if (isset($contents['bundledpackage'])) { // bundles of packages
  184.             $contents = $contents['bundledpackage'];
  185.             if (!isset($contents[0])) {
  186.                 $contents = array($contents);
  187.             }
  188.             $packageDir = $where;
  189.             foreach ($contents as $i => $package) {
  190.                 $fname = $package;
  191.                 $file = $pkgdir . DIRECTORY_SEPARATOR . $fname;
  192.                 if (!file_exists($file)) {
  193.                     return $packager->raiseError("File does not exist: $fname");
  194.                 }
  195.                 $tfile = $packageDir . DIRECTORY_SEPARATOR . $fname;
  196.                 System::mkdir(array('-p', dirname($tfile)));
  197.                 copy($file, $tfile);
  198.                 $filelist[$i++] = $tfile;
  199.                 $packager->log(2, "Adding package $fname");
  200.             }
  201.         } else { // normal packages
  202.             $contents = $contents['dir']['file'];
  203.             if (!isset($contents[0])) {
  204.                 $contents = array($contents);
  205.             }
  206.     
  207.             $packageDir = $where;
  208.             foreach ($contents as $i => $file) {
  209.                 $fname = $file['attribs']['name'];
  210.                 $atts = $file['attribs'];
  211.                 $orig = $file;
  212.                 $file = $pkgdir . DIRECTORY_SEPARATOR . $fname;
  213.                 if (!file_exists($file)) {
  214.                     return $packager->raiseError("File does not exist: $fname");
  215.                 } else {
  216.                     $tfile = $packageDir . DIRECTORY_SEPARATOR . $fname;
  217.                     unset($orig['attribs']);
  218.                     if (count($orig)) { // file with tasks
  219.                         // run any package-time tasks
  220.                         $contents = file_get_contents($file);
  221.                         foreach ($orig as $tag => $raw) {
  222.                             $tag = str_replace(
  223.                                 array($this->_packagefile->getTasksNs() . ':', '-'),
  224.                                 array('', '_'), $tag);
  225.                             $task = "PEAR_Task_$tag";
  226.                             $task = &new $task($this->_packagefile->_config,
  227.                                 $this->_packagefile->_logger,
  228.                                 PEAR_TASK_PACKAGE);
  229.                             $task->init($raw, $atts, null);
  230.                             $res = $task->startSession($this->_packagefile, $contents, $tfile);
  231.                             if (!$res) {
  232.                                 continue; // skip this task
  233.                             }
  234.                             if (PEAR::isError($res)) {
  235.                                 return $res;
  236.                             }
  237.                             $contents = $res; // save changes
  238.                             System::mkdir(array('-p', dirname($tfile)));
  239.                             $wp = fopen($tfile, "wb");
  240.                             fwrite($wp, $contents);
  241.                             fclose($wp);
  242.                         }
  243.                     }
  244.                     if (!file_exists($tfile)) {
  245.                         System::mkdir(array('-p', dirname($tfile)));
  246.                         copy($file, $tfile);
  247.                     }
  248.                     $filelist[$i++] = $tfile;
  249.                     $this->_packagefile->setFileAttribute($fname, 'md5sum', md5_file($tfile), $i - 1);
  250.                     $packager->log(2, "Adding file $fname");
  251.                 }
  252.             }
  253.         }
  254.             // }}}
  255.         if ($pf1 !== null) {
  256.             $name = 'package2.xml';
  257.         } else {
  258.             $name = 'package.xml';
  259.         }
  260.         $packagexml = $this->toPackageFile($where, PEAR_VALIDATE_PACKAGING, $name);
  261.         if ($packagexml) {
  262.             $tar =& new Archive_Tar($dest_package, $compress);
  263.             $tar->setErrorHandling(PEAR_ERROR_RETURN); // XXX Don't print errors
  264.             // ----- Creates with the package.xml file
  265.             $ok = $tar->createModify(array($packagexml), '', $where);
  266.             if (PEAR::isError($ok)) {
  267.                 return $packager->raiseError($ok);
  268.             } elseif (!$ok) {
  269.                 return $packager->raiseError('PEAR_Packagefile_v2::toTgz(): adding ' . $name .
  270.                     ' failed');
  271.             }
  272.             // ----- Add the content of the package
  273.             if (!$tar->addModify($filelist, $pkgver, $where)) {
  274.                 return $packager->raiseError(
  275.                     'PEAR_Packagefile_v2::toTgz(): tarball creation failed');
  276.             }
  277.             // add the package.xml version 1.0
  278.             if ($pf1 !== null) {
  279.                 $pfgen = &$pf1->getDefaultGenerator();
  280.                 $packagexml1 = $pfgen->toPackageFile($where, PEAR_VALIDATE_PACKAGING,
  281.                     'package.xml', true);
  282.                 if (!$tar->addModify(array($packagexml1), '', $where)) {
  283.                     return $packager->raiseError(
  284.                         'PEAR_Packagefile_v2::toTgz(): adding package.xml failed');
  285.                 }
  286.             }
  287.             return $dest_package;
  288.         }
  289.     }
  290.  
  291.     function toPackageFile($where = null, $state = PEAR_VALIDATE_NORMAL, $name = 'package.xml')
  292.     {
  293.         if (!$this->_packagefile->validate($state)) {
  294.             return PEAR::raiseError('PEAR_Packagefile_v2::toPackageFile: invalid package.xml',
  295.                 null, null, null, $this->_packagefile->getValidationWarnings());
  296.         }
  297.         if ($where === null) {
  298.             if (!($where = System::mktemp(array('-d')))) {
  299.                 return PEAR::raiseError('PEAR_Packagefile_v2::toPackageFile: mktemp failed');
  300.             }
  301.         } elseif (!@System::mkDir(array('-p', $where))) {
  302.             return PEAR::raiseError('PEAR_Packagefile_v2::toPackageFile: "' . $where . '" could' .
  303.                 ' not be created');
  304.         }
  305.         $newpkgfile = $where . DIRECTORY_SEPARATOR . $name;
  306.         $np = @fopen($newpkgfile, 'wb');
  307.         if (!$np) {
  308.             return PEAR::raiseError('PEAR_Packagefile_v2::toPackageFile: unable to save ' .
  309.                "$name as $newpkgfile");
  310.         }
  311.         fwrite($np, $this->toXml($state));
  312.         fclose($np);
  313.         return $newpkgfile;
  314.     }
  315.  
  316.     function &toV2()
  317.     {
  318.         return $this->_packagefile;
  319.     }
  320.  
  321.     /**
  322.      * Return an XML document based on the package info (as returned
  323.      * by the PEAR_Common::infoFrom* methods).
  324.      *
  325.      * @return string XML data
  326.      */
  327.     function toXml($state = PEAR_VALIDATE_NORMAL, $options = array())
  328.     {
  329.         $this->_packagefile->setDate(date('Y-m-d'));
  330.         $this->_packagefile->setTime(date('H:i:s'));
  331.         if (!$this->_packagefile->validate($state)) {
  332.             return false;
  333.         }
  334.         if (is_array($options)) {
  335.             $this->options = array_merge($this->_defaultOptions, $options);
  336.         } else {
  337.             $this->options = $this->_defaultOptions;
  338.         }
  339.         $arr = $this->_packagefile->getArray();
  340.         if (isset($arr['filelist'])) {
  341.             unset($arr['filelist']);
  342.         }
  343.         if (isset($arr['_lastversion'])) {
  344.             unset($arr['_lastversion']);
  345.         }
  346.         if ($state ^ PEAR_VALIDATE_PACKAGING && !isset($arr['bundle'])) {
  347.             $use = $this->_recursiveXmlFilelist($arr['contents']['dir']['file']);
  348.             unset($arr['contents']['dir']['file']);
  349.             if (isset($use['dir'])) {
  350.                 $arr['contents']['dir']['dir'] = $use['dir'];
  351.             }
  352.             if (isset($use['file'])) {
  353.                 $arr['contents']['dir']['file'] = $use['file'];
  354.             }
  355.             $this->options['beautifyFilelist'] = true;
  356.         }
  357.         $arr['attribs']['packagerversion'] = '1.7.1';
  358.         if ($this->serialize($arr, $options)) {
  359.             return $this->_serializedData . "\n";
  360.         }
  361.         return false;
  362.     }
  363.  
  364.  
  365.     function _recursiveXmlFilelist($list)
  366.     {
  367.         $dirs = array();
  368.         if (isset($list['attribs'])) {
  369.             $file = $list['attribs']['name'];
  370.             unset($list['attribs']['name']);
  371.             $attributes = $list['attribs'];
  372.             $this->_addDir($dirs, explode('/', dirname($file)), $file, $attributes);
  373.         } else {
  374.             foreach ($list as $a) {
  375.                 $file = $a['attribs']['name'];
  376.                 $attributes = $a['attribs'];
  377.                 unset($a['attribs']);
  378.                 $this->_addDir($dirs, explode('/', dirname($file)), $file, $attributes, $a);
  379.             }
  380.         }
  381.         $this->_formatDir($dirs);
  382.         $this->_deFormat($dirs);
  383.         return $dirs;
  384.     }
  385.  
  386.     function _addDir(&$dirs, $dir, $file = null, $attributes = null, $tasks = null)
  387.     {
  388.         if (!$tasks) {
  389.             $tasks = array();
  390.         }
  391.         if ($dir == array() || $dir == array('.')) {
  392.             $dirs['file'][basename($file)] = $tasks;
  393.             $attributes['name'] = basename($file);
  394.             $dirs['file'][basename($file)]['attribs'] = $attributes;
  395.             return;
  396.         }
  397.         $curdir = array_shift($dir);
  398.         if (!isset($dirs['dir'][$curdir])) {
  399.             $dirs['dir'][$curdir] = array();
  400.         }
  401.         $this->_addDir($dirs['dir'][$curdir], $dir, $file, $attributes, $tasks);
  402.     }
  403.  
  404.     function _formatDir(&$dirs)
  405.     {
  406.         if (!count($dirs)) {
  407.             return array();
  408.         }
  409.         $newdirs = array();
  410.         if (isset($dirs['dir'])) {
  411.             $newdirs['dir'] = $dirs['dir'];
  412.         }
  413.         if (isset($dirs['file'])) {
  414.             $newdirs['file'] = $dirs['file'];
  415.         }
  416.         $dirs = $newdirs;
  417.         if (isset($dirs['dir'])) {
  418.             uksort($dirs['dir'], 'strnatcasecmp');
  419.             foreach ($dirs['dir'] as $dir => $contents) {
  420.                 $this->_formatDir($dirs['dir'][$dir]);
  421.             }
  422.         }
  423.         if (isset($dirs['file'])) {
  424.             uksort($dirs['file'], 'strnatcasecmp');
  425.         };
  426.     }
  427.  
  428.     function _deFormat(&$dirs)
  429.     {
  430.         if (!count($dirs)) {
  431.             return array();
  432.         }
  433.         $newdirs = array();
  434.         if (isset($dirs['dir'])) {
  435.             foreach ($dirs['dir'] as $dir => $contents) {
  436.                 $newdir = array();
  437.                 $newdir['attribs']['name'] = $dir;
  438.                 $this->_deFormat($contents);
  439.                 foreach ($contents as $tag => $val) {
  440.                     $newdir[$tag] = $val;
  441.                 }
  442.                 $newdirs['dir'][] = $newdir;
  443.             }
  444.             if (count($newdirs['dir']) == 1) {
  445.                 $newdirs['dir'] = $newdirs['dir'][0];
  446.             }
  447.         }
  448.         if (isset($dirs['file'])) {
  449.             foreach ($dirs['file'] as $name => $file) {
  450.                 $newdirs['file'][] = $file;
  451.             }
  452.             if (count($newdirs['file']) == 1) {
  453.                 $newdirs['file'] = $newdirs['file'][0];
  454.             }
  455.         }
  456.         $dirs = $newdirs;
  457.     }
  458.  
  459.     /**
  460.     * reset all options to default options
  461.     *
  462.     * @access   public
  463.     * @see      setOption(), XML_Unserializer()
  464.     */
  465.     function resetOptions()
  466.     {
  467.         $this->options = $this->_defaultOptions;
  468.     }
  469.  
  470.    /**
  471.     * set an option
  472.     *
  473.     * You can use this method if you do not want to set all options in the constructor
  474.     *
  475.     * @access   public
  476.     * @see      resetOption(), XML_Serializer()
  477.     */
  478.     function setOption($name, $value)
  479.     {
  480.         $this->options[$name] = $value;
  481.     }
  482.     
  483.    /**
  484.     * sets several options at once
  485.     *
  486.     * You can use this method if you do not want to set all options in the constructor
  487.     *
  488.     * @access   public
  489.     * @see      resetOption(), XML_Unserializer(), setOption()
  490.     */
  491.     function setOptions($options)
  492.     {
  493.         $this->options = array_merge($this->options, $options);
  494.     }
  495.  
  496.    /**
  497.     * serialize data
  498.     *
  499.     * @access   public
  500.     * @param    mixed    $data data to serialize
  501.     * @return   boolean  true on success, pear error on failure
  502.     */
  503.     function serialize($data, $options = null)
  504.     {
  505.         // if options have been specified, use them instead
  506.         // of the previously defined ones
  507.         if (is_array($options)) {
  508.             $optionsBak = $this->options;
  509.             if (isset($options['overrideOptions']) && $options['overrideOptions'] == true) {
  510.                 $this->options = array_merge($this->_defaultOptions, $options);
  511.             } else {
  512.                 $this->options = array_merge($this->options, $options);
  513.             }
  514.         }
  515.         else {
  516.             $optionsBak = null;
  517.         }
  518.         
  519.         //  start depth is zero
  520.         $this->_tagDepth = 0;
  521.  
  522.         $this->_serializedData = '';
  523.         // serialize an array
  524.         if (is_array($data)) {
  525.             if (isset($this->options['rootName'])) {
  526.                 $tagName = $this->options['rootName'];
  527.             } else {
  528.                 $tagName = 'array';
  529.             }
  530.  
  531.             $this->_serializedData .= $this->_serializeArray($data, $tagName, $this->options['rootAttributes']);
  532.         }
  533.         
  534.         // add doctype declaration
  535.         if ($this->options['addDoctype'] === true) {
  536.             $this->_serializedData = PEAR_PackageFile_Generator_v2_XML_Util::getDoctypeDeclaration($tagName, $this->options['doctype'])
  537.                                    . $this->options['linebreak']
  538.                                    . $this->_serializedData;
  539.         }
  540.  
  541.         //  build xml declaration
  542.         if ($this->options['addDecl']) {
  543.             $atts = array();
  544.             if (isset($this->options['encoding']) ) {
  545.                 $encoding = $this->options['encoding'];
  546.             } else {
  547.                 $encoding = null;
  548.             }
  549.             $this->_serializedData = PEAR_PackageFile_Generator_v2_XML_Util::getXMLDeclaration('1.0', $encoding)
  550.                                    . $this->options['linebreak']
  551.                                    . $this->_serializedData;
  552.         }
  553.         
  554.         
  555.         if ($optionsBak !== null) {
  556.             $this->options = $optionsBak;
  557.         }
  558.         
  559.         return  true;
  560.     }
  561.  
  562.    /**
  563.     * get the result of the serialization
  564.     *
  565.     * @access public
  566.     * @return string serialized XML
  567.     */
  568.     function getSerializedData()
  569.     {
  570.         if ($this->_serializedData == null ) {
  571.             return  $this->raiseError('No serialized data available. Use XML_Serializer::serialize() first.', XML_SERIALIZER_ERROR_NO_SERIALIZATION);
  572.         }
  573.         return $this->_serializedData;
  574.     }
  575.     
  576.    /**
  577.     * serialize any value
  578.     *
  579.     * This method checks for the type of the value and calls the appropriate method
  580.     *
  581.     * @access private
  582.     * @param  mixed     $value
  583.     * @param  string    $tagName
  584.     * @param  array     $attributes
  585.     * @return string
  586.     */
  587.     function _serializeValue($value, $tagName = null, $attributes = array())
  588.     {
  589.         if (is_array($value)) {
  590.             $xml = $this->_serializeArray($value, $tagName, $attributes);
  591.         } elseif (is_object($value)) {
  592.             $xml = $this->_serializeObject($value, $tagName);
  593.         } else {
  594.             $tag = array(
  595.                           'qname'      => $tagName,
  596.                           'attributes' => $attributes,
  597.                           'content'    => $value
  598.                         );
  599.             $xml = $this->_createXMLTag($tag);
  600.         }
  601.         return $xml;
  602.     }
  603.     
  604.    /**
  605.     * serialize an array
  606.     *
  607.     * @access   private
  608.     * @param    array   $array       array to serialize
  609.     * @param    string  $tagName     name of the root tag
  610.     * @param    array   $attributes  attributes for the root tag
  611.     * @return   string  $string      serialized data
  612.     * @uses     PEAR_PackageFile_Generator_v2_XML_Util::isValidName() to check, whether key has to be substituted
  613.     */
  614.     function _serializeArray(&$array, $tagName = null, $attributes = array())
  615.     {
  616.         $_content = null;
  617.         
  618.         /**
  619.          * check for special attributes
  620.          */
  621.         if ($this->options['attributesArray'] !== null) {
  622.             if (isset($array[$this->options['attributesArray']])) {
  623.                 $attributes = $array[$this->options['attributesArray']];
  624.                 unset($array[$this->options['attributesArray']]);
  625.             }
  626.             /**
  627.              * check for special content
  628.              */
  629.             if ($this->options['contentName'] !== null) {
  630.                 if (isset($array[$this->options['contentName']])) {
  631.                     $_content = $array[$this->options['contentName']];
  632.                     unset($array[$this->options['contentName']]);
  633.                 }
  634.             }
  635.         }
  636.  
  637.         /*
  638.         * if mode is set to simpleXML, check whether
  639.         * the array is associative or indexed
  640.         */
  641.         if (is_array($array) && $this->options['mode'] == 'simplexml') {
  642.             $indexed = true;
  643.             if (!count($array)) {
  644.                 $indexed = false;
  645.             }
  646.             foreach ($array as $key => $val) {
  647.                 if (!is_int($key)) {
  648.                     $indexed = false;
  649.                     break;
  650.                 }
  651.             }
  652.  
  653.             if ($indexed && $this->options['mode'] == 'simplexml') {
  654.                 $string = '';
  655.                 foreach ($array as $key => $val) {
  656.                     if ($this->options['beautifyFilelist'] && $tagName == 'dir') {
  657.                         if (!isset($this->_curdir)) {
  658.                             $this->_curdir = '';
  659.                         }
  660.                         $savedir = $this->_curdir;
  661.                         if (isset($val['attribs'])) {
  662.                             if ($val['attribs']['name'] == '/') {
  663.                                 $this->_curdir = '/';
  664.                             } else {
  665.                                 if ($this->_curdir == '/') {
  666.                                     $this->_curdir = '';
  667.                                 }
  668.                                 $this->_curdir .= '/' . $val['attribs']['name'];
  669.                             }
  670.                         }
  671.                     }
  672.                     $string .= $this->_serializeValue( $val, $tagName, $attributes);
  673.                     if ($this->options['beautifyFilelist'] && $tagName == 'dir') {
  674.                         $string .= ' <!-- ' . $this->_curdir . ' -->';
  675.                         if (empty($savedir)) {
  676.                             unset($this->_curdir);
  677.                         } else {
  678.                             $this->_curdir = $savedir;
  679.                         }
  680.                     }
  681.                     
  682.                     $string .= $this->options['linebreak'];
  683.                     //    do indentation
  684.                     if ($this->options['indent']!==null && $this->_tagDepth>0) {
  685.                         $string .= str_repeat($this->options['indent'], $this->_tagDepth);
  686.                     }
  687.                 }
  688.                 return rtrim($string);
  689.             }
  690.         }
  691.         
  692.         if ($this->options['scalarAsAttributes'] === true) {
  693.             foreach ($array as $key => $value) {
  694.                 if (is_scalar($value) && (PEAR_PackageFile_Generator_v2_XML_Util::isValidName($key) === true)) {
  695.                     unset($array[$key]);
  696.                     $attributes[$this->options['prependAttributes'].$key] = $value;
  697.                 }
  698.             }
  699.         }
  700.  
  701.         // check for empty array => create empty tag
  702.         if (empty($array)) {
  703.             $tag = array(
  704.                             'qname'      => $tagName,
  705.                             'content'    => $_content,
  706.                             'attributes' => $attributes
  707.                         );
  708.  
  709.         } else {
  710.             $this->_tagDepth++;
  711.             $tmp = $this->options['linebreak'];
  712.             foreach ($array as $key => $value) {
  713.                 //    do indentation
  714.                 if ($this->options['indent']!==null && $this->_tagDepth>0) {
  715.                     $tmp .= str_repeat($this->options['indent'], $this->_tagDepth);
  716.                 }
  717.     
  718.                 //    copy key
  719.                 $origKey    =    $key;
  720.                 //    key cannot be used as tagname => use default tag
  721.                 $valid = PEAR_PackageFile_Generator_v2_XML_Util::isValidName($key);
  722.                 if (PEAR::isError($valid)) {
  723.                     if ($this->options['classAsTagName'] && is_object($value)) {
  724.                         $key = get_class($value);
  725.                     } else {
  726.                         $key = $this->options['defaultTagName'];
  727.                     }
  728.                     }
  729.                 $atts = array();
  730.                 if ($this->options['typeHints'] === true) {
  731.                     $atts[$this->options['typeAttribute']] = gettype($value);
  732.                     if ($key !== $origKey) {
  733.                         $atts[$this->options['keyAttribute']] = (string)$origKey;
  734.                     }
  735.     
  736.                 }
  737.                 if ($this->options['beautifyFilelist'] && $key == 'dir') {
  738.                     if (!isset($this->_curdir)) {
  739.                         $this->_curdir = '';
  740.                     }
  741.                     $savedir = $this->_curdir;
  742.                     if (isset($value['attribs'])) {
  743.                         if ($value['attribs']['name'] == '/') {
  744.                             $this->_curdir = '/';
  745.                         } else {
  746.                             $this->_curdir .= '/' . $value['attribs']['name'];
  747.                         }
  748.                     }
  749.                 }
  750.  
  751.                 if (is_string($value) && $value && ($value{strlen($value) - 1} == "\n")) {
  752.                     $value .= str_repeat($this->options['indent'], $this->_tagDepth);
  753.                 }
  754.                 $tmp .= $this->_createXMLTag(array(
  755.                                                     'qname'      => $key,
  756.                                                     'attributes' => $atts,
  757.                                                     'content'    => $value )
  758.                                             );
  759.                 if ($this->options['beautifyFilelist'] && $key == 'dir') {
  760.                     if (isset($value['attribs'])) {
  761.                         $tmp .= ' <!-- ' . $this->_curdir . ' -->';
  762.                         if (empty($savedir)) {
  763.                             unset($this->_curdir);
  764.                         } else {
  765.                             $this->_curdir = $savedir;
  766.                         }
  767.                     }
  768.                 }
  769.                 $tmp .= $this->options['linebreak'];
  770.             }
  771.             
  772.             $this->_tagDepth--;
  773.             if ($this->options['indent']!==null && $this->_tagDepth>0) {
  774.                 $tmp .= str_repeat($this->options['indent'], $this->_tagDepth);
  775.             }
  776.     
  777.             if (trim($tmp) === '') {
  778.                 $tmp = null;
  779.             }
  780.             
  781.             $tag = array(
  782.                             'qname'      => $tagName,
  783.                             'content'    => $tmp,
  784.                             'attributes' => $attributes
  785.                         );
  786.         }
  787.         if ($this->options['typeHints'] === true) {
  788.             if (!isset($tag['attributes'][$this->options['typeAttribute']])) {
  789.                 $tag['attributes'][$this->options['typeAttribute']] = 'array';
  790.             }
  791.         }
  792.  
  793.         $string = $this->_createXMLTag($tag, false);
  794.         return $string;
  795.     }
  796.   
  797.    /**
  798.     * create a tag from an array
  799.     * this method awaits an array in the following format
  800.     * array(
  801.     *       'qname'        => $tagName,
  802.     *       'attributes'   => array(),
  803.     *       'content'      => $content,      // optional
  804.     *       'namespace'    => $namespace     // optional
  805.     *       'namespaceUri' => $namespaceUri  // optional
  806.     *   )
  807.     *
  808.     * @access   private
  809.     * @param    array   $tag tag definition
  810.     * @param    boolean $replaceEntities whether to replace XML entities in content or not
  811.     * @return   string  $string XML tag
  812.     */
  813.     function _createXMLTag( $tag, $replaceEntities = true )
  814.     {
  815.         if ($this->options['indentAttributes'] !== false) {
  816.             $multiline = true;
  817.             $indent    = str_repeat($this->options['indent'], $this->_tagDepth);
  818.  
  819.             if ($this->options['indentAttributes'] == '_auto') {
  820.                 $indent .= str_repeat(' ', (strlen($tag['qname'])+2));
  821.  
  822.             } else {
  823.                 $indent .= $this->options['indentAttributes'];
  824.             }
  825.         } else {
  826.             $multiline = false;
  827.             $indent    = false;
  828.         }
  829.     
  830.         if (is_array($tag['content'])) {
  831.             if (empty($tag['content'])) {
  832.                 $tag['content'] =   '';
  833.             }
  834.         } elseif(is_scalar($tag['content']) && (string)$tag['content'] == '') {
  835.             $tag['content'] =   '';
  836.         }
  837.     
  838.         if (is_scalar($tag['content']) || is_null($tag['content'])) {
  839.             if ($this->options['encoding'] == 'UTF-8' &&
  840.                   version_compare(phpversion(), '5.0.0', 'lt')) {
  841.                 $encoding = PEAR_PackageFile_Generator_v2_XML_Util_ENTITIES_UTF8_XML;
  842.             } else {
  843.                 $encoding = PEAR_PackageFile_Generator_v2_XML_Util_ENTITIES_XML;
  844.             }
  845.             $tag = PEAR_PackageFile_Generator_v2_XML_Util::createTagFromArray($tag, $replaceEntities, $multiline, $indent, $this->options['linebreak'], $encoding);
  846.         } elseif (is_array($tag['content'])) {
  847.             $tag    =   $this->_serializeArray($tag['content'], $tag['qname'], $tag['attributes']);
  848.         } elseif (is_object($tag['content'])) {
  849.             $tag    =   $this->_serializeObject($tag['content'], $tag['qname'], $tag['attributes']);
  850.         } elseif (is_resource($tag['content'])) {
  851.             settype($tag['content'], 'string');
  852.             $tag    =   PEAR_PackageFile_Generator_v2_XML_Util::createTagFromArray($tag, $replaceEntities);
  853.         }
  854.         return  $tag;
  855.     }
  856. }
  857.  
  858. // well, it's one way to do things without extra deps ...
  859. /* vim: set expandtab tabstop=4 shiftwidth=4: */
  860. // +----------------------------------------------------------------------+
  861. // | PHP Version 4                                                        |
  862. // +----------------------------------------------------------------------+
  863. // | Copyright (c) 1997-2002 The PHP Group                                |
  864. // +----------------------------------------------------------------------+
  865. // | This source file is subject to version 2.0 of the PHP license,       |
  866. // | that is bundled with this package in the file LICENSE, and is        |
  867. // | available at through the world-wide-web at                           |
  868. // | http://www.php.net/license/2_02.txt.                                 |
  869. // | If you did not receive a copy of the PHP license and are unable to   |
  870. // | obtain it through the world-wide-web, please send a note to          |
  871. // | license@php.net so we can mail you a copy immediately.               |
  872. // +----------------------------------------------------------------------+
  873. // | Authors: Stephan Schmidt <schst@php-tools.net>                       |
  874. // +----------------------------------------------------------------------+
  875. //
  876. //    $Id: v2.php,v 1.38 2008/01/03 20:26:37 cellog Exp $
  877.  
  878. /**
  879.  * error code for invalid chars in XML name
  880.  */
  881. define("PEAR_PackageFile_Generator_v2_XML_Util_ERROR_INVALID_CHARS", 51);
  882.  
  883. /**
  884.  * error code for invalid chars in XML name
  885.  */
  886. define("PEAR_PackageFile_Generator_v2_XML_Util_ERROR_INVALID_START", 52);
  887.  
  888. /**
  889.  * error code for non-scalar tag content
  890.  */
  891. define("PEAR_PackageFile_Generator_v2_XML_Util_ERROR_NON_SCALAR_CONTENT", 60);
  892.     
  893. /**
  894.  * error code for missing tag name
  895.  */
  896. define("PEAR_PackageFile_Generator_v2_XML_Util_ERROR_NO_TAG_NAME", 61);
  897.     
  898. /**
  899.  * replace XML entities
  900.  */
  901. define("PEAR_PackageFile_Generator_v2_XML_Util_REPLACE_ENTITIES", 1);
  902.  
  903. /**
  904.  * embedd content in a CData Section
  905.  */
  906. define("PEAR_PackageFile_Generator_v2_XML_Util_CDATA_SECTION", 2);
  907.  
  908. /**
  909.  * do not replace entitites
  910.  */
  911. define("PEAR_PackageFile_Generator_v2_XML_Util_ENTITIES_NONE", 0);
  912.  
  913. /**
  914.  * replace all XML entitites
  915.  * This setting will replace <, >, ", ' and &
  916.  */
  917. define("PEAR_PackageFile_Generator_v2_XML_Util_ENTITIES_XML", 1);
  918.  
  919. /**
  920.  * replace only required XML entitites
  921.  * This setting will replace <, " and &
  922.  */
  923. define("PEAR_PackageFile_Generator_v2_XML_Util_ENTITIES_XML_REQUIRED", 2);
  924.  
  925. /**
  926.  * replace HTML entitites
  927.  * @link    http://www.php.net/htmlentities
  928.  */
  929. define("PEAR_PackageFile_Generator_v2_XML_Util_ENTITIES_HTML", 3);
  930.  
  931. /**
  932.  * replace all XML entitites, and encode from ISO-8859-1 to UTF-8
  933.  * This setting will replace <, >, ", ' and &
  934.  */
  935. define("PEAR_PackageFile_Generator_v2_XML_Util_ENTITIES_UTF8_XML", 4);
  936.  
  937. /**
  938.  * utility class for working with XML documents
  939.  * 
  940.  * customized version of XML_Util 0.6.0
  941.  *
  942.  * @category XML
  943.  * @package  PEAR
  944.  * @version  0.6.0
  945.  * @author   Stephan Schmidt <schst@php.net>
  946.  * @author   Gregory Beaver <cellog@php.net>
  947.  */
  948. class PEAR_PackageFile_Generator_v2_XML_Util {
  949.  
  950.    /**
  951.     * return API version
  952.     *
  953.     * @access   public
  954.     * @static
  955.     * @return   string  $version API version
  956.     */
  957.     function apiVersion()
  958.     {
  959.         return "0.6";
  960.     }
  961.  
  962.    /**
  963.     * replace XML entities
  964.     *
  965.     * With the optional second parameter, you may select, which
  966.     * entities should be replaced.
  967.     *
  968.     * <code>
  969.     * require_once 'XML/Util.php';
  970.     * 
  971.     * // replace XML entites:
  972.     * $string = PEAR_PackageFile_Generator_v2_XML_Util::replaceEntities("This string contains < & >.");
  973.     * </code>
  974.     *
  975.     * @access   public
  976.     * @static
  977.     * @param    string  string where XML special chars should be replaced
  978.     * @param    integer setting for entities in attribute values (one of PEAR_PackageFile_Generator_v2_XML_Util_ENTITIES_XML, PEAR_PackageFile_Generator_v2_XML_Util_ENTITIES_XML_REQUIRED, PEAR_PackageFile_Generator_v2_XML_Util_ENTITIES_HTML)
  979.     * @return   string  string with replaced chars
  980.     */
  981.     function replaceEntities($string, $replaceEntities = PEAR_PackageFile_Generator_v2_XML_Util_ENTITIES_XML)
  982.     {
  983.         switch ($replaceEntities) {
  984.             case PEAR_PackageFile_Generator_v2_XML_Util_ENTITIES_UTF8_XML:
  985.                 return strtr(utf8_encode($string),array(
  986.                                           '&'  => '&',
  987.                                           '>'  => '>',
  988.                                           '<'  => '<',
  989.                                           '"'  => '"',
  990.                                           '\'' => ''' ));
  991.                 break;
  992.             case PEAR_PackageFile_Generator_v2_XML_Util_ENTITIES_XML:
  993.                 return strtr($string,array(
  994.                                           '&'  => '&',
  995.                                           '>'  => '>',
  996.                                           '<'  => '<',
  997.                                           '"'  => '"',
  998.                                           '\'' => ''' ));
  999.                 break;
  1000.             case PEAR_PackageFile_Generator_v2_XML_Util_ENTITIES_XML_REQUIRED:
  1001.                 return strtr($string,array(
  1002.                                           '&'  => '&',
  1003.                                           '<'  => '<',
  1004.                                           '"'  => '"' ));
  1005.                 break;
  1006.             case PEAR_PackageFile_Generator_v2_XML_Util_ENTITIES_HTML:
  1007.                 return htmlspecialchars($string);
  1008.                 break;
  1009.         }
  1010.         return $string;
  1011.     }
  1012.  
  1013.    /**
  1014.     * build an xml declaration
  1015.     *
  1016.     * <code>
  1017.     * require_once 'XML/Util.php';
  1018.     * 
  1019.     * // get an XML declaration:
  1020.     * $xmlDecl = PEAR_PackageFile_Generator_v2_XML_Util::getXMLDeclaration("1.0", "UTF-8", true);
  1021.     * </code>
  1022.     *
  1023.     * @access   public
  1024.     * @static
  1025.     * @param    string  $version     xml version
  1026.     * @param    string  $encoding    character encoding
  1027.     * @param    boolean $standAlone  document is standalone (or not)
  1028.     * @return   string  $decl xml declaration
  1029.     * @uses     PEAR_PackageFile_Generator_v2_XML_Util::attributesToString() to serialize the attributes of the XML declaration
  1030.     */
  1031.     function getXMLDeclaration($version = "1.0", $encoding = null, $standalone = null)
  1032.     {
  1033.         $attributes = array(
  1034.                             "version" => $version,
  1035.                            );
  1036.         // add encoding
  1037.         if ($encoding !== null) {
  1038.             $attributes["encoding"] = $encoding;
  1039.         }
  1040.         // add standalone, if specified
  1041.         if ($standalone !== null) {
  1042.             $attributes["standalone"] = $standalone ? "yes" : "no";
  1043.         }
  1044.         
  1045.         return sprintf("<?xml%s?>", PEAR_PackageFile_Generator_v2_XML_Util::attributesToString($attributes, false));
  1046.     }
  1047.  
  1048.    /**
  1049.     * build a document type declaration
  1050.     *
  1051.     * <code>
  1052.     * require_once 'XML/Util.php';
  1053.     * 
  1054.     * // get a doctype declaration:
  1055.     * $xmlDecl = PEAR_PackageFile_Generator_v2_XML_Util::getDocTypeDeclaration("rootTag","myDocType.dtd");
  1056.     * </code>
  1057.     *
  1058.     * @access   public
  1059.     * @static
  1060.     * @param    string  $root         name of the root tag
  1061.     * @param    string  $uri          uri of the doctype definition (or array with uri and public id)
  1062.     * @param    string  $internalDtd  internal dtd entries   
  1063.     * @return   string  $decl         doctype declaration
  1064.     * @since    0.2
  1065.     */
  1066.     function getDocTypeDeclaration($root, $uri = null, $internalDtd = null)
  1067.     {
  1068.         if (is_array($uri)) {
  1069.             $ref = sprintf( ' PUBLIC "%s" "%s"', $uri["id"], $uri["uri"] );
  1070.         } elseif (!empty($uri)) {
  1071.             $ref = sprintf( ' SYSTEM "%s"', $uri );
  1072.         } else {
  1073.             $ref = "";
  1074.         }
  1075.  
  1076.         if (empty($internalDtd)) {
  1077.             return sprintf("<!DOCTYPE %s%s>", $root, $ref);
  1078.         } else {
  1079.             return sprintf("<!DOCTYPE %s%s [\n%s\n]>", $root, $ref, $internalDtd);
  1080.         }
  1081.     }
  1082.  
  1083.    /**
  1084.     * create string representation of an attribute list
  1085.     *
  1086.     * <code>
  1087.     * require_once 'XML/Util.php';
  1088.     * 
  1089.     * // build an attribute string
  1090.     * $att = array(
  1091.     *              "foo"   =>  "bar",
  1092.     *              "argh"  =>  "tomato"
  1093.     *            );
  1094.     *
  1095.     * $attList = PEAR_PackageFile_Generator_v2_XML_Util::attributesToString($att);    
  1096.     * </code>
  1097.     *
  1098.     * @access   public
  1099.     * @static
  1100.     * @param    array         $attributes        attribute array
  1101.     * @param    boolean|array $sort              sort attribute list alphabetically, may also be an assoc array containing the keys 'sort', 'multiline', 'indent', 'linebreak' and 'entities'
  1102.     * @param    boolean       $multiline         use linebreaks, if more than one attribute is given
  1103.     * @param    string        $indent            string used for indentation of multiline attributes
  1104.     * @param    string        $linebreak         string used for linebreaks of multiline attributes
  1105.     * @param    integer       $entities          setting for entities in attribute values (one of PEAR_PackageFile_Generator_v2_XML_Util_ENTITIES_NONE, PEAR_PackageFile_Generator_v2_XML_Util_ENTITIES_XML, PEAR_PackageFile_Generator_v2_XML_Util_ENTITIES_XML_REQUIRED, PEAR_PackageFile_Generator_v2_XML_Util_ENTITIES_HTML)
  1106.     * @return   string                           string representation of the attributes
  1107.     * @uses     PEAR_PackageFile_Generator_v2_XML_Util::replaceEntities() to replace XML entities in attribute values
  1108.     * @todo     allow sort also to be an options array
  1109.     */
  1110.     function attributesToString($attributes, $sort = true, $multiline = false, $indent = '    ', $linebreak = "\n", $entities = PEAR_PackageFile_Generator_v2_XML_Util_ENTITIES_XML)
  1111.     {
  1112.         /**
  1113.          * second parameter may be an array
  1114.          */
  1115.         if (is_array($sort)) {
  1116.             if (isset($sort['multiline'])) {
  1117.                 $multiline = $sort['multiline'];
  1118.             }
  1119.             if (isset($sort['indent'])) {
  1120.                 $indent = $sort['indent'];
  1121.             }
  1122.             if (isset($sort['linebreak'])) {
  1123.                 $multiline = $sort['linebreak'];
  1124.             }
  1125.             if (isset($sort['entities'])) {
  1126.                 $entities = $sort['entities'];
  1127.             }
  1128.             if (isset($sort['sort'])) {
  1129.                 $sort = $sort['sort'];
  1130.             } else {
  1131.                 $sort = true;
  1132.             }
  1133.         }
  1134.         $string = '';
  1135.         if (is_array($attributes) && !empty($attributes)) {
  1136.             if ($sort) {
  1137.                 ksort($attributes);
  1138.             }
  1139.             if( !$multiline || count($attributes) == 1) {
  1140.                 foreach ($attributes as $key => $value) {
  1141.                     if ($entities != PEAR_PackageFile_Generator_v2_XML_Util_ENTITIES_NONE) {
  1142.                         $value = PEAR_PackageFile_Generator_v2_XML_Util::replaceEntities($value, $entities);
  1143.                     }
  1144.                     $string .= ' '.$key.'="'.$value.'"';
  1145.                 }
  1146.             } else {
  1147.                 $first = true;
  1148.                 foreach ($attributes as $key => $value) {
  1149.                     if ($entities != PEAR_PackageFile_Generator_v2_XML_Util_ENTITIES_NONE) {
  1150.                         $value = PEAR_PackageFile_Generator_v2_XML_Util::replaceEntities($value, $entities);
  1151.                     }
  1152.                     if ($first) {
  1153.                         $string .= " ".$key.'="'.$value.'"';
  1154.                         $first = false;
  1155.                     } else {
  1156.                         $string .= $linebreak.$indent.$key.'="'.$value.'"';
  1157.                     }
  1158.                 }
  1159.             }
  1160.         }
  1161.         return $string;
  1162.     }
  1163.  
  1164.    /**
  1165.     * create a tag
  1166.     *
  1167.     * This method will call PEAR_PackageFile_Generator_v2_XML_Util::createTagFromArray(), which
  1168.     * is more flexible.
  1169.     *
  1170.     * <code>
  1171.     * require_once 'XML/Util.php';
  1172.     * 
  1173.     * // create an XML tag:
  1174.     * $tag = PEAR_PackageFile_Generator_v2_XML_Util::createTag("myNs:myTag", array("foo" => "bar"), "This is inside the tag", "http://www.w3c.org/myNs#");
  1175.     * </code>
  1176.     *
  1177.     * @access   public
  1178.     * @static
  1179.     * @param    string  $qname             qualified tagname (including namespace)
  1180.     * @param    array   $attributes        array containg attributes
  1181.     * @param    mixed   $content
  1182.     * @param    string  $namespaceUri      URI of the namespace
  1183.     * @param    integer $replaceEntities   whether to replace XML special chars in content, embedd it in a CData section or none of both
  1184.     * @param    boolean $multiline         whether to create a multiline tag where each attribute gets written to a single line
  1185.     * @param    string  $indent            string used to indent attributes (_auto indents attributes so they start at the same column)
  1186.     * @param    string  $linebreak         string used for linebreaks
  1187.     * @param    string  $encoding          encoding that should be used to translate content
  1188.     * @return   string  $string            XML tag
  1189.     * @see      PEAR_PackageFile_Generator_v2_XML_Util::createTagFromArray()
  1190.     * @uses     PEAR_PackageFile_Generator_v2_XML_Util::createTagFromArray() to create the tag
  1191.     */
  1192.     function createTag($qname, $attributes = array(), $content = null, $namespaceUri = null, $replaceEntities = PEAR_PackageFile_Generator_v2_XML_Util_REPLACE_ENTITIES, $multiline = false, $indent = "_auto", $linebreak = "\n", $encoding = PEAR_PackageFile_Generator_v2_XML_Util_ENTITIES_XML)
  1193.     {
  1194.         $tag = array(
  1195.                      "qname"      => $qname,
  1196.                      "attributes" => $attributes
  1197.                     );
  1198.  
  1199.         // add tag content
  1200.         if ($content !== null) {
  1201.             $tag["content"] = $content;
  1202.         }
  1203.         
  1204.         // add namespace Uri
  1205.         if ($namespaceUri !== null) {
  1206.             $tag["namespaceUri"] = $namespaceUri;
  1207.         }
  1208.  
  1209.         return PEAR_PackageFile_Generator_v2_XML_Util::createTagFromArray($tag, $replaceEntities, $multiline, $indent, $linebreak, $encoding);
  1210.     }
  1211.  
  1212.    /**
  1213.     * create a tag from an array
  1214.     * this method awaits an array in the following format
  1215.     * <pre>
  1216.     * array(
  1217.     *  "qname"        => $qname         // qualified name of the tag
  1218.     *  "namespace"    => $namespace     // namespace prefix (optional, if qname is specified or no namespace)
  1219.     *  "localpart"    => $localpart,    // local part of the tagname (optional, if qname is specified)
  1220.     *  "attributes"   => array(),       // array containing all attributes (optional)
  1221.     *  "content"      => $content,      // tag content (optional)
  1222.     *  "namespaceUri" => $namespaceUri  // namespaceUri for the given namespace (optional)
  1223.     *   )
  1224.     * </pre>
  1225.     *
  1226.     * <code>
  1227.     * require_once 'XML/Util.php';
  1228.     * 
  1229.     * $tag = array(
  1230.     *           "qname"        => "foo:bar",
  1231.     *           "namespaceUri" => "http://foo.com",
  1232.     *           "attributes"   => array( "key" => "value", "argh" => "fruit&vegetable" ),
  1233.     *           "content"      => "I'm inside the tag",
  1234.     *            );
  1235.     * // creating a tag with qualified name and namespaceUri
  1236.     * $string = PEAR_PackageFile_Generator_v2_XML_Util::createTagFromArray($tag);
  1237.     * </code>
  1238.     *
  1239.     * @access   public
  1240.     * @static
  1241.     * @param    array   $tag               tag definition
  1242.     * @param    integer $replaceEntities   whether to replace XML special chars in content, embedd it in a CData section or none of both
  1243.     * @param    boolean $multiline         whether to create a multiline tag where each attribute gets written to a single line
  1244.     * @param    string  $indent            string used to indent attributes (_auto indents attributes so they start at the same column)
  1245.     * @param    string  $linebreak         string used for linebreaks
  1246.     * @return   string  $string            XML tag
  1247.     * @see      PEAR_PackageFile_Generator_v2_XML_Util::createTag()
  1248.     * @uses     PEAR_PackageFile_Generator_v2_XML_Util::attributesToString() to serialize the attributes of the tag
  1249.     * @uses     PEAR_PackageFile_Generator_v2_XML_Util::splitQualifiedName() to get local part and namespace of a qualified name
  1250.     */
  1251.     function createTagFromArray($tag, $replaceEntities = PEAR_PackageFile_Generator_v2_XML_Util_REPLACE_ENTITIES, $multiline = false, $indent = "_auto", $linebreak = "\n", $encoding = PEAR_PackageFile_Generator_v2_XML_Util_ENTITIES_XML)
  1252.     {
  1253.         if (isset($tag["content"]) && !is_scalar($tag["content"])) {
  1254.             return PEAR_PackageFile_Generator_v2_XML_Util::raiseError( "Supplied non-scalar value as tag content", PEAR_PackageFile_Generator_v2_XML_Util_ERROR_NON_SCALAR_CONTENT );
  1255.         }
  1256.  
  1257.         if (!isset($tag['qname']) && !isset($tag['localPart'])) {
  1258.             return PEAR_PackageFile_Generator_v2_XML_Util::raiseError( 'You must either supply a qualified name (qname) or local tag name (localPart).', PEAR_PackageFile_Generator_v2_XML_Util_ERROR_NO_TAG_NAME );
  1259.         }
  1260.  
  1261.         // if no attributes hav been set, use empty attributes
  1262.         if (!isset($tag["attributes"]) || !is_array($tag["attributes"])) {
  1263.             $tag["attributes"] = array();
  1264.         }
  1265.         
  1266.         // qualified name is not given
  1267.         if (!isset($tag["qname"])) {
  1268.             // check for namespace
  1269.             if (isset($tag["namespace"]) && !empty($tag["namespace"])) {
  1270.                 $tag["qname"] = $tag["namespace"].":".$tag["localPart"];
  1271.             } else {
  1272.                 $tag["qname"] = $tag["localPart"];
  1273.             }
  1274.         // namespace URI is set, but no namespace
  1275.         } elseif (isset($tag["namespaceUri"]) && !isset($tag["namespace"])) {
  1276.             $parts = PEAR_PackageFile_Generator_v2_XML_Util::splitQualifiedName($tag["qname"]);
  1277.             $tag["localPart"] = $parts["localPart"];
  1278.             if (isset($parts["namespace"])) {
  1279.                 $tag["namespace"] = $parts["namespace"];
  1280.             }
  1281.         }
  1282.  
  1283.         if (isset($tag["namespaceUri"]) && !empty($tag["namespaceUri"])) {
  1284.             // is a namespace given
  1285.             if (isset($tag["namespace"]) && !empty($tag["namespace"])) {
  1286.                 $tag["attributes"]["xmlns:".$tag["namespace"]] = $tag["namespaceUri"];
  1287.             } else {
  1288.                 // define this Uri as the default namespace
  1289.                 $tag["attributes"]["xmlns"] = $tag["namespaceUri"];
  1290.             }
  1291.         }
  1292.  
  1293.         // check for multiline attributes
  1294.         if ($multiline === true) {
  1295.             if ($indent === "_auto") {
  1296.                 $indent = str_repeat(" ", (strlen($tag["qname"])+2));
  1297.             }
  1298.         }
  1299.         
  1300.         // create attribute list
  1301.         $attList    =   PEAR_PackageFile_Generator_v2_XML_Util::attributesToString($tag["attributes"], true, $multiline, $indent, $linebreak );
  1302.         if (!isset($tag["content"]) || (string)$tag["content"] == '') {
  1303.             $tag    =   sprintf("<%s%s />", $tag["qname"], $attList);
  1304.         } else {
  1305.             if ($replaceEntities == PEAR_PackageFile_Generator_v2_XML_Util_REPLACE_ENTITIES) {
  1306.                 $tag["content"] = PEAR_PackageFile_Generator_v2_XML_Util::replaceEntities($tag["content"], $encoding);
  1307.             } elseif ($replaceEntities == PEAR_PackageFile_Generator_v2_XML_Util_CDATA_SECTION) {
  1308.                 $tag["content"] = PEAR_PackageFile_Generator_v2_XML_Util::createCDataSection($tag["content"]);
  1309.             }
  1310.             $tag    =   sprintf("<%s%s>%s</%s>", $tag["qname"], $attList, $tag["content"], $tag["qname"] );
  1311.         }        
  1312.         return  $tag;
  1313.     }
  1314.  
  1315.    /**
  1316.     * create a start element
  1317.     *
  1318.     * <code>
  1319.     * require_once 'XML/Util.php';
  1320.     * 
  1321.     * // create an XML start element:
  1322.     * $tag = PEAR_PackageFile_Generator_v2_XML_Util::createStartElement("myNs:myTag", array("foo" => "bar") ,"http://www.w3c.org/myNs#");
  1323.     * </code>
  1324.     *
  1325.     * @access   public
  1326.     * @static
  1327.     * @param    string  $qname             qualified tagname (including namespace)
  1328.     * @param    array   $attributes        array containg attributes
  1329.     * @param    string  $namespaceUri      URI of the namespace
  1330.     * @param    boolean $multiline         whether to create a multiline tag where each attribute gets written to a single line
  1331.     * @param    string  $indent            string used to indent attributes (_auto indents attributes so they start at the same column)
  1332.     * @param    string  $linebreak         string used for linebreaks
  1333.     * @return   string  $string            XML start element
  1334.     * @see      PEAR_PackageFile_Generator_v2_XML_Util::createEndElement(), PEAR_PackageFile_Generator_v2_XML_Util::createTag()
  1335.     */
  1336.     function createStartElement($qname, $attributes = array(), $namespaceUri = null, $multiline = false, $indent = '_auto', $linebreak = "\n")
  1337.     {
  1338.         // if no attributes hav been set, use empty attributes
  1339.         if (!isset($attributes) || !is_array($attributes)) {
  1340.             $attributes = array();
  1341.         }
  1342.         
  1343.         if ($namespaceUri != null) {
  1344.             $parts = PEAR_PackageFile_Generator_v2_XML_Util::splitQualifiedName($qname);
  1345.         }
  1346.  
  1347.         // check for multiline attributes
  1348.         if ($multiline === true) {
  1349.             if ($indent === "_auto") {
  1350.                 $indent = str_repeat(" ", (strlen($qname)+2));
  1351.             }
  1352.         }
  1353.  
  1354.         if ($namespaceUri != null) {
  1355.             // is a namespace given
  1356.             if (isset($parts["namespace"]) && !empty($parts["namespace"])) {
  1357.                 $attributes["xmlns:".$parts["namespace"]] = $namespaceUri;
  1358.             } else {
  1359.                 // define this Uri as the default namespace
  1360.                 $attributes["xmlns"] = $namespaceUri;
  1361.             }
  1362.         }
  1363.  
  1364.         // create attribute list
  1365.         $attList    =   PEAR_PackageFile_Generator_v2_XML_Util::attributesToString($attributes, true, $multiline, $indent, $linebreak);
  1366.         $element    =   sprintf("<%s%s>", $qname, $attList);
  1367.         return  $element;
  1368.     }
  1369.  
  1370.    /**
  1371.     * create an end element
  1372.     *
  1373.     * <code>
  1374.     * require_once 'XML/Util.php';
  1375.     * 
  1376.     * // create an XML start element:
  1377.     * $tag = PEAR_PackageFile_Generator_v2_XML_Util::createEndElement("myNs:myTag");
  1378.     * </code>
  1379.     *
  1380.     * @access   public
  1381.     * @static
  1382.     * @param    string  $qname             qualified tagname (including namespace)
  1383.     * @return   string  $string            XML end element
  1384.     * @see      PEAR_PackageFile_Generator_v2_XML_Util::createStartElement(), PEAR_PackageFile_Generator_v2_XML_Util::createTag()
  1385.     */
  1386.     function createEndElement($qname)
  1387.     {
  1388.         $element    =   sprintf("</%s>", $qname);
  1389.         return  $element;
  1390.     }
  1391.     
  1392.    /**
  1393.     * create an XML comment
  1394.     *
  1395.     * <code>
  1396.     * require_once 'XML/Util.php';
  1397.     * 
  1398.     * // create an XML start element:
  1399.     * $tag = PEAR_PackageFile_Generator_v2_XML_Util::createComment("I am a comment");
  1400.     * </code>
  1401.     *
  1402.     * @access   public
  1403.     * @static
  1404.     * @param    string  $content           content of the comment
  1405.     * @return   string  $comment           XML comment
  1406.     */
  1407.     function createComment($content)
  1408.     {
  1409.         $comment    =   sprintf("<!-- %s -->", $content);
  1410.         return  $comment;
  1411.     }
  1412.     
  1413.    /**
  1414.     * create a CData section
  1415.     *
  1416.     * <code>
  1417.     * require_once 'XML/Util.php';
  1418.     * 
  1419.     * // create a CData section
  1420.     * $tag = PEAR_PackageFile_Generator_v2_XML_Util::createCDataSection("I am content.");
  1421.     * </code>
  1422.     *
  1423.     * @access   public
  1424.     * @static
  1425.     * @param    string  $data              data of the CData section
  1426.     * @return   string  $string            CData section with content
  1427.     */
  1428.     function createCDataSection($data)
  1429.     {
  1430.         return  sprintf("<![CDATA[%s]]>", $data);
  1431.     }
  1432.  
  1433.    /**
  1434.     * split qualified name and return namespace and local part
  1435.     *
  1436.     * <code>
  1437.     * require_once 'XML/Util.php';
  1438.     * 
  1439.     * // split qualified tag
  1440.     * $parts = PEAR_PackageFile_Generator_v2_XML_Util::splitQualifiedName("xslt:stylesheet");
  1441.     * </code>
  1442.     * the returned array will contain two elements:
  1443.     * <pre>
  1444.     * array(
  1445.     *       "namespace" => "xslt",
  1446.     *       "localPart" => "stylesheet"
  1447.     *      );
  1448.     * </pre>
  1449.     *
  1450.     * @access public
  1451.     * @static
  1452.     * @param  string    $qname      qualified tag name
  1453.     * @param  string    $defaultNs  default namespace (optional)
  1454.     * @return array     $parts      array containing namespace and local part
  1455.     */
  1456.     function splitQualifiedName($qname, $defaultNs = null)
  1457.     {
  1458.         if (strstr($qname, ':')) {
  1459.             $tmp = explode(":", $qname);
  1460.             return array(
  1461.                           "namespace" => $tmp[0],
  1462.                           "localPart" => $tmp[1]
  1463.                         );
  1464.         }
  1465.         return array(
  1466.                       "namespace" => $defaultNs,
  1467.                       "localPart" => $qname
  1468.                     );
  1469.     }
  1470.  
  1471.    /**
  1472.     * check, whether string is valid XML name
  1473.     *
  1474.     * <p>XML names are used for tagname, attribute names and various
  1475.     * other, lesser known entities.</p>
  1476.     * <p>An XML name may only consist of alphanumeric characters,
  1477.     * dashes, undescores and periods, and has to start with a letter
  1478.     * or an underscore.
  1479.     * </p>
  1480.     *
  1481.     * <code>
  1482.     * require_once 'XML/Util.php';
  1483.     * 
  1484.     * // verify tag name
  1485.     * $result = PEAR_PackageFile_Generator_v2_XML_Util::isValidName("invalidTag?");
  1486.     * if (PEAR_PackageFile_Generator_v2_XML_Util::isError($result)) {
  1487.     *    print "Invalid XML name: " . $result->getMessage();
  1488.     * }
  1489.     * </code>
  1490.     *
  1491.     * @access  public
  1492.     * @static
  1493.     * @param   string  $string string that should be checked
  1494.     * @return  mixed   $valid  true, if string is a valid XML name, PEAR error otherwise
  1495.     * @todo    support for other charsets
  1496.     */
  1497.     function isValidName($string)
  1498.     {
  1499.         // check for invalid chars
  1500.         if (!preg_match("/^[[:alnum:]_\-.]\\z/", $string{0})) {
  1501.             return PEAR_PackageFile_Generator_v2_XML_Util::raiseError( "XML names may only start with letter or underscore", PEAR_PackageFile_Generator_v2_XML_Util_ERROR_INVALID_START );
  1502.         }
  1503.         
  1504.         // check for invalid chars
  1505.         if (!preg_match("/^([a-zA-Z_]([a-zA-Z0-9_\-\.]*)?:)?[a-zA-Z_]([a-zA-Z0-9_\-\.]+)?\\z/", $string)) {
  1506.             return PEAR_PackageFile_Generator_v2_XML_Util::raiseError( "XML names may only contain alphanumeric chars, period, hyphen, colon and underscores", PEAR_PackageFile_Generator_v2_XML_Util_ERROR_INVALID_CHARS );
  1507.          }
  1508.         // XML name is valid
  1509.         return true;
  1510.     }
  1511.  
  1512.    /**
  1513.     * replacement for PEAR_PackageFile_Generator_v2_XML_Util::raiseError
  1514.     *
  1515.     * Avoids the necessity to always require
  1516.     * PEAR.php
  1517.     *
  1518.     * @access   public
  1519.     * @param    string      error message
  1520.     * @param    integer     error code
  1521.     * @return   object PEAR_Error
  1522.     */
  1523.     function raiseError($msg, $code)
  1524.     {
  1525.         require_once 'PEAR.php';
  1526.         return PEAR::raiseError($msg, $code);
  1527.     }
  1528. }
  1529. ?>