/** * Adds a folder to the archive * @param string $path The folder which will be copied into the archive * @param string $name The entry name * @return $this * @throws */ public function addFolder($path, $name = null) { $fs = new Filesystem(); //check the folder exists if (!is_dir($path)) { throw new \InvalidArgumentException("Folder \"{$path}\" not found."); } $path = rtrim($path, '\\//'); //set the default name if (is_null($name)) { $name = basename($path); if ($name == '.') { $name = basename(dirname($path)); } } // @see http://us.php.net/manual/en/ziparchive.addfile.php#89813 // @see http://stackoverflow.com/questions/4620205/php-ziparchive-corrupt-in-windows $name = str_replace('\\', '/', ltrim($name, '\\/')); if (!empty($name) && $this->archive->statName($name) === false) { if ($this->archive->addEmptyDir($name) === false) { throw new \RuntimeException("Unable to add folder \"{$path}\" to ZIP archive as \"{$name}\"."); } } //** I had to use \DirectoryIterator instead of \deit\filesystem\Finder because I kept hitting the directory not empty when trying to remove files after this method $it = new \FilesystemIterator($path); foreach ($it as $p) { if (empty($name)) { $n = $fs->getRelativePath($p->getPathname(), $path); } else { $n = $name . '/' . $fs->getRelativePath($p->getPathname(), $path); } $this->add($p->getPathname(), $n); } return $this; }
public function remplace_image($search, $urlImage) { /* recherche des images dans le document * /word/media */ if (!file_exists($urlImage)) { return "RI : pb urlImage."; } $name = 'word/media/' . $search; $info = $this->_objZip->statName($name); // l'image n'est pas trouvé if ($info === FALSE) { return "RI : L'image n'est pas présente dans le docx. (" . $name . ")"; } // image est trouvé, il reste à la remplacer $ret = $this->_objZip->deleteName($name); if (!$ret) { return 'RI pb delete image'; } $ret = $this->_objZip->addFile($urlImage, $name); if (!$ret) { return 'RI addFile'; } return TRUE; }
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); } } } }
function zipfile_crc32($filename) { $zip = new ZipArchive(); $res = $zip->open($filename); $filename = basename($filename, ".zip"); $stats = $zip->statName($filename, ZipArchive::FL_NOCASE | ZipArchive::FL_NODIR); $result = dechex($stats["crc"]); $zip->close(); return $result; }
public static function assertFileExists($fileZip, $path) { $oZip = new \ZipArchive(); if ($oZip->open($fileZip) !== true) { return false; } if ($oZip->statName($path) === false) { return false; } return true; }
/** * Can the current PHPExcel_Reader_IReader read the file? * * @param string $pFilename * @return boolean * @throws PHPExcel_Reader_Exception */ public function canRead($pFilename) { // Check if file exists if (!file_exists($pFilename)) { throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); } // Check if zip class exists if (!class_exists('ZipArchive', FALSE)) { throw new PHPExcel_Reader_Exception("ZipArchive library is not enabled"); } $mimeType = 'UNKNOWN'; // Load file $zip = new ZipArchive(); if ($zip->open($pFilename) === true) { // check if it is an OOXML archive $stat = $zip->statName('mimetype'); if ($stat && $stat['size'] <= 255) { $mimeType = $zip->getFromName($stat['name']); } elseif ($stat = $zip->statName('META-INF/manifest.xml')) { $xml = simplexml_load_string($zip->getFromName('META-INF/manifest.xml')); $namespacesContent = $xml->getNamespaces(true); if (isset($namespacesContent['manifest'])) { $manifest = $xml->children($namespacesContent['manifest']); foreach ($manifest as $manifestDataSet) { $manifestAttributes = $manifestDataSet->attributes($namespacesContent['manifest']); if ($manifestAttributes->{'full-path'} == '/') { $mimeType = (string) $manifestAttributes->{'media-type'}; break; } } } } $zip->close(); return $mimeType === 'application/vnd.oasis.opendocument.spreadsheet'; } return FALSE; }
function serveFileFromZIP($baseDir, $zipName, $fileName) { $zip = new ZipArchive(); if ($zip->open($baseDir . $zipName) !== TRUE) { handleError("Could not open ZIP file '{$zipName}'"); } $contents = $zip->getStream($fileName); if ($contents === FALSE) { $zip->close(); handleError("Could not find file '{$fileName}' in ZIP file '{$zipName}'"); } $fileSize = $zip->statName($fileName)['size']; header('Content-Length: ' . $fileSize); header('Content-Type: text/plain'); fpassthru($contents); fclose($contents); $zip->close(); exit; }
/** * @param string $file_name */ public function __construct($file_name) { parent::__construct($file_name); $archive = strstr($file_name, '#', true); if (strpos($archive, 'zip://') === 0) { $this->_zip_name = substr($archive, strlen('zip://')); } else { $this->_zip_name = $archive; } $filename = substr(strstr($file_name, '#'), 1); $zip = new \ZipArchive(); $ret = $zip->open($this->_zip_name); if (true !== $ret) { $message = sprintf('zip error', $ret); throw new \RuntimeException($message); } $this->_stat = $zip->statName($filename); $this->_zip = $zip; $this->_file_name = $filename; }
public function inspect_zip(ZipArchive $zip) { $content = array('db' => false, 'fs' => false, 'auto-install' => false); if (count(array_filter(array('index.php', 'wp-config.php'), array($zip, 'statName'))) > 0) { $content['fs'] = true; } if ($zip->statName('database.txt') !== false) { $content['db'] = true; } if ($content['db'] || $content['fs']) { return $content; } $s = '/auto-install/database.txt'; for ($index = 0; $index < $zip->numFiles; ++$index) { $name = $zip->getNameIndex($index); if (substr($name, -strlen($s)) === $s) { $content['auto-install'] = true; break; } } return $content; }
protected function getFromStream() { try { $za = new ZipArchive(); if ($za->open($this->mwb)) { if (0 < $za->numFiles) { $stat = $za->statIndex(0); $filename = $stat["name"]; if (basename($filename) == "document.mwb.xml") { $fp = $za->getStream($filename); if (!$fp) { throw new Exception("Error: can't get stream to zipped file"); } else { $stat = $za->statName($stat["name"]); $buf = ""; ob_start(); while (!feof($fp)) { $buf .= fread($fp, 2048); } $xmlstream = ob_get_contents(); ob_end_clean(); if (stripos($xmlstream, "CRC error") != FALSE) { $errBuff = ''; ob_start(); echo 'CRC32 mismatch, current '; printf("%08X", crc32($buf)); //current CRC echo ', expected '; printf("%08X", $stat['crc']); //expected CRC $error = ob_get_contents(); ob_end_clean(); fclose($fp); throw new Exception($error); } fclose($fp); $this->xmlstream = $buf; } } else { throw new Exception("archive has to contain document.mwb.xml as first entry document."); } } else { $za->close(); throw new Exception("zip archive is empty"); } } else { throw new Exception("could not open archive " . $this->mwb); } } catch (Exception $e) { $this->error = $e->getMessage(); } }
private function addRunnerToArchive($archive, $worker_file_name, $options = array()) { $zip = new \ZipArchive(); if (!$zip->open($archive, \ZIPARCHIVE::CREATE) === true) { $zip->close(); throw new IronWorkerException("Archive {$archive} was not found!"); } if ($zip->statName($worker_file_name) === false) { $zip->close(); throw new IronWorkerException("File {$worker_file_name} in archive {$archive} was not found!"); } if (!empty($options['set_env']) && is_array($options['set_env'])) { $envs = $options['set_env']; } else { $envs = array(); } if (!$zip->addFromString('runner.php', $this->workerHeader($worker_file_name, $envs))) { throw new IronWorkerException("Adding Runner to the worker failed"); } $zip->close(); return true; }
private function addRunnerToArchive($archive, $worker_file_name) { $zip = new ZipArchive(); if (!$zip->open($archive, ZIPARCHIVE::CREATE) === true) { $zip->close(); throw new IronWorker_Exception("Archive {$archive} was not found!"); } if ($zip->statName($worker_file_name) === false) { $zip->close(); throw new IronWorker_Exception("File {$worker_file_name} in archive {$archive} was not found!"); } if (!$zip->addFromString('runner.php', $this->workerHeader($worker_file_name))) { throw new IronWorker_Exception("Adding Runner to the worker failed"); } $zip->close(); return true; }
/** * @author Jack * @date Sun Sep 20 21:57:13 2015 * @version 1.1 */ function zip_contents($file, $path) { $file = safe_add_extension($file, 'zip'); if (file_exists($file)) { if (filesize($file) >= 4294967296) { // If the file is bigger than 4G, we can't use PHP's zip for now $p7zip = config('p7zip', '/opt/local/bin/7z'); if (!file_exists($p7zip)) { $p7zip = '/usr/bin/7za'; } $spec = array(array("pipe", "r"), array("pipe", "w"), array("pipe", "w")); $p = proc_open("{$p7zip} x -so {$file} '{$path}'", $spec, $pipes); if (is_resource($p)) { $data = stream_get_contents($pipes[1]); fclose($pipes[1]); proc_close($p); return $data; } } else { $zip = new \ZipArchive(); if ($zip->open($file)) { if ($zip->statName($path)) { return file_get_contents('zip://' . $file . '#' . $path); } } } } return null; }
public function zipCheck($extendtype, $pluginurl, $pluginfile, $pluginfilename) { //Save extend zip file to server $data = file_get_contents($pluginurl); $fp = fopen($pluginfile, "wb"); fwrite($fp, $data); fclose($fp); if ($extendtype == "languages" || $extendtype == "themes") { return true; } elseif ($extendtype == "plugins") { $zip = new ZipArchive(); if ($zip->open(GSADMINPATH . $pluginfile) === TRUE) { if ($zip->statName($pluginfilename) != "") { return true; } else { return false; } $zip->close(); } } }
/** * Add a folder to a zip file * * @param ZipArchive &$zip_archive the zip file to add files/folder to * @param ElggObject $folder the folder to add * @param string $folder_path the path of the current folder * * @return void */ function file_tools_add_folder_to_zip(ZipArchive &$zip_archive, ElggObject $folder, $folder_path = '') { if (!$zip_archive instanceof ZipArchive || !elgg_instanceof($folder, 'object', FILE_TOOLS_SUBTYPE)) { return; } $folder_title = elgg_get_friendly_title($folder->title); $zip_archive->addEmptyDir($folder_path . $folder_title); $folder_path .= $folder_title . DIRECTORY_SEPARATOR; $file_options = ['type' => 'object', 'subtype' => 'file', 'limit' => false, 'relationship' => FILE_TOOLS_RELATIONSHIP, 'relationship_guid' => $folder->getGUID()]; // add files from this folder to the zip $files = new ElggBatch('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 . $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 . $file_name); } } // check if there are subfolders $folder_options = ['type' => 'object', 'subtype' => FILE_TOOLS_SUBTYPE, 'limit' => false, 'metadata_name_value_pairs' => ['parent_guid' => $folder->getGUID()]]; $sub_folders = new ElggBatch('elgg_get_entities_from_metadata', $folder_options); foreach ($sub_folders as $sub_folder) { file_tools_add_folder_to_zip($zip_archive, $sub_folder, $folder_path); } }
public static function getFileContents($archivefilename, $filename, &$buf = null) { $zip = new \ZipArchive(); if (!$zip->open($archivefilename)) { return array('ok' => false, 'error' => self::ZipStatusString(\ZipArchive::ER_OPEN)); } $fp = $zip->getStream($filename); //file inside archive if (!$fp) { return array('ok' => false, 'error' => self::ZipStatusString(\ZipArchive::ER_OPEN)); } $stat = $zip->statName($filename); $buf = ""; //file buffer ob_start(); //to capture CRC error message while (!feof($fp)) { $buf .= fread($fp, 2048); //reading more than 2156 bytes seems to disable internal CRC32 verification (bug?) } $s = ob_get_contents(); ob_end_clean(); if (stripos($s, "CRC error") != FALSE) { // echo 'CRC32 mismatch, current '; //\ZipArchive::ER_CRC $buf = null; fclose($fp); $zip->close(); return array('ok' => false, 'error' => self::ZipStatusString(\ZipArchive::ER_CRC), 'crc32' => sprintf("%08X", crc32($buf)), 'expected' => sprintf("%08X", $stat['crc'])); } fclose($fp); $zip->close(); //Done, unpacked file is stored in $buf return array('ok' => true, 'crc32' => sprintf("%08X", crc32($buf)), 'expected' => sprintf("%08X", $stat['crc']), 'byte' => strlen($buf), 'sha1' => sha1($buf)); }
$files[] = $matches[1]; } } } if (count($files) > 0) { $ok = $zip->extractTo($bdir, $files); } else { $ok = false; } return $ok; } unset($_SESSION["magmi_install_error"]); $zip = new ZipArchive(); $res = $zip->open($_FILES["magmi_package"]["tmp_name"]); try { $info = $zip->statName('magmi/conf/magmi.ini.default'); if ($res === TRUE && $info !== FALSE) { $ok = extractZipDir($zip, dirname(dirname(__FILE__)), "magmi"); $zip->close(); $_SESSION["magmi_install"] = array("info", "Magmi updated"); } else { $zip->close(); $_SESSION["magmi_install"] = array("error", "Invalid Magmi Archive"); } if (!$ok) { $_SESSION["magmi_install"] = array("error", "Cannot unzip Magmi Archive"); } session_write_close(); } catch (Exception $e) { session_write_close(); die($e->getMessage());
<?php $fname = dirname(__FILE__) . "/test53885.zip"; if (file_exists($fname)) { unlink($fname); } touch($fname); $nx = new ZipArchive(); $nx->open($fname); $nx->locateName("a", ZIPARCHIVE::FL_UNCHANGED); $nx->statName("a", ZIPARCHIVE::FL_UNCHANGED); ?> ==DONE== <?php error_reporting(0); $fname = dirname(__FILE__) . "/test53885.zip"; unlink($fname);
/** * check if a file exists allready * @param $NAME name of the file in the zip */ function fileExistsInZip($NAME) { $zip = new ZipArchive(); $code = $zip->open($this->functions->settings->zipFile, ZipArchive::CREATE); if ($code === TRUE) { return !($zip->statName($NAME) === FALSE); } return false; }
/** * Can the current PHPExcel_Reader_IReader read the file? * * @param string $pFileName * @return boolean * @throws Exception */ public function canRead($pFilename) { // Check if file exists if (!file_exists($pFilename)) { throw new Exception("Could not open " . $pFilename . " for reading! File does not exist."); } // Check if zip class exists if (!class_exists('ZipArchive', FALSE)) { throw new Exception("ZipArchive library is not enabled"); } // Load file $zip = new ZipArchive(); if ($zip->open($pFilename) === true) { // check if it is an OOXML archive $stat = $zip->statName('mimetype'); if ($stat && $stat['size'] <= 255) { $mimeType = $zip->getFromName($stat['name']); } else { $zip->close(); return FALSE; } $zip->close(); return $mimeType === 'application/vnd.oasis.opendocument.spreadsheet'; } return FALSE; }
function updateSoftwareArchive($path) { $statusCode = 0; $zip = new ZipArchive(); if ($zip->open($path) === true) { $fileNameInformation = $this->yellow->config->get("updateInformationFile"); for ($i = 0; $i < $zip->numFiles; ++$i) { $fileName = $zip->getNameIndex($i); if (empty($pathBase)) { preg_match("#^(.*\\/).*?\$#", $fileName, $matches); $pathBase = $matches[1]; } if ($fileName == $pathBase . $fileNameInformation) { $fileData = $zip->getFromIndex($i); break; } } foreach ($this->yellow->toolbox->getTextLines($fileData) as $line) { if (preg_match("/^\\#/", $line)) { continue; } preg_match("/^\\s*(.*?)\\s*:\\s*(.*?)\\s*\$/", $line, $matches); if (lcfirst($matches[1]) == "plugin" || lcfirst($matches[1]) == "theme") { $software = $matches[2]; } if (!empty($software) && !empty($matches[1]) && !empty($matches[2])) { list($fileName, $flags) = explode(',', $matches[2], 2); $fileData = $zip->getFromName($pathBase . $fileName); $metaData = $zip->statName($pathBase . $fileName); $modified = $metaData ? $metaData["mtime"] : 0; $statusCode = $this->updateSoftwareFile($matches[1], $fileData, $modified, $flags, $software); if ($statusCode != 200) { break; } } } $zip->close(); if ($statusCode == 200 && !$this->yellow->toolbox->deleteFile($path)) { $statusCode = 500; $this->yellow->page->error($statusCode, "Can't delete file '{$path}'!"); } } return $statusCode; }
public function restore(FW_Backup_Interface_Storage $storage, FW_Backup_Interface_File $backup_file) { /** * @var WP_Filesystem_Base $wp_filesystem */ global $wp_filesystem; if ($wp_filesystem->abspath() == '/') { throw new FW_Backup_Exception('WordPress was located at root directory (/). Restoration for this scenario was not implemented.'); } $wp = rtrim($wp_filesystem->abspath(), '/'); $wp_new = rtrim(dirname($wp), '/') . '/' . uniqid(); $wp_backup = $wp . '-' . date('Y-m-d_H-i_s'); $backup_rel = str_replace(DIRECTORY_SEPARATOR, '/', $this->backup_rel); $tmp = array(); $func = array(); try { // Fetch archive $tmp[] = $tmp_zip = $storage->fetch($backup_file); $zip = new ZipArchive(); if (($errno = $zip->open($tmp_zip)) !== true) { throw new FW_Backup_Exception(sprintf(__('$zip->open() failed: %d'), $errno)); } $func[] = array($zip, 'close'); // Restore files (should come before database: rename wordpress dir can fail) if (count(array_filter(array('index.php', 'wp-config.php'), array($zip, 'statName'))) > 0) { // Extract archive into temporary location unzip_file($tmp_zip, $wp_new); // Get rid of database.sql file, if any if ($wp_filesystem->exists("{$wp_new}/database.sql")) { $wp_filesystem->delete("{$wp_new}/database.sql"); } // Replace wordpress dir by version from backup $move = true && $wp_filesystem->move($wp, $wp_backup) && $wp_filesystem->move($wp_new, $wp) && $wp_filesystem->move("{$wp_backup}/{$backup_rel}", "{$wp}/{$backup_rel}"); if (!$move) { throw new FW_Backup_Exception('Replacing wordpress dir by version from backup failed'); } } // Restore database if ($zip->statName('database.sql') !== false) { $fp = array($fp_settings = tmpfile(), $fp_history = tmpfile()); // Preserve Backup History and Backup Settings across restore $this->ie_history->export($fp_history); $this->ie_settings->export($fp_settings); // .zip streams does not support seeking array_map('rewind', $fp); $fp[] = $fp_db = $zip->getStream('database.sql'); $this->ie_db->import($fp_db); $this->ie_history->import($fp_history); $this->ie_settings->import($fp_settings); array_map('fclose', $fp); } } catch (Exception $exception) { // Delete directory .zip was extracted into if ($wp_filesystem->exists($wp_new)) { $wp_filesystem->delete($wp_new, true); } // If backup copy was made if ($wp_filesystem->exists($wp_backup)) { // 3. Move backup_dir back if ($wp_filesystem->exists("{$wp}/{$backup_rel}")) { $wp_filesystem->move("{$wp}/{$backup_rel}", "{$wp_backup}/{$backup_rel}"); } // 2. Delete extracted version if ($wp_filesystem->exists($wp)) { $wp_filesystem->delete($wp, true); } // 1. Move backup'ed directory backup $wp_filesystem->move($wp_backup, $wp); } } // on WAMP 2.5 with PHP 5.5.12 and Apache 2.4.9 this makes php crash // array_map('call_user_func', $func); foreach ($func as $callable) { call_user_func($callable); } array_map('unlink', array_filter($tmp, 'file_exists')); if (isset($exception)) { throw $exception; } }
<?php $debug = true; include 'common.inc'; if (!$admin) { header('HTTP/1.0 403 Forbidden'); exit; } if (isset($_REQUEST['name']) && isset($_FILES['apk']['tmp_name']) && isset($_FILES['apk']['name'])) { $lock = Lock('BrowserUpload', true, 30); if ($lock) { $valid = false; $uploadResult = 'Error processing ' . htmlspecialchars($_FILES['apk']['name']); $zip = new ZipArchive(); if ($zip->open($_FILES['apk']['tmp_name'])) { if ($zip->statName('assets/content_shell.pak') !== false) { $name = $_REQUEST['name']; if (preg_match('/[a-zA-Z0-9_\\-]+/', $name)) { if (!is_file("./browsers/{$name}.apk")) { $valid = true; } else { $uploadResult = "ERROR: A browser named {$name} already exists"; } } else { $uploadResult = 'ERROR: Invalid browser name: ' . htmlspecialchars($name); } } $zip->close(); } if ($valid) { if (move_uploaded_file($_FILES['apk']['tmp_name'], "./browsers/{$name}.apk")) {
} // stores ['fullFileName' => num of occurances] // reason for 'fullFileName' as key is file1.JPG and file2.GIF are not the same $preExistingFiles = array(); foreach ($idArr as $fileid) { // for each given file ID // get data from database $query = "SELECT * FROM filestores WHERE id='{$fileid}'"; $result = mysql_query($query); $row = mysql_fetch_array($result); $fileData = $row['file']; $fileName = $row['filename']; $fileExtension = $row['extension']; // attempt add to the .ZIP, first check if file already exists $fullFileName = $fileName . '.' . $fileExtension; if ($zippy->statName($fullFileName) !== false) { if (!array_key_exists($fullFileName, $preExistingFiles)) { // 1st re-occurance of file in .ZIP, append (1) index $preExistingFiles[$fullFileName] = 1; $fileName .= "(copy 1)"; } else { // at least 2nd re-occurance of file in .ZIP, append (i) index $preExistingFiles[$fullFileName] += 1; $fileName .= '(copy ' . $preExistingFiles[$fullFileName] . ')'; } } $zippy->addFromString($fileName . '.' . $fileExtension, $fileData); } $zippy->close(); // close zippy, saving changes // send zip file to web browser with all information
/** * Adds a file to Archive * * @param $file_name string * @param $name_in_archive string * @return bool Add worked or not */ public function add_file($file_name, $name_in_archive = '') { $file_name = trim($file_name); //check param if (empty($file_name)) { trigger_error(__('File name cannot be empty', 'backwpup'), E_USER_WARNING); return FALSE; } if (version_compare(PHP_VERSION, '5.3', '>=')) { clearstatcache(TRUE, $file_name); } if (!is_readable($file_name)) { trigger_error(sprintf(_x('File %s does not exist or is not readable', 'File to add to archive', 'backwpup'), $file_name), E_USER_WARNING); return TRUE; } if (empty($name_in_archive)) { $name_in_archive = $file_name; } //remove reserved chars $name_in_archive = str_replace(array("?", "<", ">", ":", "%", "\"", "*", "|", chr(0)), '', $name_in_archive); switch ($this->get_method()) { case 'gz': if ($this->file_count > 0) { trigger_error(__('This archive method can only add one file', 'backwpup'), E_USER_WARNING); return FALSE; } //add file to archive if (!($fd = fopen($file_name, 'rb'))) { trigger_error(sprintf(__('Cannot open source file %s to archive', 'backwpup'), $file_name), E_USER_WARNING); return FALSE; } while (!feof($fd)) { fwrite($this->filehandel, fread($fd, 8192)); } fclose($fd); $this->file_count++; break; case 'bz': if ($this->file_count > 0) { trigger_error(__('This archive method can only add one file', 'backwpup'), E_USER_WARNING); return FALSE; } //add file to archive if (!($fd = fopen($file_name, 'rb'))) { trigger_error(sprintf(__('Cannot open source file %s to archive', 'backwpup'), $file_name), E_USER_WARNING); return FALSE; } while (!feof($fd)) { fwrite($this->filehandel, bzcompress(fread($fd, 8192))); } fclose($fd); $this->file_count++; break; case 'Tar': case 'TarGz': case 'TarBz2': //convert chars for archives file names if (function_exists('iconv') && stristr(PHP_OS, 'win') !== false) { $test = @iconv('ISO-8859-1', 'UTF-8', $name_in_archive); if ($test) { $name_in_archive = $test; } } return $this->tar_file($file_name, $name_in_archive); break; case 'ZipArchive': //convert chars for archives file names if (function_exists('iconv') && stristr(PHP_OS, 'win') === false) { $test = @iconv('UTF-8', 'CP437', $name_in_archive); if ($test) { $name_in_archive = $test; } } $file_size = filesize($file_name); if ($file_size === FALSE) { return FALSE; } //check if entry already in archive and delete it if it not in full size if ($zip_file_stat = $this->ziparchive->statName($name_in_archive)) { if ($zip_file_stat['size'] != $file_size) { $this->ziparchive->deleteName($name_in_archive); //reopen on deletion $this->file_count = 21; } else { //file already complete in archive return TRUE; } } //close and reopen, all added files are open on fs if ($this->file_count > 20) { //35 works with PHP 5.2.4 on win if (!$this->ziparchive->close()) { $this->ziparchive_status(); trigger_error(__('ZIP archive cannot be closed correctly', 'backwpup'), E_USER_ERROR); sleep(1); } $this->ziparchive = NULL; if (!$this->check_archive_filesize()) { return FALSE; } $this->ziparchive = new ZipArchive(); $ziparchive_open = $this->ziparchive->open($this->file, ZipArchive::CREATE); if ($ziparchive_open !== TRUE) { $this->ziparchive_status(); return FALSE; } $this->file_count = 0; } if ($file_size < 1024 * 1024 * 2) { if (!$this->ziparchive->addFromString($name_in_archive, file_get_contents($file_name))) { $this->ziparchive_status(); trigger_error(sprintf(__('Cannot add "%s" to zip archive!', 'backwpup'), $name_in_archive), E_USER_ERROR); return FALSE; } else { $file_factor = round($file_size / (1024 * 1024), 4) * 2; $this->file_count = $this->file_count + $file_factor; } } else { if (!$this->ziparchive->addFile($file_name, $name_in_archive)) { $this->ziparchive_status(); trigger_error(sprintf(__('Cannot add "%s" to zip archive!', 'backwpup'), $name_in_archive), E_USER_ERROR); return FALSE; } else { $this->file_count++; } } break; case 'PclZip': $this->pclzip_file_list[] = array(PCLZIP_ATT_FILE_NAME => $file_name, PCLZIP_ATT_FILE_NEW_FULL_NAME => $name_in_archive); if (count($this->pclzip_file_list) >= 100) { if (0 == $this->pclzip->add($this->pclzip_file_list)) { trigger_error(sprintf(__('PclZip archive add error: %s', 'backwpup'), $this->pclzip->errorInfo(TRUE)), E_USER_ERROR); return FALSE; } $this->pclzip_file_list = array(); } break; } return TRUE; }
<?php $filename = 'MYLOGOV2.GFX'; $zipname = dirname(__FILE__) . "/pecl12414.zip"; $za = new ZipArchive(); $res = $za->open($zipname); if ($res === TRUE) { $finfo = $za->statName($filename); $file_size = $finfo['size']; if ($file_size > 0) { $contents = $za->getFromName($filename); echo "ZIP contents size: " . strlen($contents) . "\n"; if (strlen($contents) != $file_size) { echo "zip_readfile recorded data does not match unpacked size: " . $zipname . " : " . $filename; } } else { $contents = false; echo "zip_readfile could not open stream from zero length file " . $zipname . " : " . $filename; } $za->close(); } else { echo "zip_readfile could not read from " . $zipname . " : " . $filename; }
/** * Warning: This test asserts multiple things at once to keep the setup short. * * @test */ public function createZipFileFromExtensionGeneratesCorrectArchive() { // 42 second of first day in 1970 - used to have achieve stable file names $GLOBALS['EXEC_TIME'] = 42; // Create extension for testing: $extKey = $this->createFakeExtension(); $extensionRoot = $this->fakedExtensions[$extKey]['siteAbsPath']; // Build mocked fileHandlingUtility: $fileHandlerMock = $this->getAccessibleMock(\TYPO3\CMS\Extensionmanager\Utility\FileHandlingUtility::class, array('getAbsoluteExtensionPath', 'getExtensionVersion')); $fileHandlerMock->expects($this->any())->method('getAbsoluteExtensionPath')->will($this->returnValue($extensionRoot)); $fileHandlerMock->expects($this->any())->method('getExtensionVersion')->will($this->returnValue('0.0.0')); // Add files and directories to extension: touch($extensionRoot . 'emptyFile.txt'); file_put_contents($extensionRoot . 'notEmptyFile.txt', 'content'); touch($extensionRoot . '.hiddenFile'); mkdir($extensionRoot . 'emptyDir'); mkdir($extensionRoot . 'notEmptyDir'); touch($extensionRoot . 'notEmptyDir/file.txt'); // Create zip-file from extension $filename = $fileHandlerMock->_call('createZipFileFromExtension', $extKey); $expectedFilename = PATH_site . 'typo3temp/ExtensionManager/' . $extKey . '_0.0.0_' . date('YmdHi', 42) . '.zip'; $this->testFilesToDelete[] = $filename; $this->assertEquals($expectedFilename, $filename, 'Archive file name differs from expectation'); // File was created $this->assertTrue(file_exists($filename), 'Zip file not created'); // Read archive and check its contents $archive = new \ZipArchive(); $this->assertTrue($archive->open($filename), 'Unable to open archive'); $this->assertEquals($archive->statName('emptyFile.txt')->size, 0, 'Empty file not in archive'); $this->assertEquals($archive->getFromName('notEmptyFile.txt'), 'content', 'Expected content not found'); $this->assertFalse($archive->statName('.hiddenFile'), 'Hidden file not in archive'); $this->assertTrue(is_array($archive->statName('emptyDir/')), 'Empty directory not in archive'); $this->assertTrue(is_array($archive->statName('notEmptyDir/')), 'Not empty directory not in archive'); $this->assertTrue(is_array($archive->statName('notEmptyDir/file.txt')), 'File within directory not in archive'); // Check that the archive has no additional content $this->assertEquals($archive->numFiles, 5, 'Too many or too less files in archive'); }
/** * Implements support for fstat(). * * @return boolean */ public function stream_stat() { return $this->archive->statName($this->fileNameInArchive); }
$folder_guids = get_input("folder_guids"); if (empty($file_guids) && empty($folder_guids)) { register_error(elgg_echo("InvalidParameterException:MissingParameter")); forward(REFERER); } $zip = new ZipArchive(); if ($zip->open($zip_filename, ZIPARCHIVE::CREATE) !== true) { register_error(elgg_echo("file:downloadfailed")); forward(REFERER); } // add files to the zip if (!empty($file_guids)) { foreach ($file_guids as $file_guid) { if ($file = get_entity($file_guid)) { // check if the name exists in the zip if ($zip->statName($file->originalfilename) === false) { // doesn't exist, so add $zip->addFile($file->getFilenameOnFilestore(), $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->addFile($file->getFilenameOnFilestore(), $file_name); } } } } // add folder (and their content) to the zip if (!empty($folder_guids)) { foreach ($folder_guids as $folder_guid) { if ($folder = get_entity($folder_guid)) {
/** * Create restore files list */ public function restore_files_list() { if (is_readable(BACKUPFOLDER)) { $dh = opendir(BACKUPFOLDER); while ($filename = readdir($dh)) { if (filetype($filename) != 'dir') { $file_type = ''; preg_match('/\\.[a-z]{2,3}/', $filename, $file_type); if ($file_type[0] == '.zip') { $zip = new ZipArchive(); $zip->open(BACKUPFOLDER . $filename); if ($zip->statName('backup.sql')) { $this->restore_files[] = array('name' => $filename, 'size' => round(filesize(BACKUPFOLDER . $filename) / 1024 / 1024, 2), 'create_date' => filemtime(BACKUPFOLDER . $filename)); } $zip->close(); } } } return $this->restore_files; } else { return FALSE; } }