-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathqetag.php
118 lines (96 loc) · 2.78 KB
/
qetag.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<?php
/**
* 最新版本 在 https://github.com/qiniu/php-sdk/blob/master/src/Qiniu/Etag.php
*/
define('BLOCK_BITS', 22);
define('BLOCK_SIZE', 1 << BLOCK_BITS);
error_reporting(E_ERROR | E_WARNING | E_PARSE);
function PackArray($v, $a) {
return call_user_func_array('pack', array_merge(array($v),(array)$a));
}
function BlockCount($fsize) {
return (($fsize + (BLOCK_SIZE - 1)) >> BLOCK_BITS);
}
function URLSafeBase64Encode($str) // URLSafeBase64Encode
{
$find = array('+', '/');
$replace = array('-', '_');
return str_replace($find, $replace, base64_encode($str));
}
function CalSha1($fhandler) {
$fdata = fread($fhandler, BLOCK_SIZE);
$sha1Str = sha1($fdata, true);
$err = error_get_last();
if ($err != null) {
return array(null, $err);
}
$byteArray = unpack('C*', $sha1Str);
return array($byteArray, null);
}
function GetEtag($filename) {
if (!is_file($filename)) {
$err = array ('message' => 'Can not open ' . $filename . ' as a file.');
return array(null, $err);
}
$fhandler = fopen($filename, 'r');
$err = error_get_last();
if ($err != null) {
return array(null, $err);
}
$fstat = fstat($fhandler);
$fsize = $fstat['size'];
$blockCnt = BlockCount($fsize);
$sha1Buf = array();
if ($blockCnt <= 1) {
$sha1Buf[] = 0x16;
list($sha1Code, $err) = CalSha1($fhandler);
if ($err != null) {
return array(null, $err);
}
fclose($fhandler);
$sha1Buf = array_merge($sha1Buf, $sha1Code);
} else {
$sha1Buf[] = 0x96;
$sha1BlockBuf = array();
for ($i=0; $i < $blockCnt; $i++) {
list($sha1Code, $err) = CalSha1($fhandler);
if ($err != null) {
return array(null, $err);
}
$sha1BlockBuf = array_merge($sha1BlockBuf, $sha1Code);
}
$tmpData = PackArray('C*', $sha1BlockBuf);
$tmpFhandler = tmpfile();
fwrite($tmpFhandler, $tmpData);
fseek($tmpFhandler, 0);
list($sha1Final, $_err) = CalSha1($tmpFhandler);
$sha1Buf = array_merge($sha1Buf, $sha1Final);
}
$etag = URLSafeBase64Encode(PackArray('C*', $sha1Buf));
return array($etag, null);
}
function isCmd () {
$selfName = basename($_SERVER['PHP_SELF']);
$cwd = getcwd();
$fullPath = $cwd . '/' . $selfName;
$isCmd = __file__ == $fullPath ? true : false;
return $isCmd;
}
function run () {
if ($_SERVER["argc"] < 2) {
echo 'Usage: php qetag.php <filename>' . "\n";
exit();
}
$filename = $_SERVER["argv"][1];
list($ret, $err) = GetEtag($filename);
if ($err != null) {
echo $err['message'] . "\n";
exit();
}
echo $ret . "\n";
exit();
}
if (isCmd()) {
run();
}
?>