1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* ZIP |
5
|
|
|
* |
6
|
|
|
* Archive compressed data. |
7
|
|
|
* |
8
|
|
|
* @package core |
9
|
|
|
* @author [email protected] |
10
|
|
|
* @copyright Caffeina srl - 2015 - http://caffeina.it |
11
|
|
|
*/ |
12
|
|
|
|
13
|
|
|
class ZIP { |
14
|
|
|
use Module; |
15
|
|
|
|
16
|
|
|
public $file, |
17
|
|
|
$name, |
18
|
|
|
$zip; |
19
|
|
|
|
20
|
|
|
public static function create($name=''){ |
21
|
|
|
return new ZIP($name); |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
public function __construct($name=''){ |
25
|
|
|
$this->name = preg_replace('/\.zip$/','',($name?:tempnam(sys_get_temp_dir(), 'ZExp').'-archive')); |
26
|
|
|
$this->file = $this->name . '.zip'; |
27
|
|
|
if (!preg_match('~^/|\./|\.\./~',$this->file)) $this->file = './'.$this->file; |
28
|
|
|
$this->zip = new \ZipArchive; |
29
|
|
|
if ( true !== ($e = $this->zip->open($this->file, |
30
|
|
|
\ZipArchive::CREATE || \ZipArchive::OVERWRITE |
31
|
|
|
))) { |
32
|
|
|
throw new Exception("Error opening temp ZIP file [".($this->file)."] Code $e", 1); |
33
|
|
|
} |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public function __destruct(){ |
37
|
|
|
$this->close(); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
public function path(){ |
41
|
|
|
return $this->file; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
public function write($filename, $data){ |
45
|
|
|
$this->zip->addFromString($filename, $data); |
46
|
|
|
return $this; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
public function close(){ |
50
|
|
|
if($this->zip) @$this->zip->close(); |
51
|
|
|
return $this; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function addDirectory($folder, $root=null) { |
55
|
|
|
$folder = rtrim($folder,'/'); |
56
|
|
|
if (null === $root) { |
57
|
|
|
$root = dirname($folder); |
58
|
|
|
$folder = basename($folder); |
59
|
|
|
} |
60
|
|
|
$this->zip->addEmptyDir($folder); |
61
|
|
|
foreach (glob("$root/$folder/*") as $item) { |
62
|
|
|
if (is_dir($item)) { |
63
|
|
|
$this->addDirectory(str_replace($root,'',$item),$root); |
64
|
|
|
} else if (is_file($item)) { |
65
|
|
|
$this->zip->addFile($item, str_replace($root,'',$item)); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
return $this; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
public function download(){ |
73
|
|
|
@$this->zip->close(); |
74
|
|
|
header('Content-Type: application/zip'); |
75
|
|
|
header('Content-Disposition: attachment;filename="'.$this->name.'"',true); |
76
|
|
|
header('Content-Transfer-Encoding: binary'); |
77
|
|
|
header('Expires: 0'); |
78
|
|
|
header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); |
79
|
|
|
header('Pragma: public'); |
80
|
|
|
header('Content-Length: '.filesize($this->file)); |
81
|
|
|
while(ob_get_level()) ob_end_clean(); |
82
|
|
|
readfile($this->file); |
83
|
|
|
exit; |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
} |
87
|
|
|
|