Exemple #1
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');
         }
     }
 }
Exemple #2
0
 public static function expand($path)
 {
     $path = realpath($path);
     $dir = dirname($path);
     #print ">> $path\n";
     $arch = new Archive_Tar($path, true);
     $arch->setErrorHandling(PEAR_ERROR_PRINT);
     if (false === $arch->extract($dir)) {
         throw new Pfw_Exception_Script(Pfw_Exception_Script::E_ARCHIVE_UNKNOWN);
     }
 }
 static function install($source, $filename)
 {
     $target = SIMPLE_EXT . substr($filename, 0, -3);
     setup::out("{t}Download{/t}: " . $source . " ...");
     if ($fz = gzopen($source, "r") and $fp = fopen($target, "w")) {
         $i = 0;
         while (!gzeof($fz)) {
             $i++;
             setup::out(".", false);
             if ($i % 160 == 0) {
                 setup::out();
             }
             fwrite($fp, gzread($fz, 16384));
         }
         gzclose($fz);
         fclose($fp);
     } else {
         sys_die("{t}Error{/t}: gzopen [2] " . $source);
     }
     setup::out();
     if (!file_exists($target) or filesize($target) == 0 or filesize($target) % 10240 != 0) {
         sys_die("{t}Error{/t}: file-check [3] Filesize: " . filesize($target) . " " . $target);
     }
     setup::out(sprintf("{t}Processing %s ...{/t}", basename($target)));
     $tar_object = new Archive_Tar($target);
     $tar_object->setErrorHandling(PEAR_ERROR_PRINT);
     $tar_object->extract(SIMPLE_EXT);
     $file_list = $tar_object->ListContent();
     if (!is_array($file_list) or !isset($file_list[0]["filename"]) or !is_dir(SIMPLE_EXT . $file_list[0]["filename"])) {
         sys_die("{t}Error{/t}: tar [4] " . $target);
     }
     self::update_modules_list();
     $ext_folder = db_select_value("simple_sys_tree", "id", "anchor=@anchor@", array("anchor" => "extensions"));
     foreach ($file_list as $file) {
         sys_chmod(SIMPLE_EXT . $file["filename"]);
         setup::out(sprintf("{t}Processing %s ...{/t}", SIMPLE_EXT . $file["filename"]));
         if (basename($file["filename"]) == "install.php") {
             setup::out("");
             require SIMPLE_EXT . $file["filename"];
             setup::out("");
         }
         if (basename($file["filename"]) == "readme.txt") {
             $data = file_get_contents(SIMPLE_EXT . $file["filename"]);
             setup::out(nl2br("\n" . q($data) . "\n"));
         }
         if (!empty($ext_folder) and basename($file["filename"]) == "folders.xml") {
             setup::out(sprintf("{t}Processing %s ...{/t}", "folder structure"));
             folders::create_default_folders(SIMPLE_EXT . $file["filename"], $ext_folder, false);
         }
     }
 }
 static function extract($target, $folder)
 {
     setup::out(sprintf("{t}Processing %s ...{/t}", basename($target)));
     $tar_object = new Archive_Tar($target);
     $tar_object->setErrorHandling(PEAR_ERROR_PRINT);
     $tar_object->extract($folder);
     $file_list = $tar_object->ListContent();
     if (!is_array($file_list) or !isset($file_list[0]["filename"]) or !is_dir($folder . $file_list[0]["filename"])) {
         sys_die("{t}Error{/t}: tar [3] " . $target);
     }
     foreach ($file_list as $file) {
         sys_chmod($folder . $file["filename"]);
     }
     @unlink($target);
     return $folder . $file_list[0]["filename"];
 }
Exemple #5
0
function nc_tgz_create($archive_name, $file_name, $additional_path = '', $exclude_tag = NULL)
{
    global $DOCUMENT_ROOT, $SUB_FOLDER;
    @set_time_limit(0);
    $path = $DOCUMENT_ROOT . $SUB_FOLDER . $additional_path;
    if (SYSTEM_TAR) {
        $exclude_tag_cmd = '';
        if ($exclude_tag) {
            $exclude_array_tmp = nc_exclude_tag_to_array($path, $exclude_tag);
            $exclude_array = array();
            foreach ($exclude_array_tmp as $item) {
                $exclude_array[] = '--exclude=' . preg_quote(ltrim(substr($item, strlen($path)), '/'));
            }
            $exclude_tag_cmd = implode(' ', $exclude_array);
        }
        exec("cd {$path}; tar -zcf '{$archive_name}' {$exclude_tag_cmd} {$file_name} 2>&1", $output, $err_code);
        if ($err_code) {
            trigger_error("{$output['0']}", E_USER_WARNING);
            return false;
        }
        return true;
    } else {
        $tar_object = new Archive_Tar($archive_name, "gz");
        $tar_object->setErrorHandling(PEAR_ERROR_PRINT);
        if ($exclude_tag) {
            $exclude_array_tmp = nc_exclude_tag_to_array($path, $exclude_tag);
            $exclude_array = array();
            foreach ($exclude_array_tmp as $item) {
                $exclude_array[] = ltrim(substr($item, strlen($path)), '/');
            }
            $tar_object->setIgnoreList($exclude_array);
        }
        chdir($path);
        ob_start();
        $file_name_array = explode(' ', $file_name);
        $res = $tar_object->create($file_name_array);
        if (!$res) {
            ob_end_flush();
        } else {
            ob_end_clean();
        }
        return $res;
    }
}
Exemple #6
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;
 }
Exemple #7
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;
 }
Exemple #8
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()) {
             $upToDate = true;
             foreach ($this->filesets as $fs) {
                 $files = $fs->getFiles($this->project, $this->includeEmpty);
                 if (!$this->archiveIsUpToDate($files, $fs->getDir($this->project))) {
                     $upToDate = false;
                 }
                 for ($i = 0, $fcount = count($files); $i < $fcount; $i++) {
                     if ($this->tarFile->equals(new PhingFile($fs->getDir($this->project), $files[$i]))) {
                         throw new BuildException("A tar file cannot include itself", $this->getLocation());
                     }
                 }
             }
             if ($upToDate) {
                 $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);
         // print errors
         $tar->setErrorHandling(PEAR_ERROR_PRINT);
         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());
         }
     } catch (IOException $ioe) {
         $msg = "Problem creating TAR: " . $ioe->getMessage();
         $this->filesets = $savedFileSets;
         throw new BuildException($msg, $ioe, $this->getLocation());
     }
     $this->filesets = $savedFileSets;
 }
$BASE_VERSION = trim(shell_exec('grep -m 1 \'<version>.*</version>\' *.xml | sed s/.*\\<version\\>// | sed s/\\<\\\\/version\\>.*//'));
if (!$BASE_VERSION || strpos($BASE_VERSION, "\n") !== false) {
    I2CE::raiseError("Unable to determine base version", E_USER_ERROR);
}
if (count(explode('.', $BASE_VERSION)) < 3) {
    I2CE::raiseError("Bad version {$BASE_VERSION}");
}
I2CE::raiseError("Base version is {$BASE_VERSION}");
$BASE_VERSION_SHORT = implode('.', array_slice(explode('.', $BASE_VERSION), 0, 2));
$BASE_VERSION_SHORT_NEXT = array_slice(explode('.', $BASE_VERSION), 0, 2);
$BASE_VERSION_SHORT_NEXT[1]++;
$BASE_VERSION_SHORT_NEXT = implode('.', $BASE_VERSION_SHORT_NEXT);
if (!$booleans['read_po_files']) {
    I2CE::raiseError("Using archive: " . realpath($archive));
    $tar = new Archive_Tar($archive);
    $tar->setErrorHandling(PEAR_ERROR_CALLBACK, array('I2CE', 'raiseError'));
    $tar_files = array();
    $tar_dirs = array();
    $files = $tar->listContent();
    foreach ($files as $data) {
        if (!array_key_exists('filename', $data)) {
            continue;
        }
        if ($data['typeflag'] == 5) {
            $tar_dirs[] = $data['filename'];
        } else {
            if ($data['typeflag'] == 0) {
                $tar_files[] = $data['filename'];
            }
        }
    }
Exemple #10
0
 /**
  * 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;
     }
 }
Exemple #11
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;
     }
 }
 /**
  * Extracts the package archive file
  * @return boolean True on success, False on error
  */
 function extractArchive()
 {
     global $_CB_framework;
     $base_Dir = _cbPathName($_CB_framework->getCfg('tmp_path'));
     $archivename = $this->installArchive();
     $tmpdir = uniqid('install_');
     $extractdir = _cbPathName($base_Dir . $tmpdir);
     $archivename = _cbPathName($archivename, false);
     $this->unpackDir($extractdir);
     if (preg_match("/\\.zip\$/i", $archivename)) {
         // Extract functions
         cbimport('pcl.pclziplib');
         $zipfile = new PclZip($archivename);
         if ($this->isWindows()) {
             define('OS_WINDOWS', 1);
         } else {
             define('OS_WINDOWS', 0);
         }
         $ret = $zipfile->extract(PCLZIP_OPT_PATH, $extractdir);
         if ($ret == 0) {
             $this->setError(1, 'Unrecoverable error "' . $zipfile->errorName(true) . '"');
             return false;
         }
     } else {
         cbimport('pcl.tar');
         // includes/Archive/Tar.php' );
         $archive = new Archive_Tar($archivename);
         $archive->setErrorHandling(PEAR_ERROR_PRINT);
         if (!$archive->extractModify($extractdir, '')) {
             $this->setError(1, 'Extract Error');
             return false;
         }
     }
     $this->installDir($extractdir);
     // Try to find the correct install dir. in case that the package have subdirs
     // Save the install dir for later cleanup
     $filesindir = cbReadDirectory($this->installDir(), '');
     if (count($filesindir) == 1) {
         if (is_dir($extractdir . $filesindir[0])) {
             $this->installDir(_cbPathName($extractdir . $filesindir[0]));
         }
     }
     return true;
 }
function extractArchive($filename)
{
    $absolute_path = JPATH_ROOT;
    $base_Dir = $absolute_path . '/tmp/';
    $archivename = $base_Dir . $filename;
    $tmpdir = uniqid('install_');
    $extractdir = $base_Dir . $tmpdir;
    //$archivename 	= mosPathName( $archivename;
    //echo $archivename;
    //$this->unpackDir( $extractdir );
    if (preg_match('/.zip$/', $archivename)) {
        // Extract functions
        require_once $absolute_path . '/administrator/components/com_swmenufree/pcl/pclzip.lib.php';
        require_once $absolute_path . '/administrator/components/com_swmenufree/pcl/pclerror.lib.php';
        require_once $absolute_path . '/administrator/components/com_swmenufree/pcl/pcltrace.lib.php';
        //require_once( $absolute_path . '/administrator/includes/pcl/pcltar.lib.php' );
        $zipfile = new PclZip($archivename);
        //if($this->isWindows()) {
        //		define('OS_WINDOWS',1);
        //	} else {
        //		define('OS_WINDOWS',0);
        //	}
        $ret = $zipfile->extract(PCLZIP_OPT_PATH, $extractdir);
        if ($ret == 0) {
            //$this->setError( 1, 'Unrecoverable error "'.$zipfile->errorName(true).'"' );
            return false;
        }
    } else {
        require_once $absolute_path . '/administrator/components/com_swmenufree/pcl/Tar.php';
        $archive = new Archive_Tar($archivename);
        $archive->setErrorHandling(PEAR_ERROR_PRINT);
        if (!$archive->extractModify($extractdir, '')) {
            $this->setError(1, 'Extract Error');
            return false;
        }
    }
    return $extractdir;
}
Exemple #14
0
function extract_tar($filename, $dirName)
{
    if (class_exists('PharData')) {
        try {
            $phar = new PharData($filename);
            $phar->extractTo($dirName);
        } catch (Exception $e) {
            return false;
        }
        return true;
    }
    $tar = new Archive_Tar($filename);
    $tar->setErrorHandling(PEAR_ERROR_PRINT);
    return $tar->extract($dirName);
}
 function upload_save($redirect = true)
 {
     global $my, $mainframe, $database, $option, $priTask, $subTask;
     global $WBG_CONFIG, $wbGalleryDB_cat, $wbGallery_common, $wbGallery_eng;
     // Prepare Runtime
     $tempDir = null;
     $known_images = array('image/pjpeg', 'image/jpeg', 'image/jpg', 'image/png', 'image/gif');
     $time = time();
     // Importing
     $importFolder = mosGetParam($_REQUEST, 'folder', '');
     if ($importFolder && !file_exists($importFolder)) {
         echo "<script> alert('Import Folder Does Not Exist'); document.location.href='index2.php?option=" . $option . "&task=image.upload'; </script>\n";
         exit;
     }
     // Default Values
     $defRow = new wbGalleryDB_img($database);
     $defRow->bind($_POST);
     // Debug
     echo "Image Processing Start: " . $time . '<br/>';
     // ==============================v========================================
     // Single File Upload
     if (!empty($_FILES['img']['tmp_name'])) {
         // Debug
         echo "Single File Detected <br/>";
         if (!in_array($_FILES['img']['type'], $known_images)) {
             echo "<script> alert('Image type: " . $_FILES['img']['type'] . " is an unknown type'); document.location.href='index2.php?option=" . $option . "&task=image.upload'; </script>\n";
             exit;
         }
         $wbGallery_eng->add($_FILES['img']['tmp_name'], $_FILES['img']['name'], $_FILES['img']['type'], $defRow);
         if ($redirect) {
             mosRedirect('index2.php?option=' . $option . '&task=image.upload', 'Image Saved');
         }
     }
     // ==============================v========================================
     // Zip File Upload
     if (!empty($_FILES['zip']['tmp_name'])) {
         //zip file upload
         // Debug
         echo "Compressed File Uploaded <br/>";
         // Create / Define Temporary Folder for Unzipped Files
         if (!mkdir($mainframe->getCfg('absolute_path') . '/media/' . $time)) {
             if (!mkdir('/tmp/' . $time)) {
                 echo "<script> alert('Unable to Create Temp Directory'); history.back(); </script>\n";
                 exit;
             } else {
                 $tempDir = '/tmp/' . $time;
             }
         } else {
             $tempDir = $mainframe->getCfg('absolute_path') . '/media/' . $time;
         }
         // Uncompress ZIP or TAR.GZ
         if (preg_match('/zip$/i', $_FILES['zip']['name'])) {
             // Load ZIP functions
             require_once $mainframe->getCfg('absolute_path') . '/administrator/includes/pcl/pclzip.lib.php';
             require_once $mainframe->getCfg('absolute_path') . '/administrator/includes/pcl/pclerror.lib.php';
             $zipfile = new PclZip($_FILES['zip']['tmp_name']);
             if (substr(PHP_OS, 0, 3) == 'WIN') {
                 define('OS_WINDOWS', 1);
             } else {
                 define('OS_WINDOWS', 0);
             }
             $ret = $zipfile->extract(PCLZIP_OPT_PATH, $tempDir);
             if ($ret == 0) {
                 $wbGallery_common->remove_dir($tempDir);
                 echo "<script> alert('ZIP Extraction Error: " . $zipfile->errorName(true) . "'); history.back(); </script>\n";
                 exit;
             }
         } elseif (preg_match('/tar.gz$/i', $_FILES['zip']['name'])) {
             // Load TAR functions
             require_once $mainframe->getCfg('absolute_path') . '/includes/Archive/Tar.php';
             $archive = new Archive_Tar($_FILES['zip']['tmp_name']);
             $archive->setErrorHandling(PEAR_ERROR_PRINT);
             if (!$archive->extractModify($tempDir, '')) {
                 $wbGallery_common->remove_dir($tempDir);
                 echo "<script> alert('TAR Extraction Error'); history.back(); </script>\n";
                 exit;
             }
         } else {
             // Unknown File...
             $wbGallery_common->remove_dir($tempDir);
             echo "<script> alert('Unknown File Format - Must be .ZIP or .TAR.GZ'); history.back(); </script>\n";
             exit;
         }
     }
     // Zip File Upload
     // ==============================v========================================
     // Process Files from Folder
     if ($tempDir || $importFolder) {
         $processDirs = array();
         $files_added = 0;
         $files_skipped = 0;
         if ($tempDir) {
             $processDirs[] = array('path' => $tempDir, 'remove' => 1);
         }
         if ($importFolder) {
             $processDirs[] = array('path' => $importFolder, 'remove' => 0);
         }
         if (count($processDirs)) {
             foreach ($processDirs as $procDir) {
                 // Read Files from Temp Folder
                 $regImg = array();
                 foreach ($known_images as $k) {
                     $regImg[] = preg_replace('/^.*\\//', '', $k) . '$';
                 }
                 $regStr = '/' . join('|', $regImg) . '/';
                 $files = $wbGallery_common->find_files($procDir['path'], $regStr);
                 unset($regImg);
                 unset($regStr);
                 // Debug
                 echo "Unzipped " . count($files) . " for processing <br/>";
                 if (count($files)) {
                     foreach ($files as $file) {
                         $filePath = $file['path'] . '/' . $file['name'];
                         $res = getimagesize($filePath);
                         $fileType = $res['mime'];
                         if (in_array($fileType, $known_images)) {
                             if ($wbGallery_eng->add($filePath, $file['name'], $fileType, $defRow)) {
                                 $files_added++;
                             } else {
                                 $files_skipped++;
                             }
                         } else {
                             $files_skipped++;
                         }
                     }
                 }
                 if ($procDir['remove']) {
                     $wbGallery_common->remove_dir($procDir['path']);
                 }
             }
             // foreach processDirs
         }
         // if processDirs
         if ($redirect) {
             if (!$files_added && !$files_skipped) {
                 mosRedirect('index2.php?option=' . $option . '&task=image.upload', 'Error: No Files were Processed or Error Finding Files');
             } else {
                 mosRedirect('index2.php?option=' . $option . '&task=image.upload', $files_added . ' images added - ' . $files_skipped . ' files skipped');
             }
         } else {
             if (!$files_added && !$files_skipped) {
                 return false;
             } else {
                 return true;
             }
         }
     }
     mosRedirect('index2.php?option=' . $option . '&task=image.upload', 'Please Specify Images for Processing');
     return false;
 }
Exemple #16
0
function extract_files($known_arrays)
{
    // Check what type of tar to use
    tgz_check_exec();
    $str = get_tr();
    // If all OK, let's make some fun :)
    // Extract stuff
    foreach ($known_arrays as $item) {
        echo $str['extracting'] . " {$item}.tgz...\n";
        flush();
        if (SYSTEM_TAR) {
            nl2br(system("tar xf {$item}.tgz 2>&1", $unpack_result));
        } else {
            $tar_object = new Archive_Tar($item . ".tgz", "gz");
            $tar_object->setErrorHandling(PEAR_ERROR_PRINT);
            $tar_object->extract(".");
        }
        echo $str['done'] . "<br />\n";
        flush();
    }
}
/** 
 * Spielt ein Backup zurück in die Datenbank und gibt eine Status-Message aus 
 * 
 * @param          string $backupfile Der Dateiname des Backups 
 * @since          0.0.1 
 * @version        0.0.1 
 * @access         private 
 * @return         string 
 * @author         Alexander Mieland 
 * @copyright      2000-2004 by APP - Another PHP Program 
 */
function _APCMS_RecoverDBBackup($backupfile)
{
    global $db, $akt_time, $_LANGUAGE;
    $backupdir = $_SESSION['APCMS']['TMP_DIR'];
    $pbackupfile = $backupdir . "/backups/" . $backupfile;
    $recoverdir = $backupdir . "/last_backup";
    if (!file_exists($pbackupfile)) {
        return $_LANGUAGE['backup_not_found'];
    }
    require_once "Archive/Tar." . $_SESSION['APCMS']['SUFFIX'];
    if (eregi(".gz\$", $backupfile)) {
        $zipped = TRUE;
    } else {
        $zipped = FALSE;
    }
    $tar_object = new Archive_Tar($pbackupfile, $zipped);
    $tar_object->setErrorHandling(PEAR_ERROR_RETURN);
    $tar_object->extract($backupdir);
    $fe = opendir($recoverdir);
    chdir($recoverdir);
    while ($file = readdir($fe)) {
        if (ereg("_CREATE_", $file)) {
            unset($rec);
            $drop = "";
            $create = "";
            $rec = file($file);
            for ($a = 0; $a < count($rec); $a++) {
                if (!ereg("^##", $rec[$a])) {
                    if (ereg("DROP TABLE", $rec[$a])) {
                        $drop .= $rec[$a];
                    } else {
                        $create .= $rec[$a];
                    }
                }
            }
            if (trim($drop) != "") {
                $db->unbuffered_query(preg_replace("|(`;([\\ \\r\\n]{0,})\$)|", "`", $drop));
                #print("<pre>".preg_replace("|(`;([\ \\r\\n]{0,})$)|","`",$drop)."</pre>");
            }
            $db->unbuffered_query(preg_replace("|(\\)([\\ (TYPE=MyISAM)]{0,});([\\ \\r\\n]{0,})\$)|", ")", $create));
            #print("<pre>".preg_replace("|(\)([\ (TYPE=MyISAM)]{0,});([\ \\r\\n]{0,})$)|",")",$create)."</pre>");
        }
    }
    chdir("../../");
    closedir($fe);
    $fe = opendir($recoverdir);
    chdir($recoverdir);
    while ($file = readdir($fe)) {
        if (ereg("_INSERT_", $file)) {
            unset($rec);
            $insert = "";
            $fop = fopen($file, "r");
            $rec = fread($fop, filesize($file));
            fclose($fop);
            $insert = explode("\nINSERT INTO", $rec);
            for ($blu = 0; $blu < count($insert); $blu++) {
                if ($blu >= 1) {
                    $db->unbuffered_query("INSERT INTO" . preg_replace("|(\\);([\\ \\r\\n]{0,})\$)|", ")", $insert[$blu]));
                    #print("<pre>INSERT INTO".preg_replace("|(\);([\ \\r\\n]{0,})$)|",")",$insert[$blu])."</pre>");
                }
            }
        }
    }
    chdir("../../");
    closedir($fe);
    $fe = opendir($recoverdir);
    while ($file = readdir($fe)) {
        if ($file != "." && $file != ".." && $file != "index." . $_SESSION['APCMS']['SUFFIX'] && $file != "cvs" && $file != "CVS") {
            unlink($recoverdir . "/" . $file);
        }
    }
    closedir($fe);
    return $_LANGUAGE['backup_recovered1'] . $backupfile . $_LANGUAGE['backup_recovered2'];
}
 /**
  * Extracts the package archive file
  * @return boolean True on success, False on error
  */
 function extractArchive()
 {
     global $mosConfig_absolute_path;
     $base_Dir = mosPathName($mosConfig_absolute_path . '/media');
     $archivename = $base_Dir . $this->installArchive();
     $tmpdir = uniqid('install_');
     $extractdir = mosPathName($base_Dir . $tmpdir);
     $archivename = mosPathName($archivename, false);
     $this->unpackDir($extractdir);
     if (eregi('.zip$', $archivename)) {
         // Extract functions
         require_once $mosConfig_absolute_path . '/administrator/includes/pcl/pclzip.lib.php';
         require_once $mosConfig_absolute_path . '/administrator/includes/pcl/pclerror.lib.php';
         //require_once( $mosConfig_absolute_path . '/administrator/includes/pcl/pcltrace.lib.php' );
         //require_once( $mosConfig_absolute_path . '/administrator/includes/pcl/pcltar.lib.php' );
         $zipfile = new PclZip($archivename);
         if ($this->isWindows()) {
             define('OS_WINDOWS', 1);
         } else {
             define('OS_WINDOWS', 0);
         }
         $ret = $zipfile->extract(PCLZIP_OPT_PATH, $extractdir);
         if ($ret == 0) {
             $this->setError(1, 'Unrecoverable error "' . $zipfile->errorName(true) . '"');
             return false;
         }
     } else {
         require_once $mosConfig_absolute_path . '/includes/Archive/Tar.php';
         $archive = new Archive_Tar($archivename);
         $archive->setErrorHandling(PEAR_ERROR_PRINT);
         if (!$archive->extractModify($extractdir, '')) {
             $this->setError(1, 'Extract Error');
             return false;
         }
     }
     $this->installDir($extractdir);
     // Try to find the correct install dir. in case that the package have subdirs
     // Save the install dir for later cleanup
     $filesindir = mosReadDirectory($this->installDir(), '');
     if (count($filesindir) == 1) {
         if (is_dir($extractdir . $filesindir[0])) {
             $this->installDir(mosPathName($extractdir . $filesindir[0]));
         }
     }
     return true;
 }
Exemple #19
0
function packSPK($dir, $destPackage)
{
    $oldDir = getcwd();
    chdir($dir);
    // echo "create $dir to $destPackage";
    $package = new Archive_Tar("package.tgz", "gz");
    $package->setErrorHandling(PEAR_ERROR_PRINT);
    $package->create("package");
    $destPackage = new Archive_Tar($destPackage);
    $destPackage->create("INFO scripts package.tgz");
    @unlink("package.tgz");
    chdir($oldDir);
}
Exemple #20
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;
 }
 /** static: import a programme from the given XBMF archive */
 function importXBMF($fileName, $publish = false, $console = false)
 {
     global $db, $config, $permissions, $repository, $vocabularies;
     $pathToFile = $config['xbmfInDir'] . '/';
     // create temp folder with unique name
     $folderName = uniqid("xbmf");
     if (!mkdir($pathToFile . $folderName)) {
         logError("Could not create dir for XBMF", $pathToFile . $folderName);
         return false;
     }
     // untar contents of file to folder
     $tar = new Archive_Tar($fileName, true);
     // create archive handler
     $tar->setErrorHandling(PEAR_ERROR_PRINT);
     // enable error reporting
     $result = $tar->extract($pathToFile . $folderName);
     // untar contents
     debug("untar result", $result);
     //parse the xml file
     $metaFile = $pathToFile . $folderName . "/XBMF/Metadata.xml";
     if (!is_file($metaFile)) {
         $metaFile = $pathToFile . $folderName . "/XBMF/metadata.xml";
         if (!is_file($metaFile)) {
             logError("no metadata file found in XBMF!", $folderName);
             return false;
         }
     }
     $myPack = new unpackXML($metaFile);
     if (!$myPack->error) {
         //if the file has been found
         $metadata = $myPack->process();
     }
     if (!$metadata or $myPack->error) {
         //errors during import - stop execution
         sotf_Utils::delete($pathToFile . $folderName);
         echo "<font color=#FF0000><b>The import of {$fileName} did not succeed!</b></font>";
         logError("XML processing failed within this XBMF", $folderName);
         return false;
         //did not succeed
     } else {
         /*
         echo "Came In: " . $myPack->encoding . "<br>";
         echo "Went Out: " . $myPack->outencoding . "<br>";
         echo "<pre>";
         print_r($metadata);
         echo "</pre>";
         */
         dump($metadata, "METADATA");
         debug("METADATA", $metadata);
     }
     $db->begin();
     // Select station
     $stId = trim($metadata['stationid']);
     if (is_numeric($stId)) {
         $stId = $newPrg->makeId($config['nodeId'], 'sotf_stations', (int) $stId);
     }
     $station =& $repository->getObject($stId);
     if (!$station) {
         logError("invalid stationid: " . $metadata['stationid']);
         return false;
         // by default I put the programme into the first station
         //$stId = $db->getOne("SELECT id FROM sotf_stations ORDER BY id");
         //$station = &$repository->getObject($stId);
     }
     // select/create programme entry
     if ($metadata['identifier']) {
         $prgId = sotf_Programme::getMapping($station->id, $metadata['identifier'], 'prg');
     }
     if ($prgId) {
         // updating an exisiting programme
         debug("updating existing programme", $prgId);
         $newPrg = new sotf_Programme($prgId);
         if ($station->id != $newPrg->get('station_id')) {
             logError("station provided in metadata is different from the station saved previously!");
             return false;
         }
         //$station = &$repository->getObject($newPrg->get('station_id'));
         $updatingPrg = 1;
     } else {
         // a new programme
         $newPrg = new sotf_Programme();
         $track = $metadata['title'];
         debug("create new programme with track", $track);
         $newPrg->create($station->id, $track);
         sotf_Programme::addMapping($station->id, $metadata['identifier'], 'prg', $newPrg->id);
     }
     $newPrg->set('foreign_id', $metadata['identifier']);
     // select/create series
     if ($metadata['series'] && $metadata['series']['id']) {
         $seriesId = sotf_Programme::getMapping($station->id, $metadata['series']['id'], 'series');
         if (!$seriesId) {
             $series1 = new sotf_Series();
             $series1->set('name', $metadata['series']['title']);
             $series1->set('station_id', $station->id);
             $series1->find();
             if ($series1->exists()) {
                 $seriesId = $series1->id;
             }
         }
         if ($seriesId) {
             $newPrg->set('series_id', $seriesId);
             $series =& $repository->getObject($seriesId);
         } else {
             $newSeries = 1;
             $series = new sotf_Series();
             $series->set('station_id', $station->id);
         }
         $series->set('name', $metadata['series']['title']);
         $series->set('description', $metadata['series']['description']);
         if ($series->exists()) {
             $series->update();
         } else {
             $series->create();
             sotf_Programme::addMapping($station->id, $metadata['series']['id'], 'series', $series->id);
         }
     }
     // permissions
     foreach (array($metadata['owner'], $metadata['publishedby']) as $foreignUser) {
         if (is_array($foreignUser)) {
             $userId = sotf_User::getUserid($foreignUser['login']);
             debug("owner/publisher", $foreignUser);
             if ($userId) {
                 if ($permissions->hasPermission($station->id, 'admin', $userId) || $series && $permissions->hasPermission($series->id, 'create', $userId)) {
                     // add permission for user
                     $permissions->addPermission($newPrg->id, $userId, 'admin');
                     $admins[] = $userId;
                 }
             }
         }
     }
     // if we did not get permission info, add permissions for all station/series admins
     debug("admins2", $admins);
     if (empty($admins)) {
         if ($series) {
             $admins1 = $permissions->listUsersWithPermission($series->id, 'admin');
         }
         if (!$admins1) {
             $admins1 = $permissions->listUsersWithPermission($station->id, 'admin');
         }
         while (list(, $admin) = each($admins1)) {
             $admins[] = $admin['id'];
             $permissions->addPermission($newPrg->id, $admin['id'], 'admin');
         }
     }
     debug("admins3", $admins);
     // now create permissions
     while (list(, $adminId) = each($admins)) {
         $permissions->addPermission($newPrg->id, $adminId, 'admin');
         if ($newSeries) {
             $permissions->addPermission($series->id, $adminId, 'admin');
         }
     }
     /*
      * PART 2.2 - Insert all the relevant data from the xml file into the database
      */
     // basic metadata
     $newPrg->set('title', sotf_Programme::normalizeText($metadata['title'], 255));
     $newPrg->set('alternative_title', sotf_Programme::normalizeText($metadata['alternative'], 255));
     $newPrg->set('episode_sequence', 0);
     if (!empty($metadata['episodesequence'])) {
         $epiSeq = sotf_Programme::normalizeText($metadata['episodesequence']);
         if (is_numeric($epiSeq)) {
             $newPrg->set('episode_sequence', (int) $epiSeq);
         } else {
             logError("Bad episode sequence: " . $metadata['episodesequence']);
         }
     }
     $newPrg->set('abstract', sotf_Programme::normalizeText($metadata['description']));
     $newPrg->set('keywords', sotf_Programme::normalizeText($metadata['keywords']));
     $newPrg->set("production_date", date('Y-m-d', strtotime($metadata['created'])));
     $newPrg->set("broadcast_date", date('Y-m-d', strtotime($metadata['issued'])));
     $newPrg->set("modify_date", date('Y-m-d', strtotime($metadata['modified'])));
     $newPrg->set('language', $metadata['language']);
     if ($metadata['language'] == 'ger') {
         $newPrg->set('language', 'deu');
     }
     if ($metadata['language'] == 'English') {
         $newPrg->set('language', 'eng');
     }
     $newPrg->update();
     // topic
     if ($metadata['topic']) {
         $vocabularies->addToTopic($newPrg->id, $metadata['topic']);
     }
     // genre
     $genre = trim($metadata['genre']);
     if (is_numeric($genre)) {
         $newPrg->set('genre_id', $genre);
     } else {
         logError("invalid genre id: " . $genre);
     }
     // rights
     $rights = new sotf_NodeObject("sotf_rights");
     $rights->set('prog_id', $newPrg->id);
     $rights->set('rights_text', $metadata['rights']);
     $rights->find();
     $rights->save();
     $db->commit();
     // contacts
     //$role = 21; // Other
     foreach ($metadata['publisher'] as $contact) {
         $role = 23;
         // Publisher
         $id = sotf_Programme::importContact($contact, $role, $newPrg->id, $station->id, $admins);
     }
     foreach ($metadata['creator'] as $contact) {
         $role = 22;
         // Creator
         $id = sotf_Programme::importContact($contact, $role, $newPrg->id, $station->id, $admins);
     }
     if (is_array($metadata['contributor'])) {
         foreach ($metadata['contributor'] as $contact) {
             $role = 24;
             // Contributor
             $id = sotf_Programme::importContact($contact, $role, $newPrg->id, $station->id, $admins);
         }
     }
     /*
      * PART 2.1 - Move the audio data to the specified station folder
      */
     // insert audio
     $dirPath = $pathToFile . $folderName . "/XBMF/audio";
     $dir = dir($dirPath);
     while ($entry = $dir->read()) {
         if ($entry != "." && $entry != "..") {
             $currentFile = $dirPath . "/" . $entry;
             if (!is_dir($currentFile)) {
                 if (is_file($currentFile)) {
                     debug("insert audio", $currentFile);
                     $newPrg->setAudio($currentFile, true);
                 }
             }
         }
     }
     $dir->close();
     // insert other files
     $dirPath = $pathToFile . $folderName . "/XBMF/files";
     $dir = dir($dirPath);
     while ($entry = $dir->read()) {
         if ($entry != "." && $entry != "..") {
             $currentFile = $dirPath . "/" . $entry;
             if (!is_dir($currentFile)) {
                 $id = $newPrg->setOtherFile($currentFile, true);
                 debug("insert other", $currentFile);
                 /* by default, no need for this
                 		 if($id) {
                 			$fileInfo = &$repository->getObject($id);
                 			$fileInfo->set('public_access', 't');
                 			$fileInfo->update();
                 		 }
                 		 */
             }
         }
     }
     $dir->close();
     // insert metadata
     if (is_readable($metaFile)) {
         debug("insert meta", $metaFile);
         $target1 = $newPrg->getMetaDir() . '/metadata.xml';
         $target2 = $newPrg->getMetaDir() . '/metadata-in.xml';
         if (!copy($metaFile, $target1)) {
             logError("Could not copy metadata into {$target1}");
         }
         if (!copy($metaFile, $target2)) {
             logError("Could not copy metadata into {$target2}");
         }
     }
     // insert icon
     $logoFile = $pathToFile . $folderName . "/icon.png";
     if (is_readable($logoFile)) {
         debug("insert icon", $logoFile);
         $newPrg->setIcon($logoFile);
     }
     // convert missing formats!
     $audioFiles =& new sotf_FileList();
     $audioFiles->getAudioFromDir($newPrg->getAudioDir());
     $checker =& new sotf_AudioCheck($audioFiles);
     $checker->console = $console;
     // if we don't want progress bars
     $targets = $checker->convertAll($newPrg->id);
     if (is_array($targets)) {
         foreach ($targets as $target) {
             $newPrg->setAudio($target);
         }
     }
     /*
      * PART 2.3 - Remove (unlink) the xbmf file and the temp dir
      */
     //publish if needed
     if ($publish) {
         $newPrg->publish();
     }
     sotf_Utils::delete($pathToFile . $folderName);
     //unlink($fileName);
     return $newPrg->id;
 }
 public function submitAddLang()
 {
     $arr_import_lang = explode('|', Tools::getValue('params_import_language'));
     /* 0 = Language ISO code, 1 = PS version */
     if (Validate::isLangIsoCode($arr_import_lang[0])) {
         $array_stream_context = @stream_context_create(array('http' => array('method' => 'GET', 'timeout' => 10)));
         $content = Tools::file_get_contents('http://www.prestashop.com/download/lang_packs/gzip/' . $arr_import_lang[1] . '/' . Tools::strtolower($arr_import_lang[0]) . '.gzip', false, $array_stream_context);
         if ($content) {
             $file = _PS_TRANSLATIONS_DIR_ . $arr_import_lang[0] . '.gzip';
             if ((bool) @file_put_contents($file, $content)) {
                 require_once _PS_TOOL_DIR_ . '/tar/Archive_Tar.php';
                 $gz = new Archive_Tar($file, true);
                 if (_PS_MODE_DEV_) {
                     $gz->setErrorHandling(PEAR_ERROR_TRIGGER, E_USER_WARNING);
                 }
                 $files_list = AdminTranslationsController::filterTranslationFiles($gz->listContent());
                 if ($error = $gz->extractList(AdminTranslationsController::filesListToPaths($files_list), _PS_TRANSLATIONS_DIR_ . '../')) {
                     if (is_object($error) && !empty($error->message)) {
                         $this->errors[] = Tools::displayError('The archive cannot be extracted.') . ' ' . $error->message;
                     } else {
                         if (!Language::checkAndAddLanguage($arr_import_lang[0])) {
                             $conf = 20;
                         } else {
                             // Reset cache
                             Language::loadLanguages();
                             // Clear smarty modules cache
                             Tools::clearCache();
                             AdminTranslationsController::checkAndAddMailsFiles($arr_import_lang[0], $files_list);
                             if ($tab_errors = AdminTranslationsController::addNewTabs($arr_import_lang[0], $files_list)) {
                                 $this->errors += $tab_errors;
                             }
                         }
                         if (!unlink($file)) {
                             $this->errors[] = sprintf(Tools::displayError('Cannot delete the archive %s.'), $file);
                         }
                         $this->redirect(false, isset($conf) ? $conf : '15');
                     }
                 } else {
                     $this->errors[] = sprintf(Tools::displayError('Cannot decompress the translation file for the following language: %s'), $arr_import_lang[0]);
                     $checks = array();
                     foreach ($files_list as $f) {
                         if (isset($f['filename'])) {
                             if (is_file(_PS_ROOT_DIR_ . DIRECTORY_SEPARATOR . $f['filename']) && !is_writable(_PS_ROOT_DIR_ . DIRECTORY_SEPARATOR . $f['filename'])) {
                                 $checks[] = dirname($f['filename']);
                             } elseif (is_dir(_PS_ROOT_DIR_ . DIRECTORY_SEPARATOR . $f['filename']) && !is_writable(_PS_ROOT_DIR_ . DIRECTORY_SEPARATOR . dirname($f['filename']))) {
                                 $checks[] = dirname($f['filename']);
                             }
                         }
                     }
                     $checks = array_unique($checks);
                     foreach ($checks as $check) {
                         $this->errors[] = sprintf(Tools::displayError('Please check rights for folder and files in %s'), $check);
                     }
                     if (!unlink($file)) {
                         $this->errors[] = sprintf(Tools::displayError('Cannot delete the archive %s.'), $file);
                     }
                 }
             } else {
                 $this->errors[] = Tools::displayError('The server does not have permissions for writing.') . ' ' . sprintf(Tools::displayError('Please check rights for %s'), dirname($file));
             }
         } else {
             $this->errors[] = Tools::displayError('Language not found.');
         }
     } else {
         $this->errors[] = Tools::displayError('Invalid parameter.');
     }
 }
    function backup_interface()
    {
        global $serendipity;
        $BACKUPDIR = $this->get_config('abspath_backupdir');
        $TEMPDIR = $BACKUPDIR . "/tmp";
        $ARCHIVDIR = $BACKUPDIR;
        $TITLE = "";
        $TITLE .= "<h2>" . PLUGIN_BACKUP_TITLE . "</h2>\n";
        $TITLE .= PLUGIN_BACKUP_DESC . "<br /><br />\n";
        if (!file_exists($BACKUPDIR)) {
            @mkdir($BACKUPDIR, 0777);
            @chmod($BACKUPDIR, 0777);
        }
        if (!file_exists($BACKUPDIR . "/tmp")) {
            @mkdir($BACKUPDIR . "/tmp", 0777);
            @chmod($BACKUPDIR . "/tmp", 0777);
        }
        if (!file_exists($BACKUPDIR . "/tmp/last_backup")) {
            @mkdir($BACKUPDIR . "/tmp/last_backup", 0777);
            @chmod($BACKUPDIR . "/tmp/last_backup", 0777);
        }
        if (isset($serendipity['POST']['action']) && $serendipity['POST']['action'] == "makesqlbackup") {
            $STATUSMSG = '';
            unset($UPDATECONF);
            if (!isset($serendipity['POST']['complete']) || $serendipity['POST']['complete'] != 1) {
                $serendipity['POST']['complete'] = 0;
            }
            if (!isset($serendipity['POST']['drop']) || $serendipity['POST']['drop'] != 1) {
                $serendipity['POST']['drop'] = 0;
            }
            if (!isset($serendipity['POST']['pack']) || $serendipity['POST']['pack'] != 1) {
                $serendipity['POST']['pack'] = 0;
            }
            $DATA_BACKUP = $serendipity['POST']['complete'];
            $DATA_BACKUP .= "|^|";
            $DATA_BACKUP .= isset($serendipity['POST']['complete']) && $serendipity['POST']['complete'] == 1 ? serialize(array()) : serialize($serendipity['POST']['tables']);
            $DATA_BACKUP .= "|^|";
            $DATA_BACKUP .= $serendipity['POST']['data'];
            $DATA_BACKUP .= "|^|";
            $DATA_BACKUP .= $serendipity['POST']['drop'];
            $DATA_BACKUP .= "|^|";
            $DATA_BACKUP .= $serendipity['POST']['pack'];
            if (!isset($serendipity['POST']['delete']) && isset($serendipity['POST']['bakautomatik']) && $serendipity['POST']['bakautomatik'] == 1) {
                $UPDATECONF = "UPDATE {$serendipity['dbPrefix']}dma_sqlbackup SET ";
                $UPDATECONF .= "\t\tauto_backup='1', ";
                $UPDATECONF .= "\t\ttime_backup='" . $serendipity['POST']['interval'] . "', ";
                $UPDATECONF .= "\t\tlast_backup='" . time() . "', ";
                $UPDATECONF .= "\t\tdata_backup='" . addslashes($DATA_BACKUP) . "' ";
                $STATUSMSG .= '<b>' . PLUGIN_BACKUP_AUTO_SQL_BACKUP_STARTED . '</b><br />';
            } elseif (!isset($serendipity['POST']['delete']) && (count($serendipity['POST']) >= 1 && !isset($serendipity['POST']['bakautomatik']))) {
                $UPDATECONF = "UPDATE {$serendipity['dbPrefix']}dma_sqlbackup SET ";
                $UPDATECONF .= "\t\tauto_backup='0', ";
                $UPDATECONF .= "\t\ttime_backup='0', ";
                $UPDATECONF .= "\t\tlast_backup='0', ";
                $UPDATECONF .= "\t\tdata_backup='" . addslashes($DATA_BACKUP) . "' ";
                $STATUSMSG .= '<b>' . PLUGIN_BACKUP_AUTO_SQL_BACKUP_STOPPED . '</b><br />';
            }
            if (isset($UPDATECONF)) {
                serendipity_db_query($UPDATECONF);
            }
            unset($UPDATECONF);
            if (!isset($serendipity['POST']['delete']) && isset($serendipity['POST']['delautomatik']) && $serendipity['POST']['delautomatik'] == 1) {
                $UPDATECONF = "UPDATE {$serendipity['dbPrefix']}dma_sqlbackup SET ";
                $UPDATECONF .= "\t\tauto_backdel='1', ";
                $UPDATECONF .= "\t\ttime_backdel='" . $serendipity['POST']['delage'] . "', ";
                $UPDATECONF .= "\t\tlast_backdel='" . time() . "' ";
                $STATUSMSG .= '<b>' . PLUGIN_BACKUP_AUTO_SQL_DELETE_STARTED . '</b><br />';
            } elseif (!isset($serendipity['POST']['delete']) && (count($serendipity['POST']) >= 1 && !isset($serendipity['POST']['delautomatik']))) {
                $UPDATECONF = "UPDATE {$serendipity['dbPrefix']}dma_sqlbackup SET ";
                $UPDATECONF .= "\t\tauto_backdel='0', ";
                $UPDATECONF .= "\t\ttime_backdel='0', ";
                $UPDATECONF .= "\t\tlast_backdel='0' ";
                $STATUSMSG .= '<b>' . PLUGIN_BACKUP_AUTO_SQL_DELETE_STOPPED . '</b><br />';
            }
            if (isset($UPDATECONF)) {
                serendipity_db_query($UPDATECONF);
            }
            if (isset($serendipity['POST']['backup']) && $serendipity['POST']['backup'] == 1) {
                if (isset($serendipity['POST']['complete']) && $serendipity['POST']['complete'] == 1) {
                    $this->MakeSQLBackup(1, NULL, $serendipity['POST']['data'], $serendipity['POST']['drop']);
                } else {
                    $this->MakeSQLBackup(0, $serendipity['POST']['tables'], $serendipity['POST']['data'], $serendipity['POST']['drop']);
                }
                if ($serendipity['POST']['pack'] == 1) {
                    $archiv = "../" . date("Y-m-d-H-i", time()) . "_sqlbackup.tar.gz";
                    chdir($TEMPDIR);
                    if (file_exists($archiv)) {
                        unlink($archiv);
                    }
                    $this->getTar();
                    $tar_object = new Archive_Tar($archiv, "gz");
                    $tar_object->setErrorHandling(PEAR_ERROR_RETURN);
                    $filelist[0] = "./last_backup";
                    $tar_object->create($filelist);
                    chmod($archiv, 0666);
                    chdir($serendipity['serendipityPath']);
                } else {
                    $archiv = "../" . date("Y-m-d-H-i", time()) . "_sqlbackup.tar";
                    chdir($TEMPDIR);
                    if (file_exists($archiv)) {
                        unlink($archiv);
                    }
                    $this->getTar();
                    $tar_object = new Archive_Tar($archiv, FALSE);
                    $tar_object->setErrorHandling(PEAR_ERROR_RETURN);
                    $filelist[0] = "./last_backup";
                    $tar_object->create($filelist);
                    chmod($archiv, 0666);
                    chdir($serendipity['serendipityPath']);
                }
                $fe = opendir($TEMPDIR . "/last_backup");
                while ($file = readdir($fe)) {
                    if ($file != "." && $file != ".." && $file != "index.php" && $file != "cvs" && $file != "CVS") {
                        unlink($TEMPDIR . "/last_backup/" . $file);
                    }
                }
                closedir($fe);
                $STATUSMSG .= '<b>' . PLUGIN_BACKUP_SQL_SAVED . '</b><br />';
            }
        }
        if (isset($serendipity['POST']['action']) && $serendipity['POST']['action'] == "makehtmlbackup") {
            $STATUSMSG = '';
            unset($UPDATECONF);
            if (!isset($serendipity['POST']['complete']) || $serendipity['POST']['complete'] != 1) {
                $serendipity['POST']['complete'] = 0;
            }
            $DATA_BACKUP = $serendipity['serendipityPath'];
            $DATA_BACKUP .= "|^|";
            $s9ypath = trim($serendipity['serendipityPath']);
            $s9ydir = preg_replace("`^.*\\/([^\\/]*)\\/\$`", "\\1", $s9ypath);
            if (substr($s9ypath, strlen($s9ypath) - 1, strlen($s9ypath)) == "/") {
                $s9ypath = substr($s9ypath, 0, strlen($s9ypath) - 1);
            }
            $dirs_to_exclude = array();
            $fd = opendir($s9ypath);
            while ($dir = readdir($fd)) {
                if (is_dir($dir) && $dir != "." && $dir != "..") {
                    if (is_array($serendipity['POST']['dirs']) && !in_array($dir, $serendipity['POST']['dirs'])) {
                        $dirs_to_exclude[] = $dir;
                    }
                }
            }
            closedir($fd);
            $DATA_BACKUP .= isset($serendipity['POST']['complete']) && $serendipity['POST']['complete'] == 1 ? serialize(array()) : serialize($dirs_to_exclude);
            if (!isset($serendipity['POST']['delete']) && isset($serendipity['POST']['bakautomatik']) && $serendipity['POST']['bakautomatik'] == 1) {
                $UPDATECONF = "UPDATE {$serendipity['dbPrefix']}dma_htmlbackup SET ";
                $UPDATECONF .= "\t\tauto_backup='1', ";
                $UPDATECONF .= "\t\ttime_backup='" . $serendipity['POST']['interval'] . "', ";
                $UPDATECONF .= "\t\tlast_backup='" . time() . "', ";
                $UPDATECONF .= "\t\tdata_backup='" . addslashes($DATA_BACKUP) . "' ";
                $STATUSMSG .= '<b>' . PLUGIN_BACKUP_AUTO_HTML_BACKUP_STARTED . '</b><br />';
            } elseif (!isset($serendipity['POST']['delete']) && (count($serendipity['POST']) >= 1 && !isset($serendipity['POST']['bakautomatik']))) {
                $UPDATECONF = "UPDATE {$serendipity['dbPrefix']}dma_htmlbackup SET ";
                $UPDATECONF .= "\t\tauto_backup='0', ";
                $UPDATECONF .= "\t\ttime_backup='0', ";
                $UPDATECONF .= "\t\tlast_backup='0', ";
                $UPDATECONF .= "\t\tdata_backup='" . addslashes($DATA_BACKUP) . "' ";
                $STATUSMSG .= '<b>' . PLUGIN_BACKUP_AUTO_HTML_BACKUP_STOPPED . '</b><br />';
            }
            if (isset($UPDATECONF)) {
                serendipity_db_query($UPDATECONF);
            }
            unset($UPDATECONF);
            if (!isset($serendipity['POST']['delete']) && isset($serendipity['POST']['delautomatik']) && $serendipity['POST']['delautomatik'] == 1) {
                $UPDATECONF = "UPDATE {$serendipity['dbPrefix']}dma_htmlbackup SET ";
                $UPDATECONF .= "\t\tauto_backdel='1', ";
                $UPDATECONF .= "\t\ttime_backdel='" . $serendipity['POST']['delage'] . "', ";
                $UPDATECONF .= "\t\tlast_backdel='" . time() . "' ";
                $STATUSMSG .= '<b>' . PLUGIN_BACKUP_AUTO_HTML_DELETE_STARTED . '</b><br />';
            } elseif (!isset($serendipity['POST']['delete']) && (count($serendipity['POST']) >= 1 && !isset($serendipity['POST']['delautomatik']))) {
                $UPDATECONF = "UPDATE {$serendipity['dbPrefix']}dma_htmlbackup SET ";
                $UPDATECONF .= "\t\tauto_backdel='0', ";
                $UPDATECONF .= "\t\ttime_backdel='0', ";
                $UPDATECONF .= "\t\tlast_backdel='0' ";
                $STATUSMSG .= '<b>' . PLUGIN_BACKUP_AUTO_HTML_DELETE_STOPPED . '</b><br />';
            }
            if (isset($UPDATECONF)) {
                serendipity_db_query($UPDATECONF);
            }
            if (isset($serendipity['POST']['backup']) && $serendipity['POST']['backup'] == 1) {
                if (isset($serendipity['POST']['complete']) && $serendipity['POST']['complete'] == 1) {
                    $this->MakeHTMLBackup($s9ypath);
                } else {
                    $this->MakeHTMLBackup($s9ypath, $dirs_to_exclude);
                }
                $STATUSMSG .= '<b>' . PLUGIN_BACKUP_HTML_SAVED . '</b><br />';
            }
        }
        if (isset($serendipity['POST']['del']) and count($serendipity['POST']['del']) >= 1) {
            for ($a = 0; $a < count($serendipity['POST']['del']); $a++) {
                unlink($ARCHIVDIR . "/" . basename($serendipity['POST']['del'][$a]));
            }
        }
        if (isset($_GET['recover']) && isset($_GET['backup']) && $_GET['recover'] == 1 && trim($_GET['backup']) != "") {
            $STATUSMSG .= $this->RecoverSQLBackup($_GET['backup']);
        } elseif (isset($_GET['download']) && isset($_GET['backup']) && $_GET['download'] == 1 && trim($_GET['backup']) != "") {
            $file = $BACKUPDIR . "/" . basename($_GET['backup']);
            $fp = fopen($file, "r");
            if (preg_match("@.gz\$@", $_GET['backup'])) {
                header("Content-Type: application/x-gzip-compressed");
            } elseif (preg_match("@.tar\$@", $_GET['backup'])) {
                header("Content-Type: application/x-tar-compressed");
            }
            header("Content-Transfer-Encoding: Binary");
            header("Content-length: " . filesize($BACKUPDIR . "/" . $_GET['backup']));
            header("Content-disposition: attachment; filename=" . basename($_GET['backup']));
            while (!feof($fp)) {
                $buff = fread($fp, 4096);
                print $buff;
            }
        }
        $retconfs = serendipity_db_query("SELECT * FROM {$serendipity['dbPrefix']}dma_sqlbackup");
        foreach ($retconfs[0] as $key => $val) {
            $backupconfig[$key] = stripslashes(trim($val));
        }
        $backupdatas_array = explode("|^|", $backupconfig['data_backup']);
        $complete = intval($backupdatas_array[0]);
        $tables = unserialize($backupdatas_array[1]);
        $data = $backupdatas_array[2];
        $drop = intval($backupdatas_array[3]);
        $pack = intval($backupdatas_array[4]);
        if (isset($tdbgcolor) && $tdbgcolor == "#ebebeb") {
            $tdbgcolor = "#efefef";
        } else {
            $tdbgcolor = "#ebebeb";
        }
        $BACKUPFORM = "<div align=\"center\"><b>" . PLUGIN_BACKUP_SQL_BACKUP . "</b></div>\n";
        $BACKUPFORM .= '<table width="100%" border="0" cellspacing="1" cellpadding="2" align="center">';
        $BACKUPFORM .= '<form name="NewBackupForm" action="?" method="POST">';
        $BACKUPFORM .= '<input type="hidden" name="serendipity[c]" value="backup" />
						<input type="hidden" name="serendipity[action]" value="makesqlbackup" />
						<input type="hidden" name="serendipity[backup]" value="1" />';
        $BACKUPFORM .= "<input type=\"hidden\" name=\"serendipity[adminModule]\" value=\"event_display\" />\n";
        $BACKUPFORM .= "<input type=\"hidden\" name=\"serendipity[adminAction]\" value=\"backup\" />\n";
        $BACKUPFORM .= '<tr>';
        $BACKUPFORM .= '<td width="250px" rowspan="3" style="background-color:' . $tdbgcolor . '" align="left"><select style="width:250px" name="serendipity[tables][]" size="11" multiple>';
        $QUERY = serendipity_db_query("SHOW TABLES");
        $co = 0;
        foreach ($QUERY as $THISTABLE) {
            if (count($tables) >= 1) {
                if (@in_array($THISTABLE[0], $tables)) {
                    $BACKUPFORM .= '<option value="' . $THISTABLE[0] . '" selected>' . $THISTABLE[0] . '</option>';
                } else {
                    $BACKUPFORM .= '<option value="' . $THISTABLE[0] . '">' . $THISTABLE[0] . '</option>';
                }
            } else {
                $BACKUPFORM .= '<option value="' . $THISTABLE[0] . '"';
                if ($co == 0) {
                    $BACKUPFORM .= ' selected';
                }
                $BACKUPFORM .= '>' . $THISTABLE[0] . '</option>';
            }
            $co++;
        }
        $BACKUPFORM .= '</select></td>';
        $BACKUPFORM .= '<td style="background-color:' . $tdbgcolor . '" align="left" valign="top">
							<select name="serendipity[data]">
								<option value="0"> --- ' . PLUGIN_BACKUP_PLEASE_CHOOSE . ' --- </option>';
        if (isset($data) && $data == "data") {
            $BACKUPFORM .= '		<option value="data" selected>' . PLUGIN_BACKUP_STRUCT_AND_DATA . '</option>';
            $BACKUPFORM .= '		<option value="structure">' . PLUGIN_BACKUP_ONLY_STRUCT . '</option>';
            $BACKUPFORM .= '		<option value="dataonly">' . PLUGIN_BACKUP_ONLY_DATA . '</option>';
        } elseif (isset($data) && $data == "structure") {
            $BACKUPFORM .= '		<option value="data">' . PLUGIN_BACKUP_STRUCT_AND_DATA . '</option>';
            $BACKUPFORM .= '		<option value="structure" selected>' . PLUGIN_BACKUP_ONLY_STRUCT . '</option>';
            $BACKUPFORM .= '		<option value="dataonly">' . PLUGIN_BACKUP_ONLY_DATA . '</option>';
        } elseif (isset($data) && $data == "dataonly") {
            $BACKUPFORM .= '		<option value="data">' . PLUGIN_BACKUP_STRUCT_AND_DATA . '</option>';
            $BACKUPFORM .= '		<option value="structure">' . PLUGIN_BACKUP_ONLY_STRUCT . '</option>';
            $BACKUPFORM .= '		<option value="dataonly" selected>' . PLUGIN_BACKUP_ONLY_DATA . '</option>';
        } else {
            $BACKUPFORM .= '		<option value="data" selected>' . PLUGIN_BACKUP_STRUCT_AND_DATA . '</option>';
            $BACKUPFORM .= '		<option value="structure">' . PLUGIN_BACKUP_ONLY_STRUCT . '</option>';
            $BACKUPFORM .= '		<option value="dataonly">' . PLUGIN_BACKUP_ONLY_DATA . '</option>';
        }
        $BACKUPFORM .= '	</select><br />';
        if (isset($drop) && $drop == 1) {
            $BACKUPFORM .= '	<input class="input_checkbox" type="checkbox" name="serendipity[drop]" value="1" checked /> ' . PLUGIN_BACKUP_WITH_DROP_TABLE . '<br />';
        } elseif (isset($drop) && $drop == "0") {
            $BACKUPFORM .= '	<input class="input_checkbox" type="checkbox" name="serendipity[drop]" value="1" /> ' . PLUGIN_BACKUP_WITH_DROP_TABLE . '<br />';
        } elseif (!isset($drop)) {
            $BACKUPFORM .= '	<input class="input_checkbox" type="checkbox" name="serendipity[drop]" value="1" checked /> ' . PLUGIN_BACKUP_WITH_DROP_TABLE . '<br />';
        }
        if (isset($pack) && $pack == 1) {
            $BACKUPFORM .= '	<input class="input_checkbox" type="checkbox" name="serendipity[pack]" value="1" checked /> ' . PLUGIN_BACKUP_ZIPPED . '<br />';
        } elseif (isset($pack) && $pack == "0") {
            $BACKUPFORM .= '	<input class="input_checkbox" type="checkbox" name="serendipity[pack]" value="1" /> ' . PLUGIN_BACKUP_ZIPPED . '<br />';
        } elseif (!isset($pack)) {
            $BACKUPFORM .= '	<input class="input_checkbox" type="checkbox" name="serendipity[pack]" value="1" checked /> ' . PLUGIN_BACKUP_ZIPPED . '<br />';
        }
        if (isset($complete) && $complete == 1) {
            $BACKUPFORM .= '	<input class="input_checkbox" type="checkbox" name="serendipity[complete]" value="1" checked /> ' . PLUGIN_BACKUP_WHOLE_DATABASE . '<br />';
        } elseif (isset($complete) && $complete == "0") {
            $BACKUPFORM .= '	<input class="input_checkbox" type="checkbox" name="serendipity[complete]" value="1" /> ' . PLUGIN_BACKUP_WHOLE_DATABASE . '<br />';
        } elseif (!isset($complete)) {
            $BACKUPFORM .= '	<input class="input_checkbox" type="checkbox" name="serendipity[complete]" value="1" /> ' . PLUGIN_BACKUP_WHOLE_DATABASE . '<br />';
        }
        $BACKUPFORM .= '	</td>';
        $BACKUPFORM .= '<td width="75" style="background-color:' . $tdbgcolor . '" align="center" valign="middle"><input class="serendipityPrettyButton input_button" type="submit" name="serendipity[submit]" value="' . PLUGIN_BACKUP_START_BACKUP . '" /></td>';
        $BACKUPFORM .= '</tr>';
        $BACKUPFORM .= '<tr>';
        if ($backupconfig['auto_backup'] == 1) {
            $C_automatik = ' checked';
        } else {
            $C_automatik = '';
        }
        if ($backupconfig['auto_backdel'] == 1) {
            $C_delmatik = ' checked';
        } else {
            $C_delmatik = '';
        }
        $BAKAUTO['TIME'] = array(600, 3600, 7200, 21600, 43200, 86400, 172800, 345600, 604800, 1209600, 2419200);
        $BAKAUTO['TEXT'] = array('10 ' . PLUGIN_BACKUP_MINUTES, PLUGIN_BACKUP_EVERY . ' ' . PLUGIN_BACKUP_HOUR, PLUGIN_BACKUP_EVERY . ' 2 ' . PLUGIN_BACKUP_HOURS, PLUGIN_BACKUP_EVERY . ' 6 ' . PLUGIN_BACKUP_HOURS, PLUGIN_BACKUP_EVERY . ' 12 ' . PLUGIN_BACKUP_HOURS, PLUGIN_BACKUP_EVERY . ' 24 ' . PLUGIN_BACKUP_HOURS, PLUGIN_BACKUP_EVERY . ' 2 ' . PLUGIN_BACKUP_DAYS, PLUGIN_BACKUP_EVERY . ' 4 ' . PLUGIN_BACKUP_DAYS, PLUGIN_BACKUP_EVERY . ' 7 ' . PLUGIN_BACKUP_DAYS, PLUGIN_BACKUP_EVERY . ' 2 ' . PLUGIN_BACKUP_WEEKS, PLUGIN_BACKUP_EVERY . ' 4 ' . PLUGIN_BACKUP_WEEKS);
        $DELAUTO['TIME'] = array(43200, 86400, 172800, 345600, 604800, 1209600, 2419200, 4838400, 14515200);
        $DELAUTO['TEXT'] = array('12 ' . PLUGIN_BACKUP_HOURS, ' 24 ' . PLUGIN_BACKUP_HOURS, '2 ' . PLUGIN_BACKUP_DAYS, '4 ' . PLUGIN_BACKUP_DAYS, '7 ' . PLUGIN_BACKUP_DAYS, '2 ' . PLUGIN_BACKUP_WEEKS, '4 ' . PLUGIN_BACKUP_WEEKS, '2 ' . PLUGIN_BACKUP_MONTHS, '6 ' . PLUGIN_BACKUP_MONTHS);
        $BACKUPFORM .= '<td colspan="2" style="background-color:' . $tdbgcolor . '" align="center" valign="top">
							<table width="100%" border="0" cellspacing="0" cellpadding="0">
								<tr>
									<td colspan="2">&nbsp;&nbsp;' . PLUGIN_BACKUP_AUTO_BACKUP . '<br />
									<input class="input_checkbox" type="checkbox" name="serendipity[bakautomatik]" value="1"' . $C_automatik . ' /> ' . PLUGIN_BACKUP_ACTIVATE_AUTO_BACKUP . '<br /></td>
								</tr>
								<tr>
									<td width="170">' . PLUGIN_BACKUP_TIME_BET_BACKUPS . '</td>
									<td><select name="serendipity[interval]">';
        for ($BA = 0; $BA < count($BAKAUTO['TIME']); $BA++) {
            if ($backupconfig['time_backup'] >= 1) {
                if ($BAKAUTO['TIME'][$BA] == $backupconfig['time_backup']) {
                    $BACKUPFORM .= '<option value="' . $BAKAUTO['TIME'][$BA] . '" selected>' . $BAKAUTO['TEXT'][$BA] . '</option>';
                } else {
                    $BACKUPFORM .= '<option value="' . $BAKAUTO['TIME'][$BA] . '">' . $BAKAUTO['TEXT'][$BA] . '</option>';
                }
            } else {
                if ($BA == 3) {
                    $BACKUPFORM .= '<option value="' . $BAKAUTO['TIME'][$BA] . '" selected>' . $BAKAUTO['TEXT'][$BA] . '</option>';
                } else {
                    $BACKUPFORM .= '<option value="' . $BAKAUTO['TIME'][$BA] . '">' . $BAKAUTO['TEXT'][$BA] . '</option>';
                }
            }
        }
        $BACKUPFORM .= '				</select></td>
								</tr>
							</table>
							</td>';
        $BACKUPFORM .= '</tr>';
        $BACKUPFORM .= '<tr>';
        $BACKUPFORM .= '<td colspan="2" style="background-color:' . $tdbgcolor . '" align="center" valign="top">
							<table width="100%" border="0" cellspacing="0" cellpadding="0">
								<tr>
									<td colspan="2">&nbsp;&nbsp;' . PLUGIN_BACKUP_DEL_OLD_BACKUPS . '<br />
									<input class="input_checkbox" type="checkbox" name="serendipity[delautomatik]" value="1"' . $C_delmatik . ' /> ' . PLUGIN_BACKUP_ACTIVATE_AUTO_DELETE . '<br /></td>
								</tr>
								<tr>
									<td width="140">' . PLUGIN_BACKUP_OLDER_THAN . '</td>
									<td><select name="serendipity[delage]">';
        for ($BA = 0; $BA < count($DELAUTO['TIME']); $BA++) {
            if ($backupconfig['time_backdel'] >= 1) {
                if ($DELAUTO['TIME'][$BA] == $backupconfig['time_backdel']) {
                    $BACKUPFORM .= '<option value="' . $DELAUTO['TIME'][$BA] . '" selected>' . $DELAUTO['TEXT'][$BA] . '</option>';
                } else {
                    $BACKUPFORM .= '<option value="' . $DELAUTO['TIME'][$BA] . '">' . $DELAUTO['TEXT'][$BA] . '</option>';
                }
            } else {
                if ($BA == 6) {
                    $BACKUPFORM .= '<option value="' . $DELAUTO['TIME'][$BA] . '" selected>' . $DELAUTO['TEXT'][$BA] . '</option>';
                } else {
                    $BACKUPFORM .= '<option value="' . $DELAUTO['TIME'][$BA] . '">' . $DELAUTO['TEXT'][$BA] . '</option>';
                }
            }
        }
        $BACKUPFORM .= '				</select>&nbsp;&nbsp;' . PLUGIN_BACKUP_WILL_BE_DELETED . '</td>
								</tr>
							</table>
							</td>';
        $BACKUPFORM .= '</tr>';
        $BACKUPFORM .= '</form>';
        $BACKUPFORM .= '</table><br />';
        unset($BACKUPS);
        $retconfh = serendipity_db_query("SELECT * FROM {$serendipity['dbPrefix']}dma_htmlbackup");
        foreach ($retconfh[0] as $key => $val) {
            $htmlbackupconfig[$key] = stripslashes(trim($val));
        }
        $backupdatah_array = explode("|^|", $htmlbackupconfig['data_backup']);
        $dir_to_backup = trim($backupdata_array[0]);
        if (substr($dir_to_backup, strlen($dir_to_backup) - 1, strlen($dir_to_backup)) == "/") {
            $dir_to_backup = substr($dir_to_backup, 0, strlen($dir_to_backup) - 1);
        }
        $exclude = unserialize(trim($backupdatah_array[1]));
        $BACKUPFORM .= "<div align=\"center\"><b>" . PLUGIN_BACKUP_HTML_BACKUP . "</b></div>\n";
        if (isset($tdbgcolor) && $tdbgcolor == "#ebebeb") {
            $tdbgcolor = "#efefef";
        } else {
            $tdbgcolor = "#ebebeb";
        }
        $BACKUPFORM .= '<table width="100%" border="0" cellspacing="1" cellpadding="2" align="center">';
        $BACKUPFORM .= '<form name="NewHBackupForm" action="?" method="POST">';
        $BACKUPFORM .= '<input type="hidden" name="serendipity[c]" value="backup" />
						<input type="hidden" name="serendipity[action]" value="makehtmlbackup" />
						<input type="hidden" name="serendipity[backup]" value="1" />';
        $BACKUPFORM .= "<input type=\"hidden\" name=\"serendipity[adminModule]\" value=\"event_display\" />\n";
        $BACKUPFORM .= "<input type=\"hidden\" name=\"serendipity[adminAction]\" value=\"backup\" />\n";
        $BACKUPFORM .= '<tr>';
        $BACKUPFORM .= '<td width="250px" rowspan="3" style="background-color:' . $tdbgcolor . '" align="left">
							<select style="width:250px" name="serendipity[dirs][]" size="8" multiple>';
        $s9ypath = trim($serendipity['serendipityPath']);
        $s9ydir = preg_replace("`^.*\\/([^\\/]*)\\/\$`", "\\1", $s9ypath);
        $dirs = array();
        $fd = opendir($s9ypath);
        while ($dir = readdir($fd)) {
            if (is_dir($dir) && $dir != "." && $dir != "..") {
                $dirs[] = $dir;
            }
        }
        closedir($fd);
        unset($dir);
        @reset($dirs);
        asort($dirs);
        @reset($dirs);
        foreach ($dirs as $dir) {
            if (is_array($exclude) && count($exclude) >= 1) {
                if (!in_array($dir, $exclude)) {
                    $BACKUPFORM .= '<option value="' . $dir . '" selected>' . $s9ydir . "/" . $dir . '</option>';
                } else {
                    $BACKUPFORM .= '<option value="' . $dir . '">' . $s9ydir . "/" . $dir . '</option>';
                }
            } else {
                $BACKUPFORM .= '<option value="' . $dir . '"';
                if ($co == 0) {
                    $BACKUPFORM .= ' selected';
                }
                $BACKUPFORM .= '>' . $s9ydir . "/" . $dir . '</option>';
            }
            $co++;
        }
        $BACKUPFORM .= '</select></td>';
        $BACKUPFORM .= '<td style="background-color:' . $tdbgcolor . '" align="left" valign="top">';
        if (!is_array($exclude) || count($exclude) <= 0) {
            $BACKUPFORM .= '	<input class="input_checkbox" type="checkbox" name="serendipity[complete]" value="1" checked /> ' . PLUGIN_BACKUP_WHOLE_BLOG . '<br />';
        } else {
            $BACKUPFORM .= '	<input class="input_checkbox" type="checkbox" name="serendipity[complete]" value="1" /> ' . PLUGIN_BACKUP_WHOLE_BLOG . '<br />';
        }
        $BACKUPFORM .= '	</td>';
        $BACKUPFORM .= '<td width="75" style="background-color:' . $tdbgcolor . '" align="center" valign="middle"><input class="serendipityPrettyButton input_button" type="submit" name="serendipity[submit]" value="' . PLUGIN_BACKUP_START_BACKUP . '" /></td>';
        $BACKUPFORM .= '</tr>';
        $BACKUPFORM .= '<tr>';
        if ($htmlbackupconfig['auto_backup'] == 1) {
            $C_automatik = ' checked';
        } else {
            $C_automatik = '';
        }
        if ($htmlbackupconfig['auto_backdel'] == 1) {
            $C_delmatik = ' checked';
        } else {
            $C_delmatik = '';
        }
        $BACKUPFORM .= '<td colspan="2" style="background-color:' . $tdbgcolor . '" align="center" valign="top">
							<table width="100%" border="0" cellspacing="0" cellpadding="0">
								<tr>
									<td colspan="2">&nbsp;&nbsp;' . PLUGIN_BACKUP_AUTO_BACKUP . '<br />
									<input class="input_checkbox" type="checkbox" name="serendipity[bakautomatik]" value="1"' . $C_automatik . ' /> ' . PLUGIN_BACKUP_ACTIVATE_AUTO_BACKUP . '<br /></td>
								</tr>
								<tr>
									<td width="170">' . PLUGIN_BACKUP_TIME_BET_BACKUPS . '</td>
									<td><select name="serendipity[interval]">';
        for ($BA = 0; $BA < count($BAKAUTO['TIME']); $BA++) {
            if ($htmlbackupconfig['time_backup'] >= 1) {
                if ($BAKAUTO['TIME'][$BA] == $htmlbackupconfig['time_backup']) {
                    $BACKUPFORM .= '<option value="' . $BAKAUTO['TIME'][$BA] . '" selected>' . $BAKAUTO['TEXT'][$BA] . '</option>';
                } else {
                    $BACKUPFORM .= '<option value="' . $BAKAUTO['TIME'][$BA] . '">' . $BAKAUTO['TEXT'][$BA] . '</option>';
                }
            } else {
                if ($BA == 3) {
                    $BACKUPFORM .= '<option value="' . $BAKAUTO['TIME'][$BA] . '" selected>' . $BAKAUTO['TEXT'][$BA] . '</option>';
                } else {
                    $BACKUPFORM .= '<option value="' . $BAKAUTO['TIME'][$BA] . '">' . $BAKAUTO['TEXT'][$BA] . '</option>';
                }
            }
        }
        $BACKUPFORM .= '				</select></td>
								</tr>
							</table>
							</td>';
        $BACKUPFORM .= '</tr>';
        $BACKUPFORM .= '<tr>';
        $BACKUPFORM .= '<td colspan="2" style="background-color:' . $tdbgcolor . '" align="center" valign="top">
							<table width="100%" border="0" cellspacing="0" cellpadding="0">
								<tr>
									<td colspan="2">&nbsp;&nbsp;' . PLUGIN_BACKUP_DEL_OLD_BACKUPS . '<br />
									<input class="input_checkbox" type="checkbox" name="serendipity[delautomatik]" value="1"' . $C_delmatik . ' /> ' . PLUGIN_BACKUP_ACTIVATE_AUTO_DELETE . '<br /></td>
								</tr>
								<tr>
									<td width="140">' . PLUGIN_BACKUP_OLDER_THAN . '</td>
									<td><select name="serendipity[delage]">';
        for ($BA = 0; $BA < count($DELAUTO['TIME']); $BA++) {
            if ($htmlbackupconfig['time_backdel'] >= 1) {
                if ($DELAUTO['TIME'][$BA] == $htmlbackupconfig['time_backdel']) {
                    $BACKUPFORM .= '<option value="' . $DELAUTO['TIME'][$BA] . '" selected>' . $DELAUTO['TEXT'][$BA] . '</option>';
                } else {
                    $BACKUPFORM .= '<option value="' . $DELAUTO['TIME'][$BA] . '">' . $DELAUTO['TEXT'][$BA] . '</option>';
                }
            } else {
                if ($BA == 6) {
                    $BACKUPFORM .= '<option value="' . $DELAUTO['TIME'][$BA] . '" selected>' . $DELAUTO['TEXT'][$BA] . '</option>';
                } else {
                    $BACKUPFORM .= '<option value="' . $DELAUTO['TIME'][$BA] . '">' . $DELAUTO['TEXT'][$BA] . '</option>';
                }
            }
        }
        $BACKUPFORM .= '				</select>&nbsp;&nbsp;' . PLUGIN_BACKUP_WILL_BE_DELETED . '</td>
								</tr>
							</table>
							</td>';
        $BACKUPFORM .= '</tr>';
        $BACKUPFORM .= '</form>';
        $BACKUPFORM .= '</table><br />';
        unset($BACKUPS);
        $bc = 0;
        $fd = opendir($BACKUPDIR);
        while ($backup = readdir($fd)) {
            if (preg_match("@backup@", $backup)) {
                $BACKUPS['NAME'][$bc] = $backup;
                $BACKUPS['FILE'][$bc] = $BACKUPDIR . "/" . $backup;
                $BACKUPS['TIME'][$bc] = filemtime($BACKUPDIR . "/" . $backup);
                $BACKUPS['SIZE'][$bc] = filesize($BACKUPDIR . "/" . $backup);
                $bc++;
            }
        }
        closedir($fd);
        @reset($BACKUPS);
        @array_multisort($BACKUPS['TIME'], SORT_DESC, SORT_NUMERIC, $BACKUPS['NAME'], $BACKUPS['FILE'], $BACKUPS['SIZE']);
        if (isset($tdbgcolor) && $tdbgcolor == "#ebebeb") {
            $tdbgcolor = "#efefef";
        } else {
            $tdbgcolor = "#ebebeb";
        }
        if (count($BACKUPS['NAME']) >= 1) {
            $BACKUPFORM .= "\n\n\n" . '<table width="100%" border="0" cellspacing="1" cellpadding="2" align="center">' . "\n";
            $BACKUPFORM .= '<form name="UPForm" action="?" method="POST">' . "\n";
            $BACKUPFORM .= '<input type="hidden" name="serendipity[c]" value="backup" />
							<input type="hidden" name="serendipity[action]" value="deletesqlbackup" />' . "\n";
            $BACKUPFORM .= "<input type=\"hidden\" name=\"serendipity[adminModule]\" value=\"event_display\" />\n";
            $BACKUPFORM .= "<input type=\"hidden\" name=\"serendipity[adminAction]\" value=\"backup\" />\n";
            $BACKUPFORM .= '<tr>' . "\n";
            $BACKUPFORM .= '<td style="background-color:' . $tdbgcolor . '" align="left"><span style="font-weight: bolder;">' . PLUGIN_BACKUP_FILENAME . '</span></td>' . "\n";
            $BACKUPFORM .= '<td width="100" style="background-color:' . $tdbgcolor . '" align="right"><span style="font-weight: bolder;">' . PLUGIN_BACKUP_FILESIZE . '</span></td>' . "\n";
            $BACKUPFORM .= '<td width="140" style="background-color:' . $tdbgcolor . '" align="right"><span style="font-weight: bolder;">' . PLUGIN_BACKUP_DATE . '</span></td>' . "\n";
            $BACKUPFORM .= '<td width="60" style="background-color:' . $tdbgcolor . '" align="center"><span style="font-weight: bolder;">' . PLUGIN_BACKUP_OPTION . '</span></td>' . "\n";
            $BACKUPFORM .= '</tr>' . "\n";
            for ($bco = 0; $bco < count($BACKUPS['NAME']); $bco++) {
                if (isset($tdbgcolor) && $tdbgcolor == "#ebebeb") {
                    $tdbgcolor = "#efefef";
                } else {
                    $tdbgcolor = "#ebebeb";
                }
                $BACKUPFORM .= '<tr>' . "\n";
                $BACKUPFORM .= '<td style="background-color:' . $tdbgcolor . '" align="left"><a href="' . $serendipity['baseURL'] . ($serendipity['rewrite'] == "none" ? $serendipity['indexFile'] . "?/" : "") . 'plugin/dlbackup_' . $BACKUPS['NAME'][$bco] . '">' . $BACKUPS['NAME'][$bco] . '</a></td>' . "\n";
                $BACKUPFORM .= '<td width="100" style="background-color:' . $tdbgcolor . '" align="right">' . $this->calcFilesize($BACKUPS['SIZE'][$bco]) . '</td>' . "\n";
                $BACKUPFORM .= '<td width="140" style="background-color:' . $tdbgcolor . '" align="right">' . date("d.m.Y, H:i", $BACKUPS['TIME'][$bco]) . '</td>' . "\n";
                $BACKUPFORM .= '<td width="60" style="background-color:' . $tdbgcolor . '" align="center">' . "\n";
                if (preg_match("@htmlbackup@", $BACKUPS['NAME'][$bco])) {
                    $BACKUPFORM .= "\t<img alt=\"\" src=\"" . $this->getRelPath() . "/img/e.gif\" width=18 height=18 border=\"0\" valign=\"absmiddle\" align=\"middle\" />";
                } else {
                    $BACKUPFORM .= "\t<a href=\"./serendipity_admin.php?serendipity[adminModule]=event_display&amp;serendipity[adminAction]=backup&amp;backup=" . $BACKUPS['NAME'][$bco] . "&amp;recover=1\"><img alt=\"\" src=\"" . $this->getRelPath() . "/img/recover.gif\" width=18 height=18 border=\"0\" valign=\"absmiddle\" align=\"middle\" title=\"" . PLUGIN_BACKUP_RECOVER_THIS . "\" alt=\"" . PLUGIN_BACKUP_RECOVER_THIS . "\" /></a>";
                }
                $BACKUPFORM .= '	<input class="input_checkbox" type="checkbox" name="serendipity[del][]" value="' . $BACKUPS['NAME'][$bco] . '" /></td>' . "\n";
                $BACKUPFORM .= '</tr>' . "\n";
            }
            if (isset($tdbgcolor) && $tdbgcolor == "#ebebeb") {
                $tdbgcolor = "#efefef";
            } else {
                $tdbgcolor = "#ebebeb";
            }
            $BACKUPFORM .= '<tr>' . "\n";
            $BACKUPFORM .= '<td colspan="4" style="background-color:' . $tdbgcolor . '" align="right"><span style="font-weight: bolder;">
								<input class="serendipityPrettyButton input_button" type="submit" name="serendipity[delete]" value="' . PLUGIN_BACKUP_DELETE . '" />
								</span></td>' . "\n";
            $BACKUPFORM .= '</tr>' . "\n";
            $BACKUPFORM .= '</form>' . "\n";
            $BACKUPFORM .= '</table>' . "\n\n\n";
        } else {
            $BACKUPFORM .= '<table width="100%" border="0" cellspacing="1" cellpadding="2">' . "\n";
            $BACKUPFORM .= '<tr>' . "\n";
            $BACKUPFORM .= '<td style="background-color:' . $tdbgcolor . '" align="center"><span style="font-weight: bolder;">' . PLUGIN_BACKUP_NO_BACKUPS . '</span></td>' . "\n";
            $BACKUPFORM .= '</tr>' . "\n";
            $BACKUPFORM .= '</table>' . "\n";
        }
        echo $TITLE;
        if (isset($STATUSMSG) && trim($STATUSMSG) != "") {
            echo $STATUSMSG . "<br /><br />";
        }
        echo $BACKUPFORM;
    }
Exemple #24
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) . '"');
         }
     }
 }
function createPatch($updatecache = false)
{
    include_once "Lib/Archive/Tar.php";
    include_once 'Lib/Text/Diff.php';
    include_once 'Lib/Text/Diff/Renderer/unified.php';
    $start = microtime(true);
    $tar_object = new Archive_Tar(_bmoddir . "Data/Cache.tar");
    $tar_object->setErrorHandling(PEAR_ERROR_PRINT);
    $tardata = $tar_object->listContent();
    $working = checkDir2("");
    $fmerged = array_merge($tardata, $working);
    $tarf_db = reIndexByFile($tardata);
    $work_db = reIndexByFile($working);
    $workidx = indexFilename($working);
    $tar_idx = indexFilename($tardata);
    $f_names = array_unique(array_merge($workidx, $tar_idx));
    $out = "";
    foreach ($f_names as $file) {
        //speed optimization
        if ($tarf_db[$file] && $work_db[$file] && $tarf_db[$file]["mtime"] == $work_db[$file]["mtime"] && $updatecache != true) {
            continue;
        }
        if ($tarf_db[$file]) {
            $fts1 = $tarf_db[$file]["mtime"];
            $fdata = $tar_object->extractInString($file);
            $lines1 = explode("\n", $fdata);
            //$lines1 = file("Data/$file");
            if (substr($fdata, -1, 1) == "\n") {
                //$lines1[] = "";
            }
        } else {
            $fts1 = 0;
            $lines1 = array();
        }
        if ($work_db[$file]) {
            $fts2 = $work_db[$file]["mtime"];
            //$lines2 = file(_bpatdir."$file");
            $filetext = file_get_contents(_bmoddir . _bpatdir . "{$file}");
            $lines2 = explode("\n", $filetext);
        } else {
            $fts2 = 0;
            $lines2 = array();
            $filetext = "";
        }
        if (array_search($file, $workidx) === false && array_search($file, $tar_idx) !== false) {
            //delted file
            $out .= renderHeader($file, $fts1, $fts2);
            $out .= "@@ -0,0 @@\n\n";
            continue;
        }
        if (array_search($file, $workidx) !== false && array_search($file, $tar_idx) === false) {
            //added file
        }
        if ($filetext == $fdata) {
            continue;
        }
        $diff = new Text_Diff('auto', array($lines1, $lines2));
        $renderer = new Text_Diff_Renderer_unified();
        $render = $renderer->render($diff);
        if ($render != "") {
            $out .= renderHeader($file, $fts1, $fts2);
            //get ts to work!
            $out .= $render . "\n";
            if (substr($filetext, -1, 1) != "\n") {
                $out .= "\\ No newline at end of file\n\n";
            }
        }
    }
    if ($updatecache == true) {
        $tar_object->create(array());
        foreach ($f_names as $file) {
            $tar_object->addString($file, file_get_contents(_bmoddir . _bpatdir . "{$file}"));
        }
    }
    return array(microtime(true) - $start, $out, count($addlist));
}
Exemple #26
0
<?php

if ($key == 'archive') {
    $to_archive = ".";
    if ($handle = opendir($to_archive)) {
        $to_archive = array();
        while (false !== ($file = readdir($handle))) {
            if ($file != "." && $file != "..") {
                $to_archive[] = $file;
            }
        }
        closedir($handle);
    }
    if ($gzip) {
        $archive .= $archive . ".gz";
        $tar_object = new Archive_Tar("{$archive}", true);
    } else {
        $tar_object = new Archive_Tar("{$archive}");
    }
    $tar_object->setErrorHandling(PEAR_ERROR_PRINT);
    $result = $tar_object->create($to_archive);
} elseif ($key == 'extract') {
    $destination = getcwd();
    $tar_object = new Archive_Tar("{$file}");
    $tar_object->setErrorHandling(PEAR_ERROR_PRINT);
    $result = $tar_object->extract("{$destination}");
} elseif ($key == 'unextract') {
    echo "NOT supported 'unextract' ";
} else {
    echo "NOT supported " . $key . " ";
}
 /**
  * Extracts the package archive file
  * @return boolean True on success, False on error
  */
 public function extractArchive()
 {
     $base_Dir = JPath::clean(JPATH_BASE . '/media');
     $archivename = $base_Dir . $this->_realname;
     $tmpdir = uniqid('install_');
     $extractdir = JPath::clean($base_Dir . $tmpdir);
     $archivename = JPath::clean($archivename, false);
     $this->_unpackdir = $extractdir;
     if (preg_match('/.zip$/', $archivename)) {
         // Extract functions
         require_once JPATH_ADMINISTRATOR . '/includes/pcl/pclzip.lib.php';
         require_once JPATH_ADMINISTRATOR . '/includes/pcl/pclerror.lib.php';
         $zipfile = new PclZip($this->_uploadfile);
         if ($this->_iswin) {
             define('OS_WINDOWS', 1);
         } else {
             define('OS_WINDOWS', 0);
         }
         $ret = $zipfile->extract(PCLZIP_OPT_PATH, $extractdir);
         if ($ret == 0) {
             $this->errno = 1;
             $this->error = 'Unrecoverable error "' . $zipfile->errorName(true) . '"';
             return false;
         }
     } else {
         require_once JPATH_SITE . '/includes/Archive/Tar.php';
         $archive = new Archive_Tar($this->_uploadfile);
         $archive->setErrorHandling(PEAR_ERROR_PRINT);
         if (!$archive->extractModify($extractdir, '')) {
             $this->setError(1, 'Extract Error');
             return false;
         }
     }
     // Try to find the correct install dir. in case that the package have subdirs
     // Save the install dir for later cleanup
     jimport('joomla.filesystem.folder');
     $this->_uploadfile = JFolder::files($extractdir, '');
     if (count($this->_uploadfile) == 1) {
         if (is_dir($extractdir . $this->_uploadfile[0])) {
             $this->_unpackdir = JPath::clean($extractdir . $this->_uploadfile[0]);
             $this->_uploadfile = JFolder::files($extractdir, '');
         }
     }
     return true;
 }
Exemple #28
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)
 {
     jimport('pear.archive_tar.Archive_Tar');
     if (is_string($files)) {
         $files = array($files);
     }
     if ($autoExt) {
         $archive .= '.' . $compress;
     }
     $tar = new Archive_Tar($archive, $compress);
     $tar->setErrorHandling(PEAR_ERROR_PRINT);
     $tar->createModify($files, $addPath, $removePath);
     if ($cleanUp) {
         JFile::delete($files);
     }
     return $tar;
 }
 function stepUnpack(Am_BatchProcessor $batch)
 {
     foreach ($this->getSession()->upgrades as $k => $upgrade) {
         $upgrade->dir = null;
         if (!empty($upgrade->dir)) {
             continue;
         }
         // already unpacked?
         $record = $this->getDi()->uploadTable->load($upgrade->upload_id);
         $tar = new Archive_Tar($fn = $record->getFullPath());
         $upgrade->dir = DATA_DIR . DIRECTORY_SEPARATOR . $record->getFilename() . '-unpack';
         if (!mkdir($upgrade->dir)) {
             throw new Am_Exception_InputError("Could not create folder to unpack downloaded archive: [{$upgrade->dir}]");
             unset($upgrade->dir);
         }
         $tar->setErrorHandling(PEAR_ERROR_CALLBACK, array($this, '_tarError'));
         try {
             if (!$tar->extract($upgrade->dir)) {
                 throw new Am_Exception_InputError("Could not unpack downloaded archive: [{$fn}] to [{$upgrade->dir}]");
             }
         } catch (Exception $e) {
             $this->getDi()->errorLogTable->logException($e);
             unset($upgrade->dir);
             @rmdir($upgrade->dir);
         }
         // normally we delete uploaded archive
         $record->delete();
         unset($upgrade->upload_id);
     }
     return true;
 }
Exemple #30
0
<?php

/**
 * This file is part of EC-CUBE WebPay module
 *
 * @copyright 2014 WebPay All Rights Reserved.
 */
require_once '../../../../html/require.php';
require_once MODULE_REALDIR . 'mdl_webpay/inc/include.php';
require_once MDL_WEBPAY_CLASS_REALDIR . 'models/SC_Mdl_WebPay_Models_Module.php';
SC_Mdl_WebPay_Models_Module::insert();
$setting_path = '/admin/load_module_config.php?module_id=' . MDL_WEBPAY_ID;
echo 'インストールが終了しました。ログインして ' . $setting_path . ' から設定をおこなってください。' . "\n";
$origdir = getcwd();
$tar_path = MDL_WEBPAY_REALDIR . 'WebPayExt.tar.gz';
$tar = new Archive_Tar($tar_path, true);
chdir(MDL_WEBPAY_REALDIR . '/plugin/');
$tar->setErrorHandling(PEAR_ERROR_PRINT);
$tar->create('.');
echo $tar_path . ' に拡張用プラグインを作成しました。管理画面のプラグイン管理からインストールしてください。' . "\n";
chdir($origdir);