<?php

function curl_get($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

function daddslashes($string, $force = 0, $strip = false) {
    if ($force) {
        if (is_array($string)) {
            foreach ($string as $key => $val) {
                $string[$key] = daddslashes($val, $force, $strip);
            }
        } else {
            $string = addslashes($strip ? stripslashes($string) : $string);
        }
    }
    return $string;
}

function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
    $ckey_length = 4;
    $key = md5($key ? $key : SYS_KEY);
    $keya = md5(substr($key, 0, 16));
    $keyb = md5(substr($key, 16, 16));
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';
    $cryptkey = $keya . md5($keya . $keyc);
    $key_length = strlen($cryptkey);
    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
    $string_length = strlen($string);
    $result = '';
    $box = range(0, 255);
    $rndkey = array();
    for ($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }
    for ($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }
    for ($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }
    if ($operation == 'DECODE') {
        if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
            return substr($result, 26);
        } else {
            return '';
        }
    } else {
        return $keyc . str_replace('=', '', base64_encode($result));
    }
}

function showmsg($content, $type = 1, $back = true) {
    $types = array('success', 'info', 'warning', 'danger');
    $type = isset($types[$type - 1]) ? $types[$type - 1] : 'info';
    $back_url = $back ? "window.history.back()" : "window.location.href='/'";
    echo "<script>alert('{$content}');{$back_url};</script>";
    exit;
}

function sysmsg($msg, $die = true) {
    echo "<!DOCTYPE html><html><head><meta charset='utf-8'><title>系统提示</title></head><body style='font-family:Microsoft YaHei;padding:50px;text-align:center;'><h3>{$msg}</h3></body></html>";
    if ($die) exit;
}

function logjl($czuser, $lx, $lr, $qk, $DBZHER = '') {
    global $DB;
    $date = date('Y-m-d H:i:s');
    $ip = x_real_ip();
    $sql = "INSERT INTO `log` (`user`, `lx`, `lr`, `date`, `ip`) VALUES ('{$czuser}', '{$lx}', '{$lr}', '{$date}', '{$ip}')";
    $DB->query($sql);
}

function send_post($url, $post_data) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($ch, CURLOPT_TIMEOUT, 4);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

function ary_asd($mn_conf) {
    $str = "<?php\nreturn " . var_export($mn_conf, true) . ";\n?>";
    return $str;
}

function deldir($dir) {
    if (!@is_dir($dir)) return false;
    $files = @scandir($dir);
    if ($files === false) return false;
    foreach ($files as $file) {
        if ($file == '.' || $file == '..') continue;
        $path = $dir . '/' . $file;
        if (@is_dir($path)) {
            deldir($path);
        } else {
            @unlink($path);
        }
    }
    @rmdir($dir);
    return true;
}

function dirfiles($data, $type = '') {
    $arr = array();
    foreach ($data as $v) {
        if ($v == '.user.ini') continue;
        if ($type && !preg_match('/\.' . $type . '$/', $v)) continue;
        $arr[] = $v;
    }
    return $arr;
}

function delval_array($arr, $value, $path = '') {
    foreach ($arr as $k => $v) {
        if ($v == $value) {
            unset($arr[$k]);
        }
        if (!preg_match('/^[a-zA-Z0-9_\-\.\s]+$/', $v)) {
            unset($arr[$k]);
        }
    }
    if (empty($arr)) {
        return false;
    }
    return $arr;
}

function zipfile($path, $paths, $zipth, $filetext = '') {
    $zip = new ZipArchive();
    $zipfile = $zipth . time() . '.zip';
    if ($zip->open($zipfile, ZipArchive::CREATE) !== TRUE) {
        return false;
    }
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
    foreach ($iterator as $key => $value) {
        $filepath = $key;
        $localpath = substr($filepath, strlen($path));
        if (in_array(basename($filepath), array('.', '..'))) continue;
        if (is_dir($filepath)) continue;
        $zip->addFile($filepath, $localpath);
    }
    if ($filetext) {
        $zip->addFromString($filetext['name'], $filetext['content']);
    }
    $zip->close();
    return $zipfile;
}

function x_real_ip() {
    $ip = '';
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $ip = trim($ips[0]);
    } elseif (isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['HTTP_CF_CONNECTING_IP']) && !empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
        $ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
    } elseif (isset($_SERVER['HTTP_X_REAL_IP']) && !empty($_SERVER['HTTP_X_REAL_IP'])) {
        $ip = $_SERVER['HTTP_X_REAL_IP'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    if (preg_match('/^10\./', $ip) || preg_match('/^172\.(1[6-9]|2\d|3[01])\./', $ip) || preg_match('/^192\.168\./', $ip)) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

function cc_defender() {
    if (!isset($_COOKIE['cc_defender'])) {
        $code = rand(100000, 999999);
        setcookie('cc_defender', $code, time() + 3600);
    } else {
        if (!isset($_SESSION['cc_count'])) {
            $_SESSION['cc_count'] = 0;
        }
        $_SESSION['cc_count']++;
        if ($_SESSION['cc_count'] > 10) {
            header('HTTP/1.1 403 Forbidden');
            exit('访问过于频繁，请稍后再试');
        }
    }
}

/**
 * 发送邮件函数 - 使用原生SMTP
 * @param string $to 收件人邮箱
 * @param string $subject 邮件主题
 * @param string $message 邮件内容
 * @param array $custom_config 可选的自定义邮件配置，用于测试
 * @return bool|array 发送成功返回true，失败返回包含错误信息的数组
 */
function sendEmail($to, $subject, $message, $custom_config = null) {
    global $conf;
    
    // 使用自定义配置或全局配置
    $mail_config = $custom_config ?: $conf;
    
    // 检查邮件配置是否完整
    if (empty($mail_config['mailhost']) || empty($mail_config['mailuser']) || empty($mail_config['mailpassword']) || empty($mail_config['mailport'])) {
        $error = '邮件配置不完整，无法发送邮件';
        return array('success' => false, 'error' => $error);
    }
    
    $host = $mail_config['mailhost'];
    $port = intval($mail_config['mailport']);
    $username = $mail_config['mailuser'];
    $password = $mail_config['mailpassword'];
    $from_name = isset($mail_config['name']) ? $mail_config['name'] : '系统邮件';
    
    // 使用SSL连接
    $socket = @fsockopen('ssl://' . $host, $port, $errno, $errstr, 30);
    if (!$socket) {
        $error = "SMTP连接失败: $errstr ($errno)";
        return array('success' => false, 'error' => $error);
    }
    
    // 读取服务器响应
    $response = fgets($socket, 515);
    if (substr($response, 0, 3) != '220') {
        $error = 'SMTP服务器响应错误: ' . trim($response);
        fclose($socket);
        return array('success' => false, 'error' => $error);
    }
    
    // 发送EHLO
    $ehlo_host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost';
    fputs($socket, "EHLO " . $ehlo_host . "\r\n");
    $response = fgets($socket, 515);
    if (substr($response, 0, 3) != '250') {
        $error = 'EHLO命令失败: ' . trim($response);
        fclose($socket);
        return array('success' => false, 'error' => $error);
    }
    
    // 读取EHLO响应
    while (substr($response, 3, 1) != ' ') {
        $response = fgets($socket, 515);
    }
    
    // 发送AUTH LOGIN
    fputs($socket, "AUTH LOGIN\r\n");
    $response = fgets($socket, 515);
    if (substr($response, 0, 3) != '334') {
        $error = 'AUTH LOGIN失败: ' . trim($response);
        fclose($socket);
        return array('success' => false, 'error' => $error);
    }
    
    // 发送用户名（Base64编码）
    fputs($socket, base64_encode($username) . "\r\n");
    $response = fgets($socket, 515);
    if (substr($response, 0, 3) != '334') {
        $error = '用户名验证失败: ' . trim($response);
        fclose($socket);
        return array('success' => false, 'error' => $error);
    }
    
    // 发送密码（Base64编码）
    fputs($socket, base64_encode($password) . "\r\n");
    $response = fgets($socket, 515);
    if (substr($response, 0, 3) != '235') {
        $error = '密码验证失败: ' . trim($response) . ' (请确认使用的是授权码而非登录密码)';
        fclose($socket);
        return array('success' => false, 'error' => $error);
    }
    
    // 发送MAIL FROM
    fputs($socket, "MAIL FROM:<$username>\r\n");
    $response = fgets($socket, 515);
    if (substr($response, 0, 3) != '250') {
        $error = 'MAIL FROM失败: ' . trim($response);
        fclose($socket);
        return array('success' => false, 'error' => $error);
    }
    
    // 发送RCPT TO
    fputs($socket, "RCPT TO:<$to>\r\n");
    $response = fgets($socket, 515);
    if (substr($response, 0, 3) != '250') {
        $error = 'RCPT TO失败: ' . trim($response);
        fclose($socket);
        return array('success' => false, 'error' => $error);
    }
    
    // 发送DATA
    fputs($socket, "DATA\r\n");
    $response = fgets($socket, 515);
    if (substr($response, 0, 3) != '354') {
        $error = 'DATA命令失败: ' . trim($response);
        fclose($socket);
        return array('success' => false, 'error' => $error);
    }
    
    // 构建邮件内容
    $boundary = md5(time());
    $headers = "From: =?UTF-8?B?" . base64_encode($from_name) . "?= <$username>\r\n";
    $headers .= "To: $to\r\n";
    $headers .= "Subject: =?UTF-8?B?" . base64_encode($subject) . "?=\r\n";
    $headers .= "Date: " . date('r') . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
    $headers .= "Content-Transfer-Encoding: base64\r\n";
    
    $email_content = $headers . "\r\n" . chunk_split(base64_encode($message)) . "\r\n.\r\n";
    
    // 发送邮件内容
    fputs($socket, $email_content);
    $response = fgets($socket, 515);
    if (substr($response, 0, 3) != '250') {
        $error = '邮件内容发送失败: ' . trim($response);
        fclose($socket);
        return array('success' => false, 'error' => $error);
    }
    
    // 发送QUIT
    fputs($socket, "QUIT\r\n");
    fclose($socket);
    
    return true;
}
?>
