<?php
include "conn.php";
checkLogin("");

// Modern PHP file upload handler
// @requires xhEditor
// @author Original: Yanis.Wang<yanis.wang@gmail.com>
// @site http://xheditor.com/
// @licence LGPL(http://www.opensource.org/licenses/lgpl-license.php)
// Converted to PHP8 with improved security and functionality



$inputname = 'filedata'; // Form file field name
$attachdir = 'u'; // Upload directory, no trailing slash
$dirtype = 2; // 1:by day 2:by month 3:by extension
$maxattachsize = 2097152; // Max upload size, default 2M
$upext = 'txt,rar,zip,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid'; // Allowed extensions
$msgtype = 2; // Return format: 1=only url, 2=parameter array
$immediate = $_GET['immediate'] ?? ''; // Immediate upload mode (demo only)

$err = '';
$msg = "''";

// Check if file was uploaded
if (!isset($_FILES[$inputname])) {
    $err = "无数据提交";
} else {
    $file = $_FILES[$inputname];
    
    // Check file size
    if ($file['size'] > $maxattachsize) {
        $err = "文件大小超过 " . $maxattachsize . "字节";
    } else {
        // Check file extension
        $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $allowed_extensions = explode(',', $upext);
        if (!in_array($extension, $allowed_extensions)) {
            $err = "上传文件扩展名必需为:" . $upext;
        } else {
            // Create subdirectory based on dirtype
            switch ($dirtype) {
                case 1:
                    $attach_subdir = "day_" . date("ymd");
                    break;
                case 2:
                    $attach_subdir = "m" . date("ym");
                    break;
                case 3:
                    $attach_subdir = "ext_" . $extension;
                    break;
            }
            
            $attach_dir = $attachdir . "/" . $attach_subdir . "/";
            
            // Create directory if it doesn't exist
            if (!file_exists($attach_dir)) {
                mkdir($attach_dir, 0777, true);
            }
            
            // Generate random filename
            $filename = date("dHis") . rand(10, 99) . "." . $extension;
            $target = $attach_dir . $filename;
            
            // Move uploaded file
            if (move_uploaded_file($file['tmp_name'], $target)) {
                // Process image if it's a JPEG
                if (in_array($extension, ['jpg', 'jpeg']) && extension_loaded('gd')) {
                    $image = imagecreatefromjpeg($target);
                    if ($image) {
                        $orig_width = imagesx($image);
                        $orig_height = imagesy($image);
                        
                        $img_w = 520 / $orig_width;
                        $img_h = 520 / $orig_height;
                        
                        if ($img_w < 1 || $img_h < 1) {
                            $new_width = $img_w < $img_h ? round($orig_width * $img_h) : 520;
                            $new_height = $img_w < $img_h ? 520 : round($orig_height * $img_w);
                            
                            $new_image = imagecreatetruecolor(520, 520);
                            imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $orig_width, $orig_height);
                            
                            // Crop to square
                            $final_image = imagecreatetruecolor(520, 520);
                            imagecopyresampled($final_image, $new_image, 0, 0, 0, 0, 520, 520, 520, 520);
                            
                            imagejpeg($final_image, $target, 100);
                            imagedestroy($final_image);
                            imagedestroy($new_image);
                        } else {
                            imagejpeg($image, $target, 100);
                        }
                        imagedestroy($image);
                    }
                }
                
                // Save to database
                $cpid = $_GET['cpid'] ?? '';
                $keys = urlencode($_GET['Keys'] ?? '');
                $ord = urlencode($_GET['Ord'] ?? '');
                $page = $_GET['Page'] ?? '';
                
                $sql = "INSERT INTO pic (cpid, picurl) VALUES (?, ?)";
                $stmt = $conn->prepare($sql);
                $stmt->execute([$cpid, "/system/" . $target]);
                
                header("Location: pic.php?cpid=$cpid&Page=$page&Keys=$keys&Ord=$ord");
                exit;
            } else {
                $err = "文件上传失败";
            }
        }
    }
}

header('Content-Type: text/html; charset=UTF-8');
// If there was an error, output it
if ($err !== '') {
    echo "<script>alert('$err');</script>";
}
?>