/**
  * @param string $path        full path to package file
  * @param string $packagefile (optional) name of package file
  * @param array  $options     (optional) list of generation options
  *
  * @throws PEAR_PACKAGEFILEMANAGER2_INVALID_PACKAGE
  * @throws PEAR_PACKAGEFILEMANAGER2_PATH_DOESNT_EXIST
  * @return true|PEAR_Error
  * @uses   _generateNewPackageXML() if no package.xml is found, it
  *          calls this to create a new one
  * @access private
  * @static
  * @since  1.6.0a1
  */
 function &_getExistingPackageXML($path, $packagefile = 'package.xml', $options = array())
 {
     if (is_string($path) && is_dir($path)) {
         $contents = false;
         if (file_exists($path . $packagefile)) {
             $contents = file_get_contents($path . $packagefile);
         }
         if (!$contents) {
             $a = PEAR_PackageFileManager2::_generateNewPackageXML();
             return $a;
         } else {
             include_once 'PEAR/PackageFile/Parser/v2.php';
             $pkg =& new PEAR_PackageFile_Parser_v2();
             $z =& PEAR_Config::singleton();
             $pkg->setConfig($z);
             $pf =& $pkg->parse($contents, $path . $packagefile, false, 'PEAR_PackageFileManager2');
             if (PEAR::isError($pf)) {
                 return $pf;
             }
             if (!$pf->validate(PEAR_VALIDATE_DOWNLOADING)) {
                 $errors = '';
                 foreach ($pf->getValidationWarnings() as $warning) {
                     $errors .= "\n" . ucfirst($warning['level']) . ': ' . $warning['message'];
                 }
                 if (php_sapi_name() != 'cli') {
                     $errors = nl2br(htmlspecialchars($errors));
                 }
                 $a = $pf->raiseError(PEAR_PACKAGEFILEMANAGER2_INVALID_PACKAGE, $errors);
                 return $a;
             }
             $pf->setOld();
             if (isset($options['cleardependencies']) && $options['cleardependencies']) {
                 $pf->clearDeps();
             }
             if (!isset($options['clearcontents']) || $options['clearcontents']) {
                 $pf->clearContents();
             } else {
                 // merge options is required to use PEAR_PackageFileManager2::addPostinstallTask()
                 if (PEAR::isError($ret = $pf->_importOptions($packagefile, $options))) {
                     return $ret;
                 }
                 $pf->_importTasks($options);
             }
         }
         return $pf;
     } else {
         if (!is_string($path)) {
             $path = gettype($path);
         }
         include_once 'PEAR.php';
         $a = PEAR::raiseError('Path does not exist: ' . $path, PEAR_PACKAGEFILEMANAGER2_PATH_DOESNT_EXIST);
         return $a;
     }
 }