Files
img/public/index.php
T
2023-04-24 09:35:18 +08:00

422 lines
11 KiB
PHP

<?php
init();
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- <link rel="shortcut icon" href="/favicon.ico" /> -->
<title><?php echo get_page_title(); ?></title>
<link rel="stylesheet" href="/css/style.css">
<script src="https://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
</head>
<body class="" style="background-color: #fafaf9;">
<div class="w-full flex justify-center">
<div class="flex h-12 p-3 w-[1080px] justify-center font-thin">
<!-- <div class="flex text-xl">
Logo
</div> -->
<div class="flex space-x-5 text-xl px-5">
<div>
<a href="/" class="<?php if ($_SERVER["REQUEST_URI"] == "/index") echo "text-red-300"; ?>">Home</a>
</div>
<div>
<a href="/about" class="<?php if ($_SERVER["REQUEST_URI"] == "/about") echo "text-red-300"; ?>">About</a>
</div>
</div>
</div>
</div>
<div class="w-full flex justify-center">
<div class="flex justify-center w-[1080px]">
<div class="p-2 md:p-3 w-full">
<div class="md:h-[50px] h-[10px]"></div>
<?php show_page(); ?>
<div class="md:h-[100px] h-[20px]"></div>
</div>
</div>
</div>
</body>
</html>
<?php
// page func start
function show_index()
{
ob_start(); ?>
<form role="form" action="##" onsubmit="return false" method="post" enctype="multipart/form-data" id="uploadForm">
<input type="file" class="input-file" id="file" name="file" style="display: none" multiple="multiple" accept="image/png, image/jpeg, image/jpg, image/gif">
</form>
<div class="grid grid-cols-1 w-full space-y-5">
<div>
<div class="text-2xl w-full">1.选择图片&上传</div>
<div class="flex space-x-5 py-3">
<button class="h-10 w-20 bg-red-300" id="choosePic">选择图片</button>
<button class="h-10 w-20 bg-blue-300" id="submitBtn">开始上传</button>
</div>
<div class="text-red-500">!!!文件大小不能超过5MB.</div>
</div>
<div>
<div class="text-2xl w-full">2.图片链接</div>
<div class="">
<table class="table-fixed border-collapse border border-green-800">
<thead>
<tr class="border border-green-600">
<th class="border border-green-600 w-100 text-center">名称</th>
<th class="border border-green-600 w-30 text-center">大小</th>
<th class="border border-green-600 w-40 text-center">状态</th>
<th class="border border-green-600 w-200 text-center">链接</th>
</tr>
</thead>
<tbody id="tbodyId">
</tbody>
</table>
</div>
</div>
</div>
<script type="text/javascript">
var queue = [];
$('#choosePic').click(function() {
$("#file").click();
});
var fileInput = document.querySelector('#file')
var fileList = fileInput.files
file = fileList.item(0)
fileInput.addEventListener('change', function(e) {
for (var i = 0; i < this.files.length; i++) {
const file = this.files[i];
if (file.size > 5 * 1024 * 1024) {
alert('文件大小不能超过5MB,已忽略。');
continue;
}
const id = "picId_" + Math.random().toString(36).substr(2, 8);
const tpl = '<tr class="border border-green-600 text-center"><td class="border border-green-600 text-center">' + file.name + '</td><td class="border border-green-600 text-center">' + (file.size / 1024 / 1024).toFixed(2) + 'MB</td><td class="border border-green-600 text-center">等待上传</td><td id="' + id + '"></td></tr>';
$('#tbodyId').append(tpl);
data = {
'id': id,
'file': file,
'upload': false,
}
queue.push(data);
}
});
$("#submitBtn").click(function() {
if (queue.length == 0) {
alert('请选择图片');
return false;
}
for (var i = 0; i < queue.length; i++) {
if (queue[i].upload) {
continue;
}
var formData = new FormData();
formData.append('file', queue[i].file);
formData.append('id', queue[i].id);
$("#" + queue[i].id).prev().text('上传中');
$.ajax({
url: "/api/upload",
type: 'POST',
dataType: "json",
data: formData,
cache: false,
processData: false,
contentType: false,
success: function(data) {
if (data.code == 0) {
$("#" + data.data.id).html("<a target='_blank' href='" + data.data.src + "'>" + data.data.src + "</a>");
$("#" + data.data.id).prev().text('上传成功');
// $("#textareaId").append(data.src + "\n");
queue[data.data.id].upload = true;
} else {
$("#" + data.data.id).html("上传失败");
$("#" + data.data.id).prev().text('上传失败');
}
},
error: function(data) {
alert('上传失败');
}
});
}
});
</script>
<?php
$html = ob_get_contents();
ob_clean();
echo $html;
}
?>
<?php function show_about()
{
$stmt = get_db()->prepare("SELECT count(1) as count FROM files");
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
ob_start(); ?>
<div class="">
<p class="text-2xl">
这是一个简单图床.
</p>
<br>
<p>
目前共成功上传了: <span class="text-red-500"><?php echo $row["count"]; ?></span> 张图片.
</p>
</div>
<?php
$html = ob_get_contents();
ob_clean();
echo $html;
}
?>
<?php function show_404()
{
ob_start(); ?>
<div class="">
404 NOT FOUND
</div>
<?php
$html = ob_get_contents();
ob_clean();
echo $html;
}
// page func end
?>
<?php
// api func start
function check_api()
{
$uri = $_SERVER["REQUEST_URI"];
$func = ltrim(implode("_", explode("/", $uri)), "_");
if (str_starts_with($uri, "/api")) {
if (!function_exists($func)) echo_json([
"code" => 1,
"msg" => "uri错误",
"data" => []
]);
call_user_func($func);
}
}
function echo_json($data)
{
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data, JSON_UNESCAPED_UNICODE);
die;
}
function api_test()
{
echo_json([
"code" => 0,
"msg" => "test",
"data" => []
]);
}
function api_upload()
{
$web = get_config('common', 'web');
$url = "https://telegra.ph/upload";
$filePath = $_FILES["file"]["tmp_name"];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'file' => new CURLFile($filePath)
));
$response = curl_exec($ch);
curl_close($ch);
$jsonArr = json_decode($response, true);
$src = $jsonArr[0]["src"] ?? "";
$uuid = uniqidReal();
exec_db("INSERT INTO files (uuid, src) VALUES ('{$uuid}', '{$src}')");
echo_json([
"code" => empty($src) ? 1 : 0,
"msg" => "",
"data" => [
"id" => $_POST["id"],
"src" => $web . "/file/{$uuid}"
]
]);
}
// api func end
?>
<?php
// common func start
function init()
{
define("BASE_PATH", __DIR__ . "/../");
define("CONFIG_PATH", BASE_PATH . "/./config/");
define("PUBLIC_PATH", BASE_PATH . "/./public/");
define("DATA_PATH", BASE_PATH . "/./data/");
inti_db();
empty($_SERVER['REQUEST_URI']) || $_SERVER['REQUEST_URI'] == "/" && $_SERVER['REQUEST_URI'] = "/index";
check_api();
check_file();
}
function get_page_title()
{
$uri = $_SERVER['REQUEST_URI'];
$pages = json_decode(file_get_contents(CONFIG_PATH . "page.json"), true);
return $pages[$uri]["title"] ?? "404 NOT FOUND";
}
function show_page()
{
$uri = $_SERVER["REQUEST_URI"];
$func = ltrim(implode("_", explode("/", $uri)), "_");
if (function_exists("show_{$func}")) {
call_user_func("show_{$func}");
} else {
call_user_func("show_404");
}
}
function get_db()
{
$db = new PDO('sqlite:' . DATA_PATH . 'data.db');
return $db;
}
function exec_db($sql)
{
$db = get_db();
$db->exec($sql);
}
function inti_db()
{
exec_db('CREATE TABLE IF NOT EXISTS files (id INTEGER PRIMARY KEY, uuid TEXT, src TEXT)');
}
function uniqidReal($lenght = 13)
{
// uniqid gives 13 chars, but you could adjust it to your needs.
if (function_exists("random_bytes")) {
$bytes = random_bytes(ceil($lenght / 2));
} elseif (function_exists("openssl_random_pseudo_bytes")) {
$bytes = openssl_random_pseudo_bytes(ceil($lenght / 2));
} else {
throw new Exception("no cryptographically secure random function available");
}
return substr(bin2hex($bytes), 0, $lenght);
}
function check_file()
{
if (str_starts_with($_SERVER['REQUEST_URI'], "/file")) {
$id = explode("/", $_SERVER['REQUEST_URI'])[2] ?? "";
$stmt = get_db()->prepare("SELECT * FROM files WHERE uuid=:uuid LIMIT 1");
$stmt->bindParam(':uuid', $id);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (empty($row['src'])) {
echo_json([
"code" => 1,
"msg" => "图片不存在",
"data" => []
]);
}
$imgUrl = "https://telegra.ph{$row['src']}";
$content = file_get_contents($imgUrl);
header('Content-Type: image/jpeg');
header('Content-Length: ' . strlen($content));
echo $content;
die;
}
}
function get_config($file, $path)
{
if (!file_exists(CONFIG_PATH . $file . ".json")) {
return "";
}
$conf = file_get_contents(CONFIG_PATH . $file . ".json");
$arr = json_decode($conf, true);
$value = $arr;
foreach (explode(".", $path) as $p) {
$value = $value[$p] ?? "";
if (!$value) break;
}
return $value;
}
// common func end
?>