-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathapi.php
379 lines (332 loc) · 13.1 KB
/
api.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
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
<?php
//include 'other/validate.php';
require_once 'other/webp.php';
$config = parse_ini_file('./other/config.ini');
$validToken = $config['validToken'];
$dbHost = $config['dbHost'];
$dbUser = $config['dbUser'];
$dbPass = $config['dbPass'];
$dbName = $config['dbName'];
$storage = $config['storage'];
$mysqli = new mysqli($dbHost, $dbUser, $dbPass, $dbName);
if ($mysqli->connect_error) {
die("数据库连接失败: " . $mysqli->connect_error);
}
function logMessage($message) {
$logFile = '运行日志.txt';
$currentTime = date('Y-m-d H:i:s');
$logMessage = "[$currentTime] $message" . PHP_EOL;
file_put_contents($logFile, $logMessage, FILE_APPEND);
}
function respondAndExit($response) {
ob_end_clean();
echo json_encode($response);
ob_flush();
flush();
exit;
}
function isValidToken($token) {
global $validToken;
return $token === $validToken;
}
try {
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['image'])) {
$file = $_FILES['image'];
$token = isset($_POST['token']) ? $_POST['token'] : '';
if (!isValidToken($token)) {
respondAndExit(['result' => 'error', 'code' => 403, 'message' => 'Token错误']);
}
$uploadDir = 'uploads/';
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml', 'application/octet-stream', 'image/avif'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$fileMimeType = finfo_file($finfo, $_FILES['image']['tmp_name']);
finfo_close($finfo);
$datePath = date('Y/m/d');
$uploadDirWithDatePath = $uploadDir . $datePath . '/';
if (!is_dir($uploadDirWithDatePath)) {
if (!mkdir($uploadDirWithDatePath, 0777, true)) {
logMessage('无法创建上传目录: ' . $uploadDirWithDatePath);
respondAndExit(['result' => 'error', 'code' => 500, 'message' => '无法创建上传目录']);
}
}
if (!in_array($fileMimeType, $allowedTypes)) {
logMessage('不支持的文件类型: ' . $fileMimeType);
respondAndExit(['result' => 'error', 'code' => 406, 'message' => '不支持的文件类型']);
}
$imageInfo = getimagesize($_FILES['image']['tmp_name']);
if ($imageInfo === false && $fileMimeType !== 'image/svg+xml' && $fileMimeType !== 'image/avif') {
logMessage('文件不是有效的图片');
respondAndExit(['result' => 'error', 'code' => 406, 'message' => '文件不是有效的图片']);
}
if ($fileMimeType === 'application/octet-stream') {
$imageData = file_get_contents($_FILES['image']['tmp_name']);
$image = imagecreatefromstring($imageData);
if ($image === false) {
logMessage('文件不是有效的图片');
respondAndExit(['result' => 'error', 'code' => 406, 'message' => '文件不是有效的图片']);
}
imagedestroy($image);
}
$randomFileName = str_pad(mt_rand(0, 999999999), 9, '0', STR_PAD_LEFT);
$newFilePathWithoutExt = $uploadDirWithDatePath . $randomFileName;
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$newFilePath = $newFilePathWithoutExt . '.' . $extension;
if (move_uploaded_file($file['tmp_name'], $newFilePath)) {
$startTime = microtime(true);
logMessage("接收文件成功: $newFilePath");
ini_set('memory_limit', '1024M');
set_time_limit(60);
$quality = isset($_POST['quality']) ? intval($_POST['quality']) : 70;
if ($quality === 100) {
$finalFilePath = $newFilePath;
} else {
$convertSuccess = true;
if ($fileMimeType === 'image/gif') {
$convertSuccess = GifToWebp($newFilePath, $newFilePathWithoutExt . '.webp', $quality);
if ($convertSuccess) {
$finalFilePath = $newFilePathWithoutExt . '.webp';
unlink($newFilePath);
}
} elseif ($fileMimeType !== 'image/webp' && $fileMimeType !== 'image/svg+xml' && $fileMimeType !== 'image/avif') {
$convertSuccess = ToWebp($newFilePath, $newFilePathWithoutExt . '.webp', $quality);
if ($convertSuccess) {
$finalFilePath = $newFilePathWithoutExt . '.webp';
unlink($newFilePath);
}
} else {
$finalFilePath = $newFilePath;
}
$endTime = microtime(true);
$processingTime = round(($endTime - $startTime) * 1000);
}
if ($fileMimeType !== 'image/svg+xml') {
if ($fileMimeType === 'image/avif') {
$image = new Imagick($finalFilePath);
$compressedWidth = $image->getImageWidth();
$compressedHeight = $image->getImageHeight();
} else {
$compressedInfo = getimagesize($finalFilePath);
if (!$compressedInfo) {
logMessage('无法获取压缩后图片信息');
respondAndExit(['result' => 'error', 'code' => 500, 'message' => '无法获取压缩后图片信息']);
}
$compressedWidth = $compressedInfo[0];
$compressedHeight = $compressedInfo[1];
}
} else {
$compressedWidth = 100;
$compressedHeight = 100;
}
$compressedSize = filesize($finalFilePath);
interface StorageInterface {
public function upload($filePath, $datePath);
public function getFileUrl($path);
}
class OssStorage implements StorageInterface {
private $ossClient;
private $bucket;
private $cdndomain;
public function __construct($ossClient, $bucket, $cdndomain) {
$this->ossClient = $ossClient;
$this->bucket = $bucket;
$this->cdndomain = $cdndomain;
}
public function upload($filePath, $datePath) {
$ossFilePath = $datePath . '/' . basename($filePath);
$this->ossClient->uploadFile($this->bucket, $ossFilePath, $filePath);
return $ossFilePath;
}
public function getFileUrl($path) {
return 'https://' . $this->cdndomain . '/' . $path;
}
}
class LocalStorage implements StorageInterface {
public function upload($filePath, $datePath) {
return 'uploads/' . $datePath . '/' . basename($filePath);
}
public function getFileUrl($path) {
return 'https://' . $_SERVER['HTTP_HOST'] . '/' . $path;
}
}
class S3Storage implements StorageInterface {
private $s3Client;
private $bucket;
private $domain;
private $customUrlPrefix;
public function __construct($config) {
$this->s3Client = new Aws\S3\S3Client([
'version' => 'latest',
'region' => $config['S3Region'],
'endpoint' => $config['S3Endpoint'],
'use_path_style_endpoint' => true,
'credentials' => [
'key' => $config['S3AccessKeyId'],
'secret' => $config['S3AccessKeySecret'],
],
]);
$this->bucket = $config['S3Bucket'];
$this->customUrlPrefix = isset($config['customUrlPrefix']) ?
str_replace('http://', 'https://', $config['customUrlPrefix']) : '';
}
public function upload($filePath, $datePath) {
$s3FilePath = $datePath . '/' . basename($filePath);
try {
$result = $this->s3Client->putObject([
'Bucket' => $this->bucket,
'Key' => $s3FilePath,
'SourceFile' => $filePath,
'ACL' => 'public-read',
]);
logMessage("文件上传到S3成功: $s3FilePath");
} catch (Aws\Exception\AwsException $e) {
throw new Exception("S3 上传失败: " . $e->getMessage());
}
return $this->getFileUrl($result['ObjectURL']);
}
public function getFileUrl($s3Url) {
if (!empty($this->customUrlPrefix)) {
$parsedUrl = parse_url($s3Url);
$path = $parsedUrl['path'];
return rtrim($this->customUrlPrefix, '/') . '/' . ltrim($path, '/');
} else {
return $s3Url;
}
}
}
class FtpStorage implements StorageInterface {
private $ftpConn;
private $ftpConfig;
public function __construct($config) {
$this->ftpConfig = $config;
$this->ftpConn = ftp_connect($config['host'], $config['port']);
if (!$this->ftpConn) {
throw new Exception("FTP 连接失败");
}
$login = ftp_login($this->ftpConn, $config['username'], $config['password']);
if (!$login) {
throw new Exception("FTP 登录失败");
}
ftp_pasv($this->ftpConn, true); // 启用被动模式
}
public function upload($filePath, $datePath) {
if (!file_exists($filePath)) {
throw new Exception("本地文件不存在: $filePath");
}
$ftpFilePath = $datePath . '/' . basename($filePath);
$ftpDir = dirname($ftpFilePath);
$this->createDirectoryIfNotExists($ftpDir);
if (!ftp_put($this->ftpConn, $ftpFilePath, $filePath, FTP_BINARY)) {
$error = error_get_last()['message'];
throw new Exception("FTP 上传失败: " . $error);
}
return $ftpFilePath;
}
private function createDirectoryIfNotExists($ftpDir) {
$dirs = explode('/', $ftpDir);
$path = '';
foreach ($dirs as $dir) {
if ($dir === '') continue;
$path .= '/' . $dir;
if (!$this->directoryExists($path)) {
if (!@ftp_mkdir($this->ftpConn, $path)) {
$error = error_get_last()['message'];
throw new Exception("无法创建目录: $path. 错误信息: " . $error);
}
}
}
}
private function directoryExists($path) {
$currentDir = ftp_pwd($this->ftpConn);
if (@ftp_chdir($this->ftpConn, $path)) {
ftp_chdir($this->ftpConn, $currentDir);
return true;
}
ftp_chdir($this->ftpConn, $currentDir);
return false;
}
public function getFileUrl($path) {
return 'https://' . $this->ftpConfig['domain'] . '/' . $path;
}
public function __destruct() {
if ($this->ftpConn) {
ftp_close($this->ftpConn);
}
}
}
function getStorage($storage) {
global $config;
switch ($storage) {
case 'oss':
if (!class_exists('OSS\OssClient')) {
require_once 'vendor/autoload.php';
}
$ossClientClass = 'OSS\OssClient';
$ossExceptionClass = 'OSS\Core\OssException';
if (!class_exists($ossClientClass) || !class_exists($ossExceptionClass)) {
throw new Exception("OSS 类未加载");
}
$ossClient = new $ossClientClass($config['ossAccessKeyId'], $config['ossAccessKeySecret'], $config['ossEndpoint']);
return new OssStorage($ossClient, $config['ossBucket'], $config['ossdomain']);
case 'local':
return new LocalStorage();
case 's3':
if (!class_exists('Aws\S3\S3Client')) {
require_once 'vendor/autoload.php';
}
return new S3Storage($config);
case 'ftp':
return new FtpStorage([
'host' => $config['ftpHost'],
'port' => $config['ftpPort'],
'username' => $config['ftpUsername'],
'password' => $config['ftpPassword'],
'domain' => $config['ftpdomain']
]);
default:
throw new Exception("不支持的存储类型: " . $storage);
}
}
try {
$storageInstance = getStorage($storage);
$uploadedFilePath = $storageInstance->upload($finalFilePath, $datePath);
if ($storage !== 'local') {
if (file_exists($finalFilePath)) {
unlink($finalFilePath);
if ($finalFilePath !== $newFilePath) {
unlink($newFilePath);
}
} else {
logMessage("尝试删除不存在的文件: {$finalFilePath}");
}
}
$fileUrl = $storageInstance->getFileUrl($uploadedFilePath);
$stmt = $mysqli->prepare("INSERT INTO images (url, path, srcName , storage) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $fileUrl, $uploadedFilePath, $randomFileName, $storage);
$stmt->execute();
$stmt->close();
respondAndExit([
'result' => 'success',
'code' => 200,
'url' => $fileUrl,
'srcName' => $randomFileName,
'width' => $compressedWidth,
'height' => $compressedHeight,
'ptime' => $processingTime,
'size' => $compressedSize
]);
} catch (Exception $e) {
logMessage('文件上传失败: ' . $e->getMessage());
respondAndExit(['result' => 'error', 'code' => 500, 'message' => '文件上传失败: ' . $e->getMessage()]);
}
} else {
logMessage('文件上传失败: ' . $file['error']);
respondAndExit(['result' => 'error', 'code' => 500, 'message' => '文件上传失败']);
}
} else {
respondAndExit(['result' => 'error', 'code' => 204, 'message' => '无文件上传']);
}
} catch (Exception $e) {
logMessage('未知错误: ' . $e->getMessage());
respondAndExit(['result' => 'error', 'code' => 500, 'message' => '发生未知错误: ' . $e->getMessage()]);
}
?>