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

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

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

if($islogin2 && $userrow['level']>0){
    $conf['upload_limit']=0;
    $conf['videoreview']=0;
    $conf['type_block']=null;
    $conf['name_block']=null;
}

if(!$_POST['url'])exit('{"code":-1,"msg":"请输入URL地址"}');
$url = trim($_POST['url']);
if(!filter_var($url, FILTER_VALIDATE_URL))exit('{"code":-1,"msg":"URL地址不正确"}');
if($conf['forcelogin']==1 && !$islogin2)exit('{"code":-1,"msg":"请先登录"}');

$filename = basename(parse_url($url, PHP_URL_PATH));
if(empty($filename)) $filename = substr(md5($url), 0, 8);

$hash = md5($url.time());
$tmpfile = sys_get_temp_dir().'/'.$hash;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$data = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if($httpcode!=200 || empty($data))exit('{"code":-1,"msg":"下载文件失败"}');

if(!file_put_contents($tmpfile, $data))exit('{"code":-1,"msg":"保存文件失败"}');

$filesize = filesize($tmpfile);
$limit_size = intval($conf['upload_size']);
if($limit_size > 0 && $filesize > $limit_size * 1024 * 1024){
    unlink($tmpfile);
    exit('{"code":-1,"msg":"文件大小超出限制'.$limit_size.'MB"}');
}

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

$ext = get_file_ext($filename);
if($conf['type_block']){
    $type_block = explode('|',$conf['type_block']);
    if(in_array($ext,$type_block)){
        unlink($tmpfile);
        exit('{"code":-1,"msg":"文件上传失败，不支持上传该格式文件"}');
    }
}

$result = $stor->savefile($hash, $tmpfile, minetype($ext));
unlink($tmpfile);
if(!$result)exit('{"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'=>$ext, ':size'=>$filesize, ':hash'=>$hash, ':ip'=>$clientip, ':uid'=>($uid?$uid:0)]);
if(!$sds)exit('{"code":-1,"msg":"上传失败'.$DB->error().'","error":"database"}');
$id = $DB->lastInsertId();

$_SESSION['fileids'][] = $id;
$result = ['code'=>0, 'msg'=>'远程下载成功！', 'hash'=>$hash, 'name'=>$filename, 'size'=>$filesize, 'type'=>$ext, 'id'=>$id];
exit(json_encode($result));