/** * 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); }
/** * 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; } }
function getToC($archive) { $toc = array(); if (endsWith($archive, ".cbz")) { $zip = new ZipArchive(); if ($zip->open($archive)) { for ($i = 0; $i < $zip->numFiles; $i++) { if (endsWith($zip->getNameIndex($i), '.jpg') || endsWith($zip->getNameIndex($i), '.gif') || endsWith($zip->getNameIndex($i), '.png')) { $toc[] = $zip->getNameIndex($i); } } natcasesort($toc); $toc = array_values($toc); $zip->close(); } } else { if (endsWith($archive, ".cbr")) { $rar = RarArchive::open($archive); if ($rar !== false) { $rar_entries = $rar->getEntries(); for ($i = 0; $i < count($rar_entries); $i++) { if (endsWith($rar_entries[$i]->getName(), '.jpg') || endsWith($rar_entries[$i]->getName(), '.gif') || endsWith($rar_entries[$i]->getName(), '.png')) { $toc[] = $rar_entries[$i]->getName(); } } natcasesort($toc); $toc = array_values($toc); $rar->close(); } } } return $toc; }
function test_forProjectJson() { $req = $this->requester; $result = $req->request("Data.Download.project", ['robertblackwell', 'project1', ['format' => 'json', 'template' => ['zip' => "{organization_name}_{project_name}", 'file' => 'strings.{format}', 'dir' => "{format}/{language_code}"]]]); // print_r($result); $this->assertGoodResponse($result, 200); $arr = $this->extractApiResult($result); $url = $arr['url']; /* * @TODO - fix */ $zipFileName = __DIR__ . "/temp-json.gzip"; $this->requester->getFile($url, $zipFileName); $this->assertTrue(file_exists($zipFileName)); $zip = new \ZipArchive(); if (!file_exists($zipFileName)) { print "gzip file does not exist\n"; } $res = $zip->open($zipFileName); $dir_name = $zip->getNameIndex(0); $archive_name = basename($url) . "-dir/"; $archive_name = basename($url) . "/"; print "\n archive_name {$archive_name}\n"; print "\n index 1 " . $zip->getNameIndex(1) . "\n"; // $this->assertTrue($dir_name === "robertblackwell_project1"); }
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; } }
/** * {@inheritdoc} */ public function listContents() { $files = array(); for ($i = 0; $i < $this->zip->numFiles; $i++) { $files[] = $this->zip->getNameIndex($i); } return $files; }
/** * Add method * * @return void Redirects on successful add, renders view otherwise. */ public function add() { if ($this->request->is('post')) { $mc = 0; $mc1 = 0; switch ($this->request->data('Archive')['type']) { case "application/x-rar": break; case "application/octet-stream": case "application/x-zip": case "application/x-zip-compressed": case "application/zip": $zip = new \ZipArchive(); $zip->open($this->request->data('Archive')['tmp_name']); for ($i = 0; $i < $zip->numFiles; $i++) { $filepath = pathinfo($zip->getNameIndex($i)); if (isset($filepath['extension']) && $filepath['extension'] == 'dm' && $filepath['dirname'] == '.') { $mod = $this->Mods->newEntity(); $mod = $this->Mods->patchEntity($mod, $this->request->data); $mod->dmname = $filepath['basename']; if (!file_exists('tmp/mods/')) { mkdir('tmp/mods/', 0777, true); } $zip->extractTo(WWW_ROOT . 'tmp/mods/', $zip->getNameIndex($i)); $fd = fopen(WWW_ROOT . 'tmp/mods/' . $zip->getNameIndex($i), 'r'); $hash = crc32(fread($fd, 99999999)); $mod->crc32 = $hash; $clash = $this->Mods->find('all')->where(['crc32' => $hash])->first(); if ($clash) { $mc1++; } else { fclose($fd); if ($this->Mods->save($mod)) { $mc++; } else { } } } } $zip->close(); break; case "7z": break; } $this->Flash->success(__($mc . ' mods found and saved.' . ($mc1 == 0 ? "" : ' ' . $mc1 . " mods had already been uploaded"))); return $this->redirect(['action' => 'index']); } $mod = $this->Mods->newEntity(); $this->set(compact('mod')); $this->set('_serialize', ['mod']); }
public function beforeSave($event, $entity, $options) { if ($entity->get('Archive')['tmp_name'] != '') { switch ($entity->get('Archive')['type']) { case "application/x-rar": break; case "application/zip": case "application/octet-stream": case "application/x-zip-compressed": case "application/x-zip": $zip = new \ZipArchive(); $zip->open($entity->get('Archive')['tmp_name']); for ($i = 0; $i < $zip->numFiles; $i++) { $filepath = pathinfo($zip->getNameIndex($i)); if ($filepath['basename'] == $entity->get('dmname')) { $fd = fopen(WWW_ROOT . 'tmp/mods/' . $zip->getNameIndex($i), 'r'); if ($fd) { rewind($fd); while (($line = fgets($fd)) !== false) { if (strpos($line, '#disableoldnations') !== false) { $entity->set('disableoldnations', 1); } $arr = explode(' ', $line); switch ($arr[0]) { case '--': break; case '#version': $entity->set('version', trim(substr($line, strlen('#version ')))); break; case '#description': $entity->set('description', trim(str_replace('"', '', substr($line, strlen('#description '))))); break; case '#modname': $entity->set('name', trim(str_replace('"', '', substr($line, strlen('#modname '))))); break; case '#icon': $entity->set('icon', trim(str_Replace('"', '', substr($line, strlen('#icon '))))); break; } } fclose($fd); } $zip->close(); return true; } } break; } return true; } }
/** * @inheritDoc */ public function getFiles($only_root = false) { $files = array(); $zip = new \ZipArchive(); if ($zip->open($this->file)) { $num_files = $zip->numFiles; $counter = 0; for ($i = 0; $i < $num_files; $i++) { $file = $zip->getNameIndex($i); $parent_directories = $this->getParentDirStack($file); if ($only_root) { if (empty($parent_directories)) { $files[$file] = $counter++; } else { $files[end($parent_directories)] = $counter++; } } else { $files[$file] = $counter++; foreach ($parent_directories as $parent_dir_path) { $files[$parent_dir_path] = $counter++; } } } $files = array_flip($files); $zip->close(); } $zip = null; sort($files); return $files; }
public function postInstall() { User::onlyHas("modules-view"); if (isset($_FILES['module'])) { $zip = new ZipArchive(); $result = $zip->open($_FILES['module']['tmp_name']); if ($result) { // get install, frontent and backend files $files = array(); for ($i = 0; $i < $zip->numFiles; $i++) { $files[] = $zip->getNameIndex($i); } if (!in_array('install.php', $files)) { echo "INSTALL.PHP is required"; return; } // extract files $zip->extractTo($_SERVER['DOCUMENT_ROOT'] . "/tmp/zip/"); //rename($_SERVER['DOCUMENT_ROOT'] . "/tmp/zip/backend/", $_SERVER['DOCUMENT_ROOT'] . "/apps/backend/modules/"); //rename($_SERVER['DOCUMENT_ROOT'] . "/tmp/zip/frontend/", $_SERVER['DOCUMENT_ROOT'] . "/apps/frontend/modules/"); require_once $_SERVER['DOCUMENT_ROOT'] . '/tmp/zip/install.php'; array_map('unlink', glob($_SERVER['DOCUMENT_ROOT'] . "/tmp/zip/*")); $zip->close(); } else { } } Redirect::to('module'); $this->layout = null; }
public function setUploadFile($ulFileName = "") { if ($ulFileName) { //URL to existing file if (file_exists($ulFileName)) { $pos = strrpos($ulFileName, "/"); if (!$pos) { $pos = strrpos($ulFileName, "\\"); } $this->uploadFileName = substr($ulFileName, $pos + 1); //$this->outputMsg($this->uploadFileName; copy($ulFileName, $this->uploadTargetPath . $this->uploadFileName); } } elseif (array_key_exists('uploadfile', $_FILES)) { $this->uploadFileName = $_FILES['uploadfile']['name']; move_uploaded_file($_FILES['uploadfile']['tmp_name'], $this->uploadTargetPath . $this->uploadFileName); } if (file_exists($this->uploadTargetPath . $this->uploadFileName) && substr($this->uploadFileName, -4) == ".zip") { $zip = new ZipArchive(); $zip->open($this->uploadTargetPath . $this->uploadFileName); $zipFile = $this->uploadTargetPath . $this->uploadFileName; $this->uploadFileName = $zip->getNameIndex(0); $zip->extractTo($this->uploadTargetPath); $zip->close(); unlink($zipFile); } }
/** * Retrieve plugin info from meta.json in zip * @param $zipPath * @return bool|mixed * @throws CakeException */ public function getPluginMeta($zipPath) { $Zip = new \ZipArchive(); if ($Zip->open($zipPath) === true) { $search = 'config/meta.json'; $indexJson = $Zip->locateName('meta.json', \ZipArchive::FL_NODIR); if ($indexJson === false) { throw new Exception(__d('spider', 'Invalid meta information in archive')); } else { $fileName = $Zip->getNameIndex($indexJson); $fileJson = json_decode($Zip->getFromIndex($indexJson)); if (empty($fileJson->name)) { throw new Exception(__d('spider', 'Invalid meta.json or missing plugin name')); } else { $pluginRootPath = str_replace($search, '', $fileName); $fileJson->rootPath = $pluginRootPath; } } $Zip->close(); if (!isset($fileJson) || empty($fileJson)) { throw new Exception(__d('spider', 'Invali meta.json')); } return $fileJson; } else { throw new CakeException(__d('spider', 'Invalid zip archive')); } return false; }
public function extractTo($extractPath, $files = null) { $fs = new FileSystem(); $ds = DIRECTORY_SEPARATOR; for ($i = 0; $i < $this->numFiles; $i++) { $oldName = parent::getNameIndex($i); $newName = mb_convert_encoding($this->getNameIndex($i), 'ISO-8859-1', 'CP850,UTF-8'); //we cheat a little because we can't tell wich name the extracted part should have //so we put it a directory wich share it's name $tmpDir = $extractPath . $ds . '__claro_zip_hack_' . $oldName; parent::extractTo($tmpDir, parent::getNameIndex($i)); //now we move the content of the directory and we put the good name on it. foreach ($iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($tmpDir, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST) as $item) { if ($item->isFile()) { $fs->mkdir(dirname($extractPath . $ds . $oldName)); $fs->rename($item->getPathname(), $extractPath . $ds . $oldName); } } } //we remove our 'trash here' $iterator = new \DirectoryIterator($extractPath); foreach ($iterator as $item) { if (strpos($item->getFilename(), '_claro_zip_hack')) { $fs->rmdir($item->getRealPath(), true); } } }
/** * Sets the hash that is used to uniquely identify this plugin */ public function setHash() { $archiveName = $this->getFilenameOnFilestore(); $zip = new ZipArchive(); $result = $zip->open($archiveName); if ($result !== true) { return false; } for ($i = 0; $i < $zip->numFiles; $i++) { $filename = $zip->getNameIndex($i); if (stripos($filename, 'manifest.xml') !== false) { $manifest = $zip->getFromIndex($i); $id = substr($filename, 0, strpos($filename, '/')); break; } } $zip->close(); if (!isset($manifest)) { return false; } try { $manifest = new ElggPluginManifest($manifest); $author = $manifest->getAuthor(); $version = $manifest->getVersion(); $this->hash = md5($id . $version . $author); } catch (Exception $e) { // skip invalid manifests } }
/** * Expand archive * * @param bool $cleanup Whether or not to clean up after expansion (i.e. removing known OS files, etc...) * @return bool */ public function expand($cleanup = true) { // Create local tmp copy of the archive that's being expanded $temp = Manager::getTempPath($this->getName()); $this->copy($temp); $zip = new \ZipArchive(); // Open the temp archive (we use the absolute path because we're on the local filesystem) if ($zip->open($temp->getAbsolutePath()) === true) { // We don't actually have to extract the archive, we can just read out of it and copy over to the original location for ($i = 0; $i < $zip->numFiles; $i++) { $filename = $zip->getNameIndex($i); $entity = Entity::fromPath($this->getParent() . '/' . $filename, $this->getAdapter()); if ($entity->isFile()) { // Open $item = fopen('zip://' . $temp->getAbsolutePath() . '#' . $filename, 'r'); // Write stream $entity->putStream($item); // Close fclose($item); } else { // Create the directory $entity->create(); } } // Clean up $zip->close(); $temp->delete(); return parent::expand($cleanup); } return false; }
/** * Validate the object. * @return boolean */ public function isValid() { # File exists if (!file_exists($this->zippedContent->getFilename())) { return false; } # Can open zip file $zip = new \ZipArchive(); if ($zip->open($this->zippedContent->getFilename()) !== true) { return false; } # Check if an XML and XSD file are present $xmlFile = false; $xsdFile = false; for ($i = 0; $i < $zip->numFiles; $i++) { $filename = $zip->getNameIndex($i); $file = new File($filename); $extension = strtolower($file->getExtension()); if ($extension === 'xml') { $xmlFile = true; } elseif ($extension === 'xsd') { $xsdFile = true; } } $zip->close(); return $xmlFile && $xsdFile; }
public function parse($ipaFile, $infoFile = self::INFO_PLIST) { $zipObj = new ZipArchive(); if ($zipObj->open($ipaFile) !== true) { throw new PListException("unable to open {$ipaFile} file!"); } //scan plist file $plistFile = null; for ($i = 0; $i < $zipObj->numFiles; $i++) { $name = $zipObj->getNameIndex($i); if (preg_match('/Payload\\/(.+)?\\.app\\/' . preg_quote($infoFile) . '$/i', $name)) { $plistFile = $name; break; } } //parse plist file if (!$plistFile) { throw new PListException("unable to parse plist file!"); } //deal in memory $plistHandle = fopen('php://memory', 'wb'); fwrite($plistHandle, $zipObj->getFromName($plistFile)); rewind($plistHandle); $zipObj->close(); $plist = new CFPropertyList($plistHandle, CFPropertyList::FORMAT_AUTO); $this->plistContent = $plist->toArray(); return true; }
function process(&$error = null) { $file = $this->file; $name = $this->title; $zip = new ZipArchive(); $res = $zip->open($file); if (!$res) { $error = __d('newsletter', 'Cant read archive', true); return false; } $newsletterFileName = strtolower(Inflector::slug($name)); ///////// create needed folder ///////// if (!file_exists(WWW_ROOT . 'img' . DS . 'newsletter' . DS . $newsletterFileName)) { if (!mkdir(WWW_ROOT . 'img' . DS . 'newsletter' . DS . $newsletterFileName, 0777)) { $error = __d('newsletter', 'Cant create img folder', true); return false; } } ///////// map files ///////// $contentFileFilter = array('/^html.html$/', '/^(?:[^\\/]*\\/)?html.html$/', '/^(?:[^\\/]*\\/)?index.html$/'); $imageFilter = '/^(?:[^\\/]*\\/)?(img|images)\\/.*\\.(jpg|gif|png)$/'; $images = array(); for ($i = 0; $i < $zip->numFiles; $i++) { $filename = $zip->getNameIndex($i); if (preg_match($imageFilter, $filename)) { $images[] = $filename; } foreach ($contentFileFilter as $priority => $filter) { if (preg_match($filter, $filename)) { if (empty($contentFile) || $contentFilePriority >= $priority) { $contentFile = $filename; $contentFilePriority = $priority; } } } } ///////// extract and format content ///////// if (empty($contentFile)) { $error = __d('newsletter', 'Cant find main html file', true); return false; } $content = $zip->getFromName($contentFile); if (empty($content)) { $error = __d('newsletter', 'Cant read main html file', true); return false; } $content = $this->formatContent($content, $newsletterFileName); file_put_contents(APP . 'views' . DS . 'elements' . DS . 'newsletter' . DS . $newsletterFileName . '.ctp', $content); ///////// create config file ///////// $pluginPath = App::pluginPath('Newsletter'); ob_start(); include $pluginPath . 'vendors' . DS . 'config_template.php'; $configFile = ob_get_clean(); file_put_contents(APP . 'config' . DS . 'plugins' . DS . 'newsletter' . DS . $newsletterFileName . '.php', $configFile); ///////// extract images ///////// $this->zipExtractToFlat($zip, WWW_ROOT . 'img' . DS . 'newsletter' . DS . $newsletterFileName, $images); $zip->close(); return true; }
/** * Returns either the name if an id is given or the id if a name is given. * @param $mixed * @param int $options * @return int index , name or FALSE @params mixed, mixed (FL_NODIR, FL_NOCASE) */ function find($mixed, $options = 0) { if (is_string($mixed)) { return $this->zip->locatename($mixed, $options); } else { return $this->zip->getNameIndex($mixed); } }
protected function execute(InputInterface $input, OutputInterface $output) { $this->voterService->setConnectionName($input->getArgument('dbname')); if ($input->getOption('config')) { $this->voterService->setConfigFolder($input->getOption('config')); } else { $this->voterService->setConfigFolder('/usr/local/etc/votertools'); } $this->voterService->setAttributes([\PDO::MYSQL_ATTR_LOCAL_INFILE => true]); $filePath = $input->getArgument('fileName'); if ($input->getOption('tmp')) { $tempfile = \tempnam($input->getOption('tmp'), ''); } else { $tempfile = \tempnam(\sys_get_temp_dir(), ''); } $output->writeln("Creating temp file to store unzipped voter file: " . $tempfile); $op = \fopen($tempfile, 'a'); $zip = new \ZipArchive(); $info = []; $voterDate = ''; if ($zip->open($filePath) === TRUE) { for ($i = 0; $i < $zip->numFiles; $i++) { if (empty($voterDate)) { $info = $zip->statIndex($i); $voterDate = date("Ymd", $info["mtime"]); $output->writeln("Import Date: " . date("Ymd", $info["mtime"])); } $output->writeln("Reading Voter File: " . $zip->getNameIndex($i)); $fp = $zip->getStream($zip->getNameIndex($i)); while (!feof($fp)) { \fwrite($op, fread($fp, 2)); } } $output->writeln("Extraced to " . $tempfile); $zip->close(); fclose($op); chmod($tempfile, 0644); $output->writeln("Importing " . $tempfile . " for " . $voterDate); $this->voterService->loadRawData($voterDate, $tempfile, "florida/VoterLoadImport"); $output->writeln("Cleaned up " . $tempfile); $output->writeln("Starting append of Party Affiliation to PartyHistories table "); $this->voterService->appendFloridaPartyHistories(); $output->writeln("Completed append of Party Affiliation to PartyHistories table "); } }
public function testSimpleZipContainsOneFile() { $filename = PHING_TEST_BASE . "/etc/tasks/ext/tmp/simple-test.zip"; $this->executeTarget(__FUNCTION__); $this->assertFileExists($filename); $archive = new ZipArchive(); $archive->open($filename); $this->assertEquals('test.txt', $archive->getNameIndex(0)); }
/** * List archive content * @param PhingFile Zip file to list content * @return array List of files inside $zipfile */ protected function listArchiveContent(PhingFile $zipfile) { $zip = new ZipArchive(); $zip->open($zipfile->getAbsolutePath()); $content = array(); for ($i = 0; $i < $zip->numFiles; $i++) { $content[] = array('filename' => $zip->getNameIndex($i)); } return $content; }
/** * Unpack file. * * @param string $source * @param string $destination * * @return string */ public function unpack($source, $destination) { $zip = new \ZipArchive(); $zip->open($source); $filename = $zip->getNameIndex(0); $zip->extractTo(dirname($destination), $filename); rename(dirname($destination) . '/' . $filename, $destination); $zip->close(); return $destination; }
function unpack_player_archive($player_package) { if (!class_exists("ZipArchive")) { return zip_fallback($player_package); } $zip = new ZipArchive(); if ($zip->open($player_package)) { $contents = ""; $dir = $zip->getNameIndex(0); $fp = $zip->getStream($dir . "player.swf"); if (!$fp) { return READ_ERROR; } while (!feof($fp)) { $contents .= fread($fp, 2); } fclose($fp); $result = @file_put_contents(LongTailFramework::getPrimaryPlayerPath(), $contents); if (!$result) { return WRITE_ERROR; } chmod(LongTailFramework::getPrimaryPlayerPath(), 0777); $contents = ""; $fp = $zip->getStream($dir . "yt.swf"); if (!$fp) { return READ_ERROR; } while (!feof($fp)) { $contents .= fread($fp, 2); } fclose($fp); $result = @file_put_contents(str_replace("player.swf", "yt.swf", LongTailFramework::getPrimaryPlayerPath()), $contents); if (!$result) { return WRITE_ERROR; } chmod(str_replace("player.swf", "yt.swf", LongTailFramework::getPrimaryPlayerPath()), 0777); $fp = $zip->getStream($dir . "jwplayer.js"); if ($fp) { $contents = ""; while (!feof($fp)) { $contents .= fread($fp, 2); } fclose($fp); $result = @file_put_contents(LongTailFramework::getEmbedderPath(), $contents); if (!$result) { return WRITE_ERROR; } chmod(LongTailFramework::getEmbedderPath(), 0777); } $zip->close(); } unlink($player_package); return SUCCESS; }
/** * @return string|null */ public function getDirname() { if ($this->_dirname === null) { $firstEntry = $this->_zip->getNameIndex(0); $isDir = substr($firstEntry, -1) == DIRECTORY_SEPARATOR; if ($isDir) { $this->_dirname = str_replace(DIRECTORY_SEPARATOR, '', $firstEntry); } } return $this->_dirname; }
private function assertZipContains(array $contents, $file) { $zip = new \ZipArchive(); $zip->open($file); $actual = array(); for ($i = 0; $i < $zip->numFiles; $i++) { $actual[$zip->getNameIndex($i)] = $zip->getFromIndex($i); } $zip->close(); $this->assertEquals($contents, $actual); }
function getExtractDir($inFile, $inPackageName) { $fullPath = str_replace(".", "/", $inPackageName) . "/"; $zip = new ZipArchive(); if ($zip->open($inFile)) { // checking the last file is ad hoc and may not work $a = $zip->getNameIndex($zip->numFiles - 1); $folder = getPrefixPath($fullPath, $a); $zip->close(); return $folder; } }
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; }
/** * @param $filePath * @param \ZipArchive $zip * @return string */ private function searchFileInZip($filePath, \ZipArchive $zip) { $filePath = preg_quote($filePath); $pattern = "#(?P<namespace>Backend|Core|Frontend)/(?P<name>.*)/(?P<file>{$filePath})#i"; for ($i = 0; $i < $zip->numFiles; $i++) { $filename = $zip->getNameIndex($i); if (preg_match($pattern, $filename)) { return $filename; } } throw new \RuntimeException(sprintf("File %s not found in zip", $filePath)); }
/** * @covers XLSXWriter::writeToFile */ public function testWriteToFile() { $filename = tempnam("/tmp", "xlsx_writer"); $header = array('0' => 'string', '1' => 'string', '2' => 'string', '3' => 'string'); $sheet = array(array('55', '66', '77', '88'), array('10', '11', '12', '13')); $xlsx_writer = new XLSXWriter(); $xlsx_writer->writeSheet($sheet, 'mysheet', $header); $xlsx_writer->writeToFile($filename); $zip = new ZipArchive(); $r = $zip->open($filename); $this->assertTrue($r); $r = $zip->numFiles > 0 ? true : false; $this->assertTrue($r); $out_sheet = array(); for ($z = 0; $z < $zip->numFiles; $z++) { $inside_zip_filename = $zip->getNameIndex($z); if (preg_match("/sheet(\\d+).xml/", basename($inside_zip_filename))) { $out_sheet = $this->stripCellsFromSheetXML($zip->getFromName($inside_zip_filename)); array_shift($out_sheet); $out_sheet = array_values($out_sheet); } } $zip->close(); @unlink($filename); $r1 = self::array_diff_assoc_recursive($out_sheet, $sheet); $r2 = self::array_diff_assoc_recursive($sheet, $out_sheet); $this->assertEmpty($r1); $this->assertEmpty($r2); }