PHP ZipArchive Code Examples

This page contains top rated real world PHP examples of ZipArchive extracted from open source projects. You can rate examples to help us improve the quality of examples
Example #1
Show file File: Component.php Project: koala-framework/koala-framework
0
 public static function getMediaOutput($id, $type, $className)
 {
     if ($type == 'list') {
         $component = Kwf_Component_Data_Root::getInstance()->getComponentById($id);
         if ($component) {
             $galleryComponent = $component->parent;
             $components = $galleryComponent->getChildComponents(array('generator' => 'child'));
             $paths = array();
             foreach ($components as $component) {
                 $data = $component->getComponent()->getImageData();
                 if ($data['file']) {
                     $paths[$data['file']] = $data['filename'];
                 }
             }
         }
         if (!$paths) {
             throw new Kwf_Exception_NotFound();
         }
         Kwf_Util_TempCleaner::clean();
         $tmpname = "temp/" . uniqid() . ".zip";
         $zip = new ZipArchive();
         if ($zip->open($tmpname, ZIPARCHIVE::CREATE) !== TRUE) {
             throw new Kwf_Exception('Could not open file for writing: ' . $filename);
         }
         foreach ($paths as $path => $filename) {
             $zip->addFile($path, $filename);
         }
         $zip->close();
         $file = array('file' => $tmpname, 'mimeType' => 'application/zip', 'downloadFilename' => $galleryComponent->getPage()->name . '.zip');
         Kwf_Media_Output::output($file);
         exit;
     }
 }
Example #2
Show file File: OpenXml.php Project: nhp/shopware-4
0
    /**
     * Extract metadata from document
     *
     * @param ZipArchive $package    ZipArchive OpenXML package
     * @return array    Key-value pairs containing document meta data
     */
    protected function extractMetaData(ZipArchive $package)
    {
        // Data holders
        $coreProperties = array();

        // Read relations and search for core properties
        $relations = simplexml_load_string($package->getFromName("_rels/.rels"));
        foreach ($relations->Relationship as $rel) {
            if ($rel["Type"] == Zend_Search_Lucene_Document_OpenXml::SCHEMA_COREPROPERTIES) {
                // Found core properties! Read in contents...
                $contents = simplexml_load_string(
                    $package->getFromName(dirname($rel["Target"]) . "/" . basename($rel["Target"]))
                );

                foreach ($contents->children(Zend_Search_Lucene_Document_OpenXml::SCHEMA_DUBLINCORE) as $child) {
                    $coreProperties[$child->getName()] = (string)$child;
                }
                foreach ($contents->children(Zend_Search_Lucene_Document_OpenXml::SCHEMA_COREPROPERTIES) as $child) {
                    $coreProperties[$child->getName()] = (string)$child;
                }
                foreach ($contents->children(Zend_Search_Lucene_Document_OpenXml::SCHEMA_DUBLINCORETERMS) as $child) {
                    $coreProperties[$child->getName()] = (string)$child;
                }
            }
        }

        return $coreProperties;
    }
Example #3
Show file File: TestOfBackupMySQLDAO.php Project: rgoncalves/ThinkUp
0
 /**
  * test export data
  */
 public function testExportData() {
     $dao = new BackupMySQLDAO();
     $export_file = $dao->export();
     $this->assertTrue( file_exists($export_file) );
     $zip_stats = stat($export_file);
     $this->assertTrue($zip_stats['size'] > 0);
     $za = new ZipArchive();
     $za->open($export_file);
     $zip_files = array();
     for ($i=0; $i<$za->numFiles;$i++) {
         $zfile = $za->statIndex($i);
         $zip_files[$zfile['name']] = $zfile['name'];
     }
     //verify we have create table file
     $this->assertTrue($zip_files["create_tables.sql"]);
     $za->close();
     $q = "show tables";
     $q2 = "show create table ";
     $stmt = $this->pdo->query($q);
     // verify we have all table files
     while($data = $stmt->fetch(PDO::FETCH_ASSOC)) {
         foreach($data as $key => $value) {
             $zfile = '/' . $value .'.txt';
             $this->assertTrue($zip_files[$zfile]);
         }
     }
 }
Example #4
Show file File: ZipController.php Project: github-zjh/task
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 #5
Show file File: Utils.php Project: richard-cai/Zend-Framework-Extended
0
	private static function getZippedFile($filename) {
		
		if(!self::zipModuleLoaded()) {
			throw new WURFL_WURFLException("The Zip extension is not loaded. Load the extension or use the flat wurfl.xml file");
		}
		
		
		$tmpDir = sys_get_temp_dir();
		
		$zip = new ZipArchive();

		if ($zip->open($filename)!==TRUE) {
			exit("cannot open <$filename>\n");
		}
		$zippedFile = $zip->statIndex(0);
		$wurflFile = $zippedFile['name'];
		
		//$wurflFile = md5(uniqid(rand(), true)); 
		
		//$zip->extractTo($tmpDir, $wurflFile);
		$zip->extractTo($tmpDir);

		$zip->close();
		
		return $tmpDir . '/' .$wurflFile;
	}
Example #6
Show file File: extension_manager.php Project: betsyzhang/chyrp
0
 public function route_makeRequest()
 {
     $type = pluralize(strip_tags($_GET['type']));
     set_time_limit(0);
     $fp = fopen("../{$type}/latest.zip", 'w+');
     $url = str_replace(" ", "%20", strip_tags($_GET['url']));
     $ch = curl_init($url);
     curl_setopt($ch, CURLOPT_TIMEOUT, 50);
     curl_setopt($ch, CURLOPT_FILE, $fp);
     # write curl response to file
     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
     curl_exec($ch);
     curl_close($ch);
     fclose($fp);
     $zip = new ZipArchive();
     if ($zip->open("../{$type}/latest.zip") == true) {
         mkdir("../{$type}/latest", 0777);
         $zip->extractTo("../{$type}/latest");
         $zip->close();
         $handle = opendir("../{$type}/latest");
         if ($handle) {
             while (($file = readdir($handle)) !== false) {
                 if (is_dir("../{$type}/latest/{$file}")) {
                     if ($file != '.' and $file != '..') {
                         rename("../{$type}/latest/{$file}", "../{$type}/{$file}");
                     }
                 }
             }
         }
         $this->rrmdir("../{$type}/latest");
         unlink("../{$type}/latest.zip");
         $this->rrmdir("../{$type}/__MACOSX");
     }
     Flash::notice(__("Extension downloaded successfully.", "extension_manager"), "/admin/?action=extend_manager");
 }
Example #7
Show file File: upload.php Project: RustyNomad/bitsybay
0
 /**
  * Validate file
  *
  * @param array $file
  * @param int $max_file_size MB
  * @param string $allowed_file_extension
  * @return bool TRUE if valid ot FALSE if else
  */
 public static function fileValid($file, $max_file_size, $allowed_file_extension)
 {
     // Dependencies test
     if (!isset($file['tmp_name']) || !isset($file['name'])) {
         return false;
     } else {
         if (empty($file['tmp_name']) || empty($file['name'])) {
             return false;
         } else {
             // Common test
             if (mb_strtolower($allowed_file_extension) != @pathinfo(self::_extensionPrepare($file['name']), PATHINFO_EXTENSION)) {
                 return false;
             } else {
                 if ($max_file_size < @filesize($file['tmp_name']) / 1000000) {
                     return false;
                 }
             }
             // Extension test
             if (mb_strtolower($allowed_file_extension) == 'zip') {
                 $zip = new ZipArchive();
                 if (true !== $zip->open($file['tmp_name'], ZipArchive::CHECKCONS)) {
                     $zip->close();
                     return false;
                 }
                 $zip->close();
             }
         }
     }
     return true;
 }
Example #8
Show file File: MainAccountController.php Project: branJakJak/biOaypiaccount
0
 public function actionBulk()
 {
     if (Yii::app()->request->isPostRequest) {
         $numOfItems = intval($_POST['numOfItems']);
         $archiveFileName = tempnam(sys_get_temp_dir(), uniqid()) . '.zip';
         /*iterate n times*/
         $templateGenerator = new TemplateGenerator();
         $archiveFile = new ZipArchive();
         $archiveFile->open($archiveFileName, ZipArchive::CREATE);
         foreach (range(1, $numOfItems) as $key => $value) {
             /*generate template*/
             $template1 = $templateGenerator->generate();
             /*put to archive*/
             $archiveFile->addFromString(basename($template1), file_get_contents($template1));
         }
         $archiveFile->close();
         /*publish archive file*/
         $publishedUrl = Yii::app()->assetManager->publish($archiveFileName);
         $messageoutput = CHtml::link('Download files', $publishedUrl);
         /*put link at flash*/
         Yii::app()->user->setFlash("success", $messageoutput);
         /*redirect */
         $this->redirect('/mainAccount/bulk');
         /*done*/
     }
     $this->render('//main_account/bulk');
 }
Example #9
Show file File: archive.php Project: redaxo/redaxo4
0
 public static function copyDirToArchive($dir, $archive, $basename = null, $excludeDirs = null)
 {
     $dir = rtrim($dir, '/\\');
     $basename = $basename ?: basename($dir);
     rex_dir::create(dirname($archive));
     $files = array();
     $iterator = rex_finder::factory($dir)->recursive()->filesOnly();
     if ($excludeDirs) {
         $iterator->ignoreDirs($excludeDirs, false);
     }
     foreach ($iterator as $path => $file) {
         $subpath = str_replace($dir, $basename, $path);
         $subpath = str_replace('\\', '/', $subpath);
         $files[$subpath] = $path;
     }
     if (class_exists('ZipArchive')) {
         $zip = new ZipArchive();
         $zip->open($archive, ZipArchive::CREATE);
         foreach ($files as $path => $realpath) {
             $zip->addFile($realpath, $path);
         }
         $zip->close();
     } else {
         $phar = new PharData($archive, 0, null, Phar::ZIP);
         $phar->buildFromIterator(new ArrayIterator($files));
         $phar->compressFiles(Phar::GZ);
         foreach ($files as $path => $realpath) {
             if (filesize($realpath) == 0) {
                 $phar[$path]->decompress();
             }
         }
     }
 }
Example #10
Show file File: Zipper.php Project: Selwyn-b/elefant
0
 /**
  * Unzip a file into the specified directory. Throws a RuntimeException
  * if the extraction failed.
  */
 public static function unzip($source, $base = null)
 {
     $base = $base ? $base : self::$folder;
     @ini_set('memory_limit', '256M');
     if (!is_dir($base)) {
         mkdir($base);
         chmod($base, 0777);
     }
     if (class_exists('ZipArchive')) {
         // use ZipArchive
         $zip = new ZipArchive();
         $res = $zip->open($source);
         if ($res === true) {
             $zip->extractTo($base);
             $zip->close();
         } else {
             throw new RuntimeException('Could not open zip file [ZipArchive].');
         }
     } else {
         // use PclZip
         $zip = new PclZip($source);
         if ($zip->extract(PCLZIP_OPT_PATH, $base) === 0) {
             throw new RuntimeException('Could not extract zip file [PclZip].');
         }
     }
     return true;
 }
Example #11
Show file File: ZipJob.php Project: anukat2015/xmlps
0
 /**
  * Process job
  *
  * @param Job $job
  * @return Job $job
  */
 public function process(Job $job)
 {
     if (!class_exists('\\ZipArchive')) {
         throw new \Exception('Zip extension is missing');
     }
     $zipFile = $job->getDocumentPath() . '/documents.zip';
     if (file_exists($zipFile)) {
         @unlink($zipFile);
     }
     $zip = new \ZipArchive();
     if ($zip->open($zipFile, \ZipArchive::CREATE) !== TRUE) {
         throw new \Exception('Couldn\'t create zip archive');
     }
     foreach ($job->getOutputDocuments() as $document) {
         $zip->addFile($document->path, str_replace($job->getDocumentPath() . '/', '', $document->path));
     }
     $zip->close();
     $documentDAO = $this->sm->get('Manager\\Model\\DAO\\DocumentDAO');
     $docxDocument = $documentDAO->getInstance();
     $docxDocument->path = $zipFile;
     $docxDocument->job = $job;
     $docxDocument->conversionStage = JOB_CONVERSION_STAGE_ZIP;
     $job->documents[] = $docxDocument;
     $job->conversionStage = JOB_CONVERSION_STAGE_ZIP;
     return $job;
 }
Example #12
Show file
0
 /**
  * 'upload_zip' upload field must refer to a zip file containing 
  *   all files for the pubnode (may be at top-level or inside a subdirectory)
  */
 public function import(&$form_state, $docid = NULL)
 {
     $validators = array('file_validate_extensions' => array('zip'), 'file_validate_size' => array(100000000, 0));
     if ($file = file_save_upload($this->fieldname, $validators, file_directory_temp(), FILE_EXISTS_REPLACE)) {
         $zip = new ZipArchive();
         if ($zip->open($file->filepath) !== TRUE) {
             form_set_error(t("Cannot open !file", array("!file" => $file->filename)), 'error');
             return FALSE;
         }
         // else
         if (empty($docid)) {
             $docid = $this->hashFile($file->filepath);
         }
         $pubpath = $this->constructPubPath($docid);
         //drupal_set_message("PUBPATH: " . $pubpath);
         file_check_directory($pubpath, FILE_CREATE_DIRECTORY);
         $zip->extractTo($pubpath);
         drupal_set_message(t("Extracted !num files to directory !dir", array('!num' => $zip->numFiles, '!dir' => $pubpath)));
         $zip->close();
         $this->pubpath = $pubpath;
         return TRUE;
     }
     // else validations failed and error message will be set by upload function
     return FALSE;
 }
Example #13
Show file File: class-boilerplate-zip-generator.php Project: idhamhafidz/foogallery
0
 /**
  * Creates the new zip file based on the source_directory
  */
 function generate()
 {
     $zip = new ZipArchive();
     $zip->open($this->options['zip_temp_filename'], ZipArchive::CREATE && ZipArchive::OVERWRITE);
     $source_path = realpath($this->options['source_directory']);
     $iterator = new RecursiveDirectoryIterator($source_path);
     foreach (new RecursiveIteratorIterator($iterator) as $filename) {
         if (in_array(basename($filename), $this->options['exclude_files'])) {
             continue;
         }
         foreach ($this->options['exclude_directories'] as $directory) {
             if (strstr($filename, "/{$directory}/")) {
                 continue 2;
             }
         }
         // continue the parent foreach loop
         $zip_filepath = $filename->getRealPath();
         $zip_filename = ltrim(str_replace($source_path, '', $zip_filepath), '\\');
         $zip_filename = apply_filters("{$this->slug}_zip_generator_process_filename", $zip_filename);
         $contents = $this->process_file_contents(file_get_contents($filename), basename($filename));
         $zip->addFromString(trailingslashit($this->options['zip_root_directory']) . $zip_filename, $contents);
     }
     do_action("{$this->slug}_zip_generator_post_process", $zip, $this->options);
     $zip->close();
 }
Example #14
Show file File: index.php Project: avilleret/Rekall
0
function createProject($name, $videoUrl, $sha1password)
{
    $retours = array("success" => 0, "error" => "", "value" => "");
    $name = sanitize($name);
    if ($name == "") {
        $name = sha1(rand());
    }
    if (!file_exists($name)) {
        $zip = new ZipArchive();
        $res = $zip->open("create.zip");
        if ($res === TRUE) {
            $zip->extractTo($name);
            $zip->close();
            file_put_contents($name . "/file/project.xml", str_replace("__video__", $videoUrl, file_get_contents($name . "/file/project.xml")));
            file_put_contents($name . "/file/projectPassword.txt", $sha1password);
            $retours["success"] = 1;
        } else {
            $retours["success"] = -1;
            $retours["error"] = "No seed found";
        }
    } else {
        $retours["success"] = 0;
        $retours["error"] = "Project already exists";
    }
    $retours["value"] = $name;
    echo json_encode($retours);
}
Example #15
Show file File: ArtifactAttachmentExporterTest.php Project: pombredanne/tuleap
0
 private function extractArchive()
 {
     $this->archive->close();
     $this->archive->open($this->archive_path);
     $this->archive->extractTo($this->extraction_path);
     $this->archive->close();
 }
Example #16
Show file File: DataPortability.php Project: igez/gaiaehr
0
 function export($params = null)
 {
     $patients = $this->Patient->getPatients($params);
     unset($this->Patient);
     $zip = new ZipArchive();
     $file = 'GaiaEHR-Patients-Export-' . time() . '.zip';
     if ($zip->open($file, ZipArchive::CREATE) !== true) {
         throw new Exception("cannot open <{$file}>");
     }
     $zip->addFromString('cda2.xsl', file_get_contents(ROOT . '/lib/CCRCDA/schema/cda2.xsl'));
     foreach ($patients as $i => $patient) {
         $patient = (object) $patient;
         $this->CCDDocument->setPid($patient->pid);
         $this->CCDDocument->createCCD();
         $this->CCDDocument->setTemplate('toc');
         $this->CCDDocument->createCCD();
         $ccd = $this->CCDDocument->get();
         $zip->addFromString($patient->pid . '-Patient-CDA' . '.xml', $ccd);
         unset($patients[$i], $ccd);
     }
     $zip->close();
     header('Content-Type: application/zip');
     header('Content-Length: ' . filesize($file));
     header('Content-Disposition: attachment; filename="' . $file . '"');
     readfile($file);
 }
Example #17
Show file File: archive.class.php Project: bbspike/sentora-core
0
 /**
  * Uncompresses a ZIP archive to a given location.
  * @author Bobby Allen (ballen@bobbyallen.me)
  * @param string $archive Full path and filename to the ZIP archive.
  * @param string $dest The full path to the folder to extract the archive into (with trailing slash!)
  * @return boolean 
  */
 static function Unzip($archive, $dest)
 {
     global $zlo;
     if (!class_exists('ZipArchive')) {
         return false;
     }
     $zip = new ZipArchive();
     $result = $zip->open($archive);
     if ($result) {
         if (@$zip->extractTo($dest)) {
             $zip->close();
             return true;
         } else {
             $zlo->logcode = "623";
             $zlo->detail = "Unable to extract file '" . $archive . "' to '" . $dest . "'.";
             $zlo->writeLog();
             return false;
         }
     } else {
         $zlo->logcode = "621";
         $zlo->detail = "The archive file '" . $archive . "' appears to be invalid.";
         $zlo->writeLog();
         return false;
     }
 }
Example #18
Show file File: print_return_label.php Project: darthur-inpost/iris-management
0
function print_many_labels(&$params, &$parcels, $username)
{
    require "config.php";
    $return = array();
    $zipname = "test_" . $username . '_' . session_id() . ".zip";
    $zip = new ZipArchive();
    $res = $zip->open($zipname, ZipArchive::CREATE);
    if ($res === TRUE) {
        $timestamp = date('dmy_His', time());
        foreach ($parcels as $key => $parcel) {
            $params['url'] = $base_url . 'reverselogistics/' . $parcel . '/label.json';
            //echo json_encode($params);
            $restApi2 = new RestApi($params);
            $file_name = "InPost_Return_Label" . $timestamp . $key . ".pdf";
            $pdf = $restApi2->getResponse();
            $info = $restApi2->getInfo();
            if ($info['http_code'] != 200) {
                $_SESSION['error_message'] = 'Failed to create your labels ' . $info["http_code"];
                continue;
            }
            $binary = base64_decode($pdf);
            // Add to the list of parcels that need their status
            // updated.
            $return[] = $parcel;
            // Add the PDF to the main ZIP file.
            $zip->addFromString($file_name, $binary);
        }
        $zip->close();
    } else {
        $_SESSION['error_message'] = 'Failed to create ZIP file for your labels.';
        header("Location: r_orders.php");
        return $return;
    }
    return $return;
}
Example #19
Show file File: ZipBackup.php Project: indigo423/blog.no42.org
0
 /**
  * @param $folder
  * @param $zipFile
  * @param $exclusiveLength
  * @param $messager
  */
 private static function folderToZip($folder, \ZipArchive &$zipFile, $exclusiveLength, callable $messager = null)
 {
     $handle = opendir($folder);
     while (false !== ($f = readdir($handle))) {
         if ($f != '.' && $f != '..') {
             $filePath = "{$folder}/{$f}";
             // Remove prefix from file path before add to zip.
             $localPath = substr($filePath, $exclusiveLength);
             if (in_array($f, static::$ignoreFolders)) {
                 continue;
             } elseif (in_array($localPath, static::$ignorePaths)) {
                 $zipFile->addEmptyDir($f);
                 continue;
             }
             if (is_file($filePath)) {
                 $zipFile->addFile($filePath, $localPath);
                 $messager && $messager(['type' => 'progress', 'percentage' => false, 'complete' => false]);
             } elseif (is_dir($filePath)) {
                 // Add sub-directory.
                 $zipFile->addEmptyDir($localPath);
                 static::folderToZip($filePath, $zipFile, $exclusiveLength, $messager);
             }
         }
     }
     closedir($handle);
 }
Example #20
Show file File: BackupCommand.php Project: miguelramos/grav
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $output->getFormatter()->setStyle('red', new OutputFormatterStyle('red'));
     $output->getFormatter()->setStyle('cyan', new OutputFormatterStyle('cyan'));
     $output->getFormatter()->setStyle('green', new OutputFormatterStyle('green'));
     $output->getFormatter()->setStyle('magenta', new OutputFormatterStyle('magenta'));
     $this->progress = new ProgressBar($output);
     $this->progress->setFormat('Archiving <cyan>%current%</cyan> files [<green>%bar%</green>] %elapsed:6s% %memory:6s%');
     $name = basename($this->source);
     $dir = dirname($this->source);
     $date = date('YmdHis', time());
     $filename = $name . '-' . $date . '.zip';
     $destination = $input->getArgument('destination') ? $input->getArgument('destination') : ROOT_DIR;
     $destination = rtrim($destination, DS) . DS . $filename;
     $output->writeln('');
     $output->writeln('Creating new Backup "' . $destination . '"');
     $this->progress->start();
     $zip = new \ZipArchive();
     $zip->open($destination, \ZipArchive::CREATE);
     $zip->addEmptyDir($name);
     $this->folderToZip($this->source, $zip, strlen($dir . DS), $this->progress);
     $zip->close();
     $this->progress->finish();
     $output->writeln('');
     $output->writeln('');
 }
Example #21
Show file File: Archive.php Project: stof/spreadsheet-parser
0
 /**
  * Closes the archive
  */
 protected function closeArchive()
 {
     if ($this->zip) {
         $this->zip->close();
         $this->zip = null;
     }
 }
Example #22
Show file File: file_manipulator.php Project: yamaguchitarou/bakesale
0
 /**
  * Unzip file
  */
 public function unZip($fromFile, $toDir)
 {
     $zip = new ZipArchive();
     $zip->open($fromFile);
     $zip->extractTo($toDir);
     $zip->close();
 }
Example #23
Show file File: ZipArchive.php Project: nnnnathann/piwik
0
 /**
  * Extract files from archive to target directory
  *
  * @param string  $pathExtracted  Absolute path of target directory
  * @return mixed  Array of filenames if successful; or 0 if an error occurred
  */
 public function extract($pathExtracted)
 {
     if (substr_compare($pathExtracted, '/', -1)) {
         $pathExtracted .= '/';
     }
     $fileselector = array();
     $list = array();
     $count = $this->ziparchive->numFiles;
     if ($count === 0) {
         return 0;
     }
     for ($i = 0; $i < $count; $i++) {
         $entry = $this->ziparchive->statIndex($i);
         $filename = str_replace('\\', '/', $entry['name']);
         $parts = explode('/', $filename);
         if (!strncmp($filename, '/', 1) || array_search('..', $parts) !== false || strpos($filename, ':') !== false) {
             return 0;
         }
         $fileselector[] = $entry['name'];
         $list[] = array('filename' => $pathExtracted . $entry['name'], 'stored_filename' => $entry['name'], 'size' => $entry['size'], 'compressed_size' => $entry['comp_size'], 'mtime' => $entry['mtime'], 'index' => $i, 'crc' => $entry['crc']);
     }
     $res = $this->ziparchive->extractTo($pathExtracted, $fileselector);
     if ($res === false) {
         return 0;
     }
     return $list;
 }
Example #24
Show file File: updater.php Project: omusico/isle-web-framework
0
 public static function update($version, $backupBase)
 {
     if (!is_dir($backupBase)) {
         throw new \Exception("Backup directory {$backupBase} is not found");
     }
     set_include_path($backupBase . PATH_SEPARATOR . $backupBase . '/core/lib' . PATH_SEPARATOR . $backupBase . '/core/config' . PATH_SEPARATOR . $backupBase . '/3rdparty' . PATH_SEPARATOR . $backupBase . '/apps' . PATH_SEPARATOR . get_include_path());
     $tempDir = self::getTempDir();
     Helper::mkdir($tempDir, true);
     $installed = Helper::getDirectories();
     $sources = Helper::getSources($version);
     try {
         $thirdPartyUpdater = new Location_3rdparty($installed[Helper::THIRDPARTY_DIRNAME], $sources[Helper::THIRDPARTY_DIRNAME]);
         $thirdPartyUpdater->update($tempDir . '/' . Helper::THIRDPARTY_DIRNAME);
         self::$processed[] = $thirdPartyUpdater;
         $coreUpdater = new Location_Core($installed[Helper::CORE_DIRNAME], $sources[Helper::CORE_DIRNAME]);
         $coreUpdater->update($tempDir . '/' . Helper::CORE_DIRNAME);
         self::$processed[] = $coreUpdater;
         $appsUpdater = new Location_Apps('', $sources[Helper::APP_DIRNAME]);
         $appsUpdater->update($tempDir . '/' . Helper::APP_DIRNAME);
         self::$processed[] = $appsUpdater;
     } catch (\Exception $e) {
         self::rollBack();
         self::cleanUp();
         throw $e;
     }
     // zip backup
     $zip = new \ZipArchive();
     if ($zip->open($backupBase . ".zip", \ZIPARCHIVE::CREATE) === true) {
         Helper::addDirectoryToZip($zip, $backupBase, $backupBase);
         $zip->close();
         \OCP\Files::rmdirr($backupBase);
     }
     return true;
 }
Example #25
Show file File: Export.php Project: olegfox/landing
0
 /**
  * Создание Zip архива
  *
  * @param $source
  * @param $destination
  * @return bool
  */
 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) === true) {
         $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source), \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_dir($file) === true) {
                 $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
             } else {
                 if (is_file($file) === true) {
                     $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
                 }
             }
         }
     } else {
         if (is_file($source) === true) {
             $zip->addFromString(basename($source), file_get_contents($source));
         }
     }
     return $zip->close();
 }
Example #26
Show file File: Theme.php Project: nima7r/phpfox-dist
0
 public function import($zip = null, $extra = null)
 {
     $file = PHPFOX_DIR_FILE . 'static/' . uniqid() . '/';
     mkdir($file);
     if ($zip === null) {
         $zip = $file . 'import.zip';
         file_put_contents($zip, file_get_contents('php://input'));
     }
     $Zip = new \ZipArchive();
     $Zip->open($zip);
     $Zip->extractTo($file);
     $Zip->close();
     $themeId = null;
     $File = \Phpfox_File::instance();
     foreach (scandir($file) as $f) {
         if ($File->extension($f) == 'json') {
             $data = json_decode(file_get_contents($file . $f));
             $themeId = $this->make(['name' => $data->name, 'extra' => $extra ? json_encode($extra) : null], $data->files);
             $File->delete_directory($file);
             $iteration = 0;
             foreach ($data->flavors as $flavorId => $flavorName) {
                 $iteration++;
                 $this->db->insert(':theme_style', ['theme_id' => $themeId, 'name' => $flavorName, 'folder' => $flavorId, 'is_default' => $iteration === 1 ? '1' : '0']);
             }
         }
     }
     if ($themeId === null) {
         throw new \Exception('Theme is missing its JSON file.');
     }
     return $themeId;
 }
Example #27
Show file File: Storage.php Project: grrr-amsterdam/garp3
0
 /**
  * @param int $destination Target path of the zip, if you do not want to use $this->_targetPath
  * @return void
  */
 public function zip($destination = null)
 {
     $source = $this->_workingDir;
     if (!$destination) {
         $destination = $this->_targetPath;
     }
     $this->_preZipChecks();
     $zip = new ZipArchive();
     if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
         throw new Exception("Could not open a new zip archive at {$destination}.");
     }
     $source = str_replace('\\', '/', realpath($source));
     if (is_dir($source) === true) {
         $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::LEAVES_ONLY);
         foreach ($files as $file) {
             $file = str_replace('\\', '/', $file);
             // Ignore "." and ".." folders
             if (in_array(substr($file, strrpos($file, '/') + 1), array('.', '..'))) {
                 continue;
             }
             $file = realpath($file);
             if (is_dir($file) === true) {
                 $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
             } elseif (is_file($file) === true) {
                 $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
             }
         }
     } elseif (is_file($source) === true) {
         $zip->addFromString(basename($source), file_get_contents($source));
     }
     $zip->close();
 }
Example #28
Show file File: Serialized.php Project: sensorsix/app
0
 /**
  * Save PHPExcel to file
  *
  * @param 	string 		$pFileName
  * @throws 	Exception
  */
 public function save($pFilename = null)
 {
     if (!is_null($this->_spreadSheet)) {
         // Garbage collect...
         foreach ($this->_spreadSheet->getAllSheets() as $sheet) {
             $sheet->garbageCollect();
         }
         // Create new ZIP file and open it for writing
         $objZip = new ZipArchive();
         // Try opening the ZIP file
         if ($objZip->open($pFilename, ZIPARCHIVE::OVERWRITE) !== true) {
             if ($objZip->open($pFilename, ZIPARCHIVE::CREATE) !== true) {
                 throw new Exception("Could not open " . $pFilename . " for writing.");
             }
         }
         // Add media
         $sheetCount = $this->_spreadSheet->getSheetCount();
         for ($i = 0; $i < $sheetCount; ++$i) {
             for ($j = 0; $j < $this->_spreadSheet->getSheet($i)->getDrawingCollection()->count(); ++$j) {
                 if ($this->_spreadSheet->getSheet($i)->getDrawingCollection()->offsetGet($j) instanceof PHPExcel_Worksheet_BaseDrawing) {
                     $imgTemp = $this->_spreadSheet->getSheet($i)->getDrawingCollection()->offsetGet($j);
                     $objZip->addFromString('media/' . $imgTemp->getFilename(), file_get_contents($imgTemp->getPath()));
                 }
             }
         }
         // Add phpexcel.xml to the document, which represents a PHP serialized PHPExcel object
         $objZip->addFromString('phpexcel.xml', $this->_writeSerialized($this->_spreadSheet, $pFilename));
         // Close file
         if ($objZip->close() === false) {
             throw new Exception("Could not close zip file {$pFilename}.");
         }
     } else {
         throw new Exception("PHPExcel object unassigned.");
     }
 }
Example #29
Show file File: controller.php Project: james-Ballyhoo/com_orphan
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 #30
Show file File: gallery.php Project: uweb/story-central
0
 function image_assets()
 {
     // TODO: check if ziparchive is installed cms/cmsdev
     $zip = new ZipArchive();
     $ids = explode(',', $_GET['ids']);
     $name = $_GET['name'] . '.zip';
     $path = get_temp_dir() . $name;
     if ($zip->open($path, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== TRUE) {
         die(json_encode(array('error' => 'Could not retrieve files.')));
     }
     foreach ($ids as $id) {
         $image = get_attached_file($id);
         if (file_exists($image)) {
             $zip->addFile($image, basename($image));
         } else {
             // die("File $filepath doesnt exit");
         }
     }
     $zip->close();
     header('Content-Type: application/zip');
     header('Content-disposition: attachment; filename=' . $name);
     header('Content-Length: ' . filesize($path));
     //TODO: alternate method to make zip file work?
     ob_clean();
     flush();
     readfile($path);
     wp_die();
 }