<?php
if (!defined('puyuetian')) {
    exit('403');
}

if (!InArray(getUserQX(), 'uploadfile')) {
    uploadexit('您无权上传文件');
}
$t = input('get.t/s');
if (!InArray('image,file,music,video', $t)) {
    uploadexit('非法的目录请求');
}

$date                = date('Ymd');
$useruploadfilespath = PK_UPLOAD_PATH . "{$t}s/" . user('id') . "/{$date}/";
if (file_exists($useruploadfilespath) && (Cnum(JsonData(user('data'), 'dayuploadfilesize')) || Cnum(set('dayuploadfilesize')))) {
    $uploadedfiles = scandir($useruploadfilespath);
    $filesizecount = 0;
    if (Cnum(JsonData(user('data'), 'dayuploadfilesize'))) {
        $dayuploadfilesize = Cnum(JsonData(usergroup('data'), 'dayuploadfilesize'));
    } else {
        $dayuploadfilesize = Cnum(JsonData(user('data'), 'dayuploadfilesize'));
    }
    if ($dayuploadfilesize) {
        $cfilesizecount = $dayuploadfilesize * 1024;
    } else {
        $cfilesizecount = Cnum(set('dayuploadfilesize')) * 1024;
    }
    foreach ($uploadedfiles as $file) {
        if (str_replace('.', '', $file)) {
            $filesizecount += filesize($useruploadfilespath . $file);
        }
    }
    if ($filesizecount > $cfilesizecount) {
        uploadexit('您已达到每日上传文件最大上限' . Cnum($cfilesizecount / 1024) . 'KB');
    }
}

if (count($_FILES['file']['tmp_name']) - 1 > Cnum(set('uploadfilecount'), 5)) {
    uploadexit('一次最多上传' . Cnum(set('uploadfilecount'), 5) . '个文件');
}

$jscode = '';
if (!$_FILES['file']['error']) {
    uploadexit(true);
}
foreach ($_FILES['file']['error'] as $key => $value) {
    if ($_FILES['file']['error'][$key] > 0) {
        switch ($_FILES['file']['error'][$key]) {
            case 1:
                $errortip = $_FILES['file']['name'][$key] . '的大小超过了php.ini中upload_max_filesize选项限制的值';
                break;
            case 2:
                $errortip = $_FILES['file']['name'][$key] . '的大小超过了HTML表单中MAX_FILE_SIZE选项指定的值';
                break;
            case 3:
                $errortip = $_FILES['file']['name'][$key] . '只有部分被上传';
                break;
            case 4:
                $errortip = $_FILES['file']['name'][$key] . '没有文件被上传';
                break;
            case 6:
                $errortip = $_FILES['file']['name'][$key] . '找不到临时文件夹';
                break;
            case 7:
                $errortip = $_FILES['file']['name'][$key] . '写入失败';
                break;
            default:
                $errortip = $_FILES['file']['name'][$key] . '未知错误';
                break;
        }
        uploadexit("{$key}:{$errortip}");
    }

    if ($_FILES['file']['size'][$key] < 10) {
        uploadexit($_FILES['file']['name'][$key] . '文件过小或未选择文件！');
    }
    if (Cnum(JsonData(usergroup('data'), 'uploadsize'))) {
        $uploadsize = Cnum(JsonData(usergroup('data'), 'uploadsize'));
    } else {
        $uploadsize = Cnum(JsonData(user('data'), 'uploadsize'));
    }
    if ($uploadsize) {
        if ($_FILES['file']['size'][$key] > ($uploadsize * 1024)) {
            uploadexit('上传文件不能超过' . ($uploadsize * 1024) . 'KB');
        }
    } else {
        if (!Cnum(set('uploadfilesize'))) {
            uploadexit('本站禁止上传文件');
        }
        if ($_FILES['file']['size'][$key] > (Cnum(set('uploadfilesize')) * 1024)) {
            uploadexit("上传文件不能超过" . set('uploadfilesize') . "KB");
        }
    }

    $suffix = strtolower(end(explode('.', $_FILES['file']['name'][$key])));
    switch ($t) {
        case 'image':
            $image_suffixs = 'jpg,jpeg,png,gif,bmp,webp,svg,tif,tiff,ico';
            if (!InArray($image_suffixs, $suffix)) {
                uploadexit('只能上传图片文件：' . $image_suffixs);
            }
            break;
        case 'music':
            $music_suffixs = 'mp3,ogg,wav,aac,wma,m4a';
            if (!InArray($music_suffixs, $suffix)) {
                uploadexit('只能上传音频文件：' . $music_suffixs);
            }
            break;
        case 'video':
            $video_suffixs = 'mp4,m4v,mpeg,avi,webm,ogg,ogm,ogv,mov,wmv,flv,mkv,mid,flash,3gp,mpg';
            if (!InArray($video_suffixs, $suffix)) {
                uploadexit('只能上传视频文件：' . $video_suffixs);
            }
            break;
        default:
            if (!InArray(set('uploadfiletypes'), $suffix, '|')) {
                uploadexit("不允许的文件后缀:{$suffix}，请核对后再上传");
            }
            break;
    }

    if (!is_uploaded_file($_FILES['file']['tmp_name'][$key])) {
        uploadexit('上传失败！未通过系统检验');
    }

    if (!file_exists($useruploadfilespath) && !mkdir($useruploadfilespath, 0777, true)) {
        uploadexit('创建目录失败');
    }

    //更名，保存文件至指定目录
    $idcode   = md5_file($_FILES['file']['tmp_name'][$key]);
    $filesize = ceil($_FILES['file']['size'][$key] / 1024);
    $uploaded = table('upload')->where('idcode', $idcode)->find();
    if (set('smartupload') && $uploaded) {
        $uid      = $uploaded['uid'];
        $date     = substr($uploaded['datetime'], 0, 8);
        $time     = substr($uploaded['datetime'], 8);
        $rand     = $uploaded['rand'];
        $suffix   = $uploaded['suffix'];
        $filename = "{$time}_{$rand}.{$suffix}";
    } else {
        $uid      = user('id');
        $date     = date('Ymd');
        $time     = date('His');
        $rand     = CreateRandomString(6);
        $filename = "{$time}_{$rand}.{$suffix}";
        move_uploaded_file($_FILES['file']['tmp_name'][$key], $useruploadfilespath . $filename);
    }
    if (!(set('smartupload') && $uploaded)) {
        //图片压缩
        $compress_wh = explode(',', aAS('compress_wh'));
        if ('image' == $t && InArray('jpg,jpeg,png,bmp,webp', $suffix) && count($compress_wh) == 2) {
            $image      = false;
            $m_w        = Cnum($compress_wh[0]);
            $m_h        = Cnum($compress_wh[1]);
            $image_path = $useruploadfilespath . $filename;
            $image_info = getimagesize($image_path);
            if ($m_w < $image_info[0] && $m_w) {
                //宽度超过了要求，压缩图片
                $image = imagecreatefromstring(file_get_contents($image_path));
                if (InArray('jpg,jpeg,png,bmp', $suffix)) {
                    $_h     = $image_info[1] / $image_info[0] * $m_w;
                    $_image = imagecreatetruecolor($m_w, $_h);
                    imagecopyresampled($_image, $image, 0, 0, 0, 0, $m_w, $_h, $image_info[0], $image_info[1]);
                }
                if ($image) {
                    switch ($suffix) {
                        case 'jpg':
                        case 'jpeg':
                            imagejpeg($_image, $image_path);
                            break;
                        case 'bmp':
                            imagebmp($_image, $image_path);
                            break;
                        case 'gif':
                            imagegif($_image, $image_path);
                            break;
                        case 'webp':
                            imagewebp($_image, $image_path, 80);
                            break;
                        default:
                            imagepng($_image, $image_path);
                            break;
                    }
                }
            }
            $image_info = getimagesize($image_path);
            if ($m_h < $image_info[1] && $m_h) {
                //高度超过了要求，压缩图片
                $image = imagecreatefromstring(file_get_contents($image_path));
                if (InArray('jpg,jpeg,png,bmp', $suffix)) {
                    $_w     = $image_info[0] / $image_info[1] * $m_h;
                    $_image = imagecreatetruecolor($_w, $m_h);
                    imagecopyresampled($_image, $image, 0, 0, 0, 0, $_w, $m_h, $image_info[0], $image_info[1]);
                }
                if ($image) {
                    switch ($suffix) {
                        case 'jpg':
                        case 'jpeg':
                            imagejpeg($_image, $image_path);
                            break;
                        case 'bmp':
                            imagebmp($_image, $image_path);
                            break;
                        case 'gif':
                            imagegif($_image, $image_path);
                            break;
                        case 'webp':
                            imagewebp($_image, $image_path, 80);
                            break;
                        default:
                            imagepng($_image, $image_path);
                            break;
                    }
                }
            }
        }
        //图片加水印
        if ('image' == $t && InArray('jpg,jpeg,png,bmp', $suffix) && aAS('watermark_text')) {
            $image    = imagecreatefromstring(file_get_contents($image_path));
            $color    = imagecolorallocate($image, Cnum(aAS('watermark_textcolor_r')), Cnum(aAS('watermark_textcolor_g')), Cnum(aAS('watermark_textcolor_b')));
            $wmf_path = PK_APP_PATH . 'puyuetianeditor/template/font/default.ttc';
            if (!file_exists($wmf_path)) {
                imagestring($image, 5, 10, 5, aAS('watermark_text'), $color);
            } else {
                imagettftext($image, Cnum(aAS('watermark_fontsize'), 18), Cnum(aAS('watermark_pp')), Cnum(aAS('watermark_px')), Cnum(aAS('watermark_py')), $color, $wmf_path, aAS('watermark_text'));
            }
            switch ($suffix) {
                case 'jpg':
                case 'jpeg':
                    imagejpeg($image, $image_path);
                    break;
                case 'bmp':
                    imagebmp($image, $image_path);
                    break;
                case 'gif':
                    imagegif($image, $image_path);
                    break;
                case 'webp':
                    imagewebp($image, $image_path, 100);
                    break;
                default:
                    imagepng($image, $image_path);
                    break;
            }
        }
    }
    $uploadarray                  = [];
    $uploadarray['uid']           = $uid;
    $uploadarray['datetime']      = $date . $time;
    $uploadarray['rand']          = $rand;
    $uploadarray['suffix']        = $suffix;
    $uploadarray['idcode']        = $idcode;
    $uploadarray['jifen']         = 0;
    $uploadarray['tiandou']       = 0;
    $uploadarray['downloadcount'] = 0;
    $uploadarray['name']          = '';
    $uploadarray['uploadtime']    = time();
    if (set('smartupload') && $uploaded) {
        $uploadarray['target'] = $uploaded['target'];
        $id                    = $uploaded['id'];
    } else {
        $uploadarray['target'] = $t;
        $id                    = table('upload')->insertGetId($uploadarray);
    }
    $target = $uploadarray['target'];

    if ('file' != $t) {
        $url = "uploadfiles/{$target}s/{$uid}/{$date}/{$time}_{$rand}.{$suffix}";
        if ('image' == $t) {
            if (input('get.easy/s')) {
                $jscode .= 'parent.$("#PytEasyImagesBox").prepend(\'<div class="_image"><img src="' . $url . '" onclick="LookImage(this)"><i class="fa fa-fw fa-trash-o pk-text-danger" onclick="$(this).parent().remove()"></i></div>\');';
            } else {
                $jscode .= 'if(typeof(parent.PytAddImageInbox)=="function"){parent.PytAddImageInbox("' . $url . '");}else{parent.document.getElementById("PytImagesBox").innerHTML+="<div class=\"pk-w-sm-3 pk-margin-bottom-10\"><img class=\"pk-active\" src=\"' . $url . '\" onclick=\"$(this).toggleClass(\'pk-active\')\"></div>";}';
            }
        } else {
            if (input('get.easy/s')) {
                $jscode .= 'parent.$("#PytEasyImagesBox").prepend(\'<div class="_image"><video src="' . $url . '" controls="controls"></video><i class="fa fa-fw fa-trash-o pk-text-danger" onclick="$(this).parent().remove()"></i></div>\');';
            } else {
                $jscode .= 'parent.document.getElementById("Pyt' . strtoupper(substr($t, 0, 1)) . substr($t, 1) . 'Url").value="' . $url . '";';
            }
        }
    } else {
        $url = "index.php?c=app&a=puyuetianeditor&s=showfile&id={$id}";
        $jscode .= 'parent.document.getElementById("PytFileUrl").value="' . $url . '";parent.document.getElementById("PytFileStatus").innerHTML="待插入[ID:' . $id . ']";';
    }
}
exit('
<script>
    ' . $jscode . ';
    if("' . input('get.easy/s') . '"=="1"){
	    parent.pkpopup.close(' . input('get.pppid/d') . ');
    }else{
	    location.href="app/puyuetianeditor/template/upload.html?t=' . $t . '&align=' . input('get.align/s') . '&rnd=' . g('rnd') . '";
    }
</script>
');

function uploadexit($str)
{
    if (true === $str) {
        $str = '";str=document.getElementsByTagName("body")[0].innerText;"';
    } else {
        $str = str_replace('"', '\\"', $str);
    }
    exit('
<script>
    var str="' . $str . '";
    parent.ppp({title:"出错",icon:2,content:str});
    if("' . input('get.easy/s') . '"=="1"){
	    parent.pkpopup.close(' . input('get.pppid/d') . ');
    }else{
	    location.href="app/puyuetianeditor/template/upload.html?t=' . input('get.t/s') . '&align=' . input('get.align/s') . '&rnd=' . g('rnd') . '";
    }
</script>
');
}
