/** * 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."); } }
function unzip_content() { $zip = new ZipArchive(); if (file_exists('application.zip')) { $res = $zip->open('application.zip'); if ($res === TRUE) { echo '<p>Unzipped Application <i class="fa fa-check-circle-o"></i></p>'; $zip->extractTo('./'); $zip->close(); unlink('application.zip'); } else { echo '<p>Could not unzip application.zip <i class="fa fa-times-circle-o"></i></p>'; } } else { echo '<p>Application already unzipped <i class="fa fa-check-circle-o"></i></p>'; } new_line(); if (file_exists('content.zip')) { $res = $zip->open('content.zip'); if ($res === TRUE) { echo '<p>Unzipped Content <i class="fa fa-check-circle-o"></i></p>'; $zip->extractTo('./'); $zip->close(); unlink('content.zip'); } else { echo '<p>Could not unzip content.zip <i class="fa fa-times-circle-o"></i></p>'; } } else { echo '<p>Content already unzipped <i class="fa fa-check-circle-o"></i></p>'; } new_line(); }
/** * Test all methods * * @param string $zipClass * @covers ::<public> */ public function testZipArchive($zipClass = 'ZipArchive') { // Preparation $existingFile = __DIR__ . '/../_files/documents/sheet.xls'; $zipFile = __DIR__ . '/../_files/documents/ziptest.zip'; $destination1 = __DIR__ . '/../_files/documents/extract1'; $destination2 = __DIR__ . '/../_files/documents/extract2'; @mkdir($destination1); @mkdir($destination2); Settings::setZipClass($zipClass); $object = new ZipArchive(); $object->open($zipFile, ZipArchive::CREATE); $object->addFile($existingFile, 'xls/new.xls'); $object->addFromString('content/string.txt', 'Test'); $object->close(); $object->open($zipFile); // Run tests $this->assertEquals(0, $object->locateName('xls/new.xls')); $this->assertFalse($object->locateName('blablabla')); $this->assertEquals('Test', $object->getFromName('content/string.txt')); $this->assertEquals('Test', $object->getFromName('/content/string.txt')); $this->assertFalse($object->getNameIndex(-1)); $this->assertEquals('content/string.txt', $object->getNameIndex(1)); $this->assertFalse($object->extractTo('blablabla')); $this->assertTrue($object->extractTo($destination1)); $this->assertTrue($object->extractTo($destination2, 'xls/new.xls')); $this->assertFalse($object->extractTo($destination2, 'blablabla')); // Cleanup $this->deleteDir($destination1); $this->deleteDir($destination2); @unlink($zipFile); }
private function extractArchive() { $this->archive->close(); $this->archive->open($this->archive_path); $this->archive->extractTo($this->extraction_path); $this->archive->close(); }
/** * Upload component * * @requires component package file, * * @return bool; */ public function upload() { $archive = new ZipArchive(); $data_dir = ossn_get_userdata('tmp/components'); if (!is_dir($data_dir)) { mkdir($data_dir, 0755, true); } $zip = $_FILES['com_file']; $newfile = "{$data_dir}/{$zip['name']}"; if (move_uploaded_file($zip['tmp_name'], $newfile)) { if ($archive->open($newfile) === TRUE) { $archive->extractTo($data_dir); //make community components works on installer #394 $validate = $archive->statIndex(0); $validate = str_replace('/', '', $validate['name']); $archive->close(); if (is_dir("{$data_dir}/{$validate}") && is_file("{$data_dir}/{$validate}/ossn_com.php") && is_file("{$data_dir}/{$validate}/ossn_com.xml")) { $archive->open($newfile); $archive->extractTo(ossn_route()->com); $archive->close(); $this->newCom($validate); OssnFile::DeleteDir($data_dir); return true; } } } return false; }
/** * Upload component * * @requires component package file, * * @return bool; */ public function upload() { $archive = new ZipArchive(); $data_dir = ossn_get_userdata('tmp/components'); if (!is_dir($data_dir)) { mkdir($data_dir, 0755, true); } $zip = $_FILES['com_file']; $newfile = "{$data_dir}/{$zip['name']}"; if (move_uploaded_file($zip['tmp_name'], $newfile)) { if ($archive->open($newfile) === TRUE) { $archive->extractTo($data_dir); $archive->close(); $validate = pathinfo($zip['name'], PATHINFO_FILENAME); if (is_file("{$data_dir}/{$validate}/ossn_com.php") && is_file("{$data_dir}/{$validate}/ossn_com.xml")) { $archive->open($newfile); $archive->extractTo(ossn_route()->com); $archive->close(); $this->newCom($validate); OssnFile::DeleteDir($data_dir); return true; } } } return false; }
/** * ZipArchive クラスによる展開 * * @param $source * @param $target * @return bool */ protected function _extractByPhpLib($source, $target) { if ($this->Zip->open($source) === true && $this->Zip->extractTo($target)) { $archivePath = $this->Zip->getNameIndex(0); $archivePathAry = explode(DS, $archivePath); $this->topArchiveName = $archivePathAry[0]; return true; } else { return false; } }
/** * Add all file and string contents to zip file. * * @param string $zipFileUrl */ private function fillZipWithFileContents($zipFileUrl) { $this->zip->open($zipFileUrl, \ZipArchive::CREATE); $this->finalizeSheet(); $this->finalizeStyles(); $this->finalizeDefaultXmls(); }
/** * Constructs a Zip object. * * @param string $file_path * The full system path of the archive to manipulate. Only local files * are supported. If the file does not yet exist, it will be created if * appropriate. * * @throws \Drupal\Core\Archiver\ArchiverException */ public function __construct($file_path) { $this->zip = new \ZipArchive(); if ($this->zip->open($file_path) !== TRUE) { throw new ArchiverException(t('Cannot open %file_path', array('%file_path' => $file_path))); } }
/** * Save PhpPresentation to file * * @param string $pFilename * @throws \Exception */ public function save($pFilename) { if (empty($pFilename)) { throw new \Exception("Filename is empty."); } if (!is_null($this->presentation)) { // Create new ZIP file and open it for writing $objZip = new \ZipArchive(); // Try opening the ZIP file if ($objZip->open($pFilename, \ZipArchive::CREATE) !== true) { if ($objZip->open($pFilename, \ZipArchive::OVERWRITE) !== true) { throw new \Exception("Could not open " . $pFilename . " for writing."); } } // Add media $slideCount = $this->presentation->getSlideCount(); for ($i = 0; $i < $slideCount; ++$i) { for ($j = 0; $j < $this->presentation->getSlide($i)->getShapeCollection()->count(); ++$j) { if ($this->presentation->getSlide($i)->getShapeCollection()->offsetGet($j) instanceof AbstractDrawing) { $imgTemp = $this->presentation->getSlide($i)->getShapeCollection()->offsetGet($j); $objZip->addFromString('media/' . $imgTemp->getFilename(), file_get_contents($imgTemp->getPath())); } } } // Add PhpPresentation.xml to the document, which represents a PHP serialized PhpPresentation object $objZip->addFromString('PhpPresentation.xml', $this->writeSerialized($this->presentation, $pFilename)); // Close file if ($objZip->close() === false) { throw new \Exception("Could not close zip file {$pFilename}."); } } else { throw new \Exception("PhpPresentation object unassigned."); } }
public function __construct($archive_path) { $this->archive = new \ZipArchive(); $this->archive_path = $archive_path; if ($this->archive->open($this->archive_path, \ZipArchive::CREATE) !== true) { throw new ArchiveException('Cannot create zip archive: ' . $this->archive_path); } }
/** * Crea un archivo ZIP */ public function __construct() { # create new zip opbject $this->_zip = new ZipArchive(); # create a temp file & open it $this->_tempfile = tempnam('.', ''); $this->_zip->open($this->_tempfile, ZipArchive::CREATE); }
/** * ZipArchiveCreator constructor * * @param string $file Path to archive * @throws \Exception */ public function __construct($file) { $this->zip = new \ZipArchive(); $this->file = $file; if ($this->zip->open($this->file, \ZipArchive::CREATE) !== true) { throw new \Exception('Unable create archive'); } }
/** * @param string $filePath * @return $this * @throws Exception\Zip\FileOpenException */ private function zipOpen($filePath) { if ($code = $this->zip->open($filePath) !== true) { throw new Exception\Zip\FileOpenException($filePath, $code); } $this->filePath = $filePath; return $this; }
/** * Constructor * * @param string $filename Name of the .zip archive * @throws Exception */ public function __construct($filename) { $this->filename = $filename; $this->ziparchive = new ZipArchive(); if ($this->ziparchive->open($filename) !== true) { throw new Exception('Error opening ' . $filename); } }
/** * zipファイルを作成する * * @throws D9magai\Zip\Exception */ protected function open() { // $retには成功時にtrue,失敗時にエラーコードがセットされる $ret = $this->zipArchive->open($this->path, \ZipArchive::CREATE | \ZipArchive::OVERWRITE); if ($ret !== true) { throw new Exception('Zipファイルの作成に失敗しました', $ret); } }
/** * Opens a file archive. * * @param string $filename The file name of the archive to open. * * @return void * @throws Exception */ public function open($filename) { if ($this->zip->open($filename) !== true) { throw new \Exception('Unable to open zip archive ' . $filename); } $this->open = true; $this->getDetails(); }
/** * @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); }
public function __construct($archive_path, $tmpdir) { $this->archive_path = $archive_path; $this->extraction_path = $this->tempdir($tmpdir); $this->archive = new \ZipArchive(); if ($this->archive->open($this->archive_path) !== true) { throw new ArchiveException('Cannot open zip archive: ' . $archive_path); } }
/** * Opens the file at the given file path to make it ready to be read. * * @param string $filePath Path of the file to be read * @return void * @throws \Box\Spout\Common\Exception\IOException If the file at the given path or its content cannot be read * @throws \Box\Spout\Reader\Exception\NoSheetsFoundException If there are no sheets in the file */ protected function openReader($filePath) { $this->zip = new \ZipArchive(); if ($this->zip->open($filePath) === true) { $this->sheetIterator = new SheetIterator($filePath); } else { throw new IOException("Could not open {$filePath} for reading."); } }
/** * Create a new Template Object * * @param string $strFilename */ public function __construct($strFilename) { $path = dirname($strFilename); $this->_tempFileName = $path . DIRECTORY_SEPARATOR . time() . '.docx'; copy($strFilename, $this->_tempFileName); // Copy the source File to the temp File $this->_objZip = new ZipArchive(); $this->_objZip->open($this->_tempFileName); $this->_documentXML = $this->_objZip->getFromName('word/document.xml'); }
public function initialize() { $filename = $this->getFile(date('Y-m-d_h-i-s') . '_' . sprintf('%03d', mt_rand(1, 999)) . '.zip'); $this->zip = new \ZipArchive(); if (false === $this->zip->open($filename, \ZipArchive::CREATE)) { throw new \Exception(sprintf('Can\'t create archive %s.', $filename)); } $this->result = $filename; return $this; }
/** * Returns the archive * * @return \ZipArchive */ protected function getArchive() { if (!$this->zip) { $this->zip = new \ZipArchive(); if (true !== ($errorCode = $this->zip->open($this->archivePath))) { $this->zip = null; throw new \RuntimeException('Error opening file: ' . $this->getErrorMessage($errorCode)); } } return $this->zip; }
protected function setUp() { if (!extension_loaded('zip')) { $this->markTestSkipped('The zip extension is not available'); } $this->zipFile = new \ZipArchive(); $this->zipFile->open($this->zipFilename, \ZipArchive::CREATE); $this->zipFile->addFromString($this->filename, $this->fileContents); $this->zipFile->close(); $this->collection = new ResourceCollection([new FileResource(FileTransport::create($this->zipFilename))]); }
/** * Returns the archive * * @return \ZipArchive */ protected function getArchive() { if (!$this->zip) { $this->zip = new \ZipArchive(); if (true !== $this->zip->open($this->archivePath)) { $this->zip = null; throw new \RuntimeException('Error opening file'); } } return $this->zip; }
protected function retrieveResponse() { $response = $this->initResponse(); if (strpos($this->fileStem, '.zip') !== false) { if (!class_exists('ZipArchive')) { throw new KurogoException("class ZipArchive (php-zip) not available"); } $response->setContext('zipped', true); $zip = new ZipArchive(); if (strpos($this->fileStem, 'http') === 0 || strpos($this->fileStem, 'ftp') === 0) { $tmpFile = Kurogo::tempFile(); copy($this->fileStem, $tmpFile); $zip->open($tmpFile); } else { $zip->open($this->fileStem); } // locate valid shapefile components $shapeNames = array(); for ($i = 0; $i < $zip->numFiles; $i++) { if (preg_match('/(.+)\\.(shp|dbf|prj)$/', $zip->getNameIndex($i), $matches)) { $shapeName = $matches[1]; $extension = $matches[2]; if (!isset($shapeNames[$shapeName])) { $shapeNames[$shapeName] = array(); } $shapeNames[$shapeName][] = $extension; } } $responseData = array(); foreach ($shapeNames as $shapeName => $extensions) { if (in_array('dbf', $extensions) && in_array('shp', $extensions)) { $fileData = array('dbf' => $zip->getFromName("{$shapeName}.dbf"), 'shp' => $zip->getFromName("{$shapeName}.shp")); if (in_array('prj', $extensions)) { $prjData = $zip->getFromName("{$shapeName}.prj"); $fileData['projection'] = new MapProjection($prjData); } $responseData[$shapeName] = $fileData; } } $response->setResponse($responseData); } elseif (realpath_exists("{$this->fileStem}.shp") && realpath_exists("{$this->fileStem}.dbf")) { $response->setContext('zipped', false); $response->setContext('shp', "{$this->fileStem}.shp"); $response->setContext('dbf', "{$this->fileStem}.dbf"); if (realpath_exists("{$this->fileStem}.prj")) { $prjData = file_get_contents("{$this->fileStem}.prj"); $response->setContext('projection', new MapProjection($prjData)); } } else { throw new KurogoDataException("Cannot find {$this->fileStem}"); } return $response; }
function merge($data, $outputPath = null) { //open the Archieve to a temp folder $this->workingDir = sys_get_temp_dir() . "/DocxTemplating"; if (!file_exists($this->workingDir)) { mkdir($this->workingDir, 0777, true); } $workingFile = tempnam($this->workingDir, ''); if ($workingFile === FALSE || !copy($this->template, $workingFile)) { throw new Exception("Error in initializing working copy of the template"); } $this->workingDir = $workingFile . "_"; $zip = new ZipArchive(); if ($zip->open($workingFile) === TRUE) { $zip->extractTo($this->workingDir); $zip->close(); } else { throw new Exception('Failed to extract Template'); } if (!file_exists($this->workingDir)) { throw new Exception('Failed to extract Template'); } $filesToParse = array(array("name" => "word/document.xml", "required" => true), array("name" => "word/header1.xml"), array("name" => "word/header2.xml"), array("name" => "word/header3.xml"), array("name" => "word/footer1.xml"), array("name" => "word/footer2.xml"), array("name" => "word/footer3.xml"), array("name" => "word/footnotes.xml"), array("name" => "word/endnotes.xml")); foreach ($filesToParse as $fileToParse) { if (isset($fileToParse["required"]) && !file_exists($this->workingDir . '/' . $fileToParse["name"])) { throw new Exception("Can not merge, Template is corrupted"); } if (file_exists($this->workingDir . '/' . $fileToParse["name"])) { $this->mergeFile($this->workingDir . '/' . $fileToParse["name"], $data); } } // once merge is happened , zip the working directory and rename $mergedFile = $this->workingDir . '/output.docx'; if ($zip->open($mergedFile, ZipArchive::CREATE) === FALSE) { throw new Exception("Error in creating output"); } // Create recursive directory iterator $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->workingDir, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::LEAVES_ONLY); foreach ($files as $name => $file) { $name = substr($name, strlen($this->workingDir . "/")); $zip->addFile($file->getRealPath(), $name); //echo "\n".$name ." : ".$file->getRealPath(); } $zip->close(); //once merged file is available copy it to $outputPath or write as downloadable file if (isset($outputPath)) { copy($mergedFile, $outputPath); } else { } // remove workingDir and workingFile unlink($workingFile); $this->deleteDir($this->workingDir); }
/** * Returns the binary content of the currently opened/loaded ODS file. * To store any changed which have been made the odsResource gets closed * first, then the file is read and finally it is reopened again. * * @return string The binary data of the current ODS file with all changes. */ public function getFileData() { if (!$this->odsResource instanceof \ZipArchive) { throw new \Exception('No ODS file opened!'); } $this->odsResource->close(); $data = file_get_contents($this->temporaryFileName); if ($this->odsResource->open($this->temporaryFileName) !== true) { throw new \Exception('Couldn\'t reopen ODS file!'); } return $data; }
public function __construct($path) { if (!extension_loaded('zip')) { throw new RuntimeException('zip extension is not available'); } $this->_zip = new ZipArchive(); if (!file_exists($path)) { $this->_zip->open($path, ZipArchive::CREATE); } else { $this->_zip->open($path); } }
public function setUp() { parent::setUp(); $this->tmp_dir = '/var/tmp'; $this->fixtures_dir = dirname(__FILE__) . '/_fixtures'; $this->project_id = getmypid(); $this->project = stub('Project')->getID()->returns($this->project_id); $this->zip = new ZipArchive(); if ($this->zip->open($this->fixtures_dir . '/archive.zip') !== true) { $this->fail('unable to open fixture archive.zip'); } $this->archive = new ProjectXMLImporter_XMLImportZipArchive($this->project, $this->zip, $this->tmp_dir); }