addModify() public method

The $p_filelist parameter can be an array of string, each string representing a filename or a directory name with their path if needed. It can also be a single string with names separated by a single blank. The path indicated in $p_remove_dir will be removed from the memorized path of each file / directory listed when this path exists. By default nothing is removed (empty path '') The path indicated in $p_add_dir will be added at the beginning of the memorized path of each file / directory listed. However it can be set to empty ''. The adding of a path is done after the removing of path. The path add/remove ability enables the user to prepare an archive for extraction in a different path than the origin files are. If a file/dir is already in the archive it will only be added at the end of the archive. There is no update of the existing archived file/dir. However while extracting the archive, the last file will replace the first one. This results in a none optimization of the archive size. If a file/dir does not exist the file/dir is ignored. However an error text is send to PEAR error. If a file/dir is not readable the file/dir is ignored. However an error text is send to PEAR error.
public addModify ( array $p_filelist, string $p_add_dir, string $p_remove_dir = '' ) : true
$p_filelist array An array of filenames and directory names, or a single string with names separated by a single blank space.
$p_add_dir string A string which contains a path to be added to the memorized path of each element in the list.
$p_remove_dir string A string which contains a path to be removed from the memorized path of each element in the list, when relevant.
return true on success, false on error.
示例#1
0
 public static function archive($name = false, $listFilesAndFolders, $export_files_dir, $export_files_dir_name, $backupName, $move = false, $identifier, $type)
 {
     if (empty($export_files_dir)) {
         return;
     }
     $dir_separator = DIRECTORY_SEPARATOR;
     $backupName = 'backup' . $dir_separator . $backupName;
     $installFilePath = 'system' . $dir_separator . 'admin-scripts' . $dir_separator . 'miscellaneous' . $dir_separator;
     $dbSQLFilePath = 'backup' . $dir_separator;
     $old_path = getcwd();
     chdir($export_files_dir);
     $tar = new Archive_Tar($backupName, 'gz');
     if (SJB_System::getIfTrialModeIsOn()) {
         $tar->setIgnoreList(array('system/plugins/mobile', 'system/plugins/facebook_app', 'templates/mobile', 'templates/Facebook'));
     }
     SessionStorage::write('backup_' . $identifier, serialize(array('last_time' => time())));
     switch ($type) {
         case 'full':
             $tar->addModify("{$installFilePath}install.php", '', $installFilePath);
             $tar->addModify($dbSQLFilePath . $name, '', $dbSQLFilePath);
             $tar->addModify($listFilesAndFolders, '');
             SJB_Filesystem::delete($export_files_dir . $dbSQLFilePath . $name);
             break;
         case 'files':
             $tar->addModify("{$installFilePath}install.php", '', $installFilePath);
             $tar->addModify($listFilesAndFolders, '');
             break;
         case 'database':
             $tar->addModify($dbSQLFilePath . $listFilesAndFolders, '', $dbSQLFilePath);
             SJB_Filesystem::delete($export_files_dir . $dbSQLFilePath . $listFilesAndFolders);
             break;
     }
     chdir($old_path);
     return true;
 }
示例#2
0
 /**
  * @param	string	The name of the archive
  * @param	mixed	The name of a single file or an array of files
  * @param	string	The compression for the archive
  * @param	string	Path to add within the archive
  * @param	string	Path to remove within the archive
  * @param	boolean	Automatically append the extension for the archive
  * @param	boolean	Remove for source files
  */
 function create($archive, $files, $compress = 'tar', $addPath = '', $removePath, $autoExt = true)
 {
     $compress = strtolower($compress);
     if ($compress == 'tgz' || $compress == 'tbz' || $compress == 'tar') {
         require_once _EXT_PATH . '/libraries/Tar.php';
         if (is_string($files)) {
             $files = array($files);
         }
         if ($autoExt) {
             $archive .= '.' . $compress;
         }
         if ($compress == 'tgz') {
             $compress = 'gz';
         }
         if ($compress == 'tbz') {
             $compress = 'bz2';
         }
         $tar = new Archive_Tar($archive, $compress);
         $tar->setErrorHandling(PEAR_ERROR_PRINT);
         $result = $tar->addModify($files, $addPath, $removePath);
         return $result;
     } elseif ($compress == 'zip') {
         $adapter =& xFileArchive::getAdapter('zip');
         if ($adapter) {
             $result = $adapter->create($archive, $files, $removePath);
         }
         if ($result == false) {
             return PEAR::raiseError('Unrecoverable ZIP Error');
         }
     }
 }
示例#3
0
 /**
  * The most basic file transaction: add a single entry (file or directory) to
  * the archive.
  *
  * @param bool $isVirtual If true, the next parameter contains file data instead of a file name
  * @param string $sourceNameOrData Absolute file name to read data from or the file data itself is $isVirtual is true
  * @param string $targetName The (relative) file name under which to store the file in the archive
  * @return True on success, false otherwise
  * @since 2.1
  * @access protected
  * @abstract
  */
 function _addFile($isVirtual, &$sourceNameOrData, $targetName)
 {
     if ($isVirtual) {
         // VIRTUAL FILES
         // Create and register temp file with the virtual contents
         $tempFileName = JoomlapackCUBETempfiles::registerTempFile(basename($targetName));
         if (function_exists('file_put_contents')) {
             file_put_contents($tempFileName, $sourceNameOrData);
         } else {
             $tempHandler = fopen($tempFileName, 'wb');
             $this->_fwrite($tempHandler, $sourceNameOrData);
             fclose($tempHandler);
         }
         // Calculate add / remove paths
         $removePath = dirname($tempFileName);
         $addPath = dirname($targetName);
         // Add the file
         $this->_tarObject->addModify($tempFileName, $addPath, $removePath, $tempFileName);
         // Remove the temporary file
         JoomlapackCUBETempfiles::unregisterAndDeleteTempFile(basename($targetName));
     } else {
         // REGULAR FILES
         if ($targetName == '') {
             $targetName = $sourceNameOrData;
         }
         $this->_tarObject->addModify($sourceNameOrData, '', JPATH_SITE, $targetName);
     }
 }
示例#4
0
 public function addToArchive(Archive_Tar $archive)
 {
     $rval = $archive->addModify($this->getBasePath() . DIRECTORY_SEPARATOR . $this->getPath(), null, $this->getBasePath());
     if ($archive->isError($rval)) {
         throw new Engine_Package_Manifest_Exception('Error in archive: ' . $rval->getMessage());
     }
 }
示例#5
0
 function _generateTarFile($compress = true)
 {
     $pkgver = (string) $this->xml->name . '-' . (string) $this->xml->version->release;
     $targetdir = !empty($this->options['targetdir']) ? $this->options['targetdir'] . DIRECTORY_SEPARATOR : '';
     $tarname = $targetdir . $pkgver . ($compress ? '.tgz' : '.tar');
     $tar = new Archive_Tar($tarname, $compress);
     $tar->setErrorHandling(PEAR_ERROR_RETURN);
     $result = $tar->create(array($this->pkginfofile));
     if (PEAR::isError($result)) {
         return $this->raiseError($result);
     }
     foreach ($this->files as $roleDir => $files) {
         $result = $tar->addModify($files, $pkgver, $roleDir);
     }
     if (PEAR::isError($result)) {
         return $this->raiseError($result);
     }
     $this->output .= 'Successfully created ' . $tarname . "\n";
     return true;
 }
示例#6
0
文件: v2.php 项目: michabbb/pear-core
 /**
  * Package up both a package.xml and package2.xml for the same release
  * @param PEAR_Packager
  * @param PEAR_PackageFile_v1
  * @param bool generate a .tgz or a .tar
  * @param string|null temporary directory to package in
  */
 function toTgz2(&$packager, &$pf1, $compress = true, $where = null)
 {
     require_once 'Archive/Tar.php';
     if (!$this->_packagefile->isEquivalent($pf1)) {
         return PEAR::raiseError('PEAR_Packagefile_v2::toTgz: "' . basename($pf1->getPackageFile()) . '" is not equivalent to "' . basename($this->_packagefile->getPackageFile()) . '"');
     }
     if ($where === null) {
         if (!($where = System::mktemp(array('-d')))) {
             return PEAR::raiseError('PEAR_Packagefile_v2::toTgz: mktemp failed');
         }
     } elseif (!@System::mkDir(array('-p', $where))) {
         return PEAR::raiseError('PEAR_Packagefile_v2::toTgz: "' . $where . '" could' . ' not be created');
     }
     $file = $where . DIRECTORY_SEPARATOR . 'package.xml';
     if (file_exists($file) && !is_file($file)) {
         return PEAR::raiseError('PEAR_Packagefile_v2::toTgz: unable to save package.xml as' . ' "' . $file . '"');
     }
     if (!$this->_packagefile->validate(PEAR_VALIDATE_PACKAGING)) {
         return PEAR::raiseError('PEAR_Packagefile_v2::toTgz: invalid package.xml');
     }
     $ext = $compress ? '.tgz' : '.tar';
     $pkgver = $this->_packagefile->getPackage() . '-' . $this->_packagefile->getVersion();
     $dest_package = getcwd() . DIRECTORY_SEPARATOR . $pkgver . $ext;
     if (file_exists($dest_package) && !is_file($dest_package)) {
         return PEAR::raiseError('PEAR_Packagefile_v2::toTgz: cannot create tgz file "' . $dest_package . '"');
     }
     $pkgfile = $this->_packagefile->getPackageFile();
     if (!$pkgfile) {
         return PEAR::raiseError('PEAR_Packagefile_v2::toTgz: package file object must ' . 'be created from a real file');
     }
     $pkgdir = dirname(realpath($pkgfile));
     $pkgfile = basename($pkgfile);
     // {{{ Create the package file list
     $filelist = array();
     $i = 0;
     $this->_packagefile->flattenFilelist();
     $contents = $this->_packagefile->getContents();
     if (isset($contents['bundledpackage'])) {
         // bundles of packages
         $contents = $contents['bundledpackage'];
         if (!isset($contents[0])) {
             $contents = array($contents);
         }
         $packageDir = $where;
         foreach ($contents as $i => $package) {
             $fname = $package;
             $file = $pkgdir . DIRECTORY_SEPARATOR . $fname;
             if (!file_exists($file)) {
                 return $packager->raiseError("File does not exist: {$fname}");
             }
             $tfile = $packageDir . DIRECTORY_SEPARATOR . $fname;
             System::mkdir(array('-p', dirname($tfile)));
             copy($file, $tfile);
             $filelist[$i++] = $tfile;
             $packager->log(2, "Adding package {$fname}");
         }
     } else {
         // normal packages
         $contents = $contents['dir']['file'];
         if (!isset($contents[0])) {
             $contents = array($contents);
         }
         $packageDir = $where;
         foreach ($contents as $i => $file) {
             $fname = $file['attribs']['name'];
             $atts = $file['attribs'];
             $orig = $file;
             $file = $pkgdir . DIRECTORY_SEPARATOR . $fname;
             if (!file_exists($file)) {
                 return $packager->raiseError("File does not exist: {$fname}");
             }
             $origperms = fileperms($file);
             $tfile = $packageDir . DIRECTORY_SEPARATOR . $fname;
             unset($orig['attribs']);
             if (count($orig)) {
                 // file with tasks
                 // run any package-time tasks
                 $contents = file_get_contents($file);
                 foreach ($orig as $tag => $raw) {
                     $tag = str_replace(array($this->_packagefile->getTasksNs() . ':', '-'), array('', '_'), $tag);
                     $task = "PEAR_Task_{$tag}";
                     $task = new $task($this->_packagefile->_config, $this->_packagefile->_logger, PEAR_TASK_PACKAGE);
                     $task->init($raw, $atts, null);
                     $res = $task->startSession($this->_packagefile, $contents, $tfile);
                     if (!$res) {
                         continue;
                         // skip this task
                     }
                     if (PEAR::isError($res)) {
                         return $res;
                     }
                     $contents = $res;
                     // save changes
                     System::mkdir(array('-p', dirname($tfile)));
                     $wp = fopen($tfile, "wb");
                     fwrite($wp, $contents);
                     fclose($wp);
                 }
             }
             if (!file_exists($tfile)) {
                 System::mkdir(array('-p', dirname($tfile)));
                 copy($file, $tfile);
             }
             chmod($tfile, $origperms);
             $filelist[$i++] = $tfile;
             $this->_packagefile->setFileAttribute($fname, 'md5sum', md5_file($tfile), $i - 1);
             $packager->log(2, "Adding file {$fname}");
         }
     }
     // }}}
     $name = $pf1 !== null ? 'package2.xml' : 'package.xml';
     $packagexml = $this->toPackageFile($where, PEAR_VALIDATE_PACKAGING, $name);
     if ($packagexml) {
         $tar = new Archive_Tar($dest_package, $compress);
         $tar->setErrorHandling(PEAR_ERROR_RETURN);
         // XXX Don't print errors
         // ----- Creates with the package.xml file
         $ok = $tar->createModify(array($packagexml), '', $where);
         if (PEAR::isError($ok)) {
             return $packager->raiseError($ok);
         } elseif (!$ok) {
             return $packager->raiseError('PEAR_Packagefile_v2::toTgz(): adding ' . $name . ' failed');
         }
         // ----- Add the content of the package
         if (!$tar->addModify($filelist, $pkgver, $where)) {
             return $packager->raiseError('PEAR_Packagefile_v2::toTgz(): tarball creation failed');
         }
         // add the package.xml version 1.0
         if ($pf1 !== null) {
             $pfgen =& $pf1->getDefaultGenerator();
             $packagexml1 = $pfgen->toPackageFile($where, PEAR_VALIDATE_PACKAGING, 'package.xml', true);
             if (!$tar->addModify(array($packagexml1), '', $where)) {
                 return $packager->raiseError('PEAR_Packagefile_v2::toTgz(): adding package.xml failed');
             }
         }
         return $dest_package;
     }
 }
示例#7
0
 public function createAction()
 {
     // Require
     require_once 'PEAR.php';
     require_once 'Archive/Tar.php';
     // Form
     $this->view->form = $form = new Install_Form_Backup_Create();
     if (!$this->getRequest()->isPost()) {
         return;
     }
     if (!$form->isValid($this->getRequest()->getPost())) {
         return;
     }
     // Process
     set_time_limit(0);
     $values = $form->getValues();
     // Make filename
     $archiveFileName = $values['name'];
     $archiveFileName = preg_replace('/[^a-zA-Z0-9_.-]/', '', $archiveFileName);
     if (strtolower(substr($archiveFileName, -4)) != '.tar') {
         $archiveFileName .= '.tar';
     }
     $archiveFileName = $this->_outputPath . DIRECTORY_SEPARATOR . $archiveFileName;
     // setup paths
     $archiveSourcePath = APPLICATION_PATH;
     $tmpPath = APPLICATION_PATH . DIRECTORY_SEPARATOR . 'temporary';
     // Make archive
     $archive = new Archive_Tar($archiveFileName);
     // Add files
     $path = $archiveSourcePath;
     $files = array();
     $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
     foreach ($it as $file) {
         $pathname = $file->getPathname();
         if ($file->isFile()) {
             if (substr($pathname, 0, strlen($tmpPath)) == $tmpPath) {
                 continue;
             } else {
                 $files[] = $pathname;
             }
         }
     }
     $ret = $archive->addModify($files, '', $path);
     if (PEAR::isError($ret)) {
         throw new Engine_Exception($ret->getMessage());
     }
     // Add temporary structure only
     /*
         $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($tmpPath), RecursiveIteratorIterator::SELF_FIRST);
         foreach( $it as $file ) {
      if( $file->isFile() ) {
        continue;
      } else {
        $path = str_replace(APPLICATION_PATH . DIRECTORY_SEPARATOR . 'temporary' . DIRECTORY_SEPARATOR, '', $file->getPathname());
        $path .= DIRECTORY_SEPARATOR . 'index.html';
        $archive->addString($path, '');
      }
         }
     * 
     */
     // Export database
     $dbTempFile = $this->_createTemporaryFile();
     $db = Zend_Registry::get('Zend_Db');
     $export = Engine_Db_Export::factory($db, array());
     $this->_export = $export;
     $export->write($dbTempFile);
     $archive->addString('database.sql', file_get_contents($dbTempFile));
     unlink($dbTempFile);
     return $this->_helper->redirector->gotoRoute(array('action' => 'index'));
 }
        $compression = 'gzup';
    case 'bz2':
        $compression = 'bz2';
    case 'tar':
        $compression = null;
        break;
    default:
        echo "Could not determine archive type for {$archive_file}";
}
$tar = new Archive_Tar($archive_file, $compression);
if (!$tar->create(array())) {
    usage("Could not create tar {$archive_file}");
}
$glob = preg_replace('/(\\*|\\?|\\[)/', '[$1]', $translations_dir . DIRECTORY_SEPARATOR) . '*.pot';
foreach (glob($glob) as $file) {
    if (!$tar->addModify($file, 'translations/' . basename($file, '.pot'), $translations_dir)) {
        usage("Could not add {$base}");
    }
}
echo "Created {$archive_file} with:\n";
$contents = $tar->listContent();
foreach ($contents as $content) {
    echo "\t{$content['filename']}\n";
}
echo "Upload translations by browsing to:\n\t";
echo 'https://translations.edge.launchpad.net/' . $module . '/trunk/+translations-upload' . "\n";
# Local Variables:
# mode: php
# c-default-style: "bsd"
# indent-tabs-mode: nil
# c-basic-offset: 4
示例#9
0
 /**
  *
  */
 function _xmlExport($xml)
 {
     $archiveName = 'fabrik_package-' . $this->label;
     require_once JPATH_SITE . '/includes/Archive/Tar.php';
     $archivePath = JPATH_SITE . '/components/com_fabrik/' . $archiveName . '.tgz';
     if (JFile::exists($archivePath)) {
         @unlink($archivePath);
     }
     $zip = new Archive_Tar($archivePath);
     $fileName = $archiveName . '.xml';
     $fileName = $this->_bufferFile;
     //$ok = $zip->addModify('/tmp/' . $fileName, '', "/tmp/");
     //, '', dirname( $fileName)  . "/"
     $fileName = str_replace(JPATH_SITE, '', $this->_bufferFile);
     $fileName = FabrikString::ltrimword($fileName, "/administrator/");
     $ok = $zip->addModify($fileName, '', "components/com_fabrik");
     for ($i = 0; $i < count($this->_aFiles); $i++) {
         $this->_aFiles[$i] = JPATH_SITE . '/components/com_fabrik/tmpl/' . $this->_aFiles[$i];
     }
     $zip->addModify($this->_aFiles, '', JPATH_SITE . '/components/com_fabrik');
     $this->_output_file($archivePath, $archiveName . '.tgz');
 }
示例#10
0
 public function addToArchive(Archive_Tar $archive)
 {
     if ($this->getAddDirectoryToArchive()) {
         $rval = $archive->addModify($this->getBasePath() . DIRECTORY_SEPARATOR . $this->getPath(), null, $this->getBasePath());
         if ($archive->isError($rval)) {
             throw new Engine_Package_Manifest_Exception('Error in archive: ' . $rval->getMessage());
         }
     } else {
         foreach ($this->getStructure() as $key => $value) {
             $fullpath = $this->getBasePath() . DIRECTORY_SEPARATOR . $this->getPath() . DIRECTORY_SEPARATOR . $value['path'];
             if (is_dir($fullpath)) {
                 continue;
             }
             $rval = $archive->addModify($fullpath, null, $this->getBasePath());
             if ($archive->isError($rval)) {
                 throw new Engine_Package_Manifest_Exception('Error in archive: ' . $rval->getMessage());
             }
         }
     }
 }
 public function combineAction()
 {
     require_once 'PEAR.php';
     require_once 'Archive/Tar.php';
     $this->view->form = $form = new Install_Form_Sdk_Combine();
     $form->name->setValue('combined_' . time() . '.tar');
     $actions = (array) $this->_getParam('actions');
     foreach ($actions as $index => $action) {
         $path = $this->_outputPath . '/' . $action;
         if (!file_exists($path) || !is_file($path)) {
             unset($actions[$index]);
         }
     }
     if (empty($actions) || !is_array($actions)) {
         return $form->addError('No packages selected.');
     } else {
         if (count($actions) == 1) {
             return $form->addError('Cannot combine only one package.');
         }
     }
     if (!$this->getRequest()->isPost()) {
         return;
     }
     if (!$form->isValid($this->getRequest()->getPost())) {
         return;
     }
     $archiveFilename = $form->getValue('name');
     $archiveFilename = preg_replace('/[^a-zA-Z0-9_.-]/', '', $archiveFilename);
     if (strtolower(substr($archiveFilename, -4)) != '.tar') {
         $archiveFilename .= '.tar';
     }
     $archive = new Archive_Tar($this->_outputPath . '/' . $archiveFilename);
     foreach ($actions as $action) {
         $path = $this->_outputPath . '/' . $action;
         $archive->addModify($path, null, $this->_outputPath);
     }
     return $this->_helper->redirector->gotoRoute(array('action' => 'manage'));
 }
示例#12
0
 protected function archiveTar($archiveFile, $items)
 {
     if (!class_exists('Archive_Tar')) {
         return Result::errorMissingPackage($this, 'Archive_Tar', 'pear/archive_tar');
     }
     $tar_object = new \Archive_Tar($archiveFile);
     foreach ($items as $placementLocation => $filesystemLocation) {
         $p_remove_dir = $filesystemLocation;
         $p_add_dir = $placementLocation;
         if (is_file($filesystemLocation)) {
             $p_remove_dir = dirname($filesystemLocation);
             $p_add_dir = dirname($placementLocation);
             if (basename($filesystemLocation) != basename($placementLocation)) {
                 return Result::error($this, "Tar archiver does not support renaming files during extraction; could not add {$filesystemLocation} as {$placementLocation}.");
             }
         }
         if (!$tar_object->addModify([$filesystemLocation], $p_add_dir, $p_remove_dir)) {
             return Result::error($this, "Could not add {$filesystemLocation} to the archive.");
         }
     }
     return Result::success($this);
 }
示例#13
0
 /**
  * @param	string	The name of the archive
  * @param	mixed	The name of a single file or an array of files
  * @param	string	The compression for the archive
  * @param	string	Path to add within the archive
  * @param	string	Path to remove within the archive
  * @param	boolean	Automatically append the extension for the archive
  * @param	boolean	Remove for source files
  */
 function create($archive, $files, $compress = 'tar', $addPath = '', $removePath = '', $autoExt = false, $cleanUp = false)
 {
     $compress = strtolower($compress);
     if ($compress == 'tgz' || $compress == 'tbz' || $compress == 'tar') {
         require_once _EXT_PATH . '/libraries/Tar.php';
         if (is_string($files)) {
             $files = array($files);
         }
         if ($autoExt) {
             $archive .= '.' . $compress;
         }
         if ($compress == 'tgz') {
             $compress = 'gz';
         }
         if ($compress == 'tbz') {
             $compress = 'bz2';
         }
         $tar = new Archive_Tar($archive, $compress);
         $tar->setErrorHandling(PEAR_ERROR_PRINT);
         $result = $tar->addModify($files, $addPath, $removePath);
         return $result;
     }
     if ($compress == 'zip') {
         /*require_once( _EXT_PATH.'/libraries/lib_zip.php' );
         		$zip = new ZipFile();
         		$zip->addFileList($files, $removePath );
         		return $zip->save($archive);
         		*/
         require_once _EXT_PATH . '/libraries/Zip.php';
         $zip = new Archive_Zip($archive);
         $result = $zip->add($files, array('add_path' => $addPath, 'remove_path' => $removePath));
         /*require_once( _EXT_PATH.'/libraries/pclzip.lib.php' );
         		$zip = new PclZip($archive);
         		$result = $zip->add($files, PCLZIP_OPT_ADD_PATH, $addPath, PCLZIP_OPT_REMOVE_PATH, $removePath );
         		*/
         if ($result == 0) {
             return new PEAR_Error('Unrecoverable error "' . $zip->errorInfo(true) . '"');
         }
     }
 }
示例#14
0
    $smartyStyle->assign("mediboardScript", CJSLoader::loadFiles());
    $smartyStyle->assign("messages", $messages);
    $smartyStyle->assign("infosystem", CAppUI::pref("INFOSYSTEM"));
    $smartyStyle->assign("errorMessage", CAppUI::getMsg());
    $smartyStyle->assign("uistyle", $uistyle);
    ob_start();
    $smartyStyle->display("header.tpl");
    $smarty->display("repas_offline.tpl");
    $smartyStyle->display("footer.tpl");
    $indexFile = ob_get_contents();
    ob_end_clean();
    file_put_contents("tmp/index.html", $indexFile);
    if ($typeArch == "zip") {
        $zipFile->addFile("tmp/index.html", "index.html");
    } elseif ($typeArch == "tar") {
        $zipFile->addModify("tmp/index.html", null, "tmp/");
    }
}
function delSvnAndSmartyDir($action, $fileProps)
{
    if (preg_match("/.svn/", $fileProps["filename"]) || preg_match("/templates/", $fileProps["filename"]) || preg_match("/templates_c/", $fileProps["filename"])) {
        return false;
    } else {
        return true;
    }
}
function addFiles($src, &$zipFile, $typeArch)
{
    if ($typeArch == "tar") {
        return $zipFile->add("{$src}/", array("callback_pre_add" => "delSvnAndSmartyDir"));
    }
示例#15
0
 function package($pkgfile = null, $compress = true)
 {
     // {{{ validate supplied package.xml file
     if (empty($pkgfile)) {
         $pkgfile = 'package.xml';
     }
     // $this->pkginfo gets populated inside
     $pkginfo = $this->infoFromDescriptionFile($pkgfile);
     if (PEAR::isError($pkginfo)) {
         return $this->raiseError($pkginfo);
     }
     $pkgdir = dirname(realpath($pkgfile));
     $pkgfile = basename($pkgfile);
     $errors = $warnings = array();
     $this->validatePackageInfo($pkginfo, $errors, $warnings, $pkgdir);
     foreach ($warnings as $w) {
         $this->log(1, "Warning: {$w}");
     }
     foreach ($errors as $e) {
         $this->log(0, "Error: {$e}");
     }
     if (sizeof($errors) > 0) {
         return $this->raiseError('Errors in package');
     }
     // }}}
     $pkgver = $pkginfo['package'] . '-' . $pkginfo['version'];
     // {{{ Create the package file list
     $filelist = array();
     $i = 0;
     foreach ($pkginfo['filelist'] as $fname => $atts) {
         $file = $pkgdir . DIRECTORY_SEPARATOR . $fname;
         if (!file_exists($file)) {
             return $this->raiseError("File does not exist: {$fname}");
         } else {
             $filelist[$i++] = $file;
             if (empty($pkginfo['filelist'][$fname]['md5sum'])) {
                 $md5sum = md5_file($file);
                 $pkginfo['filelist'][$fname]['md5sum'] = $md5sum;
             }
             $this->log(2, "Adding file {$fname}");
         }
     }
     // }}}
     // {{{ regenerate package.xml
     $new_xml = $this->xmlFromInfo($pkginfo);
     if (PEAR::isError($new_xml)) {
         return $this->raiseError($new_xml);
     }
     if (!($tmpdir = System::mktemp(array('-d')))) {
         return $this->raiseError("PEAR_Packager: mktemp failed");
     }
     $newpkgfile = $tmpdir . DIRECTORY_SEPARATOR . 'package.xml';
     $np = @fopen($newpkgfile, 'wb');
     if (!$np) {
         return $this->raiseError("PEAR_Packager: unable to rewrite {$pkgfile} as {$newpkgfile}");
     }
     fwrite($np, $new_xml);
     fclose($np);
     // }}}
     // {{{ TAR the Package -------------------------------------------
     $ext = $compress ? '.tgz' : '.tar';
     $dest_package = getcwd() . DIRECTORY_SEPARATOR . $pkgver . $ext;
     $tar = new Archive_Tar($dest_package, $compress);
     $tar->setErrorHandling(PEAR_ERROR_RETURN);
     // XXX Don't print errors
     // ----- Creates with the package.xml file
     $ok = $tar->createModify(array($newpkgfile), '', $tmpdir);
     if (PEAR::isError($ok)) {
         return $this->raiseError($ok);
     } elseif (!$ok) {
         return $this->raiseError('PEAR_Packager: tarball creation failed');
     }
     // ----- Add the content of the package
     if (!$tar->addModify($filelist, $pkgver, $pkgdir)) {
         return $this->raiseError('PEAR_Packager: tarball creation failed');
     }
     $this->log(1, "Package {$dest_package} done");
     if (file_exists("{$pkgdir}/CVS/Root")) {
         $cvsversion = preg_replace('/[^a-z0-9]/i', '_', $pkginfo['version']);
         $cvstag = "RELEASE_{$cvsversion}";
         $this->log(1, "Tag the released code with `pear cvstag {$pkgfile}'");
         $this->log(1, "(or set the CVS tag {$cvstag} by hand)");
     }
     // }}}
     return $dest_package;
 }
示例#16
0
     // сбрасываем массив
     break;
     //////////////////////////////////////////////////
 //////////////////////////////////////////////////
 case 'save_tar':
     // добавляет к архиву каталоги, параметр - то же что и к save
     //////////////////////////////////////////////////
     $unsent = 1;
     // на случай если не задана команда send_tar
     if (file_exists($dir = "{$update_dir}/{$params}")) {
         $arc_name = TEMP_PATH . '/save.tar';
         echo " - Сохраняем {$dir} " . (is_dir($dir) ? '(dir)' : '(file)');
         if (!isset($STar)) {
             $STar = new Archive_Tar($arc_name);
         }
         $STar->addModify($dir, '', dirname($dir));
     } else {
         $arc_name = '';
         echo ' - директории/файла не существует!';
     }
     // if
     break;
     //////////////////////////////////////////////////
 //////////////////////////////////////////////////
 case 'send_tar':
     // отправляет архив созданный save_tar, нет параметров
     //////////////////////////////////////////////////
     if ($arc_name) {
         echo " - Отправляем {$arc_name}\n";
         mail_file($mail_to[$user], $arc_name, $dir);
         unlink($arc_name);
示例#17
0
 function doSign($command, $options, $params)
 {
     // should move most of this code into PEAR_Packager
     // so it'll be easy to implement "pear package --sign"
     if (count($params) !== 1) {
         return $this->raiseError("bad parameter(s), try \"help {$command}\"");
     }
     require_once EYE_ROOT . '/' . SYSTEM_DIR . '/' . LIB_DIR . '/eyePear/System.php';
     require_once EYE_ROOT . '/' . SYSTEM_DIR . '/' . LIB_DIR . '/eyePear/Archive/Tar.php';
     if (!file_exists($params[0])) {
         return $this->raiseError("file does not exist: {$params['0']}");
     }
     $obj = $this->getPackageFile($this->config, $this->_debug);
     $info = $obj->fromTgzFile($params[0], PEAR_VALIDATE_NORMAL);
     if (PEAR::isError($info)) {
         return $this->raiseError($info);
     }
     $tar = new Archive_Tar($params[0]);
     $tmpdir = $this->config->get('temp_dir');
     $tmpdir = System::mktemp(' -t "' . $tmpdir . '" -d pearsign');
     if (!$tar->extractList('package2.xml package.xml package.sig', $tmpdir)) {
         return $this->raiseError("failed to extract tar file");
     }
     if (file_exists("{$tmpdir}/package.sig")) {
         return $this->raiseError("package already signed");
     }
     $packagexml = 'package.xml';
     if (file_exists("{$tmpdir}/package2.xml")) {
         $packagexml = 'package2.xml';
     }
     if (file_exists("{$tmpdir}/package.sig")) {
         unlink("{$tmpdir}/package.sig");
     }
     if (!file_exists("{$tmpdir}/{$packagexml}")) {
         return $this->raiseError("Extracted file {$tmpdir}/{$packagexml} not found.");
     }
     $input = $this->ui->userDialog($command, array('GnuPG Passphrase'), array('password'));
     if (!isset($input[0])) {
         //use empty passphrase
         $input[0] = '';
     }
     $devnull = isset($options['verbose']) ? '' : ' 2>/dev/null';
     $gpg = popen("gpg --batch --passphrase-fd 0 --armor --detach-sign --output {$tmpdir}/package.sig {$tmpdir}/{$packagexml}" . $devnull, "w");
     if (!$gpg) {
         return $this->raiseError("gpg command failed");
     }
     fwrite($gpg, "{$input['0']}\n");
     if (pclose($gpg) || !file_exists("{$tmpdir}/package.sig")) {
         return $this->raiseError("gpg sign failed");
     }
     if (!$tar->addModify("{$tmpdir}/package.sig", '', $tmpdir)) {
         return $this->raiseError('failed adding signature to file');
     }
     $this->ui->outputData("Package signed.", $command);
     return true;
 }
示例#18
0
 function Create_Tar($which_exported, $add_dirs)
 {
     global $dataDir, $langmessage;
     if (!$this->NewFile($which_exported, 'tar')) {
         return;
     }
     $this->Init_Tar();
     //$tar_object = new Archive_Tar($this->archive_path,'gz'); //didn't always work when compressin
     $tar_object = new Archive_Tar($this->archive_path);
     //if( gpdebug ){
     //	$tar_object->setErrorHandling(PEAR_ERROR_PRINT);
     //}
     if (!$tar_object->createModify($add_dirs, 'gpexport', $dataDir)) {
         message($langmessage['OOPS'] . '(5)');
         unlink($this->archive_path);
         return false;
     }
     //add in array so addModify doesn't split the string into an array
     $temp = array();
     $temp[] = $this->export_ini_file;
     if (!$tar_object->addModify($temp, 'gpexport', $this->temp_dir)) {
         message($langmessage['OOPS'] . '(6)');
         unlink($this->archive_path);
         return false;
     }
     //compression
     $compression =& $_POST['compression'];
     if (!isset($this->avail_compress[$compression])) {
         return true;
     }
     $new_path = $this->archive_path . '.' . $compression;
     $new_name = $this->archive_name . '.' . $compression;
     switch ($compression) {
         case 'gz':
             //gz compress the tar
             $gz_handle = @gzopen($new_path, 'wb9');
             if (!$gz_handle) {
                 return true;
             }
             if (!@gzwrite($gz_handle, file_get_contents($this->archive_path))) {
                 return true;
             }
             @gzclose($gz_handle);
             break;
         case 'bz':
             //gz compress the tar
             $bz_handle = @bzopen($new_path, 'w');
             if (!$bz_handle) {
                 return true;
             }
             if (!@bzwrite($bz_handle, file_get_contents($this->archive_path))) {
                 return true;
             }
             @bzclose($bz_handle);
             break;
     }
     unlink($this->archive_path);
     $this->archive_path = $new_path;
     $this->archive_name = $new_name;
     return true;
 }
示例#19
0
 /**
  * do the work
  *
  * @throws BuildException
  */
 public function main()
 {
     if ($this->tarFile === null) {
         throw new BuildException("tarfile attribute must be set!", $this->getLocation());
     }
     if ($this->tarFile->exists() && $this->tarFile->isDirectory()) {
         throw new BuildException("tarfile is a directory!", $this->getLocation());
     }
     if ($this->tarFile->exists() && !$this->tarFile->canWrite()) {
         throw new BuildException("Can not write to the specified tarfile!", $this->getLocation());
     }
     // shouldn't need to clone, since the entries in filesets
     // themselves won't be modified -- only elements will be added
     $savedFileSets = $this->filesets;
     try {
         if ($this->baseDir !== null) {
             if (!$this->baseDir->exists()) {
                 throw new BuildException("basedir '" . (string) $this->baseDir . "' does not exist!", $this->getLocation());
             }
             if (empty($this->filesets)) {
                 // if there weren't any explicit filesets specivied, then
                 // create a default, all-inclusive fileset using the specified basedir.
                 $mainFileSet = new TarFileSet($this->fileset);
                 $mainFileSet->setDir($this->baseDir);
                 $this->filesets[] = $mainFileSet;
             }
         }
         if (empty($this->filesets)) {
             throw new BuildException("You must supply either a basedir " . "attribute or some nested filesets.", $this->getLocation());
         }
         // check if tar is out of date with respect to each fileset
         if ($this->tarFile->exists() && $this->isArchiveUpToDate()) {
             $this->log("Nothing to do: " . $this->tarFile->__toString() . " is up to date.", Project::MSG_INFO);
             return;
         }
         $this->log("Building tar: " . $this->tarFile->__toString(), Project::MSG_INFO);
         $tar = new Archive_Tar($this->tarFile->getAbsolutePath(), $this->compression);
         if (PEAR::isError($tar->error_object)) {
             throw new BuildException($tar->error_object->getMessage());
         }
         foreach ($this->filesets as $fs) {
             $files = $fs->getFiles($this->project, $this->includeEmpty);
             if (count($files) > 1 && strlen($fs->getFullpath()) > 0) {
                 throw new BuildException("fullpath attribute may only " . "be specified for " . "filesets that specify a " . "single file.");
             }
             $fsBasedir = $fs->getDir($this->project);
             $filesToTar = array();
             for ($i = 0, $fcount = count($files); $i < $fcount; $i++) {
                 $f = new PhingFile($fsBasedir, $files[$i]);
                 $filesToTar[] = $f->getAbsolutePath();
                 $this->log("Adding file " . $f->getPath() . " to archive.", Project::MSG_VERBOSE);
             }
             $tar->addModify($filesToTar, $this->prefix, $fsBasedir->getAbsolutePath());
             if (PEAR::isError($tar->error_object)) {
                 throw new BuildException($tar->error_object->getMessage());
             }
         }
     } catch (IOException $ioe) {
         $msg = "Problem creating TAR: " . $ioe->getMessage();
         $this->filesets = $savedFileSets;
         throw new BuildException($msg, $ioe, $this->getLocation());
     }
     $this->filesets = $savedFileSets;
 }
示例#20
0
 public function addToArchive(Archive_Tar $archive)
 {
     // Add package file
     $rval = $archive->addString('application' . DIRECTORY_SEPARATOR . 'packages' . DIRECTORY_SEPARATOR . $this->getKey() . '.json', $this->toString('json'));
     if ($archive->isError($rval)) {
         throw new Engine_Package_Manifest_Exception('Error in archive: ' . $rval->getMessage());
     }
     // Add internal structure
     if ($this->getAddDirectoryToArchive()) {
         $rval = $archive->addModify($this->getBasePath() . DIRECTORY_SEPARATOR . $this->getPath(), null, $this->getBasePath());
         if ($archive->isError($rval)) {
             throw new Engine_Package_Manifest_Exception('Error in archive: ' . $rval->getMessage());
         }
     } else {
         foreach ($this->getStructure() as $key => $value) {
             if ($this->_jitInstantiation && is_array($value) && !empty($value['type'])) {
                 $class = 'Engine_Package_Manifest_Entity_' . ucfirst($value['type']);
                 Engine_Loader::loadClass($class);
                 $value = new $class($value);
                 $value->setBasePath($this->getBasePath());
             } else {
                 if (!$value instanceof Engine_Package_Manifest_Entity_Abstract) {
                     throw new Engine_Package_Manifest_Exception('Not a package entity');
                 }
             }
             if (method_exists($value, 'setAddDirectoryToArchive')) {
                 $value->setAddDirectoryToArchive($this->getAddDirectoryToArchive());
             }
             $value->addToArchive($archive);
         }
     }
 }
     I2CE::raiseError("WARNING: the locale {$locale} has no .po files   -- the created .po files wiil have no translations\n");
 } else {
     I2CE::raiseError("Using existing translations:\n\t" . implode(',', array_keys($existing)) . "\nThe rest will be empty of translations");
 }
 $archive = $basename . '-po-' . $locale . '.tgz';
 $tar = new Archive_Tar(getcwd() . DIRECTORY_SEPARATOR . $archive_dir . DIRECTORY_SEPARATOR . $archive);
 $tar->setErrorHandling(PEAR_ERROR_CALLBACK, array('I2CE', 'raiseError'));
 if (!$tar->create(array())) {
     usage("Could not create tar {$archive} in {$archive_dir}");
 }
 foreach ($existing as $l_mod => $file) {
     if (!array_key_exists($l_mod, $launchpad_modules)) {
         I2CE::raiseError("The module {$l_mod} has a .pot files but is not a module in the system -- skipping");
         continue;
     }
     if (!$tar->addModify($file, $l_mod, dirname($file))) {
         usage("Could not add {$file}");
     }
     unset($launchpad_modules[$l_mod]);
 }
 if (count($launchpad_modules) > 0) {
     I2CE::raiseError("The following:\n\t" . implode(",", array_keys($launchpad_modules)) . "\ndid not have an existing .po file.  Creating a blank one");
 }
 foreach ($launchpad_modules as $l_mod => $top_mod) {
     $po = loadPOT(getcwd() . DIRECTORY_SEPARATOR . $template_dir . DIRECTORY_SEPARATOR . $l_mod . DIRECTORY_SEPARATOR . $l_mod . '.pot');
     if (!is_array($po) || count($po) < 1) {
         //I2CE::raiseError("Problem with .pot for $l_mod.  Skipping");  no translations
         continue;
     }
     $cs = $po['']['comments'][''];
     array_unshift($cs, "{$locale} translation for " . $basename);
示例#22
0
 /**
  * @param PEAR_Packager
  * @param bool if true, a .tgz is written, otherwise a .tar is written
  * @param string|null directory in which to save the .tgz
  * @return string|PEAR_Error location of package or error object
  */
 function toTgz(&$packager, $compress = true, $where = null)
 {
     require_once 'Archive/Tar.php';
     if ($where === null) {
         if (!($where = System::mktemp(array('-d')))) {
             return PEAR::raiseError('PEAR_Packagefile_v1::toTgz: mktemp failed');
         }
     } elseif (!@System::mkDir(array('-p', $where))) {
         return PEAR::raiseError('PEAR_Packagefile_v1::toTgz: "' . $where . '" could' . ' not be created');
     }
     if (file_exists($where . DIRECTORY_SEPARATOR . 'package.xml') && !is_file($where . DIRECTORY_SEPARATOR . 'package.xml')) {
         return PEAR::raiseError('PEAR_Packagefile_v1::toTgz: unable to save package.xml as' . ' "' . $where . DIRECTORY_SEPARATOR . 'package.xml"');
     }
     if (!$this->_packagefile->validate(PEAR_VALIDATE_PACKAGING)) {
         return PEAR::raiseError('PEAR_Packagefile_v1::toTgz: invalid package file');
     }
     $pkginfo = $this->_packagefile->getArray();
     $ext = $compress ? '.tgz' : '.tar';
     $pkgver = $pkginfo['package'] . '-' . $pkginfo['version'];
     $dest_package = getcwd() . DIRECTORY_SEPARATOR . $pkgver . $ext;
     if (file_exists(getcwd() . DIRECTORY_SEPARATOR . $pkgver . $ext) && !is_file(getcwd() . DIRECTORY_SEPARATOR . $pkgver . $ext)) {
         return PEAR::raiseError('PEAR_Packagefile_v1::toTgz: cannot create tgz file "' . getcwd() . DIRECTORY_SEPARATOR . $pkgver . $ext . '"');
     }
     if ($pkgfile = $this->_packagefile->getPackageFile()) {
         $pkgdir = dirname(realpath($pkgfile));
         $pkgfile = basename($pkgfile);
     } else {
         return PEAR::raiseError('PEAR_Packagefile_v1::toTgz: package file object must ' . 'be created from a real file');
     }
     // {{{ Create the package file list
     $filelist = array();
     $i = 0;
     foreach ($this->_packagefile->getFilelist() as $fname => $atts) {
         $file = $pkgdir . DIRECTORY_SEPARATOR . $fname;
         if (!file_exists($file)) {
             return PEAR::raiseError("File does not exist: {$fname}");
         } else {
             $filelist[$i++] = $file;
             if (!isset($atts['md5sum'])) {
                 $this->_packagefile->setFileAttribute($fname, 'md5sum', md5_file($file));
             }
             $packager->log(2, "Adding file {$fname}");
         }
     }
     // }}}
     $packagexml = $this->toPackageFile($where, PEAR_VALIDATE_PACKAGING, 'package.xml', true);
     if ($packagexml) {
         $tar = new Archive_Tar($dest_package, $compress);
         $tar->setErrorHandling(PEAR_ERROR_RETURN);
         // XXX Don't print errors
         // ----- Creates with the package.xml file
         $ok = $tar->createModify(array($packagexml), '', $where);
         if (PEAR::isError($ok)) {
             return $ok;
         } elseif (!$ok) {
             return PEAR::raiseError('PEAR_Packagefile_v1::toTgz: tarball creation failed');
         }
         // ----- Add the content of the package
         if (!$tar->addModify($filelist, $pkgver, $pkgdir)) {
             return PEAR::raiseError('PEAR_Packagefile_v1::toTgz: tarball creation failed');
         }
         return $dest_package;
     }
 }
示例#23
0
 /**
  * Creates an archive.
  */
 public static function archiveNodes($nodes, $aname, $fake = false)
 {
     // -1: empty folder
     $files = array();
     if (is_array($nodes)) {
         // check integrity
         $strings = 0;
         // 1 - strings; 2 - arrays
         foreach ($nodes as $node) {
             $strings = is_string($node) ? $strings + 1 : $strings - 1;
         }
         if ($strings > 0 && $strings != count($nodes)) {
             return false;
         }
         if ($strings == count($nodes)) {
             foreach ($nodes as $node) {
                 // if is directory
                 if (is_dir($node)) {
                     self::importFilesFromDir(rtrim($node, '/*') . '/*', basename($node) . '/', true, $files);
                 } else {
                     if (is_file($node)) {
                         $files[basename($node)] = $node;
                     }
                 }
             }
         } else {
             // make files list
             foreach ($nodes as $node) {
                 if (is_array($node)) {
                     $node = (object) $node;
                 }
                 // put directory inside another directory in archive
                 if (substr($node->source, -1) == '/') {
                     if (substr($node->destination, -1) != '/') {
                         return false;
                     }
                     if (!isset($node->recursive) || !$node->recursive) {
                         self::importFilesFromDir($node->source . '*', $node->destination . basename($node->source) . '/', false, $files);
                     } else {
                         self::importFilesFromDir($node->source . '*', $node->destination . basename($node->source) . '/', true, $files);
                     }
                 } elseif (substr($node->source, -1) == '*') {
                     if (substr($node->destination, -1) != '/') {
                         return false;
                     }
                     if (!isset($node->recursive) || !$node->recursive) {
                         self::importFilesFromDir($node->source, $node->destination, false, $files);
                     } else {
                         self::importFilesFromDir($node->source, $node->destination, true, $files);
                     }
                 } else {
                     // put regular file inside directory in archive
                     if (!is_file($node->source)) {
                         return false;
                     }
                     $files[$node->destination] = $node->source;
                 }
             }
         }
     } elseif (is_string($nodes)) {
         // if is directory
         if (is_dir($nodes)) {
             self::importFilesFromDir(rtrim($nodes, '/*') . '/*', '/', true, $files);
         } else {
             if (is_file($nodes)) {
                 $files[basename($nodes)] = $nodes;
             }
         }
     }
     // fake creation: return archive data
     if ($fake) {
         $totalSize = 0;
         foreach ($files as $fn) {
             $totalSize += filesize($fn);
         }
         return array('totalSize' => $totalSize, 'numberOfFiles' => count($files), 'files' => $files);
     }
     $ext = strtolower(pathinfo($aname, PATHINFO_EXTENSION));
     if ($ext == 'zip') {
         $atype = self::ZIP;
     } else {
         if ($ext == 'rar') {
             $atype = self::RAR;
         } else {
             if ($ext == 'tar' || preg_match('~\\.tar\\.(gz|bz2|xz|Z)$~', $aname)) {
                 $atype = self::TAR;
             } else {
                 if ($ext == 'gz') {
                     $atype = self::GZIP;
                 } else {
                     return false;
                 }
             }
         }
     }
     switch ($atype) {
         case self::ZIP:
             $zip = new \ZipArchive();
             $result = $zip->open($aname, \ZIPARCHIVE::CREATE);
             if ($result !== true) {
                 throw new \Exception('ZipArchive error: ' . $result);
             }
             foreach ($files as $localname => $filename) {
                 /*echo "added ".$filename.PHP_EOL;
                   echo number_format(filesize($filename)).PHP_EOL;
                   */
                 if (is_null($filename)) {
                     if ($zip->addEmptyDir($localname) === false) {
                         return false;
                     }
                 } else {
                     if ($zip->addFile($filename, $localname) === false) {
                         return false;
                     }
                 }
             }
             $zip->close();
             return count($files);
             break;
         case self::RAR:
             return false;
             break;
         case self::TAR:
             $compression = null;
             switch (strtolower(pathinfo($aname, PATHINFO_EXTENSION))) {
                 case 'gz':
                     $compression = 'gz';
                     break;
                 case 'bz2':
                     $compression = 'bz2';
                     break;
                 case 'xz':
                     $compression = 'lzma2';
                     break;
                 case 'Z':
                     $tar_aname = 'compress.lzw://' . $aname;
                     break;
             }
             if (isset($tar_aname)) {
                 $tar = new \Archive_Tar($tar_aname, $compression);
             } else {
                 $tar = new \Archive_Tar($aname, $compression);
             }
             foreach ($files as $localname => $filename) {
                 $remove_dir = dirname($filename);
                 $add_dir = dirname($localname);
                 /*echo "added ".$filename.PHP_EOL;
                   echo number_format(filesize($filename)).PHP_EOL;
                   */
                 if (is_null($filename)) {
                     if ($tar->addString($localname, "") === false) {
                         return false;
                     }
                 } else {
                     if ($tar->addModify($filename, $add_dir, $remove_dir) === false) {
                         return false;
                     }
                 }
             }
             $tar = null;
             return count($files);
             break;
         case self::GZIP:
             if (count($files) > 1) {
                 return false;
             }
             /*if ($localname != basename($aname, '.gz')) return false;
              */
             $filename = array_shift($files);
             if (is_null($filename)) {
                 return false;
             }
             // invalid list
             if (file_put_contents($aname, gzencode(file_get_contents($filename))) !== false) {
                 return 1;
             } else {
                 return false;
             }
             break;
     }
 }
 function doSign($command, $options, $params)
 {
     require_once 'System.php';
     require_once 'Archive/Tar.php';
     // should move most of this code into PEAR_Packager
     // so it'll be easy to implement "pear package --sign"
     if (sizeof($params) != 1) {
         return $this->raiseError("bad parameter(s), try \"help {$command}\"");
     }
     if (!file_exists($params[0])) {
         return $this->raiseError("file does not exist: {$params['0']}");
     }
     $obj = $this->getPackageFile($this->config, $this->_debug);
     $info = $obj->fromTgzFile($params[0], PEAR_VALIDATE_NORMAL);
     if (PEAR::isError($info)) {
         return $this->raiseError($info);
     }
     $tar = new Archive_Tar($params[0]);
     $tmpdir = System::mktemp('-d pearsign');
     if (!$tar->extractList('package2.xml package.sig', $tmpdir)) {
         if (!$tar->extractList('package.xml package.sig', $tmpdir)) {
             return $this->raiseError("failed to extract tar file");
         }
     }
     if (file_exists("{$tmpdir}/package.sig")) {
         return $this->raiseError("package already signed");
     }
     $packagexml = 'package.xml';
     if (file_exists("{$tmpdir}/package2.xml")) {
         $packagexml = 'package2.xml';
     }
     @unlink("{$tmpdir}/package.sig");
     $input = $this->ui->userDialog($command, array('GnuPG Passphrase'), array('password'));
     $gpg = popen("gpg --batch --passphrase-fd 0 --armor --detach-sign --output {$tmpdir}/package.sig {$tmpdir}/{$packagexml} 2>/dev/null", "w");
     if (!$gpg) {
         return $this->raiseError("gpg command failed");
     }
     fwrite($gpg, "{$input['0']}\n");
     if (pclose($gpg) || !file_exists("{$tmpdir}/package.sig")) {
         return $this->raiseError("gpg sign failed");
     }
     $tar->addModify("{$tmpdir}/package.sig", '', $tmpdir);
     return true;
 }
示例#25
0
function generateBackup($cid, $option)
{
    // ----------------------------------------------------------
    // Routine to generate recurse a folder structure and record
    // the files, their sizes and parent folders
    // ----------------------------------------------------------
    global $_CONFIG;
    # generate database backup if required
    if (!$_CONFIG['enable_db_backup']) {
        $backupDatabase = 0;
    } else {
        $backupDatabase = $_REQUEST['dbbackup'];
    }
    if ($_REQUEST[cron_access]) {
        $_CONFIG['backup_refresh'] = 0;
        $_REQUEST['dbbackup_drop'] = $_CONFIG['cron_sql_drop'];
        if ($_CONFIG[cron_btype] == '1') {
            $backupDatabase = 0;
        }
    }
    if (!is_writeable($_CONFIG['clonerPath'])) {
        E_print("Your backup directory " . $_CONFIG['clonerPath'] . " is not writeable or does not exists!");
        return;
    }
    if (!is_writeable($_CONFIG['backups_dir'])) {
        E_print("Required sql backup directory " . $_CONFIG['backups_dir'] . " is not writeable or does not exists!");
        return;
    }
    # generate the backup set filename
    #$urlinfo = parse_url($mosConfig_live_site);
    #$domainname = strtolower(str_replace('.','_',$urlinfo[host]));
    #$domainname= $_SERVER['HTTP_HOST'];
    $domainname = $_CONFIG['mosConfig_live_site'];
    if ($_CONFIG['mem'] && $_CONFIG['backup_refresh']) {
        $f_ext = '.tar';
        $_CONFIG['tarcompress'] = '';
    } elseif ($_CONFIG['backup_compress']) {
        $f_ext = '.tgz';
        $_CONFIG['tarcompress'] = 'z';
    } else {
        $f_ext = '.tar';
        $_CONFIG['tarcompress'] = '';
    }
    /*if($_CONFIG['backup_refresh']){
         $f_ext = ".tar";
        }
        elseif($_REQUEST[cron_dbonly]){
    	 $f_ext = ".tar";
    	}
    	else{
    	 $f_ext = ".tgz";
    	}*/
    if ($_REQUEST['bname'] == "") {
        if ($backupDatabase == 1) {
            if ($_REQUEST['dbbackup_drop']) {
                $filename1 = 'backup_' . date("Y-m-d_H-i") . '_' . $domainname . '-sql-drop' . $f_ext;
            } else {
                $filename1 = 'backup_' . date("Y-m-d_H-i") . '_' . $domainname . '-sql-nodrop' . $f_ext;
            }
        } else {
            $filename1 = 'backup_' . date("Y-m-d_H-i") . '_' . $domainname . '-nosql' . $f_ext;
        }
    } else {
        $filename1 = $_REQUEST['bname'] . $f_ext;
    }
    $sql_file = array();
    if ($backupDatabase == 1) {
        $tables = array();
        $tables[0] = 'all';
        $excltables = $_REQUEST['excltables'];
        $sql_file[] = doBackup($tables, 'sql', 'local', 'both', $_SERVER['HTTP_USER_AGENT'], $_CONFIG['backups_dir'], $databaseResult, 'database', $excltables, $_CONFIG['mysql_database']);
        $databaseResult = "<b>" . $_CONFIG['mysql_database'] . ":</b> " . $databaseResult;
        ############## ADD multiple databases #######################
        $databases_incl = $_REQUEST['databases_incl'];
        if (is_array($databases_incl)) {
            foreach ($databases_incl as $database_name) {
                if ($database_name != '') {
                    $excltables = "";
                    mysql_query("USE  {$database_name}");
                    $sql_file[] = doBackup($tables, 'sql', 'local', 'both', $_SERVER['HTTP_USER_AGENT'], $_CONFIG['backups_dir'], $databaseResult_incl, $database_name, $excltables, $database_name);
                    $databaseResult .= "<br /> <b>{$database_name}:</b> " . $databaseResult_incl;
                }
            }
            mysql_query("USE  " . $_CONFIG['mysql_database']);
        }
    } else {
        $databaseResult = LM_DATABASE_EXCLUDED;
    }
    $excluded = array();
    $data = "";
    $excluded[] = $_CONFIG['backups_dir'] . "/" . $filename1;
    if ($_REQUEST['cron_access']) {
        $data = $_CONFIG['cron_exclude'];
    } elseif ($_CONFIG[select_folders] == 1) {
        $data = $_REQUEST['exluded'];
    }
    ##### START THE EXCLUSION FILTER
    if (($fp = @fopen($_CONFIG['exfile'], "r")) && !$_REQUEST['cron_access']) {
        while (!feof($fp)) {
            $data .= fread($fp, 1024);
        }
        fclose($fp);
    }
    if (sizeof($_REQUEST[cid]) > 0) {
        $data .= implode("\r\n", $_REQUEST[cid]);
    }
    $_COOKIES = explode("\r\n", $data);
    if (is_array($_COOKIES)) {
        foreach ($_COOKIES as $key => $value) {
            if ($value != "") {
                $value = str_replace($_CONFIG['backup_path'], "", $value);
                if ($value[0] != '/') {
                    $value = '/' . $value;
                }
                if (substr($value, strlen($value) - 1, 1) == '/' && strlen($value) != 1) {
                    $value = substr($value, 0, strlen($value) - 1);
                }
                if ($value != "" && $value != '/administrator/backups') {
                    if (trim($value) != '/administrator') {
                        $excluded[] = str_replace("//", "/", $_CONFIG['backup_path'] . "/" . $value);
                    } else {
                        if ($handle = opendir($_CONFIG['backup_path'] . '/administrator')) {
                            while (false !== ($file = readdir($handle))) {
                                if ($file != "." && $file != ".." && $file != "backups") {
                                    $excluded[] = str_replace("//", "/", $_CONFIG['backup_path'] . "/administrator/" . $file);
                                }
                            }
                            closedir($handle);
                        }
                    }
                }
            }
        }
    }
    #### END EXCLUSION FILTER
    if (!$_CONFIG['add_backups_dir']) {
        # initialise list arrays, directories and files separately and array counters for them
        $d_arr = array();
        $d = 0;
        $f_arr = array();
        $f = 0;
        $s_arr = array();
        $s = 0;
        getBackupFiles($d_arr, $f_arr, $s_arr, $d, $f);
        $i = 0;
        while ($i < sizeof($f_arr)) {
            $excluded[] = $_CONFIG['clonerPath'] . "/" . $f_arr[$i];
            $i++;
        }
    }
    # obtain list of folders included in the backup
    $includeFolder = array();
    #print_r($excluded);exit;
    #$includeFolder = confirmBackup('nohtml');
    #initialise list arrays, directories and files separately and array counters for them
    $d_arr = array();
    $d = 0;
    $ds_arr = array();
    $f_arr = array();
    $f = 0;
    $s_arr = array();
    $s = 0;
    $mdir = 0;
    $perm_file = $_CONFIG['backups_dir'] . "/perm.txt";
    @unlink($perm_file);
    $fperm = fopen($perm_file, "w");
    for ($i = 0; $i < sizeof($excluded); $i++) {
        $excluded[$i] = str_replace("//", "/", $excluded[$i]);
    }
    #print_r($excluded);exit;
    # obtain the list of files by recursing the mambo file store
    recurseFiles($d_arr, $ds_arr, $f_arr, $s_arr, $d, $f, $s, $includeFolder, '', $excluded, $fperm);
    @fclose($fperm);
    @chmod($perm_file, 0777);
    # format total archive size
    $originalSize = getFileSizeText($s);
    # extend the file locations to include the full path
    for ($i = 0; $i < count($f_arr); $i++) {
        if (!file_exists($f_arr[$i])) {
            unset($f_arr[$i]);
        }
    }
    #if((file_exists($perm_file))&&(!in_array($perm_file, $f_arr)))
    # $f_arr[] = $perm_file;
    # add sql file to the backup
    if ($_REQUEST[cron_access]) {
        if (is_array($sql_file)) {
            foreach ($sql_file as $key => $sqlfile) {
                if ($backupDatabase == 1 && !in_array($_CONFIG['backups_dir'] . $sqlfile, $f_arr)) {
                    $f_arr[] = $sqlfile;
                }
            }
        }
    }
    $filename = $_CONFIG['clonerPath'] . '/' . $filename1;
    $f_arr = array_unique($f_arr);
    # create the Zip file from the fileset array
    @unlink($filename);
    $perm_lines = 0;
    $handle = @fopen($perm_file, "r");
    if ($handle) {
        while (!feof($handle)) {
            fgets($handle, 4096);
            $perm_lines++;
        }
        fclose($handle);
    }
    if (!$_CONFIG['mem']) {
        #### START TAR MANUAL MODE ############################################################
        if ($_CONFIG['backup_refresh']) {
            $f_arr = array($_CONFIG['backups_dir'] . "/index.html");
        }
        if ($_CONFIG['backup_refresh']) {
            $tar_type = "tar";
        } else {
            $tar_type = "tgz";
        }
        $tar_object = new Archive_Tar($filename, compression($tar_type));
        #$tar_object->setErrorHandling(PEAR_ERROR_PRINT);  // Optional error handling
        $return = $tar_object->addModify($f_arr, '', $_CONFIG['backup_path']);
        if ($return != 1) {
            echo "Backup failed using tar mode, error code {$return}!";
        }
        if ($_CONFIG['backup_refresh']) {
            echo "Starting the manual backup process!<br />";
            echo "Database backup: " . $databaseResult . "<br /><br />";
            if (file_exists($filename)) {
                echo "Backup {$filename} created, we may continue!<br />";
                #echo "Database backup: ".$databaseResult ."<br />";
                echo "<a href='index2.php?option=com_cloner&lines=" . $perm_lines . "&task=refresh&backup={$filename}&excl_manual={$excl_manual}'>Please click here to continue!</a>";
                return;
            } else {
                E_print("Backup failed, please check your tar server utility support!");
                return;
            }
        }
        #### END TAR MODE ############################################################
    } else {
        #### CREATE BACKUP USING SERVER UTILITIES
        $i = 0;
        chdir($_CONFIG['backup_path']);
        $excl_files = "";
        while ($i < sizeof($excluded)) {
            $file = $excluded[$i];
            $file = str_replace($_CONFIG['backup_path'], "", $file);
            $file = "##" . $file;
            $file = str_replace("##//", "", $file);
            $file = str_replace("##/", "", $file);
            $file = str_replace("##", "", $file);
            $excl_files .= "/" . $file . "* ";
            $i++;
        }
        chdir($_CONFIG['backup_path']);
        $excl_cmd = "";
        if ($fp = fopen($_CONFIG['exfile_tar'], "w")) {
            $i = 0;
            while ($i < sizeof($excluded)) {
                $file = $excluded[$i];
                $file = str_replace($_CONFIG['backup_path'], "", $file);
                $file = "##" . $file;
                $file = str_replace("##//", "", $file);
                $file = str_replace("##/", "", $file);
                $file = str_replace("##", "", $file);
                $excl_cmd .= " --exclude=./" . $file . " ";
                $excl_files = "./" . $file . "\r\n";
                fwrite($fp, $excl_files);
                $i++;
            }
            fclose($fp);
        }
        if ($_CONFIG['backup_refresh']) {
            ########## STARTING THE MANUAL BACKUP ######################################################
            $exclude = $excl_cmd . " -X " . $_CONFIG['exfile_tar'];
            $excl_manual = $_CONFIG['exfile_tar'] . "_manual";
            if ($fp = fopen($excl_manual, "w")) {
                fwrite($fp, $exclude);
                fclose($fp);
            }
            echo "Starting the manual backup process!<br />";
            echo "Database backup: " . $databaseResult . "<br /><br />";
            chdir($_CONFIG['backup_path']);
            #$filename = str_replace(".tgz",".tar",$filename);
            exec($_CONFIG[tarpath] . " {$exclude} -c" . $_CONFIG['tarcompress'] . "vf {$filename} ./administrator/backups/index.html");
            exec($_CONFIG[tarpath] . " -" . $_CONFIG['tarcompress'] . "vf {$filename} --update ./administrator/backups/database-sql.sql");
            exec($_CONFIG[tarpath] . " -" . $_CONFIG['tarcompress'] . "vf {$filename} --update ./administrator/backups/htaccess.txt");
            exec($_CONFIG[tarpath] . " -" . $_CONFIG['tarcompress'] . "vf {$filename} --update ./administrator/backups/perm.txt");
            if (file_exists($filename)) {
                echo "Backup {$filename} created, we may continue!<br />";
                #echo "Database backup: ".$databaseResult."<br />" ;
                echo "<a href='index2.php?option=com_cloner&lines=" . $perm_lines . "&task=refresh&backup={$filename}&excl_manual={$excl_manual}'>Please click here to continue!</a>";
                return;
            } else {
                E_print("Backup failed, please check your tar server utility support!");
                return;
            }
            return;
        }
        if ($_REQUEST[cron_dbonly] != 1) {
            exec($_CONFIG[tarpath] . " {$excl_cmd} " . " -X " . $_CONFIG['exfile_tar'] . "  -chv" . $_CONFIG['tarcompress'] . "f {$filename} ./");
        } else {
            exec($_CONFIG[tarpath] . "  -" . $_CONFIG['tarcompress'] . "cvf {$filename} ./administrator/backups/database-sql.sql");
            if (is_array($databases_incl)) {
                foreach ($databases_incl as $database_name) {
                    if ($database_name != "") {
                        exec($_CONFIG[tarpath] . "  -" . $_CONFIG['tarcompress'] . "vf {$filename} --update  ./administrator/backups/" . $database_name . "-sql.sql");
                    }
                }
            }
        }
        #######END
        chdir($_CONFIG['script_path']);
        #### END
    }
    if (!file_exists($filename)) {
        if ($_CONFIG[archive_type] == 1) {
            echo LM_MSG_BACK_12;
        } else {
            echo LM_MSG_BACK_13;
        }
        return;
    }
    # format the compressed size of the fileset
    $archiveSize = getFileSizeText(filesize($filename));
    # load presentation layer
    if ($option != 'nohtml') {
        HTML_cloner::generateBackup($filename1, $archiveSize, $originalSize, $mdir, $f, $databaseResult, $option);
    } else {
        logxx(HTML_cloner::generateBackup_text($filename1, $archiveSize, $originalSize, $mdir, $f, $databaseResult, $option));
    }
    if (is_array($databases_incl)) {
        foreach ($databases_incl as $database_name) {
            @unlink($_CONFIG['backups_dir'] . "/" . $database_name . "-sql.sql");
        }
    }
    @unlink($_CONFIG['backups_dir'] . "/database-sql.sql");
    @unlink($sql_file);
    @unlink($perm_file);
    @unlink($htaccess);
    @unlink($_CONFIG['exfile']);
    @unlink($_CONFIG['exfile_tar']);
    return $filename1;
}