Repository navigation
Expand file tree
/
Copy pathindex.php
More file actions
339 lines (291 loc) · 12.6 KB
/
Copy pathindex.php
File metadata and controls
339 lines (291 loc) · 12.6 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
<?php
// 主应用程序逻辑
try {
require_once __DIR__ . '/init.php';
$storage = createStorageStrategy($config);
// 处理API数据提交
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$show_docs) {
validateApiCredentials();
// 如果是文件上传,使用 $_POST 和 $_FILES
if (!empty($_FILES['image_file'])) {
$input = $_POST;
$input['content_type'] = 'image';
} else {
// 否则处理 JSON 输入
$input = json_decode(file_get_contents('php://input'), true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception('Invalid JSON input', 400);
}
}
// 验证必填字段
$required = ['content', 'user_name'];
foreach ($required as $field) {
if (empty($input[$field])) {
throw new Exception("Missing required field: $field", 400);
}
}
// 添加敏感词检查 - 只检查文本内容
if ($input['content_type'] === 'text') {
// 检查内容
if (!checkSensitiveWords($input['content'])) {
throw new Exception("内容包含敏感词,请修改后重新提交", 400);
}
// 检查用户名
if (!checkSensitiveWords($input['user_name'])) {
throw new Exception("用户名包含敏感词,请修改后重新提交", 400);
}
// 如果有引用来源,也检查
if (isset($input['quote_source']) && !checkSensitiveWords($input['quote_source'])) {
throw new Exception("引用来源包含敏感词,请修改后重新提交", 400);
}
}
// 准备数据 - API提交的内容默认隐藏
$data = [
'content' => $input['content_type'] === 'text' ? purifyText($input['content']) : $input['content'],
'content_type' => in_array($input['content_type'] ?? 'text', ['text', 'image']) ? $input['content_type'] : 'text',
'user_name' => purifyText($input['user_name']),
'quote_source' => isset($input['quote_source']) ? purifyText($input['quote_source']) : 'API提交',
'is_hidden' => 1,
'add_time' => time()
];
// 处理图片内容
if ($data['content_type'] === 'image') {
if (!isset($_FILES['image_file'])) {
throw new Exception('Missing image file for image type', 400);
}
$file = $_FILES['image_file'];
// 检查上传错误
if ($file['error'] !== UPLOAD_ERR_OK) {
throw new Exception('File upload error: ' . $file['error'], 400);
}
// 确保图片目录存在
if (!is_dir($config['image_storage']['path'])) {
mkdir($config['image_storage']['path'], 0755, true);
}
// 获取图片信息
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($file['tmp_name']);
// 检查图片类型
if (!isset($config['image_storage']['allowed_types'][$mime])) {
throw new Exception('Unsupported image type: ' . $mime, 400);
}
// 检查图片大小
if ($file['size'] > $config['image_storage']['max_size']) {
throw new Exception('Image size exceeds maximum allowed size', 400);
}
// 生成文件名
$imageData = file_get_contents($file['tmp_name']);
$imageHash = md5($imageData);
$ext = $config['image_storage']['allowed_types'][$mime];
$imagePath = $config['image_storage']['path'] . '/' . $imageHash . $ext;
// 保存图片
if (!move_uploaded_file($file['tmp_name'], $imagePath)) {
throw new Exception('Failed to save image', 500);
}
$data['content'] = $imageHash . $ext;
}
// 保存到数据库
if ($storage instanceof SqliteStorage) {
try {
$stmt = $storage->getDb()->prepare('INSERT INTO main (content, content_type, user_name, quote_source, is_hidden, add_time)
VALUES (:content, :content_type, :user_name, :quote_source, :is_hidden, :add_time)');
$stmt->execute($data);
$id = $storage->getDb()->lastInsertId();
$data['id'] = $id;
// 返回完整的URL路径
if ($data['content_type'] === 'image') {
$data['content_url'] = $current_domain . '/data/image/' . $data['content'];
}
apiResponse($data, '数据提交成功', 201);
} catch (PDOException $e) {
throw new Exception('Database error: ' . $e->getMessage(), 500);
}
}
}
// 获取所有引用内容
$quotes = $storage->getQuotes();
$visible_quotes = array_filter($quotes, function ($quote) {
return empty($quote['is_hidden']);
});
$lastUpdate = $storage->getLastUpdateTime();
if ($show_all) {
if (empty($visible_quotes)) {
throw new Exception("No quotes available", 404);
}
// 分页处理
$total = count($visible_quotes);
$total_pages = ceil($total / $per_page);
$offset = ($page - 1) * $per_page;
$paged_quotes = array_slice($visible_quotes, $offset, $per_page);
// 处理数据
$quotes_data = [];
foreach ($paged_quotes as $quote) {
$content = $quote['content'];
if ($quote["content_type"] === 'image') {
$content = $current_domain . '/data/image/' . $content;
}
$quotes_data[] = [
'id' => $quote['id'],
'content' => $content,
'description' => $quote['quote_source'],
'content_type' => $quote['content_type'],
'add_time' => (int)$quote['add_time'],
'user_name' => $quote['user_name']
];
}
if ($show_docs) {
// HTML响应
$content_html = '';
foreach ($quotes_data as $item) {
$display_content = $item['content_type'] === 'image'
? "<img src='{$item['content']}' alt='Quote image' style='max-width: 100%;'>"
: "<p>" . nl2br(htmlspecialchars($item['content'])) . "</p>";
$content_html .= renderTemplate('quote_item.php', [
'display_content' => $display_content,
'user_qq' => htmlspecialchars($item['user_name']),
'add_time' => date('Y-m-d H:i:s', $item['add_time'])
]);
}
$content = renderTemplate('all_quotes.php', [
'content_html' => $content_html,
'current_page' => $page,
'total_pages' => $total_pages,
'per_page' => $per_page
]);
echo renderTemplate('base.php', [
'title' => 'All Quotes',
'content' => $content,
'last_update_time' => date('Y-m-d H:i:s', (int)$lastUpdate)
]);
} else {
// JSON响应
$pagination = [
'total' => $total,
'per_page' => $per_page,
'current_page' => $page,
'total_pages' => $total_pages,
'has_more' => $page < $total_pages
];
apiResponse([
'quotes' => $quotes_data,
'pagination' => $pagination,
'last_update' => $lastUpdate
], '成功检索');
}
} else {
// 随机一条非隐藏内容
if (empty($visible_quotes)) {
throw new Exception("No quotes available", 404);
}
$quote = $visible_quotes[array_rand($visible_quotes)];
// 处理图片路径
$content = $quote['content'];
if ($quote["content_type"] === 'image') {
$quote['content'] = $current_domain . '/data/image/' . $content;
}
// 格式化数据
$response_data = [
'id' => (int)$quote['id'],
'content' => $quote['content'],
'description' => $quote['quote_source'],
'content_type' => $quote['content_type'],
'add_time' => (int)$quote['add_time'],
'user_name' => $quote['user_name']
];
if ($show_docs) {
// HTML响应
$display_content = $quote['content_type'] === 'image'
? "<img src='{$quote['content']}' alt='Quote image' style='max-width: 100%;'>"
: "<p>" . nl2br(htmlspecialchars($quote['content'])) . "</p>";
$api_example = json_encode($response_data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
$content = renderTemplate('single_quote.php', [
'display_content' => $display_content,
'user_qq' => htmlspecialchars($quote['user_name']),
'add_time' => date('Y-m-d H:i:s', (int)$quote['add_time']),
'api_example' => $api_example
]);
echo renderTemplate('base.php', [
'title' => 'Random Quote',
'content' => $content,
'last_update_time' => date('Y-m-d H:i:s', (int)$lastUpdate)
]);
} else {
// JSON响应
apiResponse($response_data, '成功检索随机引用');
}
}
} catch (Throwable $e) {
ob_clean();
$code = method_exists($e, 'getCode') ? $e->getCode() : 500;
$code = $code >= 100 && $code < 600 ? $code : 500;
// 获取所有可能的上下文信息(始终收集,用于日志)
$requestBody = file_get_contents('php://input');
$requestHeaders = function_exists('getallheaders') ? getallheaders() : [];
// 过滤敏感信息
$filteredPost = $_POST;
if (isset($filteredPost['password'])) $filteredPost['password'] = '***FILTERED***';
if (isset($filteredPost['token'])) $filteredPost['token'] = '***FILTERED***';
$filteredServer = $_SERVER;
$sensitiveKeys = ['HTTP_AUTHORIZATION', 'PHP_AUTH_PW', 'REDIS_PASSWORD', 'DB_PASSWORD'];
foreach ($sensitiveKeys as $key) {
if (isset($filteredServer[$key])) $filteredServer[$key] = '***FILTERED***';
}
//(无论是否调试模式,日志都会记录)
$fullErrorDetails = [
'error' => [
'class' => get_class($e),
'message' => $e->getMessage(),
'code' => $code,
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => $e->getTrace(),
'previous' => $e->getPrevious() ? $e->getPrevious()->getMessage() : null,
],
'request' => [
'method' => $_SERVER['REQUEST_METHOD'] ?? 'CLI',
'uri' => $_SERVER['REQUEST_URI'] ?? '',
'query' => $_GET,
'post' => $filteredPost,
'raw_input' => $requestBody,
'headers' => $requestHeaders,
],
'environment' => [
'php_version' => PHP_VERSION,
'os' => PHP_OS,
'memory_usage' => memory_get_usage(true) / 1024 / 1024 . ' MB',
'peak_memory' => memory_get_peak_usage(true) / 1024 / 1024 . ' MB',
'include_path' => get_include_path(),
],
'session' => $_SESSION ?? [],
'cookies' => $_COOKIE ?? [],
'server' => $filteredServer,
'timestamp' => date('Y-m-d H:i:s'),
];
// 决定返回给用户的信息(调试模式返回全部,否则仅返回message)
$apiResponseDetails = (isset($config['debug']) && $config['debug'] === true)
? $fullErrorDetails
: ['message' => $e->getMessage()];
// (始终记录完整信息,无论是否是调试模式)
$logDir = __DIR__ . '/data/log/';
if (!is_dir($logDir)) {
mkdir($logDir, 0777, true);
}
$logFile = $logDir . 'error_' . date('Y-m-d') . '.log';
$logData = [
'timestamp' => date('Y-m-d H:i:s'),
'error' => [
'type' => get_class($e),
'message' => $e->getMessage(),
'location' => $e->getFile() . ':' . $e->getLine(),
],
'context' => $fullErrorDetails, // 始终记录完整上下文
];
// 写
file_put_contents(
$logFile,
json_encode($logData, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n\n",
FILE_APPEND
);
// (调试模式返回详细信息,否则仅返回message)
apiResponse(null, $e->getMessage(), $code, ['details' => $apiResponseDetails]);
}