public function testAutoRollback() { // Setup $this->autoRollbackHelper(); $this->backupFile->buildFromDirectory($this->archivedDir); $this->backupFile->addEmptyDir("testDirectory"); $this->backupFile->compress(\Phar::GZ, '.tgz'); $newFile = $this->backupPath . '/' . uniqid() . '_code.tgz'; copy($this->backupFileName, $newFile); if (file_exists($this->backupFileName)) { unset($this->backupFile); unlink($this->backupFileName); } $gtzFile = str_replace('tar', 'tgz', $this->backupFileName); if (file_exists($gtzFile)) { unlink($gtzFile); } $this->backupFileName = $newFile; // Change the contents of a.txt $this->autoRollbackHelper(1); $this->assertEquals('foo changed', file_get_contents($this->archivedDir . 'a.txt')); $this->backupInfo->expects($this->once())->method('getBlacklist')->willReturn(['excluded']); // Rollback process $this->rollBack->execute($this->backupFileName); // Assert that the contents of a.txt has been restored properly $this->assertEquals('foo', file_get_contents($this->archivedDir . 'a.txt')); }
/** * @inheritDoc */ public function addDir($dir) { try { $this->phar->buildFromDirectory($dir); } catch (\PharException $e) { return false; } return true; }
/** * @covers common\classes\AutoLoader::load_extension */ public function test_load_extension() { $extensions = glob(ROOT_PATH . DS . 'extensions' . DS . '*'); foreach ($extensions as $extension) { $name = ucwords(explode('.', basename($extension))[0]); self::assertTrue(AutoLoader::load_extension($name)); } self::assertFalse(AutoLoader::load_extension('NotExistedClass')); $name = 'fakeextension'; $extension_file = ROOT_PATH . DS . 'extensions' . DS . $name; $extension_build_dir = ROOT_PATH . DS . 'tests' . DS . 'resource' . DS . $name; $extension_file_tar = "{$extension_file}.tar"; $extension_file_gz = "{$extension_file}.tar.gz"; if (file_exists($extension_file_gz)) { Phar::unlinkArchive($extension_file_gz); } $phar = new PharData($extension_file_tar); $phar->buildFromDirectory($extension_build_dir); $phar->compress(Phar::GZ); if (file_exists($extension_file_tar)) { unlink($extension_file_tar); } self::assertTrue(AutoLoader::load_extension($name)); unlink($extension_file_gz); }
/** * Files constructor. * @param $target */ public function __construct($target) { $this->tarFilename = sys_get_temp_dir() . '/' . uniqid() . '.tar'; $phar = new \PharData($this->tarFilename); $phar->buildFromDirectory($target); $this->tarStream = fopen($this->tarFilename, 'r'); }
static function gzipFolder($folder) { try { $a = new PharData($folder . '_archive.zip'); $a->buildFromDirectory($folder); } catch (Exception $e) { return false; } return true; }
/** * Internal. Backup server when it's not running * @param string $path * @param string $filename * @return boolean */ private function backupSwitchedOff($path, $filename) { try { $phar = new PharData($path . 'backups/' . $filename . '.zip'); $phar->buildFromDirectory($path . 'world/'); return TRUE; } catch (UnexpectedValueException $e) { echo $e->getMessage(); return FALSE; } }
/** * @param string $folder * * @return bool */ protected function backupFolder($folder) { GeneralUtility::mkdir_deep($this->backupPath); $compressedFileName = $folder . '_' . time() . '.tar'; $phar = new \PharData($this->backupPath . $compressedFileName); if ($phar->buildFromDirectory(PATH_site . $folder, '/^(?!_temp_|_processed_|_recycler_).*/')) { BackupUtility::generateBackupLog($folder, $compressedFileName . '.gz', $this->backupPath, $this->backupsToKeep); BackupUtility::gzCompressFile($this->backupPath . $compressedFileName); return true; } return false; }
/** * @param InputInterface $input * @param OutputInterface $output * @return int|null|void */ protected function execute(InputInterface $input, OutputInterface $output) { parent::execute($input, $output); $language = $input->getArgument('language'); $tmpFolder = $input->getOption('tmp'); $_configuration = $this->getHelper('configuration')->getConfiguration(); $connection = $this->getHelper('configuration')->getConnection(); if ($connection) { $lang = isset($language) ? $language : null; $lang = mysql_real_escape_string($lang); $q = mysql_query("SELECT * FROM language WHERE english_name = '{$lang}' "); $langInfo = mysql_fetch_array($q, MYSQL_ASSOC); if (!$langInfo) { $output->writeln("<comment>Language '{$lang}' is not registered in the Chamilo Database</comment>"); $q = mysql_query("SELECT * FROM language WHERE parent_id IS NULL or parent_id = 0"); $output->writeln("<comment>Available languages are: </comment>"); while ($langRow = mysql_fetch_array($q, MYSQL_ASSOC)) { $output->write($langRow['english_name'] . ", "); } $output->writeln(' '); $q = mysql_query("SELECT * FROM language WHERE parent_id <> 0"); $output->writeln("<comment>Available sub languages are: </comment>"); while ($langRow = mysql_fetch_array($q, MYSQL_ASSOC)) { $output->write($langRow['english_name'] . ", "); } $output->writeln(' '); exit; } else { $output->writeln("<comment>Language</comment> <info>'{$lang}'</info> <comment>is registered in the Chamilo installation with iso code: </comment><info>{$langInfo['isocode']} </info>"); } $langFolder = $_configuration['root_sys'] . 'main/lang/' . $lang; if (!is_dir($langFolder)) { $output->writeln("<comment>Language '{$lang}' does not exist in the path: {$langFolder}</comment>"); } if (empty($tmpFolder)) { $tmpFolder = '/tmp/'; $output->writeln("<comment>No temporary directory defined. Assuming /tmp/. Please make sure you have *enough space* left on that device"); } if (!is_dir($tmpFolder)) { $output->writeln("<comment>Temporary directory: {$tmpFolder} is not a valid dir path, using /tmp/ </comment>"); $tmpFolder = '/tmp/'; } if ($langInfo) { $output->writeln("<comment>Creating translation package</comment>"); $fileName = $tmpFolder . $langInfo['english_name'] . '.tar'; $phar = new \PharData($fileName); $phar->buildFromDirectory($langFolder); $phar->setMetadata($langInfo); $output->writeln("<comment>File created:</comment> <info>{$fileName}</info>"); } } }
private static function build_extension($name) { $name = strtolower($name); $extension_file = ROOT_PATH . DS . 'extensions' . DS . $name; $extension_build_dir = ROOT_PATH . DS . 'build' . DS . $name; $extension_file_tar = "{$extension_file}.tar"; $extension_file_gz = "{$extension_file}.tar.gz"; if (file_exists($extension_file_gz)) { \Phar::unlinkArchive($extension_file_gz); } $phar = new \PharData($extension_file_tar); $phar->buildFromDirectory($extension_build_dir); $phar->compress(\Phar::GZ); if (file_exists($extension_file_tar)) { unlink($extension_file_tar); } }
public function zip($from, $to) { if (!is_dir($from) || !is_readable($from)) { throw new Exception('Extension dir doesn\'t not exist or is not a readable directory'); } $outputDir = dirname($to); if (!is_dir($outputDir) || !is_writable($outputDir)) { throw new Exception('Output dir doesn\'t not exist or is not a writable directory'); } $phar = new PharData($to, null, null, PHAR::ZIP); $phar->buildFromDirectory($from); $phar->compressFiles(PHAR::GZ); unset($phar); if (!file_exists($to)) { throw new Exception('Can\'t create zip file'); } if (PHP_SAPI == 'cli') { echo "Zip file is created\n"; } }
function __c3_build_html_report(PHP_CodeCoverage $codeCoverage, $path) { $writer = new PHP_CodeCoverage_Report_HTML(); $writer->process($codeCoverage, $path . 'html'); if (file_exists($path . '.tar')) { unlink($path . '.tar'); } $phar = new PharData($path . '.tar'); $phar->setSignatureAlgorithm(Phar::SHA1); $files = $phar->buildFromDirectory($path . 'html'); array_map('unlink', $files); if (in_array('GZ', Phar::getSupportedCompression())) { if (file_exists($path . '.tar.gz')) { unlink($path . '.tar.gz'); } $phar->compress(\Phar::GZ); // close the file so that we can rename it unset($phar); unlink($path . '.tar'); rename($path . '.tar.gz', $path . '.tar'); } return $path . '.tar'; }
function compressTarGZ($tar_filename, $tar_dir, $compress_level = 5) { $compress_level = $compress_level < 1 || $compress_level > 9 ? 5 : $compress_level; $exit_code = 0; if (pathinfo($tar_filename, PATHINFO_EXTENSION) == 'gz') { $filename = rtrim($tar_filename, '.gz'); } else { $filename = $tar_filename . '.tar.gz'; } $tar = rtrim($tar_filename, '.gz'); //remove archive if exists if (is_file($tar_filename)) { unlink($tar_filename); } if (is_file($filename)) { unlink($filename); } if (is_file($tar)) { unlink($tar); } if (class_exists('PharData')) { try { $a = new PharData($tar); $a->buildFromDirectory($tar_dir); // this code creates tar-file if (file_exists($tar)) { // remove tar-file after zipping gzip($tar, $compress_level); unlink($tar); } } catch (Exception $e) { $error = new AError($e->getMessage()); $error->toLog()->toDebug(); $exit_code = 1; } } else { $exit_code = 1; } if ($exit_code) { $registry = Registry::getInstance(); $registry->get('load')->library('targz'); $targz = new Atargz(); return $targz->makeTar($tar_dir . $tar_filename, $filename, $compress_level); } else { return true; } }
/** * Pack files * * @param type $files * @param type $compress */ function packFiles($files = null, $compress = false) { try { // We remove the old archive if (is_file('netbeans.tar')) { unlink('netbeans.tar'); } $phar = new PharData('netbeans.tar'); if ($files) { // We only pack the specified files } else { // We pack the whole directory $phar->buildFromDirectory('netbeans'); } if ($compress) { $phar->compress(Phar::GZ); } } catch (Exception $e) { echo "Exception : " . $e; } }
/** * Adding files to the archive. * * @param PharData|ZipArchive $archive * @return PharData|ZipArchive * @access private * @final */ private final function addFiles($archive) { switch ($this->type) { case self::RAR: case self::TAR: $archive->buildFromDirectory($this->path); break; case self::ZIP: $this->backupDir = str_replace('\\', '/', realpath($this->path)); $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->path), RecursiveIteratorIterator::SELF_FIRST); foreach ($files as $file) { $file = str_replace('\\', '/', $file); if (in_array(substr($file, strrpos($file, '/') + 1), array('.', '..'))) { continue; } $file = realpath($file); if (is_file($file)) { $archive->addFile($file, trim(str_replace($this->path, '', $file), '/')); } } break; } return $archive; }
/** * @depends testConnect */ public function testTarRequest(ApiClient $docker) { mkdir('/project/TEMP'); $tarFilename = sys_get_temp_dir() . '/' . uniqid() . '.tar'; $phar = new \PharData($tarFilename); $phar->buildFromDirectory('/project/containers/php'); $response = $docker->put('/containers/' . getenv('HOSTNAME') . '/archive', ['path' => '/project/TEMP'], new requestHandlers\Tar($tarFilename)); $this->assertEquals(200, $response->getStatus()); $this->assertFileExists('/project/TEMP/Dockerfile'); unlink($tarFilename); exec('rm -rf /project/TEMP'); }
<?php $rand = rand(12, 5.745129542475679E+39); $path = md5($rand, false); $allowedExtensions = array('odt', 'doc', 'docx', 'rtf', 'pdf', 'rtf'); $archiveName = md5($rand, false); $upload_ext = strtolower(substr(strrchr($_FILES['file_cv']['name'], '.'), 1)); $filePath = $path . '/' . $archiveName . '.' . $upload_ext; if (in_array($upload_ext, $allowedExtensions)) { mkdir($path, 0777, true); $resultat = move_uploaded_file($_FILES['file_cv']['tmp_name'], $filePath); $phar = new PharData($archiveName . '.zip'); $phar->buildFromDirectory($path); $mail = '*****@*****.**'; // Déclaration de l'adresse de destination. if (!preg_match("#^[a-z0-9._-]+@(hotmail|live|msn).[a-z]{2,4}\$#", $mail)) { $passage_ligne = "\r\n"; } else { $passage_ligne = "\n"; } //=====Déclaration des messages au format texte et au format HTML. $message_txt = $_POST['message']; $message_html = '<p>' . $_POST['message'] . '</p>'; //========== //=====Lecture et mise en forme de la pièce jointe. $fichier = fopen($archiveName . '.zip', "r"); $attachement = fread($fichier, filesize($archiveName . '.zip')); $attachement = chunk_split(base64_encode($attachement)); fclose($fichier); //========== //=====Création de la boundary.
header('Location: /admin/?error=empty'); // redirect exit; } // create the folder structure // create base widget file $currentProject = @$_REQUEST['site']; $absPathCurrentProject = $_SERVER['DOCUMENT_ROOT'] . "/" . $currentProject; $message = "Existing"; if (!is_dir($absPathCurrentProject)) { $tar = "{$currentProject}.tar"; $phar = new PharData($tar); $result = true; try { $message = "ImageFailed"; $phar->buildFromDirectory(__DIR__ . '/skeleton'); $message = "GenerationFailed"; $result = $phar->extractTo($absPathCurrentProject); if ($result) { $message = "success"; unset($phar); unlink($tar); header("Location: /admin/?site={$currentProject}"); exit; } else { throw new Exception("Failed to create tar {$result}"); } } catch (Exception $e) { unset($phar); unlink($tar); unlink($absPathCurrentProject);
/** * Compress files with Tar archiver * * @param string $archive_name - archive name (zip, tgz, gz and tar.gz supported) * @param string $file_list - list of files to place into archive * @param string $dirname - directory, where the files should be get from * @return bool true */ function fn_compress_files($archive_name, $file_list, $dirname = '') { if (!class_exists('PharData')) { fn_set_notification('E', __('error'), __('error_class_phar_data_not_found')); return false; } if (empty($dirname)) { $dirname = Registry::get('config.dir.files'); } if (!is_array($file_list)) { $file_list = array($file_list); } $ext = fn_get_file_ext($archive_name); $_exts = explode('.', $archive_name); array_shift($_exts); $first_dot_ext = '.' . implode('.', $_exts); // https://bugs.php.net/bug.php?id=58852. Phar gets ext from the first dot: 'test.1.2.3.tgz' -> ext = 1.2.3.tgz $arch = fn_normalize_path($dirname . '/' . $archive_name); fn_rm($arch); if ($ext != 'zip') { $arch = fn_normalize_path($dirname . '/' . $archive_name . '.tmp'); fn_rm($arch); } if ($ext == 'gz' && strpos($archive_name, '.tar.gz') !== false) { $ext = 'tar.gz'; } try { $phar = new PharData($arch); foreach ($file_list as $file) { $path = fn_normalize_path($dirname . '/' . $file); if (is_file($path)) { $phar->addFile($path, basename($path)); } elseif (is_dir($path)) { $phar->buildFromDirectory($path); } } if ($ext == 'zip') { $phar->compressFiles(Phar::GZ); } else { $phar->compress(Phar::GZ, $first_dot_ext); // We need to unset Phar because the PharData class still has the file "open". // Windows servers cannot delete the files with the "open" handlers. unset($phar); fn_rm($arch); } } catch (Exception $e) { fn_set_notification('E', __('error'), $e->getMessage()); return false; } return true; }
echo "Exception : " . $e; echo "\n{$filename}\t{$base_dir}/{$year}/{$month}/{$day}\n"; exit; } try { $filename = "{$year}{$month}{$day}" . "_old.tar"; $tmppath = "tmp/{$filename}"; echo "\r{$tmppath}\r"; if (file_exists($tmppath)) { unlink($tmppath); } if (file_exists("{$tmppath}.gz")) { unlink("{$tmppath}.gz"); } $day_tar = new PharData($tmppath); $day_tar->buildFromDirectory("{$base_dir}/{$year}/{$month}/{$day}", '/\\.js\\.old/'); $day_tar->compress(Phar::GZ); if (file_exists("{$tmppath}.gz")) { $client->putObject(array('Bucket' => "uhcan", 'Key' => "{$base_upload_dir}/{$year}/{$month}/{$filename}.gz", 'SourceFile' => "{$tmppath}.gz")); $client->waitUntilObjectExists(array('Bucket' => "uhcan", 'Key' => "{$base_upload_dir}/{$year}/{$month}/{$filename}.gz")); unset($day_tar); unlink($tmppath); unlink("{$tmppath}.gz"); Phar::unlinkArchive($tmppath); Phar::unlinkArchive("{$tmppath}.gz"); //echo "\r$tmppath\r"; } else { //echo "\rNo gzip file created: $tmppath\r"; } unset($day_tar); } catch (Exception $e) {
protected function compressBackup($path) { $compressed = new \PharData(base_path() . '/backup/' . $this->timestamp . '.tar'); $compressed->buildFromDirectory($path); $compressed->compress(\Phar::GZ); }
/** * Realizar un backup de la aplicación y comprimirlo. * * @param string $backupFile nombre del archivo de backup * @throws SPException * @return bool */ private static function backupApp($backupFile) { if (!class_exists('PharData')) { if (Util::runningOnWindows()) { throw new SPException(SPException::SP_CRITICAL, _('Esta operación sólo es posible en entornos Linux')); } elseif (!self::backupAppLegacyLinux($backupFile)) { throw new SPException(SPException::SP_CRITICAL, _('Error al realizar backup en modo compatibilidad')); } return true; } $compressedFile = $backupFile . '.gz'; try { if (file_exists($compressedFile)) { unlink($compressedFile); } $archive = new \PharData($backupFile); $archive->buildFromDirectory(Init::$SERVERROOT); $archive->compress(\Phar::GZ); unlink($backupFile); } catch (\Exception $e) { throw new SPException(SPException::SP_CRITICAL, $e->getMessage()); } return file_exists($backupFile); }
foreach ($processes as $temp) { pcntl_wait($temp, $status, WUNTRACED); } fwrite(STDERR, "Daemon processes removed!" . PHP_EOL); /* while (pcntl_waitpid(0, $status) != -1) { $status = pcntl_wexitstatus($status); echo "Child $status completed\n"; } */ } if ($compressData) { fwrite(STDERR, "Compresing files and files.." . PHP_EOL); //Compres file $a = new PharData($backupFolder . '.tar'); $a->buildFromDirectory(dirname(__FILE__) . '/' . $backupFolder); file_put_contents($backupFolder . '.tar.gz', gzencode(file_get_contents($backupFolder . '.tar'), 9)); fwrite(STDERR, "Compresion complete!" . PHP_EOL); fwrite(STDERR, "Removing temp folders and files.." . PHP_EOL); //remove other files unlink(realpath($backupFolder . '.tar')); deleteDir(realpath($backupFolder)); fwrite(STDERR, "Temp folders and files removed!" . PHP_EOL); } } catch (Exception $e) { fwrite(STDERR, "{$e}" . PHP_EOL); } return; //exit(1); } else { $dumper = new Dumper($host, $port, $database, $noHistory, $callbackFile, $inlineAttachment, $binaryAttachments, $prettyJsonOutput, $separateFiles, $timeStamp, $callbackFilter);
/** * @param Driver $driver * @param int $version * * @return void */ private function doCreateResumePoint(Driver $driver, int $version) { $directory = $this->getTemporaryName(); mkdir($directory); $number = 1; $that = $this; $this->doDumpDatabase($driver, function ($query) use($that, $directory, &$number) { file_put_contents($that->getSqlFilePath($directory, $number), $query); $number++; }, 'Dumping database'); $this->output->writeln('Creating archive file'); $archiveFile = $this->getSqlDumpPath() . '/' . $version . '.tar'; $phar = new \PharData($archiveFile); $phar->buildFromDirectory($directory); $this->output->writeln('Removing temporary files'); for ($i = 1; $i < $number; $i++) { unlink($this->getSqlFilePath($directory, $i)); } rmdir($directory); }
unpack_tar($target_file); } if ($imageFileType == "zip") { unpack_zip($target_file); $target_file = str_replace('.zip', '.tar.gz', $target_file); $zip_file = pathinfo($_FILES["fileToUpload"]['name']); $tar_file = $target_dir . strtolower($zip_file['filename']); if (is_file($tar_file . '.tar.gz')) { unlink($tar_file . '.tar.gz'); } if (is_file($tar_file . '.zip')) { unlink($tar_file . '.zip'); } try { $a = new PharData($tar_file . '.tar'); $a->buildFromDirectory($target_dir . strtolower($zip_file['filename'])); $a->compress(Phar::GZ); unset($a); Phar::unlinkArchive($tar_file . '.tar'); } catch (Exception $e) { $response->status = 500; $response->message = $e->getMessage(); $response->json($response); } } $wrong_folder = current(explode(".", $_FILES["fileToUpload"]["name"])); //store data in DB $response = read_json($target_file, $id, 'gz', $wrong_folder); } else { $response->status = 500; $response->message = 'Sorry, your file was not uploaded.';
$resize = "-gravity center -trim +repage -background none -resize {$directories['maps']['res']} -extent {$directories['maps']['res']}"; doexec("convert {$mapimg} {$resize} {$dstpath}/maps/{$mapname}.png"); } foreach ($directories as $dir => $data) { $path = "{$dstpath}/{$dir}"; echo "Adding new files to {$dir}\n"; doexec("git add {$path}/*"); } //Create archive of images $dirs = implode('|', array_keys($directories)); $arc = "{$dstpath}/images.zip"; if (file_exists($arc)) { unlink($arc); } $p = new PharData($arc); $p->buildFromDirectory($dstpath, "/\\/({$dirs})\\//"); exit; function remove_ext($str) { $noext = preg_replace('/(.+)\\..*$/', '$1', $str); // print "input: $str\n"; // print "output: $noext\n\n"; return $noext; } function doexec($cmd) { // echo "DEBUG: Running {$cmd}\n"; exec($cmd); } function getvgui($name, $path = 'vgui/inventory') {
/** * @param string $format The algorithm used for the archive. * @param string $destination The path to the new archive. * @param array $contents The files and/or directories that should be included in the archive. * * @return \PharData * * @throws ArchivalException If the archive could not be created. */ protected function createArchive($format, $destination, array $contents = []) { try { $archive = new \PharData($destination, null, null, $format); foreach ($contents as $pathInArchive => $path) { if (is_integer($pathInArchive)) { $pathInArchive = null; } if (!is_readable($path)) { throw new ArchivalException(sprintf('Could not add the given file/dir to the archive: %s, it doesn\'t exist', $path)); } if (is_dir($path)) { $archive->buildFromDirectory($path); } else { if ($pathInArchive !== null) { $archive->addFile($path, $pathInArchive); } else { $archive->addFile($path); } } } } catch (\Exception $e) { throw new ArchivalException(sprintf('Failed to create archive with destination: %s', $destination), null, $e); } return $archive; }
/** * Given the path to a Known export, creates a complete .tar.gz file and returns the path to that. * If $save_path is false, will save to the temporary folder. * * @param $path * @param $save_path * @return string */ static function archiveExportFolder($path, $save_path = false) { if (!is_dir($path)) { return false; } if (substr($path, -1) != DIRECTORY_SEPARATOR) { $path .= DIRECTORY_SEPARATOR; } if (!file_exists($path . 'known.json')) { return false; } if (!class_exists('PharData')) { return false; } $filename = str_replace('.', '_', site()->config()->host); if (file_exists(site()->config()->getTempDir() . $filename . '.tar')) { @unlink(site()->config()->getTempDir() . $filename . '.tar'); @unlink(site()->config()->getTempDir() . $filename . '.tar.gz'); } $archive = new \PharData(site()->config()->getTempDir() . $filename . '.zip'); $archive->buildFromDirectory($path); //$archive->compress(\Phar::GZ); return $archive->getPath(); }
/** * テンプレート一覧からのダウンロード * * @param Application $app * @param Request $request * @param $id */ public function download(Application $app, Request $request, $id) { /** @var $Template \Eccube\Entity\Template */ $Template = $app['eccube.repository.template']->find($id); if (!$Template) { throw new NotFoundHttpException(); } // 該当テンプレートのディレクトリ $config = $app['config']; $templateCode = $Template->getCode(); $targetRealDir = $config['root_dir'] . '/app/template/' . $templateCode; $targetHtmlRealDir = $config['root_dir'] . '/html/template/' . $templateCode; // 一時ディレクトリ $uniqId = sha1(Str::random(32)); $tmpDir = $config['template_temp_realdir'] . '/' . $uniqId; $appDir = $tmpDir . '/app'; $htmlDir = $tmpDir . '/html'; // ファイル名 $tarFile = $config['template_temp_realdir'] . '/' . $uniqId . '.tar'; $tarGzFile = $tarFile . '.gz'; $downloadFileName = $Template->getCode() . '.tar.gz'; // 該当テンプレートを一時ディレクトリへコピーする. $fs = new Filesystem(); $fs->mkdir(array($appDir, $htmlDir)); $fs->mirror($targetRealDir, $appDir); $fs->mirror($targetHtmlRealDir, $htmlDir); // tar.gzファイルに圧縮する. $phar = new \PharData($tarFile); $phar->buildFromDirectory($tmpDir); // appディレクトリがない場合は, 空ディレクトリを追加 // @see https://github.com/EC-CUBE/ec-cube/issues/742 if (empty($phar['app'])) { $phar->addEmptyDir('app'); } $phar->compress(\Phar::GZ); // ダウンロード完了後にファイルを削除する. // http://stackoverflow.com/questions/15238897/removing-file-after-delivering-response-with-silex-symfony $app->finish(function (Request $request, Response $response, \Silex\Application $app) use($tmpDir, $tarFile, $tarGzFile) { $app['monolog']->addDebug('remove temp file: ' . $tmpDir); $app['monolog']->addDebug('remove temp file: ' . $tarFile); $app['monolog']->addDebug('remove temp file: ' . $tarGzFile); $fs = new Filesystem(); $fs->remove($tmpDir); $fs->remove($tarFile); $fs->remove($tarGzFile); }); return $app->sendFile($tarGzFile)->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $downloadFileName); }
/** * Package a module * @param string $module * @return string */ protected function packageModuleAction($module = 'core') { \tools::rmdir('var/pack/'); \tools::copy_dir('modules/' . $module . '/', 'var/pack/' . $module . '/'); /* If this module has a profile, retrieve profile */ if (is_dir('profiles/' . PROFILE . '/modules/' . $module . '/')) { /* Remove concats */ $concats = glob('profiles/' . PROFILE . '/modules/' . $module . '/*concat_*'); if (is_array($concats) && !empty($concats)) { foreach ($concats as $file) { unlink($file); } } \tools::copy_dir('profiles/' . PROFILE . '/modules/' . $module . '/', 'var/pack/' . $module . '/'); } /* Clean rights: keep only default rights */ /* Module Rights */ $objModule = \app::getModule($module); $rolesToRemove = array(); foreach (\app::getModule('core')->getEntity('role')->where('id_role > 4') as $role) { $rolesToRemove[] = $role->id_role; $objModule->setRights($role->id_role, 1); } \tools::serialize('var/pack/' . $module . '/module', $objModule); /* Pages rights */ foreach ($objModule->getPages() as $page) { foreach ($rolesToRemove as $idRole) { $page->setRights($idRole, 1); } \tools::serialize('var/pack/' . $module . '/pages/' . $page->getId(), $page); } /* Model rights */ foreach ($objModule->getModel() as $entity) { foreach ($rolesToRemove as $idRole) { $entity->setRights($idRole, 15); foreach ($entity->getFields() as $field) { $field->setRights($idRole, 7); } } \tools::serialize('var/pack/' . $module . '/model/' . $entity->getName(), $entity); } /* generate and send Zip to client */ $phar = new \PharData('profiles/' . PROFILE . '/modules/' . $module . '.zip'); $phar->buildFromDirectory('./var/pack'); \app::$response->setHeader('Content-type', 'application/zip'); return 'profiles/' . PROFILE . '/modules/' . $module . '.zip'; }
/** * Archive a directory * * @param Application $app Silex Application * @param Request $request Request parameters * * @return JsonResponse Array of objects, directory content after the archive process */ function archive(Application $app, Request $request) { if ($app["rights.canArchiveDirectory"] == false) { $app->abort(403, "This user doesn't have the rights to archive a directory"); } $dirpath = Utils\check_path($app['cakebox.root'], $request->get('path')); if (!isset($dirpath)) { $app->abort(400, "Missing parameters"); } $dir = "{$app['cakebox.root']}/{$dirpath}"; if (file_exists($dir) === false) { $app->abort(404, "Directory not found"); } if (is_dir($dir) === false) { $app->abort(403, "This is not a directory"); } $dirpath_info = pathinfo($dir); $dirname = $dirpath_info["dirname"]; $basename = $dirpath_info["basename"]; if (is_writable($dir) === false) { $app->abort(403, "Parent directory is not writable"); } $archive_path = "{$app['cakebox.root']}/{$dirpath}/../{$basename}.tar"; if (file_exists("{$archive_path}.inc") || file_exists($archive_path)) { $app->abort(406, "This directory already have a tar file or is already under a tar process"); } file_put_contents("{$archive_path}.inc", "Creation of {$basename}.tar.inc is in progress... If not, remove this file manualy."); $p = new \PharData($archive_path); $p->compress(\Phar::NONE); $p->buildFromDirectory($dir); unlink("{$archive_path}.inc"); $subRequest = Request::create('/api/directories', 'GET', ['path' => dirname($dirpath)]); return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST); }