-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathS3Client.php
More file actions
341 lines (286 loc) · 10.3 KB
/
Copy pathS3Client.php
File metadata and controls
341 lines (286 loc) · 10.3 KB
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
<?php
if (!defined('__TYPECHO_ROOT_DIR__')) exit;
/**
* 简单的 S3 客户端实现
*/
class S3Upload_S3Client
{
private static $instance = null;
private $options = null;
private $endpoint;
private $bucket;
private $region;
private $accessKey;
private $secretKey;
/**
* 私有构造函数
*/
private function __construct()
{
$options = \Typecho\Widget::widget('Widget\Options');
$this->options = $options->plugin('S3Upload');
$this->endpoint = $this->options->endpoint;
$this->bucket = $this->options->bucket;
$this->region = $this->options->region;
$this->accessKey = $this->options->accessKey;
$this->secretKey = $this->options->secretKey;
}
/**
* 获取实例
*/
public static function getInstance()
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
/**
* 上传文件到 S3
*/
public function putObject($path, $file)
{
S3Upload_Utils::log("S3Client::putObject 开始 - 路径: {$path}", 'debug');
$date = gmdate('Ymd\THis\Z');
$shortDate = substr($date, 0, 8);
$payload = file_get_contents($file);
if ($payload === false) {
S3Upload_Utils::log("无法读取文件: {$file}", 'error');
throw new Exception('无法读取文件');
}
S3Upload_Utils::log("文件读取成功,大小: " . strlen($payload) . " bytes", 'debug');
$contentType = S3Upload_Utils::getMimeType($file);
$contentSha256 = hash('sha256', $payload);
// 准备请求
$canonical_uri = $this->buildCanonicalUri($path);
$canonical_querystring = '';
S3Upload_Utils::log("请求URI: {$canonical_uri}, Content-Type: {$contentType}", 'debug');
// 准备请求头
$headers = array(
'content-length' => strlen($payload),
'content-type' => $contentType,
'host' => $this->endpoint,
'x-amz-content-sha256' => $contentSha256,
'x-amz-date' => $date
);
// 签名
$signature = $this->getSignature(
'PUT',
$canonical_uri,
$canonical_querystring,
$headers,
$contentSha256,
$shortDate
);
// 准备 cURL 请求
$ch = curl_init();
$url = 'https://' . $this->endpoint . $canonical_uri;
S3Upload_Utils::log("上传URL: {$url}", 'debug');
$curlHeaders = array();
foreach ($headers as $key => $value) {
$curlHeaders[] = $key . ': ' . $value;
}
$curlHeaders[] = 'Authorization: ' . $signature;
// 获取SSL验证设置
$sslVerify = isset($this->options->sslVerify) && $this->options->sslVerify === 'true';
S3Upload_Utils::log("SSL验证设置: " . ($sslVerify ? '启用' : '禁用'), 'debug');
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => $curlHeaders,
CURLOPT_CUSTOMREQUEST => 'PUT',
CURLOPT_POSTFIELDS => $payload,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => $sslVerify,
CURLOPT_SSL_VERIFYHOST => $sslVerify ? 2 : 0,
CURLOPT_HEADER => true
));
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
S3Upload_Utils::log("HTTP响应码: {$httpCode}", 'debug');
if ($httpCode !== 200) {
$errorMsg = "上传失败,HTTP状态码:{$httpCode}";
if ($curlError) {
$errorMsg .= ",cURL错误:{$curlError}";
}
$errorMsg .= "\n请求URL:{$url}\n响应:{$response}";
S3Upload_Utils::log($errorMsg, 'error');
throw new Exception($errorMsg);
}
S3Upload_Utils::log("上传成功", 'debug');
return array(
'path' => $path,
'url' => $this->getObjectUrl($path)
);
}
/**
* 删除 S3 对象
*/
public function deleteObject($path)
{
$date = gmdate('Ymd\THis\Z');
$shortDate = substr($date, 0, 8);
$canonical_uri = $this->buildCanonicalUri($path);
$canonical_querystring = '';
$headers = array(
'host' => $this->endpoint,
'x-amz-content-sha256' => 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
'x-amz-date' => $date
);
$signature = $this->getSignature(
'DELETE',
$canonical_uri,
$canonical_querystring,
$headers,
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
$shortDate
);
$ch = curl_init();
$url = 'https://' . $this->endpoint . $canonical_uri;
$curlHeaders = array();
foreach ($headers as $key => $value) {
$curlHeaders[] = $key . ': ' . $value;
}
$curlHeaders[] = 'Authorization: ' . $signature;
// 获取SSL验证设置
$sslVerify = isset($this->options->sslVerify) && $this->options->sslVerify === 'true';
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => $curlHeaders,
CURLOPT_CUSTOMREQUEST => 'DELETE',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => $sslVerify,
CURLOPT_SSL_VERIFYHOST => $sslVerify ? 2 : 0
));
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $httpCode === 204 || $httpCode === 200;
}
/**
* 获取签名
*/
private function getSignature($method, $uri, $querystring, $headers, $payload_hash, $shortDate)
{
$algorithm = 'AWS4-HMAC-SHA256';
$service = 's3';
// Canonical Request
$canonical_headers = '';
$signed_headers = '';
ksort($headers);
foreach ($headers as $key => $value) {
$canonical_headers .= strtolower($key) . ':' . trim($value) . "\n";
$signed_headers .= strtolower($key) . ';';
}
$signed_headers = rtrim($signed_headers, ';');
$canonical_request = $method . "\n"
. $uri . "\n"
. $querystring . "\n"
. $canonical_headers . "\n"
. $signed_headers . "\n"
. $payload_hash;
// String to Sign
$credential_scope = $shortDate . '/' . $this->region . '/' . $service . '/aws4_request';
$string_to_sign = $algorithm . "\n"
. $headers['x-amz-date'] . "\n"
. $credential_scope . "\n"
. hash('sha256', $canonical_request);
// Signing
$kSecret = 'AWS4' . $this->secretKey;
$kDate = hash_hmac('sha256', $shortDate, $kSecret, true);
$kRegion = hash_hmac('sha256', $this->region, $kDate, true);
$kService = hash_hmac('sha256', $service, $kRegion, true);
$kSigning = hash_hmac('sha256', 'aws4_request', $kService, true);
$signature = hash_hmac('sha256', $string_to_sign, $kSigning);
return $algorithm
. ' Credential=' . $this->accessKey . '/' . $credential_scope
. ',SignedHeaders=' . $signed_headers
. ',Signature=' . $signature;
}
/**
* 获取对象URL
*
* @param string $path 对象路径
* @return string
*/
public function getObjectUrl($path)
{
$protocol = $this->options->useHttps === 'true' ? 'https://' : 'http://';
$objectKey = $this->buildObjectKey($path);
if ($objectKey === '') {
return '';
}
// 如果设置了自定义域名
if (!empty($this->options->customDomain)) {
$domain = rtrim($this->options->customDomain, '/');
return $protocol . $domain . '/' . $objectKey;
}
// 没有自定义域名时,根据URL风格生成地址
if ($this->options->urlStyle === 'virtual') {
return $protocol . $this->bucket . '.' . $this->endpoint . '/' . $objectKey;
}
// 路径形式
return $protocol . $this->endpoint . '/' . $this->bucket . '/' . $objectKey;
}
/**
* 生成存储路径
*/
public function generatePath($file)
{
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$ext = $ext ? strtolower($ext) : '';
$date = new \Typecho\Date();
$path = $date->year . '/' . $date->month;
// 生成文件名
$fileName = sprintf('%u', crc32(uniqid())) . ($ext ? '.' . $ext : '');
// 合并路径
return $path . '/' . $fileName;
}
/**
* 构建对象 Key(自动拼接并规范化 customPath)
*/
private function buildObjectKey($path)
{
$path = ltrim((string)$path, '/');
if ($path === '') {
return '';
}
// 兼容旧调用:如果 path 已经带了原始 customPath,则先剥离,避免重复拼接
$rawCustomPath = trim((string)$this->options->customPath, '/');
if ($rawCustomPath !== '') {
if ($path === $rawCustomPath) {
$path = '';
} elseif (strpos($path, $rawCustomPath . '/') === 0) {
$path = substr($path, strlen($rawCustomPath) + 1);
}
}
$customPath = $this->getNormalizedCustomPath();
if ($customPath === '') {
return $path;
}
if ($path === '') {
return $customPath;
}
if ($path === $customPath || strpos($path, $customPath . '/') === 0) {
return $path;
}
return $customPath . '/' . $path;
}
/**
* 构建 S3 Canonical URI
*/
private function buildCanonicalUri($path)
{
$objectKey = $this->buildObjectKey($path);
return '/' . $this->bucket . '/' . ltrim($objectKey, '/');
}
/**
* 规范化 customPath
*/
private function getNormalizedCustomPath()
{
$customPath = trim((string)$this->options->customPath, '/');
return trim($customPath, '/');
}
}