Unzips a downloaded GeoIP database. Only unzips .gz & .tar.gz files.

@param string $path Path to zipped file.
@param bool $unlink Whether to unlink archive or not.
@throws Exception
491894
public static function unzipDownloadedFile($path, $unlink = false)
    {
        $parts = explode('.', basename($path));
        $filenameStart = $parts[0];

        $dbFilename = $filenameStart . '.dat';
        $tempFilename = $filenameStart . '.dat.new';
        $outputPath = GeoIp::getPathForGeoIpDatabase($tempFilename);

        // extract file
        if (substr($path, -7, 7) == '.tar.gz') {
            // find the .dat file in the tar archive
            $unzip = Unzip::factory('tar.gz', $path);
            $content = $unzip->listContent();

            if (empty($content)) {
                throw new Exception(Piwik::translate('UserCountry_CannotListContent',
                    array("'$path'", $unzip->errorInfo())));
            }

            $datFile = null;
            foreach ($content as $info) {
                $archivedPath = $info['filename'];
                if (basename($archivedPath) === $dbFilename) {
                    $datFile = $archivedPath;
                }
            }

            if ($datFile === null) {
                throw new Exception(Piwik::translate('UserCountry_CannotFindGeoIPDatabaseInArchive',
                    array($dbFilename, "'$path'")));
            }

            // extract JUST the .dat file
            $unzipped = $unzip->extractInString($datFile);

            if (empty($unzipped)) {
                throw new Exception(Piwik::translate('UserCountry_CannotUnzipDatFile',
                    array("'$path'", $unzip->errorInfo())));
            }

            // write unzipped to file
            $fd = fopen($outputPath, 'wb');
            fwrite($fd, $unzipped);
            fclose($fd);
        } else if (substr($path, -3, 3) == '.gz') {
            $unzip = Unzip::factory('gz', $path);
            $success = $unzip->extract($outputPath);

            if ($success !== true) {
                throw new Exception(Piwik::translate('UserCountry_CannotUnzipDatFile',
                    array("'$path'", $unzip->errorInfo())));
            }
        } else {
            $ext = end(explode(basename($path), '.', 2));
            throw new Exception(Piwik::translate('UserCountry_UnsupportedArchiveType', "'$ext'"));
        }

        try {
            // test that the new archive is a valid GeoIP database
            $dbType = GeoIp::getGeoIPDatabaseTypeFromFilename($dbFilename);
            if ($dbType === false) // sanity check
            {
                throw new Exception("Unexpected GeoIP archive file name '$path'.");
            }

            $customDbNames = array(
                'loc' => array(),
                'isp' => array(),
                'org' => array()
            );
            $customDbNames[$dbType] = array($tempFilename);

            $phpProvider = new Php($customDbNames);

            $location = self::getTestLocationCatchPhpErrors($phpProvider);

            if (empty($location)
                || self::$unzipPhpError !== null
            ) {
                if (self::$unzipPhpError !== null) {
                    list($errno, $errstr, $errfile, $errline) = self::$unzipPhpError;
                    Log::info("GeoIPAutoUpdater: Encountered PHP error when testing newly downloaded" .
                        " GeoIP database: %s: %s on line %s of %s.", $errno, $errstr, $errline, $errfile);
                }

                throw new Exception(Piwik::translate('UserCountry_ThisUrlIsNotAValidGeoIPDB'));
            }

            // delete the existing GeoIP database (if any) and rename the downloaded file
            $oldDbFile = GeoIp::getPathForGeoIpDatabase($dbFilename);
            if (file_exists($oldDbFile)) {
                unlink($oldDbFile);
            }

            $tempFile = GeoIp::getPathForGeoIpDatabase($tempFilename);
            if (@rename($tempFile, $oldDbFile) !== true) {
                //In case the $tempfile cannot be renamed, we copy the file.
                copy($tempFile, $oldDbFile);
                unlink($tempFile);
            }

            // delete original archive
            if ($unlink) {
                unlink($path);
            }
        } catch (Exception $ex) {
            // remove downloaded files
            if (file_exists($outputPath)) {
                unlink($outputPath);
            }
            unlink($path);

            throw $ex;
        }
    }
1322698
public function delete($path)
  {
    if (is_link($path)) {
      $this->_deleteSymlink($path);
    } elseif (is_file($path)) {
      unlink($path);
    } else {
      $iteratorRd = new RecursiveDirectoryIterator($path);
      $iteratorRi = new RecursiveIteratorIterator(
        $iteratorRd, RecursiveIteratorIterator::CHILD_FIRST
      );
      foreach ($iteratorRi as $file) {
        /* @var $file \SplFileInfo */
        $filename = $file->getPathname();
        if ($file->isLink()) {
          $this->_deleteSymlink($filename);
        } elseif ($file->isDir()) {
          if (substr($filename, -1, 1) != ".") {
            rmdir($filename);
          }
        } else {
          unlink($filename);
        }
      }
      rmdir($path);
    }
  }
920332
public function unzip($file, $destinationPath)
    {
        if (!class_exists('\ZipArchive')) {
            throw new Error("Class ZipArchive does not installed. Cannot unzip the file.");
        }

        $zip = new \ZipArchive;
        $res = $zip->open($file);

        if ($res === TRUE) {

            $this->getFileManager()->mkdir($destinationPath);

            $zip->extractTo($destinationPath);
            $zip->close();

            return true;
        }

        return false;
    }
47089
public void unzip(final FilePath target) throws IOException, InterruptedException {
        // TODO: post release, re-unite two branches by introducing FileStreamCallable that resolves InputStream
        if (this.channel!=target.channel) {// local -> remote or remote->local
            final RemoteInputStream in = new RemoteInputStream(read(), Flag.GREEDY);
            target.act(new UnzipRemote(in));
        } else {// local -> local or remote->remote
            target.act(new UnzipLocal());
        }
    }
1082693
public void decompress(String path)
		throws IOException
	{
		File bzip2 = new File(path);

		//
		File unarchived = new File(bzip2.getName().replace(".bz2", ""));

		unarchived.createNewFile();

		BufferedInputStream inputStr = new BufferedInputStream(new FileInputStream(bzip2));

		// read bzip2 prefix
		inputStr.read();
		inputStr.read();

		BufferedInputStream buffStr = new BufferedInputStream(inputStr);

		CBZip2InputStream input = new CBZip2InputStream(buffStr);

		FileOutputStream outStr = new FileOutputStream(unarchived);

		while (true) {
			byte[] compressedBytes = new byte[DECOMPRESSION_CACHE];

			int byteRead = input.read(compressedBytes);

			outStr.write(compressedBytes, 0, byteRead);
			if (byteRead != DECOMPRESSION_CACHE) {
				break;
			}
		}

		input.close();
		buffStr.close();
		inputStr.close();
		outStr.close();
	}
1103628
protected function unzipModule(UploadedFile $file)
    {
        $extractPath = false;
        $zip = new ZipArchiver(true);
        if (!$zip->open($file->getRealPath())) {
            throw new \Exception("unable to open zipfile");
        }

        $extractPath = $this->tempdir();

        if ($extractPath !== false) {
            if ($zip->extract($extractPath) === false) {
                $extractPath = false;
            }
        }

        $zip->close();

        return $extractPath;
    }
872892
public function generate($unlinkFlag = true) {
        // Determine which format we are using and call the appropriate method.
        if ($this->getReportType() === self::REPORT_EXCEL) {
            $this->generateExcel();

            // Output headers
            header('Pragma: public');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Content-Type: application/force-download');
            header('Content-Type: application/octet-stream');
            header('Content-Type: application/download');
            header('Content-Disposition: attachment;filename=' . $this->getFilename() . '.xlsx');
            header('Content-Transfer-Encoding: binary ');

            readfile($this->builder->getTempName());
            unlink($this->builder->getTempName());

            exit;
        }

        throw new UnexpectedValueException('Attempted to generate a report in an unsupported format.');
    }
760735
public function unlink($path)
    {
        $realPath = $this->resolvePath(vfsStream::path($path));
        $content  = $this->getContent($realPath);
        if (null === $content || $content->isWritable(vfsStream::getCurrentUser(), vfsStream::getCurrentGroup()) === false) {
            return false;
        }

        if ($content->getType() !== vfsStreamContent::TYPE_FILE) {
            trigger_error('unlink(' . $path . '): Operation not permitted', E_USER_WARNING);
            return false;
        }

        return $this->doUnlink($realPath);
    }
517281
protected function _unlink($path) {
		try {
			$this->dropbox->delete($path);
		} catch (Dropbox_Exception $e) {
			return $this->setError('Dropbox error: '.$e->getMessage());
		}
		$this->deltaCheck();
		return true;
	}
1079772
public static function fileToZip($path)
    {
        if (is_file($path) || is_dir($path)) {
            $zip = new \ZipArchive;
            $zip_file = ROOT . '/private/cache/zip/' . md5(microtime(true));
            if (!is_dir(dirname($zip_file))) {
                mkdir(dirname($zip_file), 0775, true);
            }

            if ($zip->open($zip_file, \ZipArchive::CREATE) === true) {
                if (is_dir($path)) {
                    $iterator = new \DirectoryIterator($path);

                    foreach ($iterator as $file) {
                        if ($file->isFile()) {
                            $bn = $file->getBasename();
                            $zip->addFile($file->getPath() . '/' . $bn, $bn);
                        }
                    }
                } else {
                    $zip->addFile($path, basename($path));
                }

                if ($zip->close()) {
                    self::send($zip_file, str_replace("/", "_", basename($path)) . '.zip');
                    unlink($zip_file);
                }
            } else {
                throw(new \Exception('failed to create zip file'));
            }
        } else {
            throw(new \Exception('No data found!'));
        }
    }
1323335
public function DecryptFile($path, $key)
	{
		if (!file_exists($path))
		{
			throw new GrabzItException("File: " . $path . " does not exist", GrabzItException::FILE_NON_EXISTANT_PATH);
		}
		$data = file_get_contents($path);
		file_put_contents($path, $this->Decrypt($data, $key));
		return true;
	}
288722
public function unzip($file, $path)
    {
        if (ends_with($file, '.zip')) {
            $this->message("Unzipping to {$file}");

            $this->unzipFile($file, $path);
        }
    }
95784
public static function delete($path)
    {
        @set_time_limit(ini_get('max_execution_time'));
    
        // Sanity check
        if (!rtrim($path, '/\\'))
        {
            // Bad programmer! Bad Bad programmer!
            throw new \Exception(__METHOD__ . ': You can not delete a base directory.');
        }
    
        // Check to make sure the path valid and clean
        $path = FileHelper::cleanPath($path);
    
        // Is this really a folder?
        if (!is_dir($path))
        {
            throw new \UnexpectedValueException(sprintf('%1$s: Path is not a folder. Path: %2$s', __METHOD__, $path));
        }
    
        // Remove all the files in folder if they exist; disable all filtering
        $files = FileHelper::files($path, true, true);
    
        if (!empty($files)) {
            File::delete($files);
        }
    
        // Remove sub-folders of folder; disable all filtering
        $folders = FileHelper::dirs($path, false, true);
        
        foreach ($folders as $folder) 
        {
            if (is_link($folder))
            {
                // Don't descend into linked directories, just delete the link.
                File::delete($folder);
            }
            else
            {
                static::delete($folder);
            }
        }
    
        // In case of restricted permissions we zap it one way or the other
        // as long as the owner is either the webserver or the ftp.
        if (@rmdir($path))
        {
            return true;
        }
        else
        {
            throw new \Exception(sprintf('%1$s: Could not delete folder. Path: %2$s', __METHOD__, $path));
        }
    }
912297
protected function setCurrentZip( $fullpath ) {

		$result = $this->zip->open( $fullpath );
		if ( true !== $result ) {
			throw new \Exception( 'Opening epub file failed' );
		}

		/* Safety dance */

		$ok = $this->getZipContent( 'META-INF/container.xml' );
		if ( ! $ok ) {
			throw new \Exception( 'Bad or corrupted META-INF/container.xml' );
		}

	}
554525
public function unlink($path)
    {
        $client = $this->openPath($path);
        $object = $this->bucket->object($this->file);

        try {
            $object->delete();
            return true;
        } catch (ServiceException $e) {
            return false;
        }
    }
1086256
public function writeUncompressedFile($uncompressedFilepath, $filepath)
	{
		$filePointer = fopen($uncompressedFilepath, 'w');
		fwrite($filePointer, gzdecode(file_get_contents($filepath, 9)));
		fclose($filePointer);
	}
493295
public static function recursiveDelete($path) {
		if(is_file($path)) {
			@unlink($path);

		} else {
			$it = new RecursiveIteratorIterator(
				new RecursiveDirectoryIterator($path),
				RecursiveIteratorIterator::CHILD_FIRST
			);

			foreach ($it as $file) {
				if (in_array($file->getBasename(), array('.', '..'))) {
					continue;
				}elseif ($file->isDir()) {
					rmdir($file->getPathname());
				}elseif ($file->isFile() || $file->isLink()) {
					unlink($file->getPathname());
				}
			}
			rmdir($path);
		}

		return false;
	}