<?php
$nosecu = true;
include("./includes/common.php");

if(!checkRefererHost())exit('{"code":403}');

@header('Content-Type: application/json; charset=UTF-8');

$filename = trim($_POST['filename']);
$content = trim($_POST['content']);

if(empty($filename)){
    exit(json_encode(['code'=>-1,'msg'=>'文件名不能为空']));
}

if(empty($content)){
    exit(json_encode(['code'=>-1,'msg'=>'文件内容不能为空']));
}

// 检查文件名是否合法
if(!preg_match('/^[a-zA-Z0-9\-\_]+$/', $filename)){
    exit(json_encode(['code'=>-1,'msg'=>'文件名只能包含字母、数字、下划线和横线']));
}

// 添加.txt后缀
$filename = $filename . '.txt';

// 创建临时文件
$hash = md5($filename.time());
$tmpfile = sys_get_temp_dir().'/'.$hash;

// 写入临时文件
if(!file_put_contents($tmpfile, $content)){
    exit(json_encode(['code'=>-1,'msg'=>'临时文件创建失败']));
}

// 获取文件大小
$filesize = filesize($tmpfile);

// 计算文件hash
$filehash = md5_file($tmpfile);

// 检查文件是否已存在
$row = $DB->getRow("SELECT * FROM pre_file WHERE hash=:hash", [':hash'=>$filehash]);
if($row){
    unlink($tmpfile);
    $result = ['code'=>1, 'msg'=>'本站已存在该文件', 'exists'=>1, 'hash'=>$filehash, 'name'=>$filename, 'size'=>$filesize, 'id'=>$row['id']];
    exit(json_encode($result));
}

// 使用存储类保存文件
$result = $stor->savefile($filehash, $tmpfile, 'text/plain');
unlink($tmpfile);
if(!$result)exit(json_encode(['code'=>-1,'msg'=>'文件保存失败','error'=>'stor','errmsg'=>$stor->errmsg()]));

// 写入数据库
$sds = $DB->exec("INSERT INTO `pre_file` (`name`,`type`,`size`,`hash`,`addtime`,`ip`,`uid`) values (:name,:type,:size,:hash,NOW(),:ip,:uid)", [':name'=>$filename, ':type'=>'txt', ':size'=>$filesize, ':hash'=>$filehash, ':ip'=>$clientip, ':uid'=>($uid?$uid:0)]);
if(!$sds)exit(json_encode(['code'=>-1,'msg'=>'数据库写入失败'.$DB->error(),'error'=>'database']));
$id = $DB->lastInsertId();

$_SESSION['fileids'][] = $id;
$result = ['code'=>0, 'msg'=>'文件创建成功！', 'hash'=>$filehash, 'name'=>$filename, 'size'=>$filesize, 'type'=>'txt', 'id'=>$id];
exit(json_encode($result));
?>