/** * 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; }
/** * 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; }
public function action($parent) { $c = $parent->config; $util = new Utility(); if (strpos($_POST['path'], '/') === 0 || strpos($_POST['path'], '../') !== false || strpos($_POST['path'], './') === 0) { $this->r = array('wrong path', 400); return; } $path = $c['current_path'] . $_POST['path']; $info = pathinfo($path); $base_folder = $c['current_path'] . $util->fix_dirname($_POST['path']) . "/"; switch ($info['extension']) { case "zip": $zip = new \ZipArchive(); if ($zip->open($path) === true) { //make all the folders for ($i = 0; $i < $zip->numFiles; $i++) { $OnlyFileName = $zip->getNameIndex($i); $FullFileName = $zip->statIndex($i); if (substr($FullFileName['name'], -1, 1) == "/") { $util->create_folder($base_folder . $FullFileName['name']); } } //unzip into the folders for ($i = 0; $i < $zip->numFiles; $i++) { $OnlyFileName = $zip->getNameIndex($i); $FullFileName = $zip->statIndex($i); if (!(substr($FullFileName['name'], -1, 1) == "/")) { $fileinfo = pathinfo($OnlyFileName); if (in_array(strtolower($fileinfo['extension']), $ext)) { copy('zip://' . $path . '#' . $OnlyFileName, $base_folder . $FullFileName['name']); } } } $zip->close(); } else { $this->r = array('Could not extract. File might be corrupt.', 500); return; } break; case "gz": $p = new \PharData($path); $p->decompress(); // creates files.tar break; case "tar": // unarchive from the tar $phar = new \PharData($path); $phar->decompressFiles(); $files = array(); $util->check_files_extensions_on_phar($phar, $files, '', $ext); $phar->extractTo($current_path . fix_dirname($_POST['path']) . "/", $files, true); break; default: $this->r = array('This extension is not supported. Valid: zip, gz, tar.', 400); return; break; } }
/** * @param \ZipArchive $stream * @return string */ private function getPluginNamespace(\ZipArchive $stream) { $segments = $stream->statIndex(0); $segments = array_filter(explode('/', $segments['name'])); if (count($segments) <= 1) { $segments = $stream->statIndex(1); $segments = array_filter(explode('/', $segments['name'])); } if (!in_array($segments[0], ['Frontend', 'Backend', 'Core'])) { throw new \RuntimeException(sprintf('Uploaded zip archive contains no plugin namespace directory: %s', $segments[1])); } return implode('/', $segments); }
protected function execute(InputInterface $input, OutputInterface $output) { $this->georgiaVoterService->setConnectionName($input->getArgument('dbname')); if ($input->getOption('config')) { $this->georgiaVoterService->setConfigFolder($input->getOption('config')); } // setConfigFolder $zip = new \ZipArchive(); $res = $zip->open($input->getArgument('zipFile')); if ($res === TRUE) { $this->georgiaVoterService->initializeGeorgiaVoterTable(); $compressedfiles = []; for ($i = 0; $i < $zip->numFiles; $i++) { $compressedfiles[] = $zip->statIndex($i); } usort($compressedfiles, function ($a, $b) { if ($a['size'] == $b['size']) { return 0; } return $a['size'] < $b['size'] ? -1 : 1; }); $maxentry = array_pop($compressedfiles); $exportDate = \date("Y-m-d", $maxentry['mtime']); $fp = $zip->getStream($maxentry['name']); while (($buffer = fgets($fp, 4096)) !== false) { $output->writeln($buffer); } } else { $output->writeln("Zip File Problem"); } }
public function testCompressFolder() { $files = array('releases-noNewPatch.xml', 'releases-patchsOnly.xml', 'releases.xml', 'folder/', 'folder/emptyFile', 'emptyFolder/'); $dest = dirname(__FILE__) . '/backup/test.zip'; $src = dirname(__FILE__) . '/sample'; taoUpdate_helpers_Zip::compressFolder($src, $dest); $this->assertTrue(is_file($dest)); $zip = new ZipArchive(); $zip->open($dest); foreach ($files as $file) { $this->assertFalse($zip->locateName($file) === false, $file . ' not found'); } $this->assertFalse($zip->locateName('.svn')); helpers_File::remove($dest); $dest = dirname(__FILE__) . '/backup/test2.zip'; taoUpdate_helpers_Zip::compressFolder($src, $dest, true); $files = array('sample/releases-noNewPatch.xml', 'sample/releases-patchsOnly.xml', 'sample/releases.xml', 'sample/folder/', 'sample/folder/emptyFile', 'sample/emptyFolder/'); $this->assertTrue(is_file($dest)); $zip = new ZipArchive(); $zip->open($dest); for ($i = 0; $i < $zip->numFiles; $i++) { $stat = $zip->statIndex($i); //cehck no .svn added in zip $this->assertFalse(strpos($stat['name'], '.svn') > 0); } foreach ($files as $file) { $this->assertFalse($zip->locateName($file) === false); } helpers_File::remove($dest); }
function import($inputFile, $targetDirectory = null) { if (!$targetDirectory) { $targetDirectory = ''; } $finfo = finfo_open(FILEINFO_MIME_TYPE); $type = finfo_file($finfo, $inputFile); finfo_close($finfo); switch ($type) { case 'application/zip': $zip = new ZipArchive(); $zip->open($inputFile); $i = 0; while ($i < $zip->numFiles) { $file = $zip->statIndex($i); $contents = ''; $fp = $zip->getStream($file['name']); while (!feof($fp)) { $contents .= fread($fp, 2); } SiteCollection::createFile($targetDirectory . $file['name'], $contents); fclose($fp); $i++; } break; default: throw new Exception('MIME type ' . $type . ' unsupported.'); } }
public function execute($args) { if ($args) { $file = $args[0]; if (file_exists($file) && \Clips\is_zip($file)) { switch (count($args)) { case 1: $p = new \ZipArchive(); $p->open($file); for ($i = 0; $i < $p->numFiles; $i++) { $stat = $p->statIndex($i); echo $stat['name'] . PHP_EOL; print_r($stat); } break; default: echo \Clips\zip_contents($file, $args[1]); } } else { $this->error("The file {$file} is not exists or is not a phar file!"); } } else { $this->error('No phar file input!'); } }
public function importtables($thisfolder) { // the main sub in our application $PHP_EOL = "\r\n"; // if (file_exists($filename)) unlink ($filename); $za = new ZipArchive(); $za->open($thisfolder.'/update.zip'); // if ($txt=="update") { echo "Files in zip archive: ".$za->numFiles.$PHP_EOL; echo "Extracting to ".$thisfolder."".$PHP_EOL; $za->extractTo($thisfolder.""); // } else { // echo "Single table mode".$PHP_EOL; // } $tablenames = array( 'Money' ); // 'Projects' $filenames = array( 'Money.dbu' ); // 'Projects.dbu' echo "------\r"; for($i = 0; $i < $za->numFiles; $i++) { $stat = $za->statIndex($i); if (in_array($stat['name'],$filenames)) { $filename=$thisfolder."/".$stat['name']; if (file_exists($filename)) echo $filename." extracted successfully".$PHP_EOL; } } echo "------\r"; for($i = 0; $i < sizeof($filenames); $i++) { $filename=$thisfolder."/".$filenames[$i]; if (file_exists($filename)) { echo "Reading data from ".$filenames[$i].$PHP_EOL; $file = conv(file_get_contents($filename)); $json = json_decode($file); if (sizeof($json)) { echo "Importing data (".strlen($file)." Kb)".$PHP_EOL; $this->importtable($json, $txt); } else { echo "JSON decode error ".echo_jerror(json_last_error()).$PHP_EOL; } echo "------\r"; } else { echo "File not found".$PHP_EOL; } } // ajax_echo_r(json_last_error()); // echo_r($json); if ($za->numFiles) { $za->close(); } }
private function locateFile(\ZipArchive $zip, $filename) { $indexOfShortestMatch = false; $lengthOfShortestMatch = -1; for ($i = 0; $i < $zip->numFiles; $i++) { $stat = $zip->statIndex($i); if (strcmp(basename($stat['name']), $filename) === 0) { $directoryName = dirname($stat['name']); if ($directoryName == '.') { return $i; } if (strpos($directoryName, '\\') !== false || strpos($directoryName, '/') !== false) { continue; } $length = strlen($stat['name']); if ($indexOfShortestMatch == false || $length < $lengthOfShortestMatch) { $contents = $zip->getFromIndex($i); if ($contents !== false) { $indexOfShortestMatch = $i; $lengthOfShortestMatch = $length; } } } } return $indexOfShortestMatch; }
/** * 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]); } } }
public function url_stat($path, $flags) { $ret = []; $zippath = preg_replace('/^myzip:\\/\\//', "", $path); $parts = explode('#', $zippath, 2); if (count($parts) != 2) { return false; } list($zippath, $subfile) = $parts; $za = new \ZipArchive(); if ($za->open($zippath) !== true) { return false; } $i = $za->locateName($subfile); if ($i === false) { return false; } $zst = $za->statIndex($i); $za->close(); unset($za); foreach ([7 => 'size', 8 => 'mtime', 9 => 'mtime', 10 => 'mtime'] as $a => $b) { if (!isset($zst[$b])) { continue; } $ret[$a] = $zst[$b]; } return $ret; }
function processPluginsFolder($folder, $requiredMpsVersion, $pluginsVersion) { $files = scandir($folder); foreach ($files as $zipfile) { if (pathinfo($zipfile, PATHINFO_EXTENSION) == 'zip') { $za = new ZipArchive(); $za->open($folder . $zipfile); for ($i = 0; $i < $za->numFiles; $i++) { $stat = $za->statIndex($i); $pluginXmlFile = $stat['name']; if (endsWith($pluginXmlFile, "META-INF/plugin.xml")) { $stream = $za->getStream($pluginXmlFile); $content = stream_get_contents($stream); $xml = simplexml_load_string($content); if (fixPluginXml($xml, $requiredMpsVersion, $pluginsVersion)) { $za->deleteName($pluginXmlFile); $za->addFromString($pluginXmlFile, $xml->asXML()); } printPluginXml($xml, $zipfile, $requiredMpsVersion, $pluginsVersion); break; } } } } }
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; }
public function import($zipfile) { if (file_exists($zipfile)) { $zip = new ZipArchive(); if ($zip->open($zipfile) !== TRUE) { throw new Exception("Unable to open import file, corrupted zip file?: " . $zipfile); } else { // validate zip file $num_files = $zip->numFiles; if ($num_files < 1) { throw new Exception("Unable to open import file, corrupted zip file?: " . $zipfile); } $num_files--; $last_file = $zip->statIndex($num_files); if ($last_file['name'] != 'create_tables.sql') { throw new Exception("Unable to open import file, corrupted zip file?: " . $zipfile); } // extract zipfile // create backip dir $bkdir = THINKUP_WEBAPP_PATH . self::CACHE_DIR . '/backup'; if (!file_exists($bkdir)) { mkdir($bkdir); } $zip->extractTo($bkdir); $create_table = $bkdir . '/create_tables.sql'; $infiles = glob($bkdir . '/*.txt'); // rebuild db $sql = file_get_contents($create_table); if (getenv('BACKUP_VERBOSE') !== false) { print " Creating tables...\n\n"; } $stmt = $this->execute($sql); $stmt->closeCursor(); unlink($create_table); // import data //var_dump($infiles); foreach ($infiles as $infile) { $table = $infile; $matches = array(); if (preg_match('#.*/(\\w+).txt$#', $table, $matches)) { $table = $matches[1]; if (getenv('BACKUP_VERBOSE') !== false) { print " Restoring data for table: {$table}\n"; } $q = "LOAD DATA INFILE '{$infile}' INTO TABLE {$table}"; $stmt = $this->execute($q); if (!$stmt) { throw new Exception("unbale to load data file: " . $infile); } $stmt->closeCursor(); unlink($infile); } } rmdir($bkdir); return true; } } else { throw new Exception("Unable to open import file: " . $zipfile); } }
/** * Find a file by name, returning the one that has the shortest path. * * @param \ZipArchive $zip * @param $filename * @return bool|int */ private function locateFile(\ZipArchive $zip, $filename) { $indexOfShortestMatch = false; $lengthOfShortestMatch = -1; for ($i = 0; $i < $zip->numFiles; $i++) { $stat = $zip->statIndex($i); if (strcmp(basename($stat['name']), $filename) === 0) { $directoryName = dirname($stat['name']); if ($directoryName == '.') { //if composer.json is in root directory //it has to be the one to use. return $i; } if (strpos($directoryName, '\\') !== false || strpos($directoryName, '/') !== false) { //composer.json files below first directory are rejected continue; } $length = strlen($stat['name']); if ($indexOfShortestMatch == false || $length < $lengthOfShortestMatch) { //Check it's not a directory. $contents = $zip->getFromIndex($i); if ($contents !== false) { $indexOfShortestMatch = $i; $lengthOfShortestMatch = $length; } } } } return $indexOfShortestMatch; }
/** Returns an array of strings (for error messages) and image objects (for successful). */ public static function createFromArchive($filename, $objAlbum) { if (!class_exists('ZipArchive')) { return "image_nozip"; } $arrRet = array(); $zipArchive = new ZipArchive(); $zipArchive->open($filename); for ($i = 0; $i < $zipArchive->numFiles; $i++) { /* We stat the file, to get its name. */ $stat = $zipArchive->statIndex($i); $strInName = $stat['name']; /* Open the temp output file. This is vulnerable to a race condition. TODO. */ $filename = tempnam("/tmp", "OSPAP2"); $out = fopen($filename, 'w'); /* Get the file stream from the archive. */ $in = $zipArchive->getStream($stat['name']); /* Read the file from the zip. It takes several iterations to get to the end, so we loop. */ while (!feof($in)) { fputs($out, fgets($in)); } /* Close the input and output files. */ fclose($out); fclose($in); /* Determine the mimetype from the filename. None of php's built-in functions seem to work.. */ if (preg_match("/\\.png\$/", $stat['name'])) { $mimetype = "image/png"; } elseif (preg_match("/\\.gif\$/", $stat['name'])) { $mimetype = "image/gif"; } elseif (preg_match("/\\.jpg\$/", $stat['name'])) { $mimetype = "image/jpeg"; } elseif (preg_match("/\\.jpeg\$/", $stat['name'])) { $mimetype = "image/jpeg"; } else { $mimetype = "unknown"; } /* Create the new file. */ $new = clsPicture::createFromFile($filename, $mimetype, $objAlbum); /* Delete the file. */ unlink($filename); if (is_string($new)) { $strError = $new; $new = new clsDB('image'); $new->set('error', $strError); $new->set('name', $stat['name']); } else { $new->set('original_name', $stat['name']); $new->set('original_mime', $mimetype); $new->set('original_size', $stat['size']); } /* Add it to the array (note that it can be a string (for an error) or an image object. */ $arrRet[] = $new; } if (sizeof($arrRet) == 0) { return 'image_nofiles'; } return $arrRet; }
/** * Extract headers and readme.txt data from a ZIP archive that contains a plugin or theme. * * Returns an associative array with these keys: * 'type' - Detected package type. This can be either "plugin" or "theme". * 'header' - An array of plugin or theme headers. See get_plugin_data() or WP_Theme for details. * 'readme' - An array of metadata extracted from readme.txt. @see self::parseReadme() * 'pluginFile' - The name of the PHP file where the plugin headers were found relative to the root directory of the ZIP archive. * 'stylesheet' - The relative path to the style.css file that contains theme headers, if any. * * The 'readme' key will only be present if the input archive contains a readme.txt file * formatted according to WordPress.org readme standards. Similarly, 'pluginFile' and * 'stylesheet' will only be present if the archive contains a plugin or a theme, respectively. * * @param string $packageFilename The path to the ZIP package. * @param bool $applyMarkdown Whether to transform markup used in readme.txt to HTML. Defaults to false. * @return array Either an associative array or FALSE if the input file is not a valid ZIP archive or doesn't contain a WP plugin or theme. */ public static function parsePackage($packageFilename, $applyMarkdown = false) { if (!file_exists($packageFilename) || !is_readable($packageFilename)) { return false; } //Open the .zip $zip = new ZipArchive(); if ($zip->open($packageFilename) !== true) { return false; } //Find and parse the plugin or theme file and (optionally) readme.txt. $header = null; $readme = null; $pluginFile = null; $stylesheet = null; $type = null; for ($fileIndex = 0; $fileIndex < $zip->numFiles && (empty($readme) || empty($header)); $fileIndex++) { $info = $zip->statIndex($fileIndex); //Normalize filename: convert backslashes to slashes, remove leading slashes. $fileName = trim(str_replace('\\', '/', $info['name']), '/'); $fileName = ltrim($fileName, '/'); $fileNameParts = explode('.', $fileName); $extension = strtolower(end($fileNameParts)); $depth = substr_count($fileName, '/'); //Skip empty files, directories and everything that's more than 1 sub-directory deep. if ($depth > 1 || $info['size'] == 0) { continue; } //readme.txt (for plugins)? if (empty($readme) && strtolower(basename($fileName)) == 'readme.txt') { //Try to parse the readme. $readme = self::parseReadme($zip->getFromIndex($fileIndex), $applyMarkdown); } //Theme stylesheet? if (empty($header) && strtolower(basename($fileName)) == 'style.css') { $fileContents = substr($zip->getFromIndex($fileIndex), 0, 8 * 1024); $header = self::getThemeHeaders($fileContents); if (!empty($header)) { $stylesheet = $fileName; $type = 'theme'; } } //Main plugin file? if (empty($header) && $extension === 'php') { $fileContents = substr($zip->getFromIndex($fileIndex), 0, 8 * 1024); $header = self::getPluginHeaders($fileContents); if (!empty($header)) { $pluginFile = $fileName; $type = 'plugin'; } } } if (empty($type)) { return false; } else { return compact('header', 'readme', 'pluginFile', 'stylesheet', 'type'); } }
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; }
function getZipContentsAsQueryable($zipFilePath) { $zip = new ZipArchive(); $zip->open($zipFilePath); $zipContents = []; for ($i = 0; $i < $zip->numFiles; $i++) { $zipContents[] = $zip->statIndex($i); } return from($zipContents); }
/** * Tim Hodson: renamed functions to avoid collisions. * * Extract plugin headers and readme.txt data from a plugin's ZIP archive. * * Returns an associative array with these keys: * 'headers' - An array of plugin headers. See get_plugin_data() for details. * 'readme' - An array of metadata extracted from readme.txt. See parsePluginReadme() for details. * 'pluginFile' - The name of the PHP file where the plugin headers were found; relative to the root directory of the ZIP archive. * * The 'readme' key will only be present if the input archive contains a readme.txt file * formatted according to WordPress.org readme standards. * * @uses parsePluginReadme() * @uses get_plugin_data() * * @param string $packageFilename The path to the plugin's ZIP package. * @param bool $applyMarkdown Whether to transform markup used in readme.txt to HTML. Defaults to false. * @return array Associative array containing 'headers', 'readme' and 'pluginFile'. Returns FALSE if the input file is not a valid ZIP archive or doesn't contain a WP plugin. */ function pm_analysePluginPackage($packageFilename, $applyMarkdown = false) { if (!file_exists($packageFilename) || !is_readable($packageFilename)) { return false; } //Open the .zip $zip = new ZipArchive(); if ($zip->open($packageFilename) !== true) { return false; } //Find and parse the plugin file and readme.txt $header = null; $readme = null; $pluginFile = null; for ($fileIndex = 0; $fileIndex < $zip->numFiles && (empty($readme) || empty($header)); $fileIndex++) { $info = $zip->statIndex($fileIndex); $fileName = trim(str_replace('\\', '/', $info['name']), '/'); //Backslashes to slashes, kill leading slashes. //readme.txt? if (empty($readme) && strtolower(basename($fileName)) == 'readme.txt') { //Try to parse the readme $readme = pm_parsePluginReadme($zip->getFromIndex($fileIndex), $applyMarkdown); continue; //Skip the rest of the checks. } //Plugin header? if (empty($header)) { //Skip directories and empty files if ($info['size'] == 0) { continue; } //We're only interested in PHP files $extension = end(explode('.', $fileName)); if (strtolower($extension) != 'php') { continue; } //WordPress only looks for plugin files in the top or second level //of the directory tree, so we do the same. if (substr_count($fileName, '/') > 1) { continue; } //Try to read the header. WP only scans the first 8kiB, so we do the same. $fileContents = substr($zip->getFromIndex($fileIndex), 0, 8 * 1024); $header = pm_getPluginHeader($fileContents); if (!empty($header)) { $pluginFile = $fileName; } } } if (empty($pluginFile)) { return false; } else { return compact('header', 'readme', 'pluginFile'); } }
function loadIndexesFromDir($output, $outputIndexes, $dir, $elementName, $mapNodes) { $local_file = basename($_SERVER['PHP_SELF']) == basename(__FILE__); if (is_dir($dir)) { if ($dh = opendir($dir)) { $zip = new ZipArchive(); while (($file = readdir($dh)) !== false) { $filename = $dir . $file; //"./test112.zip"; //print("processing file:" . $filename . "\n"); if ($zip->open($filename, ZIPARCHIVE::CHECKCONS) !== TRUE) { // echo exit("cannot open <$filename>\n"); // print($filename . " cannot open as zip\n"); continue; } $indexName = $file; $description = $zip->getCommentIndex(0); $stat = $zip->statIndex(0); $date = date('d.m.Y', $stat['mtime']); $size = number_format(filesize($filename) / (1024.0 * 1024.0), 1, '.', ''); $zip->close(); if ($local_file) { echo 'Local : ' . $indexName . ' ' . $date . ' ' . $size . '<br>'; } if (isset($mapNodes[$indexName])) { $exdate = DateTime::createFromFormat('d.m.Y', $mapNodes[$indexName]->getAttribute("date")); $localdate = DateTime::createFromFormat('d.m.Y', $date); if ($localdate->getTimestamp() <= $exdate->getTimestamp()) { continue; } $out = $mapNodes[$indexName]; //if($out -> getAttribute("parts")) { $outputIndexes->removeChild($out); $out = $output->createElement($elementName); $outputIndexes->appendChild($out); //} } else { $out = $output->createElement($elementName); $outputIndexes->appendChild($out); } $out->setAttribute("date", $date); $out->setAttribute("local", "true"); $out->setAttribute("size", $size); $out->setAttribute("name", $indexName); $out->setAttribute("description", $description); //$mapNodes[$indexName] = $out; } closedir($dh); } } else { print $dir . " not a directory!\n"; } }
/** * @param string $zipFilePath * * @return array */ protected function getTemplateSnippetIdsFromExportFile($zipFilePath) { $exportedSnippetIds = array(); $exportZip = new \ZipArchive(); $exportZip->open($zipFilePath); for ($i = 0; $i < $exportZip->numFiles; $i++) { $stat = $exportZip->statIndex($i); if (preg_match('/([^\\/]+?)\\/templateSnippet.json/', $stat['name'], $matches)) { $exportedSnippetIds[] = $matches[1]; } } return array_unique($exportedSnippetIds); }
function extractImages() { $ZipArchive = new ZipArchive(); if (true === $ZipArchive->open($this->file)) { for ($i = 0; $i < $ZipArchive->numFiles; $i++) { $zip_element = $ZipArchive->statIndex($i); if (preg_match("([^\\s]+(\\.(?i)(jpg|jpeg|png|gif|bmp))\$)", $zip_element['name'])) { $imagename = explode('/', $zip_element['name']); $imagename = end($imagename); $this->indexes[$imagename] = $i; } } } }
function list_zip_files($fileName, $bBaseNameOnly = false) { $za = new ZipArchive(); $aFiles = array(); $za->open($fileName); for ($i = 0; $i < $za->numFiles; $i++) { $stat = $za->statIndex($i); if ($bBaseNameOnly) { array_push($aFiles, basename($stat['name'])); } else { array_push($aFiles, $stat['name']); } } return $aFiles; }
protected function unzip($file) { $zippedFiles = []; $zip = new \ZipArchive(); $zip->open($file); for ($i = 0; $i < $zip->numFiles; $i++) { $f = $zip->statIndex($i); if (isset($f['name'])) { $zippedFiles[] = $f['name']; } } $zip->close(); sort($zippedFiles); return $zippedFiles; }
public function upload() { if (!$this->BuilderEngine->is_public_version()) { die("Not supported for cloud users"); } $path = $this->do_upload("module_zip"); $zip = new ZipArchive(); if ($zip->open($path) === TRUE) { $stat = $zip->statIndex(0); $folder = basename($stat['name']); $zip->extractTo(APPPATH . '../modules'); $zip->close(); unlink($path); } $this->install($folder); }
/** * Returns a XML Resource filename for the uncompressed contents of the provided zipped $filename * * @param string $filename of zipped XML data * * @throws Exception ZipArchive extension is not loaded or the ZIP file is corrupt * * @return string Full filename and path of extracted XML file */ private static function getZippedFile($filename) { if (!self::zipModuleLoaded()) { throw new Exception('The ZipArchive extension is not loaded. Load the extension or use the flat wurfl.xml file'); } $tmpDir = FileUtils::getTempDir(); $zip = new \ZipArchive(); if ($zip->open($filename) !== true) { throw new Exception('The Zip file <$filename> could not be opened'); } $zippedFile = $zip->statIndex(0); $wurflFile = $zippedFile['name']; $zip->extractTo($tmpDir); $zip->close(); return FileUtils::cleanFilename($tmpDir . DIRECTORY_SEPARATOR . $wurflFile); }
public function zfAction() { if (!extension_loaded('zip')) { return $this->sendError('You need to install the ZIP extension of PHP'); } $console = $this->getServiceLocator()->get('console'); $tmpDir = sys_get_temp_dir(); $request = $this->getRequest(); $version = $request->getParam('version'); $path = rtrim($request->getParam('path'), '/'); if (file_exists($path)) { return $this->sendError("The directory {$path} already exists. You cannot install the ZF2 library here."); } if (empty($version)) { $version = Zf::getLastVersion(); if (false === $version) { return $this->sendError("I cannot connect to the Zend Framework website."); } } else { if (!Zf::checkVersion($version)) { return $this->sendError("The specified ZF version, {$version}, doesn't exist."); } } $tmpFile = ZF::getTmpFileName($tmpDir, $version); if (!file_exists($tmpFile)) { if (!Zf::downloadZip($tmpFile, $version)) { return $this->sendError("I cannot download the ZF2 library from github."); } } $zip = new \ZipArchive(); if ($zip->open($tmpFile)) { $zipFolders = $zip->statIndex(0); $zipFolder = $tmpDir . '/' . rtrim($zipFolders['name'], "/"); if (!$zip->extractTo($tmpDir)) { return $this->sendError("Error during the unzip of {$tmpFile}."); } $result = Utility::copyFiles($zipFolder, $path); if (file_exists($zipFolder)) { Utility::deleteFolder($zipFolder); } $zip->close(); if (false === $result) { return $this->sendError("Error during the copy of the files in {$path}."); } } $console->writeLine("The ZF library {$version} has been installed in {$path}.", Color::GREEN); }
/** * * @param string $file * @return string * @throws Exception */ public function view($file = NULL) { if ($file === NULL) { $file = $this->file; } if (!file_exists($file)) { throw new Exception('File ' . $file . ' not exists'); } $za = new ZipArchive(); $files = ''; $za->open($file); for ($i = 0; $i < $za->numFiles; $i++) { $stat = $za->statIndex($i); $files .= $stat['name'] . "\n"; } return $files; }