Example #1
1
function create_zip_package($dir, $destination)
{
    $zip = new ZipArchive();
    if ($zip->open($destination, ZipArchive::OVERWRITE) !== true) {
        echo 'Failed to create ' . $destination . ' with code ' . $ret;
        return false;
    } else {
        $zip->addGlob($dir . '/*.php', GLOB_BRACE, array('add_path' => '/' . basename($dir) . '/', 'remove_all_path' => true));
        $zip->addFile($dir . '/package-info.xml', 'package-info.xml');
        $zip->addFile($dir . '/agreement.txt', 'agreement.' . basename($dir) . '.txt');
        $zip->close();
        return true;
    }
}
Example #2
0
 /**
  * 程序文件列表
  */
 public function actionIndex()
 {
     if (isset($_POST['id'])) {
         $files = $_POST['id'];
         if ($files) {
             //提交打包
             $zip = new ZipArchive();
             $name = 'yiifcmsBAK_' . date('YmdHis', time()) . '.zip';
             $zipname = WWWPATH . '/' . $name;
             //创建一个空的zip文件
             if ($zip->open($zipname, ZipArchive::OVERWRITE)) {
                 foreach ((array) $files as $file) {
                     if (is_dir($file)) {
                         //递归检索文件
                         $allfiles = Helper::scanfDir($file, true);
                         foreach ((array) $allfiles['files'] as $v) {
                             $zip->addFile(WWWPATH . '/' . $v, $v);
                         }
                     } else {
                         $zip->addFile(WWWPATH . '/' . $file, $file);
                     }
                 }
                 $zip->close();
                 //开始下载
                 Yii::app()->request->sendFile($name, file_get_contents($zipname), '', false);
                 //下载完成后要进行删除
                 @unlink($zipname);
             } else {
                 throw new CHttpException('404', 'Failed');
             }
         }
     } else {
         $files = Helper::scanfDir(WWWPATH);
         asort($files['dirs']);
         asort($files['files']);
         $files = array_merge($files['dirs'], $files['files']);
         $listfiles = array();
         foreach ($files as $file) {
             $tmpfilename = explode('/', $file);
             $filename = end($tmpfilename);
             if (is_dir($file)) {
                 $allfiles = Helper::scanfDir($file, true);
                 if ($allfiles['files']) {
                     $filesize = 0;
                     foreach ((array) $allfiles['files'] as $val) {
                         $filesize += filesize($val);
                     }
                 }
                 $listfiles[$filename]['type'] = 'dir';
             } else {
                 $filesize = filesize($file);
                 $listfiles[$filename]['type'] = 'file';
             }
             $listfiles[$filename]['id'] = $filename;
             $listfiles[$filename]['size'] = Helper::byteFormat($filesize);
             $listfiles[$filename]['update_time'] = filemtime($filename);
         }
     }
     $this->render('index', array('listfiles' => $listfiles));
 }
Example #3
0
 public function writeToFile($filename)
 {
     @unlink($filename);
     //if the zip already exists, overwrite it
     $zip = new ZipArchive();
     if (empty($this->sheets_meta)) {
         self::log("Error in " . __CLASS__ . "::" . __FUNCTION__ . ", no worksheets defined.");
         return;
     }
     if (!$zip->open($filename, ZipArchive::CREATE)) {
         self::log("Error in " . __CLASS__ . "::" . __FUNCTION__ . ", unable to create zip.");
         return;
     }
     $zip->addEmptyDir("docProps/");
     $zip->addFromString("docProps/app.xml", self::buildAppXML());
     $zip->addFromString("docProps/core.xml", self::buildCoreXML());
     $zip->addEmptyDir("_rels/");
     $zip->addFromString("_rels/.rels", self::buildRelationshipsXML());
     $zip->addEmptyDir("xl/worksheets/");
     foreach ($this->sheets_meta as $sheet_meta) {
         $zip->addFile($sheet_meta['filename'], "xl/worksheets/" . $sheet_meta['xmlname']);
     }
     if (!empty($this->shared_strings)) {
         $zip->addFile($this->writeSharedStringsXML(), "xl/sharedStrings.xml");
         //$zip->addFromString("xl/sharedStrings.xml",     self::buildSharedStringsXML() );
     }
     $zip->addFromString("xl/workbook.xml", self::buildWorkbookXML());
     $zip->addFile($this->writeStylesXML(), "xl/styles.xml");
     //$zip->addFromString("xl/styles.xml"           , self::buildStylesXML() );
     $zip->addFromString("[Content_Types].xml", self::buildContentTypesXML());
     $zip->addEmptyDir("xl/_rels/");
     $zip->addFromString("xl/_rels/workbook.xml.rels", self::buildWorkbookRelsXML());
     $zip->close();
 }
Example #4
0
function pleiofile_add_folder_to_zip(ZipArchive &$zip_archive, ElggObject $folder, $folder_path = "")
{
    if (!empty($zip_archive) && !empty($folder) && elgg_instanceof($folder, "object", "folder")) {
        $folder_title = elgg_get_friendly_title($folder->title);
        $zip_archive->addEmptyDir($folder_path . $folder_title);
        $folder_path .= $folder_title . DIRECTORY_SEPARATOR;
        $file_options = array("type" => "object", "subtype" => "file", "limit" => false, "relationship" => "folder_of", "relationship_guid" => $folder->getGUID());
        // add files from this folder to the zip
        if ($files = elgg_get_entities_from_relationship($file_options)) {
            foreach ($files as $file) {
                // check if the file exists
                if ($zip_archive->statName($folder_path . $file->originalfilename) === false) {
                    // doesn't exist, so add
                    $zip_archive->addFile($file->getFilenameOnFilestore(), $folder_path . sanitize_file_name($file->originalfilename));
                } else {
                    // file name exists, so create a new one
                    $ext_pos = strrpos($file->originalfilename, ".");
                    $file_name = substr($file->originalfilename, 0, $ext_pos) . "_" . $file->getGUID() . substr($file->originalfilename, $ext_pos);
                    $zip_archive->addFile($file->getFilenameOnFilestore(), $folder_path . sanitize_file_name($file_name));
                }
            }
        }
        // check if there are subfolders
        $folder_options = array("type" => "object", "subtype" => "folder", "limit" => false, "metadata_name_value_pairs" => array("parent_guid" => $folder->getGUID()));
        if ($sub_folders = elgg_get_entities_from_metadata($folder_options)) {
            foreach ($sub_folders as $sub_folder) {
                pleiofile_add_folder_to_zip($zip_archive, $sub_folder, $folder_path);
            }
        }
    }
}
 /**
  *	Recieves an ajax request to download an order
  */
 public function download(Request $request)
 {
     $order = Order::find($request->orderID);
     // create new zip opbject
     $zip = new \ZipArchive();
     // create a temp file & open it
     $tmp_file = tempnam('.zip', '');
     $file_name = $tmp_file;
     $zip->open($tmp_file, \ZipArchive::CREATE);
     if (strcmp($order->type, 'Album Order') == 0) {
         $selections = $order->albumSelections;
         $i = 1;
         //loop through all files
         foreach ($selections as $selection) {
             //add file to the zip
             $zip->addFile(public_path($selection->photo->photo_path_high_res), $i . '.jpg');
             $i++;
         }
     } else {
         $selections = $order->printsSelections;
         $i = 1;
         //loop through all files
         foreach ($selections as $selection) {
             //add file to the zip
             $zip->addFile(public_path($selection->photo->photo_path_high_res), $i . ' ' . $selection->format->format . ' ' . $selection->quantity . '.jpg');
             $i++;
         }
     }
     // close zip
     $zip->close();
     //send the file to the browser as a download
     return response()->download($tmp_file, 'orders.zip')->deleteFileAfterSend(true);
 }
Example #6
0
 public static function zip($source, $destination, $exclude = '')
 {
     if (extension_loaded('zip') === true) {
         if (file_exists($source) === true) {
             $zip = new ZipArchive();
             if ($zip->open($destination, ZIPARCHIVE::CREATE) === true) {
                 $source = realpath($source);
                 if (is_dir($source) === true) {
                     $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
                     foreach ($files as $file) {
                         if (strpos($file, $exclude) == 0) {
                             $file = realpath($file);
                             if (is_dir($file) === true) {
                                 $zip->addEmptyDir(str_replace($source . DIRECTORY_SEPARATOR, '', $file . DIRECTORY_SEPARATOR));
                             } else {
                                 if (is_file($file) === true) {
                                     $zip->addFile($file, str_replace($source . DIRECTORY_SEPARATOR, '', $file));
                                 }
                             }
                         }
                     }
                 } else {
                     if (is_file($source) === true) {
                         $zip->addFile($source, basename($source));
                         //$zip->addFromString(basename($source), file_get_contents($source));
                     }
                 }
             }
             return $zip->close();
         }
     }
     return false;
 }
Example #7
0
 /**
  * Zip files
  *
  * @param string $targetDir Target dir path
  * @param array  $files     Files to zip
  *
  * @throws \Exception
  */
 private function zipFiles($targetDir, $files)
 {
     $zip = new \ZipArchive();
     $zipName = pathinfo($files[0], PATHINFO_FILENAME);
     $zipPath = FileSystem::getUniquePath($targetDir . DIRECTORY_SEPARATOR . $zipName . ".zip");
     if ($zip->open($zipPath, \ZipArchive::CREATE)) {
         foreach ($files as $file) {
             $path = $targetDir . DIRECTORY_SEPARATOR . $file;
             if (is_dir($path)) {
                 $zip->addEmptyDir($file);
                 foreach (Finder::find("*")->from($path) as $item) {
                     $name = $file . DIRECTORY_SEPARATOR . substr_replace($item->getPathname(), "", 0, strlen($path) + 1);
                     if ($item->isDir()) {
                         $zip->addEmptyDir($name);
                     } else {
                         $zip->addFile($item->getRealPath(), $name);
                     }
                 }
             } else {
                 $zip->addFile($path, $file);
             }
         }
         $zip->close();
     } else {
         throw new \Exception("Can not create ZIP archive '{$zipPath}' from '{$targetDir}'.");
     }
 }
Example #8
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $info = $this->container->info()->get();
     $path = $this->container->path();
     $vers = $info['version'];
     $filter = '/' . implode('|', $this->excludes) . '/i';
     $this->line(sprintf('Starting: webpack'));
     exec('webpack -p');
     $finder = Finder::create()->files()->in($path)->ignoreVCS(true)->filter(function ($file) use($filter) {
         return !preg_match($filter, $file->getRelativePathname());
     });
     $zip = new \ZipArchive();
     if (!$zip->open($zipFile = "{$path}/pagekit-" . $vers . ".zip", \ZipArchive::OVERWRITE)) {
         $this->abort("Can't open ZIP extension in '{$zipFile}'");
     }
     foreach ($finder as $file) {
         $zip->addFile($file->getPathname(), $file->getRelativePathname());
     }
     $zip->addFile("{$path}/.bowerrc", '.bowerrc');
     $zip->addFile("{$path}/.htaccess", '.htaccess');
     $zip->addEmptyDir('tmp/');
     $zip->addEmptyDir('tmp/cache');
     $zip->addEmptyDir('tmp/temp');
     $zip->addEmptyDir('tmp/logs');
     $zip->addEmptyDir('tmp/sessions');
     $zip->addEmptyDir('tmp/packages');
     $zip->addEmptyDir('app/database');
     $zip->close();
     $name = basename($zipFile);
     $size = filesize($zipFile) / 1024 / 1024;
     $this->line(sprintf('Building: %s (%.2f MB)', $name, $size));
 }
 /**
  * Creates a zip file from a file or a folder recursively without a full nested folder structure inside the zip file
  * Based on: http://stackoverflow.com/a/1334949/3073849
  * @param      string   $source      The path of the folder you want to zip
  * @param      string   $destination The path of the zip file you want to create
  * @return     bool     Returns TRUE on success or FALSE on failure.
  */
 public static function zip($source, $destination)
 {
     if (!extension_loaded('zip') || !file_exists($source)) {
         return false;
     }
     $zip = new ZipArchive();
     if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
         return false;
     }
     $source = str_replace('\\', '/', realpath($source));
     if (is_dir($source)) {
         foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST) as $path) {
             $path = str_replace('\\', '/', $path);
             $path = realpath($path);
             if (is_dir($path)) {
                 $zip->addEmptyDir(str_replace($source . '/', '', $path . '/'));
             } elseif (is_file($path)) {
                 $zip->addFile($path, str_replace($source . '/', '', $path));
             }
         }
     } elseif (is_file($source)) {
         $zip->addFile($source, basename($source));
     }
     return $zip->close();
 }
Example #10
0
 /**
  * Exports an add-on's XML data.
  *
  * @return XenForo_ControllerResponse_Abstract
  */
 public function actionZip()
 {
     $addOnId = $this->_input->filterSingle('addon_id', XenForo_Input::STRING);
     $addOn = $this->_getAddOnOrError($addOnId);
     $rootDir = XenForo_Application::getInstance()->getRootDir();
     $zipPath = XenForo_Helper_File::getTempDir() . '/addon-' . $addOnId . '.zip';
     if (file_exists($zipPath)) {
         unlink($zipPath);
     }
     $zip = new ZipArchive();
     $res = $zip->open($zipPath, ZipArchive::CREATE);
     if ($res === TRUE) {
         $zip->addFromString('addon-' . $addOnId . '.xml', $this->_getAddOnModel()->getAddOnXml($addOn)->saveXml());
         if (is_dir($rootDir . '/library/' . $addOnId)) {
             $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($rootDir . '/library/' . $addOnId));
             foreach ($iterator as $key => $value) {
                 $zip->addFile(realpath($key), str_replace($rootDir . '/', '', $key));
             }
         }
         if (is_dir($rootDir . '/js/' . strtolower($addOnId))) {
             $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($rootDir . '/js/' . strtolower($addOnId)));
             foreach ($iterator as $key => $value) {
                 $zip->addFile(realpath($key), str_replace($rootDir . '/', '', $key));
             }
         }
         $zip->close();
     }
     if (!file_exists($zipPath) || !is_readable($zipPath)) {
         return $this->responseError(new XenForo_Phrase('devkit_error_while_creating_zip'));
     }
     $this->_routeMatch->setResponseType('raw');
     $attachment = array('filename' => 'addon-' . $addOnId . '_' . $addOn['version_string'] . '.zip', 'file_size' => filesize($zipPath), 'attach_date' => XenForo_Application::$time);
     $viewParams = array('attachment' => $attachment, 'attachmentFile' => $zipPath);
     return $this->responseView('XenForo_ViewAdmin_Attachment_View', '', $viewParams);
 }
Example #11
0
 public static function export(\Rebond\Core\ModelInterface $module)
 {
     $exportPath = \Rebond\Config::path('export');
     $tempPath = \Rebond\Config::path('temp');
     // TODO add XML model node
     // generate data script
     $dataScriptPath = $tempPath . 'data.sql';
     $table = 'app_' . strtolower($module->getTitle());
     $db = new Util\Data();
     $result = $db->select('SELECT * FROM ' . $table);
     $script = $db->backupData($table, $result);
     $result = $db->select('SELECT * FROM cms_content WHERE module_id = ?', [$module->getId()]);
     $script .= $db->backupData('cms_content', $result);
     File::save($dataScriptPath, 'w', $script);
     // create zip
     $zipFile = $module->getTitle() . '.zip';
     $zip = new \ZipArchive();
     $res = $zip->open($exportPath . $zipFile, \ZIPARCHIVE::OVERWRITE);
     if (!$res) {
         return $res;
     }
     $modulePath = FULL_PATH . 'Rebond/App/' . $module->getTitle() . '/';
     $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($modulePath));
     foreach ($iterator as $file) {
         $filename = str_replace($modulePath, '', str_replace('\\', '/', $file));
         if (file_exists($file) && substr($filename, -1) != '.') {
             $zip->addFile($file, $filename);
         }
     }
     $zip->addFile($dataScriptPath, 'data.sql');
     $zip->close();
     return $zipFile;
 }
Example #12
0
function download_zip()
{
    $filename = "tmp/{$locale}.zip";
    if (is_file($filename)) {
        unlink($filename);
    }
    $zip = new ZipArchive();
    $zip->open($filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE);
    $zip->addFile(LANG_DIR . "/{$locale}.php", "{$locale}.php");
    $zip->addEmptyDir($locale);
    $dir = opendir(LANG_DIR . "/" . $locale);
    while (false !== ($file = readdir($dir))) {
        if ($file != "." && $file != ".." && $file != "CVS") {
            $zip->addFile(LANG_DIR . "/{$locale}/{$file}", "{$locale}/{$file}");
        }
    }
    closedir($dir);
    $zip->close();
    header("Cache-Control: public");
    header("Expires: -1");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Content-Type: application/zip");
    header("Content-Length: " . (string) filesize($filename));
    header("Content-Disposition: 'attachment'; filename=\"{$locale}.zip\"");
    header("Content-Transfer-Encoding: binary");
    readfile($filename);
    die;
}
Example #13
0
 public function create_zip($facility_code)
 {
     $this->update_rollout_status($facility_code);
     $this->create_core_tables($facility_code);
     $this->create_bat($facility_code);
     $sql_filepath = 'tmp/' . $facility_code . '.sql';
     $expected_zip_sql_filepath = $facility_code . '/' . $facility_code . '.sql';
     $bat_filepath = 'tmp/' . $facility_code . '_install_db.bat';
     $expected_zip_bat_filepath = $facility_code . '/' . $facility_code . '_install_db.bat';
     $ini_filepath = 'offline/my.ini';
     $expected_ini_filepath = $facility_code . '/' . 'my.ini';
     $expected_old_filepath = $facility_code . '/old/';
     $zip = new ZipArchive();
     $zip_name = $facility_code . '.zip';
     $zip->open($zip_name, ZipArchive::CREATE);
     $zip->addFile($sql_filepath, ltrim($expected_zip_sql_filepath, '/'));
     $zip->addFile($bat_filepath, ltrim($expected_zip_bat_filepath, '/'));
     $zip->addEmptyDir($expected_old_filepath);
     $zip->addFile($ini_filepath, ltrim($expected_ini_filepath, '/'));
     $zip->close();
     // ob_end_clean();
     header("Cache-Control: public");
     header("Content-Description: File Transfer");
     // header("Content-Length: ". filesize("$zip_name").";");
     header("Content-Disposition: attachment; filename={$zip_name}");
     header("Content-type: application/zip");
     header("Content-Transfer-Encoding: binary");
     readfile($zip_name);
     unlink($sql_filepath);
     unlink($bat_filepath);
     unlink($zip_name);
     // echo "$final_output_bat";
     // echo "I worked";
     // echo "Expecto patronum";
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $file = 'build/portable-zip-api.zip';
     $pharCommand = $this->getApplication()->find('build:phar');
     $arrayInput = new ArrayInput(array('command' => 'build:phar'));
     $arrayInput->setInteractive(false);
     if ($pharCommand->run($arrayInput, $output)) {
         $output->writeln('The operation is aborted due to build:phar command');
         return 1;
     }
     if (file_exists($file)) {
         $output->writeln('Removing previous package');
         unlink($file);
     }
     $zip = new \ZipArchive();
     if ($zip->open($file, \ZipArchive::CREATE) !== true) {
         $output->writeln('Failed to open zip archive');
         return 1;
     }
     $zip->addFile('build/zip.phar.php', 'zip.phar.php');
     $zip->addFile('app/zip.sqlite.db', 'zip.sqlite.db');
     $zip->addFile('README.md', 'README.md');
     $zip->close();
     return 0;
 }
Example #15
0
 /**
  * 程序文件列表
  */
 public function actionIndex()
 {
     if (Yii::app()->request->isPostRequest) {
         $files = Yii::app()->request->getParam('id');
         if ($files) {
             //提交打包
             $zip = new ZipArchive();
             $name = 'yiifcmsBAK_' . date('YmdHis', time()) . '.zip';
             $zipname = ROOT_PATH . '/' . $name;
             //创建一个空的zip文件
             if ($zip->open($zipname, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE)) {
                 foreach ($files as $file) {
                     if (is_dir($file)) {
                         //递归检索文件
                         $allfiles = Helper::scanfDir($file, true);
                         foreach ($allfiles['files'] as $v) {
                             $zip->addFile(ROOT_PATH . '/' . $v, $v);
                         }
                     } else {
                         $zip->addFile(ROOT_PATH . '/' . $file, $file);
                     }
                 }
             } else {
                 $this->message('error', 'An error occurred creating your ZIP file.');
             }
             $zip->close();
             Yii::app()->request->sendFile($name, file_get_contents($zipname), '', false);
             //下载完成后要进行删除
             @unlink($zipname);
         }
     } else {
         $all_files = Helper::scanfDir(ROOT_PATH);
         asort($all_files['dirs']);
         asort($all_files['files']);
         $files = array_merge($all_files['dirs'], $all_files['files']);
         $listfiles = array();
         foreach ($files as $file) {
             $tmpfilename = explode('/', $file);
             $filename = end($tmpfilename);
             if (is_dir($file)) {
                 $allfiles = Helper::scanfDir($file, true);
                 if ($allfiles['files']) {
                     $filesize = 0;
                     foreach ($allfiles['files'] as $val) {
                         $filesize += filesize($val);
                     }
                 }
                 $listfiles[$filename]['type'] = 'dir';
             } else {
                 $filesize = filesize($file);
                 $listfiles[$filename]['type'] = 'file';
             }
             $listfiles[$filename]['id'] = $filename;
             $listfiles[$filename]['size'] = Helper::byteFormat($filesize);
             $listfiles[$filename]['update_time'] = filemtime($filename);
         }
         $this->render('index', array('listfiles' => $listfiles));
     }
 }
Example #16
0
 public function addFile($file, $localName = '')
 {
     if ($localName == '') {
         $this->_zip->addFile($file);
     } else {
         $this->_zip->addFile($file, $localName);
     }
 }
Example #17
0
 /**
  * @param $filePath
  * @param $newFileName
  * @param bool $overwrite
  * @return bool
  * @throws Exceptions\ZipException
  */
 public static function zip($filePath, $newFileName, $overwrite = false)
 {
     $filePath = str_replace('\\', '/', $filePath);
     if (!file_exists($filePath)) {
         throw new \Sonrisa\Component\FileSystem\Exceptions\ZipException("File {$filePath} does not exist therefore it cannot be zipped.");
     }
     if (file_exists($newFileName) && $overwrite == false) {
         throw new \Sonrisa\Component\FileSystem\Exceptions\ZipException("Cannot create {$newFileName} zip file because it already exists a file with the same name.");
     }
     $zip = new \ZipArchive();
     if ($overwrite == true) {
         $open = $zip->open($newFileName, \ZipArchive::OVERWRITE);
     } else {
         $open = $zip->open($newFileName, \ZipArchive::CREATE);
     }
     if ($open == true) {
         if (is_dir($filePath)) {
             //remove . or / from the beginning of $filePath
             if ($filePath[0] == '.' || $filePath[0] == '/') {
                 $filePath = substr($filePath, 1);
                 if ($filePath[0] == '/') {
                     $filePath = substr($filePath, 1);
                 }
             }
             //create a Zip from a directory RECURSIVELY
             if (false !== ($dir = opendir($filePath))) {
                 $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($filePath), \RecursiveIteratorIterator::SELF_FIRST);
                 foreach ($files as $file) {
                     $f = explode(DIRECTORY_SEPARATOR, $file);
                     $last = trim(end($f));
                     if ($last !== '.' && $last !== '..') {
                         $file = str_replace('\\', '/', $file);
                         //Add the files and directories
                         if (is_dir($file) === true) {
                             $zip->addEmptyDir($file);
                         } else {
                             $zip->addFile($file);
                         }
                     }
                 }
             }
         } else {
             //remove . or / from the beginning of $filePath
             if ($filePath[0] == '.' || $filePath[0] == '/') {
                 $filePath = substr($filePath, 1);
                 if ($filePath[0] == '/') {
                     $filePath = substr($filePath, 1);
                 }
             }
             //Add the file.
             $zip->addFile($filePath);
         }
         $zip->close();
     } else {
         return false;
     }
     return file_exists($newFileName);
 }
Example #18
0
 protected function getArchivers($use_cache = true)
 {
     $arcs = array('create' => array(), 'extract' => array());
     $obj = $this;
     // php 5.3 compatibility
     if (class_exists('ZipArchive')) {
         $arcs['extract']['application/zip'] = array('cmd' => function ($archive, $path) use($obj) {
             $zip = new \ZipArchive();
             if ($zip->open($archive)) {
                 for ($i = 0; $i < $zip->numFiles; $i++) {
                     $stat = $zip->statIndex($i);
                     if (empty($stat['size'])) {
                         // directory
                         continue;
                     }
                     $filename = $stat['name'];
                     if (!$obj->tyghIsUTF8($filename) && function_exists('iconv')) {
                         $newfile = iconv('cp866', 'utf-8', $filename);
                     } else {
                         $newfile = $filename;
                     }
                     $obj->tyghMkdir(dirname($path . '/' . $newfile));
                     copy('zip://' . $archive . '#' . $filename, $path . '/' . $newfile);
                 }
                 $zip->close();
                 return true;
             }
             return false;
         }, 'ext' => 'zip');
         $arcs['create']['application/zip'] = array('cmd' => function ($archive, $files) use($obj) {
             $zip = new \ZipArchive();
             if ($zip->open($archive, \ZipArchive::CREATE) === true) {
                 $base_path = dirname($archive);
                 foreach ($files as $file) {
                     $path = $base_path . DIRECTORY_SEPARATOR . $file;
                     if (is_file($path)) {
                         $zip->addFile($path, $file);
                     } elseif (is_dir($path)) {
                         foreach ($obj->tyghGetFiles($path) as $_file) {
                             $zip->addFile($path . DIRECTORY_SEPARATOR . $_file, $_file);
                         }
                     }
                 }
                 $zip->close();
                 return true;
             }
             return false;
         }, 'ext' => 'zip');
     }
     if (class_exists('PharData')) {
         $arcs['extract']['application/x-gzip'] = array('cmd' => function ($archive, $path) {
             $phar = new \PharData($archive);
             $phar->extractTo($path, null, true);
         }, 'ext' => 'tgz');
     }
     return $arcs;
 }
 public function process(Vtiger_Request $request)
 {
     $log = vglobal('log');
     $newBackup = Settings_BackUp_Module_Model::clearBackupFilesTable();
     $log->info('Settings_BackUp_CreateFileBackUp_Action::process - Start files backup');
     $dirsFromConfig = Settings_BackUp_Module_Model::getConfig('folder');
     $dirsDiffConfig = '';
     $dirs = array_filter(array_merge(glob('*'), glob('.htaccess')));
     $dirs = array_diff($dirs, array('cache'));
     if ('true' != $dirsFromConfig['storage_folder']) {
         $dirs = array_diff($dirs, ['storage']);
     }
     if ('true' != $dirsFromConfig['backup_folder']) {
         $dirs = array_diff($dirs, [Settings_BackUp_Module_Model::$destDir]);
     }
     $dbDirs = Settings_BackUp_Module_Model::getDirs();
     $newDirs = array();
     $count = 0;
     $backUpInfo = Settings_BackUp_Module_Model::getBackUpInfo();
     $sqlFileName = $backUpInfo['file_name'];
     $this->fileName = $sqlFileName . '.files';
     if ($request->get('backUpAction') == 'cron') {
         $cron = TRUE;
     } else {
         $cron = FALSE;
     }
     if ($newBackup) {
         $log->info('New files backup');
         foreach ($dirs as $dir) {
             $dir = str_replace('\\', '/', $dir);
             if (!isset($dbDirs[$dir])) {
                 $newDirs[] = $dir;
             }
             if (!isset($dbDirs[$dir]) || $dbDirs[$dir] == 0) {
                 Settings_BackUp_CreateFileBackUp_Action::zipData($dir, Settings_BackUp_Module_Model::$tempDir . '/' . $this->fileName . '.zip', 0, $cron, array(), $this->fileName);
             }
         }
         Settings_BackUp_Module_Model::addBackupDirs($newDirs);
     }
     $dbAccuallyDirs = Settings_BackUp_Module_Model::getDirs();
     foreach ($dirs as $dir) {
         Settings_BackUp_CreateFileBackUp_Action::zipData($dir, Settings_BackUp_Module_Model::$tempDir . '/' . $this->fileName . '.zip', 1, $cron, $dbAccuallyDirs, $this->fileName);
     }
     $zip = new ZipArchive();
     $zip->open(Settings_BackUp_Module_Model::$destDir . '/' . $sqlFileName . '.zip', ZipArchive::CREATE);
     $zip->addFile(Settings_BackUp_Module_Model::$tempDir . '/' . $sqlFileName . '.db.zip', "db.zip");
     $zip->addFile(Settings_BackUp_Module_Model::$tempDir . '/' . $this->fileName . '.zip', "files.zip");
     $zip->close();
     Settings_BackUp_Module_Model::sendBackupToFTP(Settings_BackUp_Module_Model::$destDir . '/', $sqlFileName . '.zip');
     Settings_BackUp_Module_Model::sendNotificationEmail();
     Settings_BackUp_Module_Model::setBackUp();
     Settings_BackUp_Module_Model::deleteTmpBackUpContent();
     Settings_BackUp_Module_Model::deleteFile($sqlFileName . '.db.zip');
     Settings_BackUp_Module_Model::deleteFile($this->fileName . '.zip');
     echo json_encode(array('percentage' => 100));
 }
 public function test_createFromFiles()
 {
     $path = tempnam(sys_get_temp_dir(), 'zip');
     $zip = new ZipArchive($path);
     $zip->addFile(__DIR__ . '/../../../composer.json');
     $zip->addFile(__DIR__ . '/../../../composer.lock');
     $zip->close();
     $this->assertGreaterThan(0, filesize($path));
     unlink($path);
 }
Example #21
0
 /**
  * Wrap up the sheet (write header, column xmls).
  */
 private function finalizeSheet()
 {
     $this->sheetFile->fwrite('</sheetData></worksheet>');
     $this->sheetFile->rewind();
     $this->sheetFile->fwrite(SheetXml::HEADER_XML);
     $this->sheetFile->fwrite($this->sheet->getDimensionXml());
     $this->sheetFile->fwrite($this->sheet->getSheetViewsXml());
     $this->sheetFile->fwrite($this->sheet->getColsXml());
     $this->zip->addFile($this->sheetFile->getFilePath(), 'xl/worksheets/sheet1.xml');
 }
Example #22
0
 /**
  * ファイル追加
  *
  * @param string $file ファイルパス
  * @throws D9magai\Zip\Exception
  */
 public function addFile($file)
 {
     if (!file_exists($file)) {
         throw new Exception('ファイル ' . $file . ' が存在しません');
     }
     $filename = basename($file);
     $ret = $this->zipArchive->addFile($file, $filename);
     if ($ret !== true) {
         throw new Exception('ファイルの追加に失敗しました');
     }
 }
 /**
  * Write the zip file to a temporary location.
  *
  * @return void
  */
 protected function writeZipFile()
 {
     $zip = new \ZipArchive();
     $zip->open($this->zipFileNameAndPath, \ZipArchive::CREATE);
     // Add the CSV content into the zipball.
     $zip->addFile($this->exportFileNameAndPath, basename($this->exportFileNameAndPath));
     // Add the files into the zipball.
     foreach ($this->collectedFiles as $file) {
         $zip->addFile($file->getForLocalProcessing(FALSE), $file->getIdentifier());
     }
     $zip->close();
 }
Example #24
0
 public function actionCreate()
 {
     echo "=== Starting export sequence at " . date("d-m-Y h:i") . " ===\r\n";
     echo "Fetching all records from the 'occurences' view\r\n";
     $query = (new \yii\db\Query())->from('occurences');
     if ($query->count()) {
         echo "Found " . $query->count() . " records, continuing\r\n";
         $occurences = $query->all();
         $fileName = "occurences-" . date("Y-m-d-H:i");
         echo "Creating the export csv with identifier " . $fileName . ".zip\r\n";
         $csvFile = fopen(__DIR__ . "/../web/nlbif/" . $fileName . ".csv", "w");
         echo "Writing csv structure on first line of document \r\n";
         fputcsv($csvFile, array_keys($occurences[0]), ',', "'") . "\r\n";
         echo "Looping trough all the results\r\n";
         foreach ($occurences as $occurence) {
             foreach ($occurence as $key => &$value) {
                 if (is_null($value) && $key != "scientificName") {
                     continue;
                 }
                 switch ($key) {
                     case 'sex':
                         $value = Observations::getSexById($value);
                         break;
                     case 'lifeStage':
                         $value = Observations::getAgeById($value);
                         break;
                     case 'reproductiveCondition':
                         $value = Observations::getSexualStatusById($value);
                         break;
                     case 'scientificName':
                         !empty($value) && $value != " " ? $value : "Chiroptera";
                 }
             }
             array_map('utf8_encode', $occurence);
             fputcsv($csvFile, $occurence, ',', "'") . "\r\n";
         }
         echo "Bundling and compressing..\r\n";
         $zip = new \ZipArchive();
         $zip->open(__DIR__ . "/../web/nlbif/" . $fileName . ".zip", \ZipArchive::CREATE);
         $zip->addFile(__DIR__ . "/../web/nlbif/EML.xml", "EML.xml");
         $zip->addFile(__DIR__ . "/../web/nlbif/meta.xml", "meta.xml");
         $zip->addFile(__DIR__ . "/../web/nlbif/" . $fileName . ".csv", $fileName . ".csv");
         $zip->close();
         echo "Cleaning up..\r\n";
         unlink(__DIR__ . "/../web/nlbif/" . $fileName . ".csv");
         echo "All done!\r\n";
     } else {
         echo "Couldn't find any records, exiting\r\n";
     }
     echo "=== Finished export sequence at " . date("d-m-Y h:i") . " ===\r\n";
 }
Example #25
0
 /**
  * 
  * zip a directory or some file
  * @param String/Array $directoryORfilesarray
  * @return boolean
  * @throws Exception
  */
 public function zip($directoryORfilesarray = '.')
 {
     //backup old zip file
     if (file_exists($this->zipName)) {
         if (!rename($this->zipName, $this->zipName . '.old')) {
             throw new Exception("Cannot backup {$this->zipName} File, check permissions!");
         }
     }
     //create zip file
     if ($this->ZipArchive->open($this->zipName, ZIPARCHIVE::CREATE) !== TRUE) {
         throw new Exception("Cannot create {$this->zipName} File, check permissions and directory!");
     }
     //zip a directory
     if (is_string($directoryORfilesarray) && is_dir($directoryORfilesarray)) {
         $dir = rtrim($directoryORfilesarray, '/');
         //get all file
         $this->_getAllFiles($dir, $this->allFiles);
         //add file to zip file
         foreach ($this->allFiles as $file) {
             if (is_dir($file)) {
                 if ($dir == '.') {
                     $file = substr($file, 2);
                 }
                 $this->ZipArchive->addEmptyDir($file);
             }
             if (is_file($file)) {
                 if ($dir == '.') {
                     $file = substr($file, 2);
                 }
                 $this->ZipArchive->addFile($file);
             }
         }
     }
     //zip some files
     if (is_array($directoryORfilesarray)) {
         foreach ($directoryORfilesarray as $file) {
             if (!file_exists($file)) {
                 throw new Exception("{$file} is not exists!");
             }
             if (is_dir($file)) {
                 $this->ZipArchive->addEmptyDir($file);
             }
             if (is_file($file)) {
                 $this->ZipArchive->addFile($file);
             }
         }
     }
     return $this->ZipArchive->close();
 }
Example #26
0
 public function display($cachable = false, $urlparams = false)
 {
     JRequest::setVar('view', JRequest::getCmd('view', 'Orphans'));
     if (isset($_POST['_orphanaction']) && $_POST['_orphanaction'] == "zipIt") {
         $file = tempnam("tmp", "zip");
         $zip = new ZipArchive();
         $zip->open($file, ZipArchive::OVERWRITE);
         foreach ($_POST['tozip'] as $_file) {
             $zip->addFile(JPATH_ROOT . "/" . $_file, $_file);
         }
         $zip->close();
         header('Content-Type: application/zip');
         header('Content-Length: ' . filesize($file));
         header('Content-Disposition: attachment; filename="orphans.zip"');
         readfile($file);
         unlink($file);
         die;
     } else {
         if (isset($_POST['_orphanaction']) && $_POST['_orphanaction'] == "delete" && isset($_POST['_confirmAction'])) {
             foreach ($_POST['tozip'] as $_file) {
                 unlink(JPATH_ROOT . "/" . $_file);
             }
         }
     }
     // call parent behavior
     parent::display($cachable);
 }
Example #27
0
 /**
  * @param string|array $files
  * @param string $nameInZip
  *
  * @return \Spatie\Backup\Tasks\Backup\Zip
  */
 public function add($files, string $nameInZip = null) : Zip
 {
     if (is_array($files)) {
         $nameInZip = null;
     }
     if (is_string($files)) {
         $files = [$files];
     }
     foreach ($files as $file) {
         if (file_exists($file)) {
             $this->zipFile->addFile($file, $nameInZip) . PHP_EOL;
         }
         $this->fileCount++;
     }
     return $this;
 }
 public function downloadAction()
 {
     $squadID = $this->params('id', 0);
     $squadRepo = $this->getEntityManager()->getRepository('Frontend\\Squads\\Entity\\Squad');
     /** @var Squad $squadEntity */
     $squadEntity = $squadRepo->findOneBy(array('user' => $this->identity(), 'id' => $squadID));
     if (!$squadEntity) {
         $this->flashMessenger()->addErrorMessage('Squad not found');
         return $this->redirect('frontend/user/squads');
     }
     $fileName = 'squad_file_pack_armasquads_' . $squadID;
     $zipTmpPath = tempnam(ini_get('upload_tmp_dir'), $fileName);
     $zip = new \ZipArchive();
     $zip->open($zipTmpPath, \ZipArchive::CHECKCONS);
     if (!$zip) {
         $this->flashMessenger()->addErrorMessage('Squad Package Download currently not possible');
         return $this->redirect('frontend/user/squads');
     }
     $zip->addFromString('squad.xml', file_get_contents('http://' . $_SERVER['SERVER_NAME'] . $this->url()->fromRoute('frontend/user/squads/xml', array('id' => $squadEntity->getPrivateID()))));
     if ($squadEntity->getSquadLogoPaa()) {
         $zip->addFile(ROOT_PATH . $squadEntity->getSquadLogoPaa(), basename($squadEntity->getSquadLogoPaa()));
     }
     $zip->addFromString('squad.dtd', file_get_contents(realpath(__DIR__ . '/../../../../view/squads/xml/') . '/squad.dtd'));
     //$zip->addFromString('squad.xsl',file_get_contents(realpath(__DIR__ . '/../../../../view/squads/xml/').'/squad.xsl'));
     $zip->close();
     header('Content-Type: application/octet-stream');
     header("Content-Transfer-Encoding: Binary");
     header("Content-disposition: attachment; filename=\"" . basename($fileName) . ".zip\"");
     readfile($zipTmpPath);
     sleep(1);
     @unlink($zipTmpPath);
     die;
 }
Example #29
0
 /**
  * add file to archive
  *
  * @param string The path to the file to add
  * @param string If supplied, this is the local name inside the ZIP archive that will override the filename
  * @param int This parameter is not used but is required to extend ZipArchive
  * @param int This parameter is not used but is required to extend ZipArchive
  * @throws FileNotFoundException
  */
 public function addFile($filename, $localname = NULL, $start = 0, $length = 0)
 {
     if ($this->throwExceptions && !file_exists($filename)) {
         throw new FileNotFoundException("File {$filename} not found!");
     }
     parent::addFile($filename, $localname, $start, $length);
 }
function bps_Zip_CC_Master_File()
{
    // Use ZipArchive
    if (class_exists('ZipArchive')) {
        $zip = new ZipArchive();
        $filename = WP_PLUGIN_DIR . '/bulletproof-security/admin/core/cc-master.zip';
        if ($zip->open($filename, ZIPARCHIVE::CREATE) !== TRUE) {
            exit("Error: Cannot Open {$filename}\n");
        }
        $zip->addFile(WP_PLUGIN_DIR . '/bulletproof-security/admin/core/cc-master.txt', "cc-master.txt");
        $zip->close();
        return true;
    } else {
        // Use PclZip
        define('PCLZIP_TEMPORARY_DIR', WP_PLUGIN_DIR . '/bulletproof-security/admin/core/');
        require_once ABSPATH . 'wp-admin/includes/class-pclzip.php';
        if (ini_get('mbstring.func_overload') && function_exists('mb_internal_encoding')) {
            $previous_encoding = mb_internal_encoding();
            mb_internal_encoding('ISO-8859-1');
        }
        $archive = new PclZip(WP_PLUGIN_DIR . '/bulletproof-security/admin/core/cc-master.zip');
        $v_list = $archive->create(WP_PLUGIN_DIR . '/bulletproof-security/admin/core/cc-master.txt', PCLZIP_OPT_REMOVE_PATH, WP_PLUGIN_DIR . '/bulletproof-security/admin/core/');
        return true;
        if ($v_list == 0) {
            die("Error : " . $archive->errorInfo(true));
            return false;
        }
    }
}