PHPzip   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 171
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 171
rs 10
c 0
b 0
f 0
wmc 11
lcom 1
cbo 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A unix2DosTime() 0 15 3
A startfile() 0 19 4
B addfile() 0 64 2
A adddir() 0 23 1
A createfile() 0 8 1
1
<?php
2
/**
3
 * @check     if login
4
 * @method:
5
 * @license   http://www.blags.org/
6
 * @created   :2010年07月24日 15时58分
7
 * @copyright 1997-2010 The Martin Group
8
 * @author    Martin <[email protected]>
9
 * */
10
include "../../../mainfile.php";
11
//验证密码
12
$password = "123465";
13
14
global $xoopsUser;
15
if (!$xoopsUser) {
16
    redirect_header(XOOPS_URL . '/user.php?xoops_redirect=/' . $_SERVER['REQUEST_URI'], 1, '您还没有登录.');
17
}
18
$isAdmin = $xoopsUser->isAdmin();
19
//var_dump($xoopsUser);
20
?>
21
<html>
22
<head>
23
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
24
    <title>ZIP压缩程序</title>
25
    <style type="text/css">
26
        <!--
27
        body, td {
28
            font-size: 14px;
29
            color: #000000;
30
        }
31
32
        a {
33
            color: #000066;
34
            text-decoration: none;
35
        }
36
37
        a:hover {
38
            color: #FF6600;
39
            text-decoration: underline;
40
        }
41
42
        -->
43
    </style>
44
</head>
45
46
<body>
47
<form name="myform" method="post" action="index.php">
48
    <font color="#FF0000">在线压缩ZIP文件程序</font><br>
49
50
    <div style="color:#FF9900">
51
        <p>使用方法:选定要压缩的文件或目录(包含子目录),即可开始压缩。</p>
52
        <p>压缩的结果保留原来的目录结构。</p>
53
    </div>
54
    <?
0 ignored issues
show
Security Best Practice introduced by
It is not recommend to use PHP's short opening tag <?, better use <?php, or <?= in case of outputting.

Short opening tags are disabled in PHP’s default configuration. In such a case, all content of this file is output verbatim to the browser without being parsed, or executed.

As a precaution to avoid these problems better use the long opening tag <?php.

Loading history...
55
    if (!$_REQUEST["myaction"]):
56
        ?>
57
        <table width="100%" border="0" cellspacing="0" cellpadding="0">
58
            <tr>
59
                <td width="11%">验证密码:</td>
60
                <td width="89%"><input name="password" type="password" id="password" size="15"></td>
61
            </tr>
62
            <tr>
63
                <td><input name="myaction" type="hidden" id="myaction" value="dolist"></td>
64
                <td><input type="submit" name="Submit" value=" 进 入 "></td>
65
            </tr>
66
        </table>
67
    <?
68
69
    elseif ($_REQUEST["myaction"] === "dolist"):
70
    if ($_REQUEST['password'] != $password) {
71
        die("输入的密码不正确,请重新输入。");
72
    }
73
    echo "选择要压缩的文件或目录:<br>";
74
    $www_path = '../../../../';
75
    $fdir     = opendir($www_path);
76
    while ($file = readdir($fdir)) {
77
        if ($file === '.' || $file === '..') {
78
            continue;
79
        }
80
        echo "<input name='dfile[]' type='checkbox' value='$www_path$file' " . ($file == basename(__FILE__) ? "" : "checked") . "> ";
81
        if (is_file($file)) {
82
            echo "文件: $file<br>";
83
        } else {
84
            echo "目录: $file<br>";
85
        }
86
    }
87
    ?>
88
    <br>
89
        压缩文件保存到目录:
90
    <input name="todir" type="hidden" id="todir" value="" size="15">
91
        (留空为本目录,必须有写入权限)<br>
92
        压缩文件名称:
93
    <input name="zipname" type="text" id="zipname" value="zip.zip" size="15">
94
        (.zip)<br>
95
    <br>
96
    <input name="password" type="hidden" id="password" value="<?= $_POST['password']; ?>">
97
    <input name="myaction" type="hidden" id="myaction" value="dozip">
98
    <input type='button' value='反选' onclick='selrev();'>
99
    <input type="submit" name="Submit" value=" 开始压缩 ">
100
        <script language='javascript'>
101
            function selrev() {
102
                with (document.myform) {
103
                    for (i = 0; i < elements.length; i++) {
104
                        thiselm = elements[i];
105
                        if (thiselm.name.match(/dfile\[]/))    thiselm.checked = !thiselm.checked;
106
                    }
107
                }
108
            }
109
        </script>
110
        <?
111
112
    elseif ($_REQUEST["myaction"] === "dozip"):
113
114
        //  set_time_limit(0);
115
116
        /**
117
         * Class PHPzip
118
         */
119
        class PHPzip
120
        {
121
122
            var $file_count  = 0;
123
            var $datastr_len = 0;
124
            var $dirstr_len  = 0;
125
            var $filedata    = ''; //该变量只被类外部程序访问
126
            var $gzfilename;
127
            var $fp;
128
            var $dirstr      = '';
129
130
            /*
131
            返回文件的修改时间格式.
132
            只为本类内部函数调用.
133
            */
134
            /**
135
             * @param int $unixtime
136
             * @return int
137
             */
138
            function unix2DosTime($unixtime = 0)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
139
            {
140
                $timearray = ($unixtime == 0) ? getdate() : getdate($unixtime);
141
142
                if ($timearray['year'] < 1980) {
143
                    $timearray['year']    = 1980;
144
                    $timearray['mon']     = 1;
145
                    $timearray['mday']    = 1;
146
                    $timearray['hours']   = 0;
147
                    $timearray['minutes'] = 0;
148
                    $timearray['seconds'] = 0;
149
                }
150
151
                return (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) | ($timearray['mday'] << 16) | ($timearray['hours'] << 11) | ($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1);
152
            }
153
154
            /*
155
            初始化文件,建立文件目录,
156
            并返回文件的写入权限.
157
            */
158
            /**
159
             * @param string $path
160
             * @return bool
161
             */
162
            function startfile($path = 'shenbin.zip')
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
163
            {
164
                $this->gzfilename = $path;
165
                $mypathdir        = array();
166
                do {
167
                    $mypathdir[] = $path = dirname($path);
168
                } while ($path !== '.');
169
                @end($mypathdir);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
170
                do {
171
                    $path = @current($mypathdir);
172
                    @mkdir($path);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
173
                } while (@prev($mypathdir));
174
175
                if ($this->fp = @fopen($this->gzfilename, "w")) {
176
                    return true;
177
                }
178
179
                return false;
180
            }
181
182
            /*
183
            添加一个文件到 zip 压缩包中.
184
            */
185
            /**
186
             * @param $data
187
             * @param $name
188
             */
189
            function addfile($data, $name)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
190
            {
191
                $name = str_replace('\\', '/', $name);
192
193
                if (strrchr($name, '/') === '/') {
194
                    return $this->adddir($name);
195
                }
196
197
                $dtime    = dechex($this->unix2DosTime());
198
                $hexdtime = '\x' . $dtime[6] . $dtime[7] . '\x' . $dtime[4] . $dtime[5] . '\x' . $dtime[2] . $dtime[3] . '\x' . $dtime[0] . $dtime[1];
199
                eval('$hexdtime = "' . $hexdtime . '";');
200
201
                $unc_len = strlen($data);
202
                $crc     = crc32($data);
203
                $zdata   = gzcompress($data);
204
                $c_len   = strlen($zdata);
205
                $zdata   = substr(substr($zdata, 0, strlen($zdata) - 4), 2);
206
207
                //新添文件内容格式化:
208
                $datastr = "\x50\x4b\x03\x04";
209
                $datastr .= "\x14\x00";            // ver needed to extract
210
                $datastr .= "\x00\x00";            // gen purpose bit flag
211
                $datastr .= "\x08\x00";            // compression method
212
                $datastr .= $hexdtime;             // last mod time and date
213
                $datastr .= pack('V', $crc);             // crc32
214
                $datastr .= pack('V', $c_len);           // compressed filesize
215
                $datastr .= pack('V', $unc_len);         // uncompressed filesize
216
                $datastr .= pack('v', strlen($name));    // length of filename
217
                $datastr .= pack('v', 0);                // extra field length
218
                $datastr .= $name;
219
                $datastr .= $zdata;
220
                $datastr .= pack('V', $crc);                 // crc32
221
                $datastr .= pack('V', $c_len);               // compressed filesize
222
                $datastr .= pack('V', $unc_len);             // uncompressed filesize
223
224
                fwrite($this->fp, $datastr);    //写入新的文件内容
225
                $my_datastr_len = strlen($datastr);
226
                unset($datastr);
227
228
                //新添文件目录信息
229
                $dirstr = "\x50\x4b\x01\x02";
230
                $dirstr .= "\x00\x00";                    // version made by
231
                $dirstr .= "\x14\x00";                    // version needed to extract
232
                $dirstr .= "\x00\x00";                    // gen purpose bit flag
233
                $dirstr .= "\x08\x00";                    // compression method
234
                $dirstr .= $hexdtime;                    // last mod time & date
235
                $dirstr .= pack('V', $crc);            // crc32
236
                $dirstr .= pack('V', $c_len);            // compressed filesize
237
                $dirstr .= pack('V', $unc_len);        // uncompressed filesize
238
                $dirstr .= pack('v', strlen($name));    // length of filename
239
                $dirstr .= pack('v', 0);                // extra field length
240
                $dirstr .= pack('v', 0);                // file comment length
241
                $dirstr .= pack('v', 0);                // disk number start
242
                $dirstr .= pack('v', 0);                // internal file attributes
243
                $dirstr .= pack('V', 32);                // external file attributes - 'archive' bit set
244
                $dirstr .= pack('V', $this->datastr_len); // relative offset of local header
245
                $dirstr .= $name;
246
247
                $this->dirstr .= $dirstr;    //目录信息
248
249
                $this->file_count++;
250
                $this->dirstr_len += strlen($dirstr);
251
                $this->datastr_len += $my_datastr_len;
252
            }
253
254
            /**
255
             * @param $name
256
             */
257
            function adddir($name)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
258
            {
259
                $name    = str_replace("\\", "/", $name);
260
                $datastr = "\x50\x4b\x03\x04\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00";
261
262
                $datastr .= pack("V", 0) . pack("V", 0) . pack("V", 0) . pack("v", strlen($name));
263
                $datastr .= pack("v", 0) . $name . pack("V", 0) . pack("V", 0) . pack("V", 0);
264
265
                fwrite($this->fp, $datastr);    //写入新的文件内容
266
                $my_datastr_len = strlen($datastr);
267
                unset($datastr);
268
269
                $dirstr = "\x50\x4b\x01\x02\x00\x00\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00";
270
                $dirstr .= pack("V", 0) . pack("V", 0) . pack("V", 0) . pack("v", strlen($name));
271
                $dirstr .= pack("v", 0) . pack("v", 0) . pack("v", 0) . pack("v", 0);
272
                $dirstr .= pack("V", 16) . pack("V", $this->datastr_len) . $name;
273
274
                $this->dirstr .= $dirstr;    //目录信息
275
276
                $this->file_count++;
277
                $this->dirstr_len += strlen($dirstr);
278
                $this->datastr_len += $my_datastr_len;
279
            }
280
281
            function createfile()
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
282
            {
283
                //压缩包结束信息,包括文件总数,目录信息读取指针位置等信息
284
                $endstr = "\x50\x4b\x05\x06\x00\x00\x00\x00" . pack('v', $this->file_count) . pack('v', $this->file_count) . pack('V', $this->dirstr_len) . pack('V', $this->datastr_len) . "\x00\x00";
285
286
                fwrite($this->fp, $this->dirstr . $endstr);
287
                fclose($this->fp);
288
            }
289
        }
290
291
        if (!trim($_REQUEST[zipname])) {
292
            $_REQUEST[zipname] = "shenbin.zip";
293
        } else {
294
            $_REQUEST[zipname] = trim($_REQUEST[zipname]);
295
        }
296
        if (!strrchr(strtolower($_REQUEST[zipname]), '.') === '.zip') {
297
            $_REQUEST[zipname] .= ".zip";
298
        }
299
        $_REQUEST[todir] = str_replace('\\', '/', trim($_REQUEST[todir]));
300
        if (!strrchr(strtolower($_REQUEST[todir]), '/') === '/') {
301
            $_REQUEST[todir] .= "/";
302
        }
303
        if ($_REQUEST[todir] === "/") {
304
            $_REQUEST[todir] = "./";
305
        }
306
307
        /**
308
         * @param string $dir
309
         * @return int
310
         */
311
        function listfiles($dir = ".")
312
        {
313
            global $faisunZIP;
314
            $sub_file_num = 0;
315
316
            if (is_file("$dir")) {
317
                if (realpath($faisunZIP->gzfilename) != realpath("$dir")) {
318
                    $faisunZIP->addfile(implode('', file("$dir")), "$dir");
319
320
                    return 1;
321
                }
322
323
                return 0;
324
            }
325
326
            $handle = opendir("$dir");
327
            while ($file = readdir($handle)) {
328
                if ($file === "." || $file === "..") {
329
                    continue;
330
                }
331
                if (is_dir("$dir/$file")) {
332
                    $sub_file_num += listfiles("$dir/$file");
333
                } else {
334
                    if (realpath($faisunZIP->gzfilename) != realpath("$dir/$file")) {
335
                        $faisunZIP->addfile(implode('', file("$dir/$file")), "$dir/$file");
336
                        $sub_file_num++;
337
                    }
338
                }
339
            }
340
            closedir($handle);
341
            if (!$sub_file_num) {
342
                $faisunZIP->addfile("", "$dir/");
343
            }
344
345
            return $sub_file_num;
346
        }
347
348
        /**
349
         * @param $num
350
         * @return string
351
         */
352
        function num_bitunit($num)
353
        {
354
            $bitunit = array(' B', ' KB', ' MB', ' GB');
355
            for ($key = 0; $key < count($bitunit); $key++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
356
                if ($num >= pow(2, 10 * $key) - 1) { //1023B 会显示为 1KB
357
                    $num_bitunit_str = (ceil($num / pow(2, 10 * $key) * 100) / 100) . " $bitunit[$key]";
358
                }
359
            }
360
361
            return $num_bitunit_str;
0 ignored issues
show
Bug introduced by
The variable $num_bitunit_str does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
362
        }
363
364
        if (is_array($_REQUEST[dfile])) {
365
            $faisunZIP = new PHPzip;
366
            if ($faisunZIP->startfile("$_REQUEST[todir]$_REQUEST[zipname]")) {
367
                echo "正在添加压缩文件...<br><br>";
368
                $filenum = 0;
369
                foreach ($_REQUEST[dfile] as $file) {
0 ignored issues
show
Bug introduced by
The expression $_REQUEST[dfile] of type string is not traversable.
Loading history...
370
                    if (is_file($file)) {
371
                        echo "文件: $file<br>";
372
                    } else {
373
                        echo "目录: $file<br>";
374
                    }
375
                    $filenum += listfiles($file);
376
                }
377
                $faisunZIP->createfile();
378
                echo "<br>压缩完成,共添加 $filenum 个文件.<br><a href='$_REQUEST[todir]$_REQUEST[zipname]'>$_REQUEST[todir]$_REQUEST[zipname] (" . num_bitunit(filesize("$_REQUEST[todir]$_REQUEST[zipname]")) . ")</a>";
379
            } else {
380
                echo "$_REQUEST[todir]$_REQUEST[zipname] 不能写入,请检查路径或权限是否正确.<br>";
381
            }
382
        } else {
383
            echo "没有选择的文件或目录.<br>";
384
        }
385
        chmod($file, 0777);
386
387
    endif;
388
389
    ?>
390
</form>
391
</body>
392
</html>
393