-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathFileHandler.php
More file actions
272 lines (233 loc) · 8.54 KB
/
FileHandler.php
File metadata and controls
272 lines (233 loc) · 8.54 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
<?php
if (!defined('__TYPECHO_ROOT_DIR__')) exit;
use Typecho\Widget\Helper\Form;
use Typecho\Common;
class S3Upload_FileHandler
{
const MIN_COMPRESS_SIZE = 102400; // 100KB
/**
* 上传文件处理函数
*/
public static function uploadHandle($file)
{
try {
if (empty($file['name'])) {
return false;
}
$ext = self::getSafeName($file['name']);
// 使用 Typecho 后台「允许上传的文件类型」设置进行校验
if (!self::isAllowedFileType($ext)) {
return false;
}
$options = \Typecho\Widget::widget('Widget\Options')->plugin('S3Upload');
$mime = $file['type'] ?? mime_content_type($file['tmp_name'] ?? '');
$isImage = self::isImage($mime);
$tempFile = null;
$webpName = null;
// 只处理大于100KB的图片
if (
$isImage &&
isset($options->compressImages) && $options->compressImages == '1' &&
self::isAllowedFileType('webp') &&
isset($file['tmp_name']) && is_file($file['tmp_name']) && filesize($file['tmp_name']) > self::MIN_COMPRESS_SIZE
) {
$quality = isset($options->compressQuality) ? (int)$options->compressQuality : 85;
$tempFile = tempnam(sys_get_temp_dir(), 'webp_') . '.webp';
if (self::convertToWebp($file['tmp_name'], $tempFile, $mime, $quality)) {
$file['tmp_name'] = $tempFile;
$file['size'] = filesize($tempFile);
$file['type'] = 'image/webp';
$webpName = self::replaceExtToWebp($file['name']);
$ext = 'webp';
} else {
@unlink($tempFile);
$tempFile = null;
}
}
if ($webpName) {
$file['name'] = $webpName;
}
$uploader = new S3Upload_StreamUploader();
$result = $uploader->handleUpload($file);
if ($tempFile && file_exists($tempFile)) {
@unlink($tempFile);
}
if ($result) {
// 保证 webp 后缀
if ($webpName) {
$result['name'] = $webpName;
$result['type'] = 'webp';
$result['mime'] = 'image/webp';
$result['extension'] = 'webp';
}
return [
'name' => $result['name'],
'path' => $result['path'],
'size' => $result['size'],
'type' => $result['type'],
'mime' => $result['mime'],
'extension' => $result['extension'],
'created' => time(),
'attachment'=> (object)['path' => $result['path']],
'isImage' => self::isImage($result['mime']),
'url' => $result['url']
];
}
return false;
} catch (Exception $e) {
S3Upload_Utils::log("上传处理错误: " . $e->getMessage(), 'error');
return false;
}
}
public static function attachmentHandle($content)
{
$path = self::extractPath($content);
if (empty($path)) return '';
$s3Client = S3Upload_S3Client::getInstance();
return $s3Client->getObjectUrl($path);
}
public static function attachmentDataHandle($content)
{
$path = self::extractPath($content);
if (empty($path)) return '';
$s3Client = S3Upload_S3Client::getInstance();
return $s3Client->getObjectUrl($path);
}
public static function modifyHandle($content, $file)
{
try {
$uploader = new S3Upload_StreamUploader();
return $uploader->handleUpload($file);
} catch (Exception $e) {
S3Upload_Utils::log("修改文件错误: " . $e->getMessage(), 'error');
return false;
}
}
public static function deleteHandle($content)
{
try {
$path = self::extractPath($content);
if (empty($path)) return false;
$s3Client = S3Upload_S3Client::getInstance();
$result = $s3Client->deleteObject($path);
// 如果配置了本地备份,也删除本地文件
$options = \Typecho\Widget::widget('Widget\Options')->plugin('S3Upload');
if (isset($options->saveLocal) && $options->saveLocal == 'true') {
$localPath = __TYPECHO_ROOT_DIR__ . '/usr/uploads/' . ltrim((string)$path, '/');
if (file_exists($localPath)) {
@unlink($localPath);
}
}
return $result;
} catch (Exception $e) {
S3Upload_Utils::log("删除文件错误: " . $e->getMessage(), 'error');
return false;
}
}
private static function getSafeName($name)
{
$ext = pathinfo($name, PATHINFO_EXTENSION);
return $ext ? strtolower($ext) : '';
}
private static function isAllowedFileType(string $ext): bool
{
$ext = strtolower(trim($ext));
if ($ext === '') {
return false;
}
// Typecho 1.3+:Widget\Upload::checkFileType 使用 Options::allowedAttachmentTypes
if (class_exists('\\Widget\\Upload') && method_exists('\\Widget\\Upload', 'checkFileType')) {
return \Widget\Upload::checkFileType($ext);
}
// 兜底:直接读取全局配置的 allowedAttachmentTypes
try {
$options = \Typecho\Widget::widget('Widget\Options');
$allowed = $options->allowedAttachmentTypes ?? null;
if (is_array($allowed)) {
return in_array($ext, $allowed, true);
}
} catch (\Throwable $e) {
// ignore
}
return false;
}
private static function isImage($mime)
{
return strpos($mime, 'image/') === 0;
}
private static function convertToWebp($src, $dest, $mime, $quality = 85)
{
if (!extension_loaded('gd')) {
return false;
}
$image = null;
switch ($mime) {
case 'image/jpeg':
$image = imagecreatefromjpeg($src);
break;
case 'image/png':
$image = imagecreatefrompng($src);
break;
case 'image/gif':
$image = imagecreatefromgif($src);
break;
default:
return false;
}
if (!$image) {
return false;
}
// 保持透明度
if ($mime === 'image/png' || $mime === 'image/gif') {
imagepalettetotruecolor($image);
imagealphablending($image, true);
imagesavealpha($image, true);
}
$result = imagewebp($image, $dest, $quality);
imagedestroy($image);
return $result;
}
private static function replaceExtToWebp($filename)
{
$info = pathinfo($filename);
$dirname = isset($info['dirname']) && $info['dirname'] !== '.' ? $info['dirname'] . '/' : '';
return $dirname . $info['filename'] . '.webp';
}
/**
* 从 Typecho 传入的内容中提取附件路径
*
* @param mixed $content
* @return string
*/
private static function extractPath($content)
{
// 1) 优先读取根级 path
if ($content instanceof \Typecho\Config || is_object($content)) {
$path = $content->path ?? '';
if (!empty($path)) {
return (string)$path;
}
} elseif (is_array($content)) {
$path = $content['path'] ?? '';
if (!empty($path)) {
return (string)$path;
}
} else {
return '';
}
// 2) 回退读取 attachment.path
$attachment = null;
if ($content instanceof \Typecho\Config || is_object($content)) {
$attachment = $content->attachment ?? null;
} elseif (is_array($content)) {
$attachment = $content['attachment'] ?? null;
}
if ($attachment instanceof \Typecho\Config || is_object($attachment)) {
return (string)($attachment->path ?? '');
}
if (is_array($attachment)) {
return (string)($attachment['path'] ?? '');
}
return '';
}
}