<?php

class bt_api {
    var $BT_PANEL;
    var $BT_KEY;

    public function __construct($bt_panel = null, $bt_key = null) {
        if ($bt_panel) {
            // 确保BT_PANEL格式正确
            if (strpos($bt_panel, '://') === false) {
                $bt_panel = 'http://' . $bt_panel;
            }
            $this->BT_PANEL = $bt_panel;
        }
        if ($bt_key) $this->BT_KEY = $bt_key;
    }

    public function GetKeyData() {
        $now_time = time();
        // 对密钥做md5处理，与ajax.php中的逻辑保持一致
        $key_md5 = md5($this->BT_KEY);
        $p_data = array(
            'request_token' => md5($now_time . '' . $key_md5),
            'request_time' => $now_time
        );
        return $p_data;
    }

    private function debug_log($message) {
        // 调试日志已禁用
        return;
        $debug_file = dirname(__FILE__) . '/user/api/debug.log';
        $log_message = date('Y-m-d H:i:s') . ' [bt_api] ' . $message . "\n";

        if (is_writable(dirname($debug_file))) {
            @file_put_contents($debug_file, $log_message, FILE_APPEND);
        } else {
            // 如果目录不可写，尝试写入系统临时目录
            $tmp_debug_file = sys_get_temp_dir() . '/bt_host_debug.log';
            @file_put_contents($tmp_debug_file, $log_message, FILE_APPEND);
        }
    }

    public function HttpPostCookie($url, $data, $timeout = 60) {
        // 定义cookie保存位置，优先使用系统临时目录，确保在虚拟空间下也能正常写入
        $tmp_dir = sys_get_temp_dir();
        if (!$tmp_dir || !is_writable($tmp_dir)) {
            $cookie_dir = dirname(__FILE__) . '/api/cookie';
        } else {
            $cookie_dir = $tmp_dir . '/bt_api_cookies';
        }

        if (!is_dir($cookie_dir)) {
            @mkdir($cookie_dir, 0755, true);
        }

        $cookie_file = $cookie_dir . '/' . md5($this->BT_PANEL) . '.cookie';
        if (!file_exists($cookie_file)) {
            $fp = @fopen($cookie_file, 'w+');
            if ($fp) {
                fclose($fp);
            }
        }
        
        // 调试：输出curl请求信息
        $this->debug_log('HttpPostCookie请求URL: ' . $url);
        $this->debug_log('HttpPostCookie请求参数: ' . (is_array($data) ? print_r($data, true) : $data));
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_POST, 1);
        
        // 检查是否包含文件上传
        $has_file = false;
        if (is_array($data)) {
            foreach ($data as $key => $value) {
                if (is_string($value) && strpos($value, '@') === 0) {
                    $has_file = true;
                    break;
                }
                if (class_exists('CURLFile') && $value instanceof CURLFile) {
                    $has_file = true;
                    break;
                }
            }
        }
        
        if ($has_file) {
            // 文件上传使用 multipart/form-data，不需要 http_build_query
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        } else {
            // 普通请求使用 application/x-www-form-urlencoded
            if (is_array($data)) {
                $data = http_build_query($data);
            }
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/x-www-form-urlencoded'
            ));
        }
        
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        
        // 允许HTTP/0.9响应（某些旧版宝塔面板需要）
        curl_setopt($ch, CURLOPT_HTTP09_ALLOWED, true);
        
        // 设置超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); // 设置连接超时时间为10秒
        
        // 文件上传时增加低速度限制和超时时间
        if ($has_file) {
            // 禁用低速度检查，避免大文件上传时因速度波动导致失败
            // curl_setopt($ch, CURLOPT_LOW_SPEED_TIME, 180);
            // curl_setopt($ch, CURLOPT_LOW_SPEED_LIMIT, 50);
            // 文件上传需要更长的总超时时间
            curl_setopt($ch, CURLOPT_TIMEOUT, 600); // 10分钟
        }
        
        // 捕获curl错误
        $output = curl_exec($ch);
        
        // 调试：输出curl响应信息
        $this->debug_log('HttpPostCookie响应输出: ' . var_export($output, true));
        
        if (curl_errno($ch)) {
            $curl_error = curl_error($ch);
            $this->debug_log('Curl错误: ' . $curl_error);
            curl_close($ch);
            return json_encode(array('status' => false, 'msg' => 'CURL错误: ' . $curl_error));
        }
        
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $this->debug_log('HttpPostCookie HTTP状态码: ' . $http_code);
        curl_close($ch);
        
        if ($http_code !== 200) {
            return json_encode(array('status' => false, 'msg' => 'HTTP错误: ' . $http_code));
        }
        
        // 不再输出API响应到响应
        return $output;
    }

    public function webkt($user, $pass, $btserw, $cptype, $ftp, $sql, $version, $path, $port = 80) {
        $url = $this->BT_PANEL . '/site?action=AddSite';
        $p_data = $this->GetKeyData();
        $p_data['webname'] = json_encode(array('domain' => $btserw, 'domainlist' => array(), 'count' => 0));
        $p_data['path'] = $path;
        $p_data['type_id'] = 0;
        $p_data['type'] = $cptype;
        $p_data['port'] = $port;
        $p_data['ftp'] = $ftp;
        $p_data['ftp_username'] = $user;
        $p_data['ftp_password'] = $pass;
        $p_data['sql'] = $sql;
        $p_data['codeing'] = 'utf8';
        $p_data['datauser'] = $user;
        $p_data['datapassword'] = $pass;
        $p_data['ps'] = '';
        $p_data['version'] = $version;
        $result = $this->HttpPostCookie($url, $p_data);
        
        // 检查返回结果是否为数组（错误信息）
        if (is_array($result)) {
            return $result;
        }
        
        // 检查返回结果是否为空
        if (empty($result)) {
            return array('status' => false, 'msg' => '宝塔API返回空数据，请检查宝塔服务器是否在线');
        }
        
        return json_decode($result, true);
    }

    public function delsite($id, $webname) {
        $url = $this->BT_PANEL . '/site?action=DeleteSite';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $p_data['webname'] = $webname;
        $p_data['ftp'] = 1;
        $p_data['database'] = 1;
        $p_data['path'] = 1;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function ztweb($id, $name) {
        $url = $this->BT_PANEL . '/site?action=SiteStop';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $p_data['name'] = $name;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function qdweb($id, $name) {
        $url = $this->BT_PANEL . '/site?action=SiteStart';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $p_data['name'] = $name;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function setdqsj($id, $edate) {
        $url = $this->BT_PANEL . '/site?action=SetEdate';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $p_data['edate'] = $edate;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function getlog($name) {
        $url = $this->BT_PANEL . '/site?action=GetSiteLogs';
        $p_data = $this->GetKeyData();
        $p_data['siteName'] = $name;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function ftpxg($id, $username, $status) {
        $url = $this->BT_PANEL . '/ftp?action=SetStatus';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $p_data['username'] = $username;
        $p_data['status'] = $status;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function setftppass($id, $username, $password) {
        $url = $this->BT_PANEL . '/ftp?action=SetUserPassword';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $p_data['ftp_username'] = $username;
        $p_data['new_password'] = $password;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function ftpcx($user) {
        $url = $this->BT_PANEL . '/data?action=getData';
        $p_data = $this->GetKeyData();
        $p_data['table'] = 'ftps';
        $p_data['search'] = $user;
        $p_data['limit'] = 100;
        $p_data['p'] = 1;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function webcx($user) {
        $url = $this->BT_PANEL . '/data?action=getData';
        $p_data = $this->GetKeyData();
        $p_data['table'] = 'sites';
        $p_data['search'] = $user;
        $p_data['limit'] = 100;
        $p_data['p'] = 1;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function ftpcreate($username, $password, $path) {
        $url = $this->BT_PANEL . '/ftp?action=AddUser';
        $p_data = $this->GetKeyData();
        $p_data['ftp_username'] = $username;
        $p_data['ftp_password'] = $password;
        $p_data['path'] = $path;
        $p_data['ps'] = '';
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function databascx($user) {
        $url = $this->BT_PANEL . '/data?action=getData';
        $p_data = $this->GetKeyData();
        $p_data['table'] = 'databases';
        $p_data['search'] = $user;
        $p_data['limit'] = 100;
        $p_data['p'] = 1;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function setmysqlpass($id, $username, $password) {
        $url = $this->BT_PANEL . '/database?action=ResDatabasePassword';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $p_data['name'] = $username;
        $p_data['password'] = $password;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function mysqlqx($user, $ip) {
        $url = $this->BT_PANEL . '/database?action=SetDatabaseAccess';
        $p_data = $this->GetKeyData();
        $p_data['name'] = $user;
        $p_data['access'] = $ip;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    // 获取数据库访问权限
    public function GetDatabaseAccess($name) {
        $url = $this->BT_PANEL . '/database?action=GetDatabaseAccess';
        $p_data = $this->GetKeyData();
        $p_data['name'] = $name;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function sqlkjhq($sqlname) {
        $url = $this->BT_PANEL . '/database?action=GetInfo';
        $p_data = $this->GetKeyData();
        $p_data['db_name'] = $sqlname;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    // phpMyAdmin外部访问配置获取 (使用较短超时)
    public function api_sql_cf() {
        $url = $this->BT_PANEL . '/plugin?action=get_soft_find';
        $p_data = $this->GetKeyData();
        $p_data['sName'] = 'phpmyadmin';
        $result = $this->HttpPostCookie($url, $p_data, 10);  // 10秒超时
        return json_decode($result, true);
    }
    
    // phpMyAdmin外部访问设置 (使用较短超时)
    public function api_sql_set($set_r) {
        $url = $this->BT_PANEL . '/system?action=ServiceAdmin';
        $p_data = $this->GetKeyData();
        $p_data['name'] = 'phpmyadmin';
        $p_data['type'] = $set_r;
        $result = $this->HttpPostCookie($url, $p_data, 10);  // 10秒超时
        return json_decode($result, true);
    }
    
    // 网站监控报表配置获取
    public function api_waf_cf() {
        $url = $this->BT_PANEL . '/plugin?action=get_soft_find';
        $p_data = $this->GetKeyData();
        $p_data['sName'] = 'btwaf';
        $result = $this->HttpPostCookie($url, $p_data, 10);
        return json_decode($result, true);
    }
    
    // 网站监控报表外部访问设置
    public function api_waf_set($set_r) {
        $url = $this->BT_PANEL . '/system?action=ServiceAdmin';
        $p_data = $this->GetKeyData();
        $p_data['name'] = 'btwaf';
        $p_data['type'] = $set_r;
        $result = $this->HttpPostCookie($url, $p_data, 10);
        return json_decode($result, true);
    }
    
    // 获取宝塔软件列表（用于流量监控）
    public function get_soft_list() {
        $url = $this->BT_PANEL . '/plugin?action=get_soft_list';
        $p_data = $this->GetKeyData();
        $result = $this->HttpPostCookie($url, $p_data, 10);
        return json_decode($result, true);
    }
    
    // 获取网站流量统计数据
    public function get_site_traffic($site_id) {
        $url = $this->BT_PANEL . '/data?action=getData';
        $p_data = $this->GetKeyData();
        $p_data['table'] = 'sites';
        $p_data['limit'] = 10;
        $p_data['p'] = 1;
        $result = $this->HttpPostCookie($url, $p_data, 10);
        return json_decode($result, true);
    }
    
    // 获取网站流量日志
    public function get_site_logs($site_id, $page = 1, $count = 100) {
        $url = $this->BT_PANEL . '/site?action=GetSiteLogs';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $site_id;
        $p_data['page'] = $page;
        $p_data['count'] = $count;
        $result = $this->HttpPostCookie($url, $p_data, 10);
        return json_decode($result, true);
    }
    
    // 获取网站带宽统计
    public function get_site_bandwidth($site_id) {
        $url = $this->BT_PANEL . '/site?action=GetBandwidth';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $site_id;
        $p_data['s'] = '1';
        $p_data['e'] = '';
        $result = $this->HttpPostCookie($url, $p_data, 10);
        return json_decode($result, true);
    }
    
    // 获取网站信息
    public function get_site($site_id) {
        $url = $this->BT_PANEL . '/site?action=GetSite';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $site_id;
        $result = $this->HttpPostCookie($url, $p_data, 10);
        return json_decode($result, true);
    }

    public function GetHostDirectory($path) {
        // 使用正确的宝塔API接口获取目录列表
        $url = $this->BT_PANEL . '/files?action=GetDir';
        $p_data = $this->GetKeyData();
        $p_data['path'] = $path;
        $p_data['disk'] = 'true';
        // 设置3秒超时，加快响应速度
        $result = $this->HttpPostCookie($url, $p_data, 3);
        return json_decode($result, true);
    }

    public function GetDirSize($path) {
        // 使用宝塔API获取目录大小
        $url = $this->BT_PANEL . '/files?action=GetDirSize';
        $p_data = $this->GetKeyData();
        $p_data['path'] = $path;
        $result = $this->HttpPostCookie($url, $p_data);
        
        // 尝试解析JSON
        $json = json_decode($result, true);
        if ($json && is_array($json)) {
            // 如果返回的是JSON，尝试提取大小值
            if (isset($json['size'])) {
                return $json['size'];
            } elseif (isset($json['data'])) {
                return $json['data'];
            }
        }
        
        // 返回原始字符串（如 "14.64 MB"）
        return $result;
    }

    public function GetFileContent($path) {
        $url = $this->BT_PANEL . '/files?action=GetFileBody';
        $p_data = $this->GetKeyData();
        $p_data['path'] = $path;
        $result = $this->HttpPostCookie($url, $p_data);
        if (is_array($result)) {
            return $result;
        }
        return json_decode($result, true);
    }
    
    public function SaveFileBody($path, $data, $encoding = 'utf-8') {
        $url = $this->BT_PANEL . '/files?action=SaveFileBody';
        $p_data = $this->GetKeyData();
        $p_data['path'] = $path;
        $p_data['data'] = $data;
        $p_data['encoding'] = $encoding;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function hqwjnr($path) {
        $url = $this->BT_PANEL . '/files?action=GetFileBody';
        $p_data = $this->GetKeyData();
        $p_data['path'] = $path;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function setwj($content, $path) {
        $url = $this->BT_PANEL . '/files?action=SaveFileBody';
        $p_data = $this->GetKeyData();
        $p_data['path'] = $path;
        $p_data['body'] = $content;
        $p_data['encoding'] = 'utf-8';
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    /**
     * 设置站点伪静态规则
     * @param string $siteName 站点名称
     * @param string $content 伪静态规则内容
     * @return array API响应结果
     */
    public function SetSiteRewrite($siteName, $content) {
        $url = $this->BT_PANEL . '/site?action=SetSiteRewrite';
        $p_data = $this->GetKeyData();
        $p_data['siteName'] = $siteName;
        $p_data['data'] = $content;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function Getymlist($siteName) {
        // 使用标准宝塔API：GetDomain
        // 首先需要获取站点ID
        $site_list_url = $this->BT_PANEL . '/data?action=getData';
        $site_list_data = $this->GetKeyData();
        $site_list_data['table'] = 'sites';
        $site_list_result = $this->HttpPostCookie($site_list_url, $site_list_data);
        $site_list = json_decode($site_list_result, true);
        
        $site_id = '';
        if ($site_list && isset($site_list['data']) && is_array($site_list['data'])) {
            foreach ($site_list['data'] as $site) {
                if (isset($site['name']) && $site['name'] == $siteName) {
                    $site_id = isset($site['id']) ? $site['id'] : '';
                    break;
                }
            }
        }
        
        // 直接使用GetSiteDomains API获取域名列表（更可靠）
        $url2 = $this->BT_PANEL . '/site?action=GetSiteDomains';
        $p_data2 = $this->GetKeyData();
        $p_data2['id'] = $site_id;
        $p_data2['siteName'] = $siteName;
        
        $result2 = $this->HttpPostCookie($url2, $p_data2);
        $decoded2 = json_decode($result2, true);
        
        if (isset($decoded2['domains']) && is_array($decoded2['domains'])) {
            return array('status' => true, 'data' => $decoded2['domains']);
        }
        
        // 如果GetSiteDomains失败，尝试使用GetDomain
        $url = $this->BT_PANEL . '/site?action=GetDomain';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $site_id;
        $p_data['webname'] = $siteName;
        
        $result = $this->HttpPostCookie($url, $p_data);
        $decoded = json_decode($result, true);
        
        // 如果返回的是域名列表格式，转换为标准格式
        if (isset($decoded['domains']) && is_array($decoded['domains'])) {
            return array('status' => true, 'data' => $decoded['domains']);
        }
        
        return $decoded;
    }

    public function GetSiteDomains($id) {
        // 尝试获取站点名称，因为某些宝塔版本需要 webname 参数
        $siteName = $this->GetSiteName($id);
        
        $url = $this->BT_PANEL . '/site?action=GetDomain';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        if (!empty($siteName)) {
            $p_data['webname'] = $siteName;
        }
        
        $this->debug_log('GetSiteDomains请求参数: ' . print_r($p_data, true));
        
        $result = $this->HttpPostCookie($url, $p_data);
        $this->debug_log('GetSiteDomains原始响应: ' . $result);
        
        $decoded = json_decode($result, true);
        
        // 宝塔 GetDomain 返回格式通常是包含 domains 数组的
        if (isset($decoded['domains']) && is_array($decoded['domains'])) {
            return $decoded['domains'];
        }
        
        // 如果返回了错误信息且包含“参数无效”，尝试备选方案
        if (isset($decoded['status']) && $decoded['status'] === false && strpos($decoded['msg'], '参数无效') !== false) {
            $this->debug_log('GetDomain 失败，尝试备选 API: getData&table=domain');
            $url = $this->BT_PANEL . '/data?action=getData&table=domain';
            $p_data = $this->GetKeyData();
            $p_data['search'] = $id; // 这里的 search 通常是 pid (站点ID)
            $result = $this->HttpPostCookie($url, $p_data);
            $decoded = json_decode($result, true);
            
            if (isset($decoded['data']) && is_array($decoded['data'])) {
                return $decoded['data'];
            }
        }
        
        // 如果是直接返回数组（某些版本）
        if (is_array($decoded) && !isset($decoded['status'])) {
            return $decoded;
        }
        
        return $decoded;
    }

    public function urllist($id) {
        $url = $this->BT_PANEL . '/site?action=GetDomain';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function shell_add($shell) {
        $url = $this->BT_PANEL . '/crontab?action=AddCrontab';
        $p_data = $this->GetKeyData();
        $p_data['name'] = '系统任务';
        $p_data['type'] = 'day';
        $p_data['where1'] = '1';
        $p_data['hour'] = '1';
        $p_data['minute'] = '1';
        $p_data['week'] = '';
        $p_data['sType'] = 'toShell';
        $p_data['sBody'] = $shell;
        $p_data['save'] = '';
        $p_data['backupTo'] = 'localhost';
        $p_data['sName'] = '';
        $p_data['urladdress'] = '';
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function shell_del($id) {
        $url = $this->BT_PANEL . '/crontab?action=DelCrontab';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function GetCron() {
        $url = $this->BT_PANEL . '/crontab?action=GetCrontab';
        $p_data = $this->GetKeyData();
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    /**
     * 获取备份列表 - 使用宝塔 /data?action=getData 接口
     * @param int $type 0=网站备份 1=数据库备份
     * @param string $search 筛选条件，如站点ID或数据库ID
     */
    public function GetBackupList($type = 0, $search = '') {
        $url = $this->BT_PANEL . '/data?action=getData';
        $p_data = $this->GetKeyData();
        $p_data['table'] = 'backup';
        $p_data['limit'] = 200;
        $p_data['p'] = 1;
        $p_data['type'] = (string) $type;
        if ($search !== '') {
            $p_data['search'] = $search;
        }
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    /**
     * 创建网站备份
     */
    public function ToBackupSite($site_id) {
        $url = $this->BT_PANEL . '/site?action=ToBackup';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $site_id;
        $p_data['backstage'] = '1';  // 后台执行
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    /**
     * 创建数据库备份
     */
    public function ToBackupDatabase($db_id) {
        $url = $this->BT_PANEL . '/database?action=ToBackup';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $db_id;
        $p_data['backstage'] = '1';
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    /**
     * 删除备份 - 根据备份类型调用对应接口
     */
    public function DelBackupById($backup_id, $backup_type = 0) {
        if ($backup_type == 1) {
            $url = $this->BT_PANEL . '/database?action=DelBackup';
        } else {
            $url = $this->BT_PANEL . '/site?action=DelBackup';
        }
        $p_data = $this->GetKeyData();
        $p_data['id'] = $backup_id;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function Restore($file) {
        $url = $this->BT_PANEL . '/site?action=Recovery';
        $p_data = $this->GetKeyData();
        $p_data['file'] = $file;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function GetRewriteRules($id = '', $siteName = '') {
        // 调试：输出请求参数到文件
        $this->debug_log('GetRewriteRules方法被调用，参数: id=' . $id . ', siteName=' . $siteName);
        
        // 尝试使用不同的API路径
        $api_paths = array(
            '/site?action=GetRewriteList',
            '/site?action=GetRewriteLists',
            '/rewrite?action=GetRewrite'
        );
        
        foreach ($api_paths as $api_path) {
            $url = $this->BT_PANEL . $api_path;
            $p_data = $this->GetKeyData();
            
            // 如果提供了网站ID，添加到请求参数中
            if (!empty($id)) {
                $p_data['id'] = $id;
            }
            // 如果提供了网站名称，添加到请求参数中
            if (!empty($siteName)) {
                $p_data['siteName'] = $siteName;
            }
            
            $this->debug_log('使用API路径: ' . $api_path . '，参数: ' . json_encode($p_data));
            
            $result = $this->HttpPostCookie($url, $p_data);
            $decoded_result = json_decode($result, true);
            
            $this->debug_log('API响应 (' . $api_path . '): ' . print_r($decoded_result, true));
            
            // 检查API调用是否成功
            if ($decoded_result && isset($decoded_result['rules']) && is_array($decoded_result['rules'])) {
                $this->debug_log('API调用成功，处理rules列表，数量: ' . count($decoded_result['rules']));
                $rules = array();
                foreach ($decoded_result['rules'] as $rule) {
                    $name = '';
                    $content = '';
                    if (is_string($rule)) {
                        $name = $rule;
                        // 优化：不再预先获取内容，由前端按需获取
                        $content = ''; 
                    } else if (is_array($rule)) {
                        $name = isset($rule['name']) ? $rule['name'] : '';
                        $content = isset($rule['content']) ? $rule['content'] : '';
                        // 优化：如果内容为空，不再强制获取
                    }
                    if (!empty($name)) {
                        $rules[] = array('name' => $name, 'content' => $content);
                    }
                }
                return $rules;
            }
            
            // 检查是否返回了规则列表
            if ($decoded_result && is_array($decoded_result)) {
                // 如果返回的是 {"rewrite": [...], "default_list": [...]} 格式
                if (isset($decoded_result['rewrite']) && is_array($decoded_result['rewrite'])) {
                    $this->debug_log('API返回了rewrite列表，数量: ' . count($decoded_result['rewrite']));
                    $rules = array();
                    foreach ($decoded_result['rewrite'] as $name) {
                        // 优化：不再预先获取所有内容，由前端按需获取
                        $rules[] = array(
                            'name' => $name,
                            'content' => '' 
                        );
                    }
                    return $rules;
                }

                // 检查是否直接返回了包含规则的数组
                $rules = array();
                $is_rule_list = false;
                foreach ($decoded_result as $item) {
                    if (is_array($item) && isset($item['name'])) {
                        $name = $item['name'];
                        $content = isset($item['content']) ? $item['content'] : '';
                        // 优化：如果内容为空，不再强制获取
                        $rules[] = array('name' => $name, 'content' => $content);
                        $is_rule_list = true;
                    }
                }
                
                if ($is_rule_list) {
                    $this->debug_log('从数组中提取规则成功，数量: ' . count($rules));
                    return $rules;
                }
                
                // 检查是否返回了模板规则列表
                if (isset($decoded_result['template_rewrites']) && is_array($decoded_result['template_rewrites'])) {
                    $this->debug_log('API调用成功，返回模板规则数量: ' . count($decoded_result['template_rewrites']));
                    
                    // 构建规则列表
                    $rules = array();
                    foreach ($decoded_result['template_rewrites'] as $template) {
                        if (isset($template['name'])) {
                            // 优化：不再预先获取内容，由前端按需获取
                            $rules[] = array(
                                'name' => $template['name'],
                                'content' => ''
                            );
                        }
                    }
                    
                    $this->debug_log('构建规则成功，返回规则数量: ' . count($rules));
                    return $rules;
                }
            }
        }
        
        // 如果所有API调用都失败，返回空数组
        $this->debug_log('所有API调用都失败，返回空数组');
        return array();
    }
    
    // 获取站点信息
    public function GetSiteInfo($id = '') {
        // 调试：输出请求参数到文件
        $this->debug_log('GetSiteInfo方法被调用，参数: id=' . $id);
        
        // 尝试使用不同的API路径
        $api_paths = array(
            '/site?action=GetSiteInfo',
            '/site',
            '/web?action=GetSiteInfo',
            '/web'
        );
        
        foreach ($api_paths as $api_path) {
            $url = $this->BT_PANEL . $api_path;
            $p_data = $this->GetKeyData();
            
            // 如果提供了网站ID，添加到请求参数中
            if (!empty($id)) {
                $p_data['id'] = $id;
            }
            
            $this->debug_log('使用API路径: ' . $api_path);
            
            $result = $this->HttpPostCookie($url, $p_data);
            
            // 确保$result是字符串
            if (is_array($result)) {
                $this->debug_log('API返回数组而非字符串: ' . print_r($result, true));
                continue;
            }
            
            // 检查响应是否是JSON格式
            if (strpos($result, '{') === 0) {
                $decoded_result = json_decode($result, true);
                
                $this->debug_log('API响应: ' . print_r($decoded_result, true));
                
                // 检查API调用是否成功
                if ($decoded_result && isset($decoded_result['status']) && $decoded_result['status'] == true) {
                    $this->debug_log('API调用成功，返回站点信息');
                    return $decoded_result;
                }
            }
        }
        
        // 如果所有API调用都失败，返回false
        $this->debug_log('所有API调用都失败，返回false');
        return false;
    }
    
    // 获取当前伪静态规则
    public function GetCurrentRewriteRule($id = '', $siteName = '') {
        // 调试：输出请求参数到文件
        $this->debug_log('GetCurrentRewriteRule方法被调用，参数: id=' . $id . ', siteName=' . $siteName);
        
        // 首先尝试读取伪静态规则文件（优先级最高）
        if (!empty($id) || !empty($siteName)) {
            $this->debug_log('首先尝试读取伪静态规则文件');
            
            // 尝试使用伪静态规则文件路径
            // 注意：优先使用siteName，因为保存时使用的是siteName
            $possible_paths = array();
            if (!empty($siteName)) {
                $possible_paths[] = '/www/server/panel/vhost/rewrite/' . $siteName . '.conf';
                $possible_paths[] = '/www/server/nginx/conf/vhost/' . $siteName . '.conf';
            }
            if (!empty($id)) {
                $possible_paths[] = '/www/server/panel/vhost/rewrite/site_' . $id . '.conf';
                $possible_paths[] = '/www/server/panel/vhost/rewrite/' . $id . '.conf';
            }
            // 注意：不要添加硬编码的兼容性路径，这会导致返回错误的伪静态规则
            
            foreach ($possible_paths as $nginx_config_path) {
                // 尝试读取配置文件
                $url = $this->BT_PANEL . '/files?action=GetFileBody';
                $p_data = $this->GetKeyData();
                $p_data['path'] = $nginx_config_path;
                
                $this->debug_log('尝试读取配置文件: ' . $nginx_config_path);
                
                $result = $this->HttpPostCookie($url, $p_data);
                
                // 确保$result是字符串
                if (is_array($result)) {
                    $this->debug_log('读取配置文件返回数组而非字符串: ' . print_r($result, true));
                    continue;
                }
                
                if (strpos($result, '{') === 0) {
                    $decoded_result = json_decode($result, true);
                    
                    $this->debug_log('读取配置文件响应 (' . $nginx_config_path . '): ' . print_r($decoded_result, true));
                    
                    if ($decoded_result && isset($decoded_result['status']) && $decoded_result['status'] && isset($decoded_result['data'])) {
                        $config_content = $decoded_result['data'];
                        
                        // 如果是伪静态规则文件，直接返回内容（包括空内容）
                        // 注意：必须确保是当前用户的配置文件，而不是其他网站的配置
                        if (strpos($nginx_config_path, '/rewrite/') !== false) {
                            // 验证路径是否匹配当前用户的网站
                            $is_user_config = false;
                            if (!empty($id) && strpos($nginx_config_path, '/' . $id . '.conf') !== false) {
                                $is_user_config = true;
                            }
                            if (!empty($siteName) && strpos($nginx_config_path, '/' . $siteName . '.conf') !== false) {
                                $is_user_config = true;
                            }
                            
                            if ($is_user_config) {
                                $this->debug_log('从用户的伪静态规则文件中读取成功');
                                
                                // 识别伪静态规则名称
                                $rule_name = $this->identifyRewriteRuleName($config_content);
                                
                                return array(
                                    'name' => $rule_name,
                                    'content' => $config_content
                                );
                            } else {
                                $this->debug_log('跳过非用户配置文件: ' . $nginx_config_path);
                            }
                        }
                        
                        // 提取伪静态规则部分
                        if (preg_match('/\s*location\s+\/\s*\{[^}]*rewrite[^{}]*\}/is', $config_content, $matches)) {
                            $this->debug_log('从配置文件中提取伪静态规则成功');
                            return array(
                                'name' => 'current',
                                'content' => $matches[0]
                            );
                        }
                        
                        // 尝试提取整个server块
                        if (preg_match('/\s*server\s*\{[\s\S]*\}/is', $config_content, $matches)) {
                            $this->debug_log('从配置文件中提取server块成功');
                            return array(
                                'name' => 'current',
                                'content' => $matches[0]
                            );
                        }
                    }
                }
            }
        }
        
        // 如果读取文件失败，尝试使用API路径
        $this->debug_log('读取文件失败，尝试使用API路径');
        
        $api_paths = array(
            '/site?action=GetRewrite',
            '/site?action=GetSiteRewrite',
            '/rewrite?action=GetRewrite',
            '/site?action=GetSiteInfo'
        );
        
        foreach ($api_paths as $api_path) {
            $url = $this->BT_PANEL . $api_path;
            $p_data = $this->GetKeyData();
            
            // 如果提供了网站ID，添加到请求参数中
            if (!empty($id)) {
                $p_data['id'] = $id;
            }
            // 如果提供了网站名称，添加到请求参数中
            if (!empty($siteName)) {
                $p_data['siteName'] = $siteName;
            }
            
            $this->debug_log('使用API路径: ' . $api_path . '，参数: ' . json_encode($p_data));
            
            $result = $this->HttpPostCookie($url, $p_data);
            
            // 确保$result是字符串
            if (is_array($result)) {
                $this->debug_log('API返回数组而非字符串: ' . print_r($result, true));
                continue;
            }
            
            // 检查响应是否是JSON格式
            if (strpos($result, '{') === 0) {
                $decoded_result = json_decode($result, true);
                
                $this->debug_log('API响应 (' . $api_path . '): ' . print_r($decoded_result, true));
                
                // 检查API调用是否成功
                if ($decoded_result) {
                    // 检查不同的响应字段
                    if (isset($decoded_result['rewrite_content'])) {
                        $this->debug_log('API调用成功，返回当前伪静态规则');
                        return array(
                            'name' => 'current',
                            'content' => $decoded_result['rewrite_content']
                        );
                    }
                    
                    if (isset($decoded_result['content'])) {
                        $this->debug_log('API调用成功，返回当前伪静态规则（content字段）');
                        return array(
                            'name' => 'current',
                            'content' => $decoded_result['content']
                        );
                    }
                    
                    if (isset($decoded_result['rewrite'])) {
                        $this->debug_log('API调用成功，返回当前伪静态规则（rewrite字段）');
                        return array(
                            'name' => 'current',
                            'content' => $decoded_result['rewrite']
                        );
                    }
                    
                    if (isset($decoded_result['data']) && isset($decoded_result['data']['rewrite'])) {
                        $this->debug_log('API调用成功，返回当前伪静态规则（data.rewrite字段）');
                        return array(
                            'name' => 'current',
                            'content' => $decoded_result['data']['rewrite']
                        );
                    }
                }
            } else {
                $this->debug_log('API响应不是JSON格式: ' . substr($result, 0, 100) . '...');
            }
        }
        
        // 如果所有方法都失败，返回空数组
        $this->debug_log('所有方法都失败，返回空数组');
        return array();
    }
    
    // 识别伪静态规则名称
    private function identifyRewriteRuleName($content) {
        // 转换为小写进行匹配
        $content_lower = strtolower($content);
        
        // 识别规则名称
        if (strpos($content_lower, 'discuz') !== false || strpos($content_lower, 'portal.php') !== false || strpos($content_lower, 'forum.php') !== false) {
            return 'discuz';
        } elseif (strpos($content_lower, 'wordpress') !== false || strpos($content_lower, 'wp-') !== false) {
            return 'wordpress';
        } elseif (strpos($content_lower, 'thinkphp') !== false || strpos($content_lower, 'index.php?s=') !== false) {
            return 'thinkphp';
        } elseif (strpos($content_lower, 'laravel') !== false || strpos($content_lower, 'public/index.php') !== false) {
            return 'laravel';
        } elseif (strpos($content_lower, 'dedecms') !== false || strpos($content_lower, 'plus/list.php') !== false) {
            return 'dedecms';
        } else {
            return 'default';
        }
    }
    
    // 获取伪静态规则内容
    public function GetRewriteContent($rule_name) {
        // 首先尝试使用宝塔API获取规则内容
        $api_paths = array(
            '/site?action=GetRewriteRule',
            '/site?action=GetRewrite',
        );
        
        foreach ($api_paths as $api_path) {
            $url = $this->BT_PANEL . $api_path;
            $p_data = $this->GetKeyData();
            $p_data['name'] = $rule_name;
            
            $result = $this->HttpPostCookie($url, $p_data);
            $decoded_result = json_decode($result, true);
            
            if ($decoded_result && isset($decoded_result['status']) && $decoded_result['status']) {
                if (isset($decoded_result['data']) && !empty($decoded_result['data'])) {
                    return $decoded_result['data'];
                }
                if (isset($decoded_result['content']) && !empty($decoded_result['content'])) {
                    return $decoded_result['content'];
                }
            }
        }
        
        // 尝试不同的规则文件路径
        $ws_options = array('nginx', 'apache');
        
        foreach ($ws_options as $ws) {
            // 构建规则文件路径
            $file_path = '/www/server/panel/rewrite/' . $ws . '/' . $rule_name . '.conf';
            
            // 尝试读取规则文件内容
            $url = $this->BT_PANEL . '/files?action=GetFileBody';
            $p_data = $this->GetKeyData();
            $p_data['path'] = $file_path;
            $result = $this->HttpPostCookie($url, $p_data);
            $decoded_result = json_decode($result, true);
            
            if ($decoded_result && isset($decoded_result['status']) && $decoded_result['status'] && isset($decoded_result['data'])) {
                return $decoded_result['data'];
            }
        }
        
        return '';
    }

    public function shell_zx($id) {
        $url = $this->BT_PANEL . '/crontab?action=StartCrontab';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    /** 设置计划任务状态 1=启用 0=禁用 (宝塔API方法名: set_cron_status) */
    public function SetCrontabStatus($id, $status) {
        $url = $this->BT_PANEL . '/crontab?action=set_cron_status';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $p_data['status'] = $status ? '1' : '0';
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function shell_list($name = '') {
        $url = $this->BT_PANEL . '/crontab?action=GetCrontab';
        $p_data = $this->GetKeyData();
        $result = $this->HttpPostCookie($url, $p_data);
        $data = json_decode($result, true);
        
        // 如果指定了名称，查找对应的任务
        if (!empty($name) && isset($data['data'])) {
            foreach ($data['data'] as $task) {
                if (isset($task['name']) && $task['name'] == $name) {
                    return ['code' => 1, 'id' => $task['id']];
                }
            }
        }
        
        return $data;
    }

    public function shell_log($id) {
        $url = $this->BT_PANEL . '/crontab?action=GetLogs';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function shell_yx($shell, $cljgty = true) {
        // 执行指定Shell命令，通过创建定时任务的方式
        if (!$shell) return ['code' => 0, 'msg' => '脚本错误！'];
        
        // 先检查是否有同名任务
        $re_rw = $this->shell_list('ELEML TOD的shell脚本');
        if (isset($re_rw['code']) && $re_rw['code']) {
            $rs_del = $this->shell_del($re_rw['id']);
            if (!isset($rs_del['status']) || !$rs_del['status']) {
                return ['code' => 0, 'msg' => '原任务删除失败，返回：' . (isset($rs_del['msg']) ? $rs_del['msg'] : '')];
            }
        }
        
        // 添加新任务
        $re_add = $this->shell_add($shell);
        if (!isset($re_add['status']) || !$re_add['status']) {
            return ['code' => 0, 'msg' => '任务添加失败，返回：' . (isset($re_add['msg']) ? $re_add['msg'] : '')];
        }
        
        // 执行任务
        $re_zx = $this->shell_zx($re_add['id']);
        if (!isset($re_zx['status']) || !$re_zx['status']) {
            $this->shell_del($re_add['id']);
            return ['code' => 0, 'msg' => '任务执行失败，返回：' . (isset($re_zx['msg']) ? $re_zx['msg'] : '')];
        }
        
        // 获取执行结果
        $re_jg = [];
        if ($cljgty) {
            sleep(1); // 等待执行处理结果
            $re_jg = $this->shell_log($re_add['id']);
            if (!isset($re_jg['code']) || !$re_jg['code']) {
                $this->shell_del($re_add['id']);
                return $re_jg;
            }
        }
        
        // 删除临时任务
        $this->shell_del($re_add['id']);
        
        return ['code' => 1, 'msg' => isset($re_jg['msg']) ? $re_jg['msg'] : ''];
    }

    public function sjlist($type) {
        $url = $this->BT_PANEL . '/data?action=getData';
        $p_data = $this->GetKeyData();
        $p_data['table'] = $type;
        $p_data['limit'] = 100;
        $p_data['p'] = 1;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function SetHasPwd($siteName, $username, $password) {
        $url = $this->BT_PANEL . '/site?action=SetHasPwd';
        $p_data = $this->GetKeyData();
        $p_data['siteName'] = $siteName;
        $p_data['username'] = $username;
        $p_data['password'] = $password;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function CloseHasPwd($siteName) {
        $url = $this->BT_PANEL . '/site?action=CloseHasPwd';
        $p_data = $this->GetKeyData();
        $p_data['siteName'] = $siteName;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function GetHasPwd($siteName) {
        $url = $this->BT_PANEL . '/site?action=GetHasPwd';
        $p_data = $this->GetKeyData();
        $p_data['siteName'] = $siteName;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function SetIndex($id, $index) {
        // 将多行文本转换为逗号分隔的字符串
        $index = str_replace(array("\r\n", "\r", "\n"), ',', $index);
        // 去除空格和多余的逗号（与宝塔面板的实现一致）
        $index = str_replace(' ', '', $index);
        $index = preg_replace('/,+/', ',', $index);
        $index = trim($index, ',');
        
        // 使用正确的 API 路径和参数名
        $url = $this->BT_PANEL . '/site?action=SetIndex';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $p_data['Index'] = $index; // 注意：参数名应该是大写的 Index，不是小写的 index
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function SetSiteRunPath($id, $path) {
        $url = $this->BT_PANEL . '/site?action=SetSiteRunPath';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $p_data['runPath'] = $path;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    /**
     * 获取网站运行目录和防跨站设置（宝塔API: GetDirUserINI）
     */
    public function GetDirUserINI($id, $path) {
        $url = $this->BT_PANEL . '/site?action=GetDirUserINI';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $p_data['path'] = $path;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function SetRewrite($id, $type, $content) {
        // 写入调试日志
        $this->debug_log('SetRewrite方法被调用，参数: id=' . $id . ', type=' . $type . ', content=' . $content);
        
        // 获取网站名称
        $site_name = $this->GetSiteName($id);
        $this->debug_log('获取到的网站名称: ' . $site_name);
        
        if (empty($site_name)) {
            $this->debug_log('错误: 无法获取网站名称');
            return array('status' => false, 'msg' => '无法获取网站名称');
        }
        
        // 如果内容为空，尝试删除伪静态配置文件
        if (empty($content)) {
            $this->debug_log('内容为空，尝试删除伪静态配置');
            return $this->DeleteRewriteConfig($site_name);
        }
        
        $rewrite_file = '/www/server/panel/vhost/rewrite/' . $site_name . '.conf';
        $this->debug_log('保存路径: ' . $rewrite_file);
        
        // 第一步：先创建文件（如果不存在）
        $this->debug_log('第一步：创建文件（如果不存在）');
        $url = $this->BT_PANEL . '/files?action=CreateFile';
        $p_data = $this->GetKeyData();
        $p_data['path'] = $rewrite_file;
        
        $result = $this->HttpPostCookie($url, $p_data);
        $decoded_result = json_decode($result, true);
        $this->debug_log('CreateFile响应: ' . print_r($decoded_result, true));
        // 创建文件的结果不影响后续操作，继续保存内容
        
        // 第二步：使用SaveFileBody API保存伪静态文件内容
        $this->debug_log('第二步：保存文件内容');
        $url = $this->BT_PANEL . '/files?action=SaveFileBody';
        $p_data = $this->GetKeyData();
        $p_data['path'] = $rewrite_file;
        $p_data['data'] = $content;
        $p_data['encoding'] = 'utf-8';
        $p_data['force'] = '1'; // 强制保存，跳过nginx配置检查
        
        $result = $this->HttpPostCookie($url, $p_data);
        $decoded_result = json_decode($result, true);
        
        $this->debug_log('SaveFileBody响应: ' . print_r($decoded_result, true));
        
        // 检查API调用是否成功
        if ($decoded_result && isset($decoded_result['status']) && $decoded_result['status']) {
            $this->debug_log('API调用成功');
            return $decoded_result;
        }
        
        // 如果失败，返回错误信息
        $error_msg = isset($decoded_result['msg']) ? $decoded_result['msg'] : '设置伪静态规则失败';
        $this->debug_log('API调用失败: ' . $error_msg);
        return array('status' => false, 'msg' => $error_msg);
    }
    
    /**
     * 删除网站伪静态配置
     * @param string $site_name 网站名称
     * @return array 操作结果
     */
    public function DeleteRewriteConfig($site_name) {
        $this->debug_log('DeleteRewriteConfig方法被调用，site_name=' . $site_name);
        
        $rewrite_file = '/www/server/panel/vhost/rewrite/' . $site_name . '.conf';
        $this->debug_log('清空配置文件内容: ' . $rewrite_file);
        
        // 方法1: 使用SaveFileBody保存空内容（彻底清空）
        $url = $this->BT_PANEL . '/files?action=SaveFileBody';
        $p_data = $this->GetKeyData();
        $p_data['path'] = $rewrite_file;
        $p_data['data'] = '';  // 空内容
        $p_data['encoding'] = 'utf-8';
        $p_data['force'] = '1'; // 强制保存
        
        $result = $this->HttpPostCookie($url, $p_data);
        $decoded_result = json_decode($result, true);
        
        $this->debug_log('SaveFileBody(清空)响应: ' . print_r($decoded_result, true));
        
        if ($decoded_result && isset($decoded_result['status']) && $decoded_result['status']) {
            $this->debug_log('清空配置文件成功');
            return array('status' => true, 'msg' => '已清空伪静态');
        }
        
        // 如果文件不存在，也算成功
        if (isset($decoded_result['msg']) && (strpos($decoded_result['msg'], '不存在') !== false || strpos($decoded_result['msg'], 'not found') !== false || strpos($decoded_result['msg'], '找不到') !== false)) {
            $this->debug_log('配置文件不存在，视为成功');
            return array('status' => true, 'msg' => '已清空伪静态');
        }
        
        $error_msg = isset($decoded_result['msg']) ? $decoded_result['msg'] : '清空伪静态失败';
        $this->debug_log('清空伪静态失败: ' . $error_msg);
        return array('status' => false, 'msg' => $error_msg);
    }
    
    // 获取网站名称
    public function GetSiteName($id) {
        $url = $this->BT_PANEL . '/data?action=getData&table=sites';
        $p_data = $this->GetKeyData();
        // 增加limit参数获取更多网站，避免分页导致ID找不到
        $p_data['limit'] = '1000';
        $p_data['where'] = 'id=' . $id;
        $result = $this->HttpPostCookie($url, $p_data);
        
        // 确保$result是字符串
        if (is_array($result)) {
            $this->debug_log('GetSiteName返回数组而非字符串: ' . print_r($result, true));
            return '';
        }
        
        $decoded_result = json_decode($result, true);
        if (isset($decoded_result['data']) && is_array($decoded_result['data']) && !empty($decoded_result['data'])) {
            // 遍历结果，找到匹配 ID 的站点，避免 where 条件失效时返回错误站点
            foreach ($decoded_result['data'] as $site) {
                if (isset($site['id']) && $site['id'] == $id) {
                    return $site['name'];
                }
            }
        }
        return '';
    }
    
    /**
     * 通过域名获取网站ID
     * 用于迁移后通过域名找到新的网站ID
     * @param string $domain 域名
     * @return int 网站ID，找不到返回0
     */
    public function GetSiteIdByDomain($domain) {
        $this->debug_log('GetSiteIdByDomain方法被调用，域名: ' . $domain);
        
        if (empty($domain)) {
            $this->debug_log('域名为空');
            return 0;
        }
        
        $url = $this->BT_PANEL . '/data?action=getData&table=sites';
        $p_data = $this->GetKeyData();
        // 增加limit参数获取更多网站
        $p_data['limit'] = '1000';
        
        $result = $this->HttpPostCookie($url, $p_data);
        $decoded_result = json_decode($result, true);
        
        if (isset($decoded_result['data']) && is_array($decoded_result['data'])) {
            foreach ($decoded_result['data'] as $site) {
                if (isset($site['name']) && $site['name'] == $domain) {
                    $this->debug_log('找到网站ID: ' . $site['id']);
                    return intval($site['id']);
                }
            }
        }
        
        $this->debug_log('未找到网站: ' . $domain);
        return 0;
    }

    /**
     * 设置网站伪静态规则（通过网站名称）
     * @param string $site_name 网站名称
     * @param string $content 伪静态规则内容
     * @return array API响应结果
     */
    public function SetRewriteRule($site_name, $content) {
        $this->debug_log('SetRewriteRule方法被调用，参数: site_name=' . $site_name);
        
        // 方法1: 尝试使用SetRewrite API直接设置
        $url = $this->BT_PANEL . '/site?action=SetRewrite';
        $p_data = $this->GetKeyData();
        $p_data['siteName'] = $site_name;
        $p_data['type'] = 'nginx';
        $p_data['content'] = $content;
        
        $this->debug_log('使用SetRewrite API: siteName=' . $site_name);
        
        $result = $this->HttpPostCookie($url, $p_data);
        $decoded_result = json_decode($result, true);
        
        $this->debug_log('SetRewrite API响应: ' . print_r($decoded_result, true));
        
        if ($decoded_result && isset($decoded_result['status']) && $decoded_result['status']) {
            return $decoded_result;
        }
        
        // 方法2: 尝试使用SetRewriteLists API
        $url2 = $this->BT_PANEL . '/site?action=SetRewriteLists';
        $p_data2 = $this->GetKeyData();
        $sites = array(
            array(
                'id' => 0,
                'name' => $site_name,
                'file' => '/www/server/panel/vhost/rewrite/' . $site_name . '.conf'
            )
        );
        $p_data2['sites'] = json_encode($sites);
        $p_data2['rewrite_data'] = $content;
        $p_data2['site_type'] = 'php';
        
        $this->debug_log('使用SetRewriteLists API');
        
        $result2 = $this->HttpPostCookie($url2, $p_data2);
        $decoded_result2 = json_decode($result2, true);
        
        $this->debug_log('SetRewriteLists API响应: ' . print_r($decoded_result2, true));
        
        if ($decoded_result2 && isset($decoded_result2['status']) && $decoded_result2['status']) {
            return $decoded_result2;
        }
        if (is_array($decoded_result2) && isset($decoded_result2[0]['status']) && $decoded_result2[0]['status']) {
            return array('status' => true, 'msg' => '伪静态设置成功');
        }
        
        // 方法3: 直接写入伪静态配置文件
        $rewrite_file = '/www/server/panel/vhost/rewrite/' . $site_name . '.conf';
        $this->debug_log('尝试直接写入配置文件: ' . $rewrite_file);
        
        // 使用宝塔的文件管理API写入文件
        $url3 = $this->BT_PANEL . '/files?action=SetFileContent';
        $p_data3 = $this->GetKeyData();
        $p_data3['path'] = $rewrite_file;
        $p_data3['content'] = $content;
        $p_data3['encoding'] = 'utf-8';
        
        $result3 = $this->HttpPostCookie($url3, $p_data3);
        $decoded_result3 = json_decode($result3, true);
        
        $this->debug_log('SetFileContent API响应: ' . print_r($decoded_result3, true));
        
        if ($decoded_result3 && isset($decoded_result3['status']) && $decoded_result3['status']) {
            // 重载Nginx配置
            $this->ReloadNginx();
            return array('status' => true, 'msg' => '伪静态设置成功');
        }
        
        // 如果所有方法都失败，返回错误
        return array('status' => false, 'msg' => '设置伪静态规则失败');
    }
    
    // 重载Nginx配置
    public function ReloadNginx() {
        $url = $this->BT_PANEL . '/system?action=ReloadNginx';
        $p_data = $this->GetKeyData();
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function SetSSL($id, $type, $key, $cert) {
        $url = $this->BT_PANEL . '/site?action=SetSSL';
        $p_data = $this->GetKeyData();
        
        // 获取站点名称，部分宝塔版本 SetSSL 需要 siteName 而不是 id
        // 且必须包含 csr 参数而非 cert 参数，否则可能返回 404
        $site_name = $this->GetSiteName($id);
        if ($site_name) {
            $p_data['siteName'] = $site_name;
        }
        
        $p_data['id'] = $id;
        $p_data['type'] = $type;
        $p_data['key'] = $key;
        $p_data['csr'] = $cert;
        
        $this->debug_log("SetSSL请求参数: " . print_r($p_data, true));
        
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function GetSSL($site_name) {
        // 使用标准宝塔API：GetSSL
        $url = $this->BT_PANEL . '/site?action=GetSSL';
        $p_data = $this->GetKeyData();
        $p_data['siteName'] = $site_name;  // 应该传递siteName，不是id
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function SetHttpToHttps($site_name) {
        // 使用标准宝塔API：HttpToHttps（开启强制HTTPS）
        $url = $this->BT_PANEL . '/site?action=HttpToHttps';
        $p_data = $this->GetKeyData();
        $p_data['siteName'] = $site_name;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function CloseHttpToHttps($site_name) {
        // 使用标准宝塔API：CloseToHttps（关闭强制HTTPS）
        $url = $this->BT_PANEL . '/site?action=CloseToHttps';
        $p_data = $this->GetKeyData();
        $p_data['siteName'] = $site_name;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function GetHttpToHttps($site_name) {
        // 通过GetSiteInfo获取强制HTTPS状态
        $siteInfo = $this->GetSiteInfo($site_name);
        if ($siteInfo && isset($siteInfo['status']) && $siteInfo['status'] === true) {
            return [
                'status' => true,
                'data' => [
                    'httpTohttps' => !empty($siteInfo['data']['httpTohttps']) || !empty($siteInfo['httpTohttps'])
                ]
            ];
        }
        return ['status' => false, 'msg' => '获取失败'];
    }

    public function CloseSSLConf($site_name) {
        // 使用标准宝塔API：CloseSSLConf（关闭SSL）
        $url = $this->BT_PANEL . '/site?action=CloseSSLConf';
        $p_data = $this->GetKeyData();
        $p_data['siteName'] = $site_name;
        // 确保siteName不为空
        if (empty($site_name)) {
            $this->debug_log('CloseSSLConf错误：siteName为空');
            return array('status' => false, 'msg' => '站点名称不能为空');
        }
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function GetSSLCerts() {
        $url = $this->BT_PANEL . '/ssl';
        $p_data = $this->GetKeyData();
        $p_data['action'] = 'get_cert_list';
        $p_data['cert_type'] = '0'; // 0表示所有类型证书
        $p_data['p'] = '1'; // 页码
        $p_data['limit'] = '100'; // 每页数量
        
        // 添加调试信息
        $this->debug_log('GetSSLCerts请求参数: ' . print_r($p_data, true));
        $this->debug_log('GetSSLCerts请求URL: ' . $url);
        
        $result = $this->HttpPostCookie($url, $p_data);
        
        // 添加调试信息
        $this->debug_log('GetSSLCerts响应: ' . $result);
        
        return json_decode($result, true);
    }
    
    public function ApplyCertificate($site_name, $brand, $auth_type, $auth_to, $domains, $site_id = '') {
        // 获取认证参数
        $key_data = $this->GetKeyData();
        
        // 将domains转换为JSON数组格式
        $domains_array = json_decode($domains, true);
        if (!is_array($domains_array)) {
            $domains_array = explode(',', $domains);
            $domains_array = array_map('trim', $domains_array);
            // 移除空值
            $domains_array = array_filter($domains_array);
        }
        
        // 验证域名列表
        if (empty($domains_array) || count($domains_array) == 0) {
            return array('status' => false, 'msg' => '请至少选择一个域名');
        }
        
        // 统一使用 /acme?action=apply_cert_api 接口
        // 这个接口支持 LiteSSL 和 Let's Encrypt，通过 ca 参数区分
        $url = $this->BT_PANEL . '/acme?action=apply_cert_api';
        
        // 需要传递站点ID
        $final_site_id = $site_id;
        if (empty($final_site_id)) {
            // 如果没有提供site_id，尝试通过site_name获取
            // 使用宝塔API获取站点列表
            $url_list = $this->BT_PANEL . '/data?action=getData';
            $p_data_list = $this->GetKeyData();
            $p_data_list['table'] = 'sites';
            $p_data_list['search'] = $site_name;
            $p_data_list['limit'] = 100;
            $p_data_list['p'] = 1;
            $site_list_result = $this->HttpPostCookie($url_list, $p_data_list);
            $site_list = json_decode($site_list_result, true);
            
            if ($site_list && isset($site_list['data']) && is_array($site_list['data'])) {
                foreach ($site_list['data'] as $site) {
                    if (isset($site['name']) && $site['name'] == $site_name) {
                        $final_site_id = isset($site['id']) ? $site['id'] : '';
                        break;
                    }
                }
            }
        }
        
        if (empty($final_site_id)) {
            return array('status' => false, 'msg' => '无法获取站点ID，请确保站点存在');
        }
        
        // 构建请求参数
        $p_data = array(
            'request_time' => $key_data['request_time'],
            'request_token' => $key_data['request_token'],
            'domains' => json_encode($domains_array),
            'auth_type' => ($auth_type == 'file' || $auth_type == 'http') ? 'http' : 'dns',
            'auth_to' => $final_site_id,  // auth_to 应该是站点ID（数字），不是路径
            'auto_wildcard' => '0',
            'id' => $final_site_id  // 站点ID
        );
        
        // 根据证书品牌设置 ca 参数
        if ($brand == 'LiteSSL' || $brand == 'litessl') {
            $p_data['ca'] = 'litessl';  // 指定使用 LiteSSL
        } else {
            // Let's Encrypt 可以不传递 ca 参数，或者传递 'letsencrypt'
            // 不传递 ca 参数时，默认使用 Let's Encrypt
            // $p_data['ca'] = 'letsencrypt';  // 可选，不传递时默认就是 Let's Encrypt
        }
        
        // DNS验证需要dnsapi参数
        if ($auth_type != 'file' && $auth_type != 'http') {
            $p_data['dnsapi'] = $auth_type;
        }
        
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function DeployCertificate($site_name, $cert_hash = '') {
        // 使用标准宝塔API：SetSSLConf
        $url = $this->BT_PANEL . '/site?action=SetSSLConf';
        $p_data = $this->GetKeyData();
        $p_data['siteName'] = $site_name;
        if (!empty($cert_hash)) {
            $p_data['hash'] = $cert_hash;
        }
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function RenewCertificate($site_name, $domain = '') {
        // 使用标准宝塔API：Renew_SSL
        $url = $this->BT_PANEL . '/site?action=Renew_SSL';
        $p_data = $this->GetKeyData();
        $p_data['siteName'] = $site_name;
        if (!empty($domain)) {
            $p_data['domain'] = $domain;
        }
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function DownloadCertificate($cert_hash) {
        // 使用标准宝塔API：downloadCRT
        $url = $this->BT_PANEL . '/site?action=downloadCRT';
        $p_data = $this->GetKeyData();
        $p_data['hash'] = $cert_hash;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function DeleteCertificate($cert_hash) {
        $this->debug_log('DeleteCertificate 开始: hash=' . $cert_hash);
        
        if (empty($cert_hash)) {
            return array('status' => false, 'msg' => '证书hash不能为空');
        }
        
        // 1. 获取证书信息
        $certList = $this->GetSSLCertList();
        $certInfo = null;
        
        if (is_array($certList)) {
            foreach ($certList as $cert) {
                if (isset($cert['hash']) && $cert['hash'] == $cert_hash) {
                    $certInfo = $cert;
                    break;
                }
            }
        }
        
        if (!$certInfo) {
            $this->debug_log('证书不存在');
            return array('status' => false, 'msg' => '证书不存在');
        }
        
        $certId = isset($certInfo['id']) ? $certInfo['id'] : '';
        $certPath = isset($certInfo['path']) ? $certInfo['path'] : '';
        $certName = isset($certInfo['subject']) ? $certInfo['subject'] : '';
        
        $this->debug_log('证书信息: id=' . $certId . ', path=' . $certPath . ', name=' . $certName);
        
        // 2. 方法1: 使用 remove_cloud_cert API (新API)
        $this->debug_log('方法1: 使用 remove_cloud_cert API');
        $url = $this->BT_PANEL . '/ssl?action=remove_cloud_cert';
        $p_data = $this->GetKeyData();
        $p_data['ssl_hash'] = $cert_hash;
        $p_data['local'] = '1';
        
        $result = $this->HttpPostCookie($url, $p_data);
        $decoded = json_decode($result, true);
        $this->debug_log('remove_cloud_cert 结果: ' . print_r($decoded, true));
        
        // 验证删除结果
        $certList = $this->GetSSLCertList();
        $still_exists = false;
        if (is_array($certList)) {
            foreach ($certList as $cert) {
                if (isset($cert['hash']) && $cert['hash'] == $cert_hash) {
                    $still_exists = true;
                    break;
                }
            }
        }
        
        if (!$still_exists) {
            $this->debug_log('remove_cloud_cert 删除成功');
            return array('status' => true, 'msg' => '删除成功');
        }
        
        // 3. 方法2: 使用 RemoveCert API (旧API)
        $this->debug_log('方法2: 使用 RemoveCert API');
        
        // 处理证书名称（去掉*.前缀）
        $certNameClean = $certName;
        if (!empty($certNameClean) && strpos($certNameClean, '*.') === 0) {
            $certNameClean = substr($certNameClean, 2);
        }
        
        if (!empty($certNameClean)) {
            $url2 = $this->BT_PANEL . '/ssl?action=RemoveCert';
            $p_data2 = $this->GetKeyData();
            $p_data2['certName'] = $certNameClean;
            
            $result2 = $this->HttpPostCookie($url2, $p_data2);
            $decoded2 = json_decode($result2, true);
            $this->debug_log('RemoveCert 结果: ' . print_r($decoded2, true));
        }
        
        // 4. 方法3: 直接删除证书目录
        $this->debug_log('方法3: 直接删除证书目录');
        
        if (!empty($certPath)) {
            $del_result = $this->DeleteDir($certPath);
            $this->debug_log('DeleteDir 结果: ' . print_r($del_result, true));
        }
        
        // 同时删除 /www/server/panel/vhost/ssl/ 目录下的证书
        if (!empty($certNameClean)) {
            $ssl_path = '/www/server/panel/vhost/ssl/' . $certNameClean;
            $del_result2 = $this->DeleteDir($ssl_path);
            $this->debug_log('DeleteDir (ssl) 结果: ' . print_r($del_result2, true));
        }
        
        // 5. 最终验证
        $certList = $this->GetSSLCertList();
        $still_exists = false;
        if (is_array($certList)) {
            foreach ($certList as $cert) {
                if (isset($cert['hash']) && $cert['hash'] == $cert_hash) {
                    $still_exists = true;
                    break;
                }
            }
        }
        
        if (!$still_exists) {
            $this->debug_log('删除成功');
            return array('status' => true, 'msg' => '删除成功');
        }
        
        $this->debug_log('所有方法都失败');
        return array('status' => false, 'msg' => '删除失败，请尝试在宝塔面板中手动删除');
    }
    
    public function GetSSLCertList($cert_type = '0', $p = 1, $limit = 100) {
        // 使用标准宝塔API获取证书列表
        $url = $this->BT_PANEL . '/ssl';
        $p_data = $this->GetKeyData();
        $p_data['action'] = 'get_cert_list';
        $p_data['cert_type'] = $cert_type; // 0=所有, 1=Let's Encrypt, 2=其他
        $p_data['p'] = $p;
        $p_data['limit'] = $limit;
        $result = $this->HttpPostCookie($url, $p_data);
        $decoded_result = json_decode($result, true);
        
        // 处理不同的返回格式，确保返回一个证书列表数组
        if (is_array($decoded_result)) {
            if (isset($decoded_result['data']['list']) && is_array($decoded_result['data']['list'])) {
                return $decoded_result['data']['list'];
            } elseif (isset($decoded_result['data']) && is_array($decoded_result['data'])) {
                return $decoded_result['data'];
            } elseif (isset($decoded_result[0]) && is_array($decoded_result[0])) {
                return $decoded_result;
            }
        }
        
        return array();
    }
    
    /**
     * 获取证书详细信息
     * @param string $cert_hash 证书hash值
     * @return array|false 证书信息或false
     */
    public function GetCertInfo($cert_hash) {
        if (empty($cert_hash)) {
            return false;
        }
        
        // 使用标准宝塔API获取证书信息
        $url = $this->BT_PANEL . '/ssl?action=get_cert_info';
        $p_data = $this->GetKeyData();
        $p_data['hash'] = $cert_hash;
        
        $result = $this->HttpPostCookie($url, $p_data);
        $decoded_result = json_decode($result, true);
        
        $this->debug_log('GetCertInfo API结果: ' . print_r($decoded_result, true));
        
        if (is_array($decoded_result)) {
            return $decoded_result;
        }
        
        return false;
    }
    
    public function GetSSLCertificateStatus($certId = '', $domain = '') {
        $certList = $this->GetSSLCertList('0', 1, 100);
        
        if (is_array($certList)) {
            $list = $certList;

            // 查找指定的证书
            $targetCert = null;
            foreach ($list as $cert) {
                if (!empty($certId) && isset($cert['id']) && $cert['id'] == $certId) {
                    $targetCert = $cert;
                    break;
                }
                if (!empty($domain) && isset($cert['dns']) && is_array($cert['dns'])) {
                    foreach ($cert['dns'] as $dns) {
                        if (strpos($dns, $domain) !== false) {
                            $targetCert = $cert;
                            break 2;
                        }
                    }
                }
            }
            
            if ($targetCert) {
                // 构建证书状态信息
                $certStatus = array(
                    'id' => isset($targetCert['id']) ? $targetCert['id'] : '',
                    'domain' => isset($targetCert['subject']) ? $targetCert['subject'] : '',
                    'type' => isset($targetCert['info']['dns']) ? (count($targetCert['info']['dns']) > 1 ? 'wildcard' : 'single') : '',
                    'brand' => isset($targetCert['info']['issuer']) ? $targetCert['info']['issuer'] : '',
                    'status' => 'active', // 假设证书状态为激活
                    'starttime' => isset($targetCert['info']['notBefore']) ? $targetCert['info']['notBefore'] : '',
                    'endtime' => isset($targetCert['info']['notAfter']) ? $targetCert['info']['notAfter'] : '',
                    'apply_time' => isset($targetCert['create_time']) ? date('Y-m-d H:i:s', $targetCert['create_time']) : '',
                    'progress' => array(),
                    'validity_period' => '',
                    'days_remaining' => 0
                );
                
                // 计算有效期和剩余天数
                if (isset($targetCert['info']['notBefore']) && isset($targetCert['info']['notAfter'])) {
                    $starttime = strtotime($targetCert['info']['notBefore']);
                    $endtime = strtotime($targetCert['info']['notAfter']);
                    $now = time();
                    
                    if ($starttime && $endtime) {
                        $certStatus['validity_period'] = $targetCert['info']['notBefore'] . ' 至 ' . $targetCert['info']['notAfter'];
                        $certStatus['days_remaining'] = max(0, ceil(($endtime - $now) / (24 * 3600)));
                    }
                }
                
                return array(
                    'status' => true,
                    'data' => $certStatus
                );
            }
        }
        
        return array(
            'status' => false,
            'msg' => '未找到指定的证书信息'
        );
    }

    public function SetHotlink($siteName, $enable, $domains, $exts) {
        // 优先尝试 API
        $url = $this->BT_PANEL . '/site?action=SetSecurity';
        $p_data = $this->GetKeyData();
        $p_data['siteName'] = $siteName;
        $p_data['status'] = $enable == 'true' ? 'true' : 'false';
        $p_data['name'] = 'referer';
        $p_data['url'] = $domains;
        $p_data['type'] = 'URI';
        $p_data['exts'] = $exts;
        
        $this->debug_log('SetHotlink请求URL: ' . $url);
        $result = $this->HttpPostCookie($url, $p_data);
        $this->debug_log('SetHotlink响应: ' . $result);
        
        $decoded = json_decode($result, true);
        
        // 如果API调用成功，直接返回
        if ($decoded && isset($decoded['status']) && ($decoded['status'] === true || $decoded['status'] === 'true' || $decoded['status'] === 1)) {
            return $decoded;
        }
        
        // 如果API调用失败（404或参数错误），尝试修改配置文件
        $this->debug_log('SetHotlink API失败，尝试修改配置文件');
        return $this->SetHotlinkByConfig($siteName, $enable, $domains, $exts);
    }

    public function SetHotlinkByConfig($siteName, $enable, $domains, $exts) {
        $configFile = '/www/server/panel/vhost/nginx/' . $siteName . '.conf';
        $fileContent = $this->GetFileContent($configFile);
        
        if (!$fileContent || !isset($fileContent['status']) || $fileContent['status'] !== true) {
            return array('status' => false, 'msg' => '无法读取配置文件');
        }
        
        $content = $fileContent['data'];
        
        // 处理后缀格式：把逗号分隔转为竖线分隔
        $exts = str_replace(',', '|', $exts);
        
        // 构造新的防盗链配置
        $hotlinkConf = '';
        if ($enable == 'true') {
            // 处理域名：把换行符转为为空格
            $domains = str_replace(array("\r\n", "\r", "\n"), ' ', $domains);
            $hotlinkConf = "    valid_referers none blocked " . $domains . ";\n    if (\$invalid_referer){\n        return 404;\n    }\n";
        }
        
        // 查找图片/静态资源的 location 块
        // 匹配 location ~ .*\.(...)$ {
        $pattern = '/location\s*~\s*\.\*\\\\\.?\(([^)]+)\)\$\s*\{/i';
        
        if (preg_match($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
            $extList = $matches[1][0];
            $matchStart = $matches[0][1];
            $matchLength = strlen($matches[0][0]);
            $blockStart = $matchStart + $matchLength;
            
            // 检查是否是图片类型的块
            if (stripos($extList, 'jpg') !== false || stripos($extList, 'png') !== false) {
                // 寻找块的结束位置（处理嵌套括号）
                $braceCount = 1;
                $blockEnd = 0;
                $len = strlen($content);
                
                for ($i = $blockStart; $i < $len; $i++) {
                    if ($content[$i] == '{') {
                        $braceCount++;
                    } elseif ($content[$i] == '}') {
                        $braceCount--;
                    }
                    
                    if ($braceCount == 0) {
                        $blockEnd = $i;
                        break;
                    }
                }
                
                if ($blockEnd > 0) {
                    // 提取块内容
                    $blockContent = substr($content, $blockStart, $blockEnd - $blockStart);
                    
                    // 清理旧的防盗链配置
                    $blockContent = preg_replace('/valid_referers\s+[^;]+;\s*/i', '', $blockContent);
                    // 清理 if ($invalid_referer) { ... } 块
                    // 使用递归模式匹配嵌套的括号
                    $blockContent = preg_replace('/if\s*\(\$invalid_referer\)\s*(\{(?:[^{}]+|(?1))*\})\s*/s', '', $blockContent);
                    
                    // 插入新的配置到块的开头
                    $newBlockContent = "\n" . $hotlinkConf . trim($blockContent, "\n") . "\n";
                    
                    // 替换原始内容
                    $newContent = substr($content, 0, $blockStart) . $newBlockContent . substr($content, $blockEnd);
                    
                    // 保存文件
                    $saveResult = $this->SaveFileBody($configFile, $newContent);
                    
                    if ($saveResult && isset($saveResult['status']) && ($saveResult['status'] === true || $saveResult['status'] === 'true' || $saveResult['status'] === 1)) {
                        // 尝试重载配置
                        // 先尝试 Reload
                        $reloadResult = $this->HttpPostCookie($this->BT_PANEL . '/site?action=Reload', array('siteName' => $siteName));
                        $decodedReload = json_decode($reloadResult, true);
                        
                        // 如果 Reload 失败（404等），尝试重启站点（会造成短暂中断但保证生效）
                        if (!$decodedReload || (isset($decodedReload['status']) && $decodedReload['status'] === false)) {
                             // 获取站点ID
                             $siteInfo = $this->GetSiteInfo('', $siteName);
                             if ($siteInfo && isset($siteInfo['id'])) {
                                 $this->ztweb($siteInfo['id'], $siteName);
                                 $this->qdweb($siteInfo['id'], $siteName);
                             }
                        }
                        
                        return array('status' => true, 'msg' => '设置成功');
                    }
                    
                    return array('status' => false, 'msg' => '保存配置文件失败');
                }
            }
        }
        
        $this->debug_log('SetHotlinkByConfig: 未找到匹配的location块');
        return array('status' => false, 'msg' => '未找到静态文件配置块，无法设置防盗链');
    }

    public function GetSecurity($siteName) {
        $url = $this->BT_PANEL . '/site?action=GetSecurity';
        $p_data = $this->GetKeyData();
        $p_data['siteName'] = $siteName;
        $result = $this->HttpPostCookie($url, $p_data);
        $decoded = json_decode($result, true);
        
        // 如果API调用失败或返回空数据，尝试从配置文件读取
        if (!$decoded || (isset($decoded['status']) && ($decoded['status'] === false || $decoded['status'] === 'false'))) {
            $this->debug_log('GetSecurity API失败，尝试读取配置文件');
            return $this->GetHotlinkByConfig($siteName);
        }
        
        return $decoded;
    }

    public function GetHotlinkByConfig($siteName) {
        $configFile = '/www/server/panel/vhost/nginx/' . $siteName . '.conf';
        $fileContent = $this->GetFileContent($configFile);
        
        if (!$fileContent || !isset($fileContent['status']) || $fileContent['status'] !== true) {
            return array('status' => false, 'msg' => '无法读取配置文件');
        }
        
        $content = $fileContent['data'];
        
        // 查找 location ~ .*\.(...)$ {
        $pattern = '/location\s*~\s*\.\*\\\\\.?\(([^)]+)\)\$\s*\{/i';
        
        if (preg_match($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
            $extList = $matches[1][0];
            $matchStart = $matches[0][1];
            $matchLength = strlen($matches[0][0]);
            $blockStart = $matchStart + $matchLength;
            
            // 检查是否是图片类型的块
            if (stripos($extList, 'jpg') !== false || stripos($extList, 'png') !== false) {
                // 寻找块的结束位置
                $braceCount = 1;
                $blockEnd = 0;
                $len = strlen($content);
                
                for ($i = $blockStart; $i < $len; $i++) {
                    if ($content[$i] == '{') {
                        $braceCount++;
                    } elseif ($content[$i] == '}') {
                        $braceCount--;
                    }
                    
                    if ($braceCount == 0) {
                        $blockEnd = $i;
                        break;
                    }
                }
                
                if ($blockEnd > 0) {
                    // 提取块内容
                    $blockContent = substr($content, $blockStart, $blockEnd - $blockStart);
                    
                    $data = array(
                        'status' => false,
                        'url' => '',
                        'exts' => str_replace('|', ',', $extList), // 转换回逗号分隔
                        'type' => 'URI'
                    );
                    
                    // 检查是否开启了防盗链
                    // 检查 valid_referers
                    if (preg_match('/valid_referers\s+none\s+blocked\s+(.+?);/i', $blockContent, $refMatches)) {
                        $data['url'] = trim($refMatches[1]);
                        
                        // 检查 if ($invalid_referer) { return 404; }
                        // 注意：这里需要匹配多行和空格
                        if (preg_match('/if\s*\(\$invalid_referer\)\s*\{\s*return\s+404;\s*\}/s', $blockContent)) {
                            $data['status'] = true;
                        }
                    }
                    
                    return array('status' => true, 'data' => $data);
                }
            }
        }
        
        // 如果没找到配置块，返回默认状态
        return array('status' => true, 'data' => array(
            'status' => false,
            'url' => '',
            'exts' => 'jpg,jpeg,gif,png,js,css',
            'type' => 'URI'
        ));
    }
    
    public function SetAccessRestriction($id, $settings) {
        $url = $this->BT_PANEL . '/site?action=SetAccessRestriction';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $p_data = array_merge($p_data, $settings);
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function SetDirectoryAuth($id, $directory, $username, $password, $name = '') {
        $url = $this->BT_PANEL . '/site?action=set_dir_auth';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $p_data['site_dir'] = $directory;
        $p_data['username'] = $username;
        $p_data['password'] = $password;
        // 如果没有提供name，使用目录路径的MD5作为name
        if (empty($name)) {
            $name = 'auth_' . substr(md5($directory), 0, 8);
        }
        $p_data['name'] = $name;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function GetDirectoryAuth($id) {
        $url = $this->BT_PANEL . '/site?action=get_dir_auth';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function DeleteDirectoryAuth($id, $name) {
        $url = $this->BT_PANEL . '/site?action=delete_dir_auth';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $p_data['name'] = $name;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function ModifyDirectoryAuthPass($id, $name, $username, $password) {
        $url = $this->BT_PANEL . '/site?action=modify_dir_auth_pass';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $p_data['name'] = $name;
        $p_data['username'] = $username;
        $p_data['password'] = $password;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function SetForbiddenAccess($id, $paths, $enable = 'true') {
        // 宝塔面板没有直接的禁止访问API，需要通过文件操作实现
        // 这里使用文件操作API来修改Nginx配置文件
        $site_name = $this->GetSiteName($id);
        if (empty($site_name)) {
            return array('status' => false, 'msg' => '获取网站名称失败');
        }
        $config_path = '/www/server/panel/vhost/nginx/' . $site_name . '.conf';
        
        // 读取配置文件
        $config_result = $this->GetFileContent($config_path);
        if (!$config_result || !isset($config_result['status']) || $config_result['status'] != true) {
            return array('status' => false, 'msg' => '获取配置文件失败');
        }
        
        $config_content = isset($config_result['data']) ? $config_result['data'] : '';
        
        // 移除旧的禁止访问配置
        $config_content = preg_replace('/\s*#FORBIDDEN_START[\s\S]*?#FORBIDDEN_END\s*/', '', $config_content);
        
        // 添加新的禁止访问配置
        if ($enable == 'true' && !empty($paths)) {
            $forbidden_config = "\n\t#FORBIDDEN_START\n";
            $path_list = is_array($paths) ? $paths : explode(',', $paths);
            foreach ($path_list as $path) {
                $path = trim($path);
                if (!empty($path)) {
                    if (strpos($path, '*.') === 0) {
                        // 后缀
                        $ext = substr($path, 2);
                        $forbidden_config .= "\tlocation ~* \\.(" . $ext . ")$ {\n";
                    } elseif (substr($path, -1) == '/') {
                        // 目录
                        $forbidden_config .= "\tlocation ^~ " . $path . " {\n";
                    } else {
                        // 文件
                        $forbidden_config .= "\tlocation = " . $path . " {\n";
                    }
                    $forbidden_config .= "\t\treturn 403;\n";
                    $forbidden_config .= "\t}\n";
                }
            }
            $forbidden_config .= "\t#FORBIDDEN_END\n";
            
            // 在server块结束前添加
            $config_content = preg_replace('/(\t\}\n)$/', $forbidden_config . '\1', $config_content);
        }
        
        // 保存配置文件
        $save_result = $this->SaveFileBody($config_path, $config_content);
        return $save_result;
    }
    
    public function SetTrafficLimit($id, $limit, $enable = 'true') {
        // 宝塔面板的流量限制API是SetLimitNet，需要perserver, perip, limit_rate参数
        // limit_rate单位是k（KB），需要转换为KB
        if ($enable == 'true') {
            $url = $this->BT_PANEL . '/site?action=SetLimitNet';
            $p_data = $this->GetKeyData();
            $p_data['id'] = $id;
            $p_data['perserver'] = '100'; // 总并发限制，默认100
            $p_data['perip'] = '10'; // IP并发限制，默认10
            $p_data['limit_rate'] = strval($limit * 1024); // 转换为KB，MB转KB需要乘以1024
            $result = $this->HttpPostCookie($url, $p_data);
            return json_decode($result, true);
        } else {
            // 关闭流量限制
            $url = $this->BT_PANEL . '/site?action=CloseLimitNet';
            $p_data = $this->GetKeyData();
            $p_data['id'] = $id;
            $result = $this->HttpPostCookie($url, $p_data);
            return json_decode($result, true);
        }
    }
    
    public function GetTrafficLimit($id) {
        // 通过读取配置文件获取流量限制信息
        $site_name = $this->GetSiteName($id);
        if (empty($site_name)) {
            return array('status' => false, 'msg' => '获取网站名称失败');
        }
        $config_path = '/www/server/panel/vhost/nginx/' . $site_name . '.conf';
        
        $config_result = $this->GetFileContent($config_path);
        if (!$config_result || !isset($config_result['status']) || $config_result['status'] != true) {
            return array('status' => false, 'msg' => '获取配置文件失败');
        }
        
        $config_content = isset($config_result['data']) ? $config_result['data'] : '';
        $enabled = false;
        $limit = 0;
        
        if (preg_match('/limit_rate\s+(\d+)([kmg]?);/i', $config_content, $matches)) {
            $enabled = true;
            $value = intval($matches[1]);
            $unit = strtolower($matches[2]);
            if ($unit == 'k') {
                $limit = $value / 1024; // KB转MB
            } elseif ($unit == 'm') {
                $limit = $value;
            } elseif ($unit == 'g') {
                $limit = $value * 1024;
            } else {
                $limit = $value / 1024 / 1024; // 字节转MB
            }
        }
        
        return array('status' => true, 'enabled' => $enabled, 'limit' => $limit);
    }
    
    /**
     * 获取网站流量统计（total插件）
     */
    public function GetSiteTraffic($id) {
        $url = $this->BT_PANEL . '/site?action=GetSiteTraffic';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $result = $this->HttpPostCookie($url, $p_data);
        $data = json_decode($result, true);
        
        $this->debug_log('GetSiteTraffic API响应: ' . $result);
        
        if (isset($data['status']) && $data['status']) {
            return $data;
        }
        return null;
    }
    
    /**
     * 获取网站流量统计（monitor插件）
     * @param string $site_name 网站名称
     * @param string $day 日期，格式 YYYY-MM-DD，默认为今天
     * @return array|null
     */
    public function GetSiteTrafficMonitor($site_name, $day = null) {
        if (empty($day)) {
            $day = date('Y-m-d');
        }
        
        $url = $this->BT_PANEL . '/plugin?action=a&name=monitor&s=get_site_total_day';
        $p_data = $this->GetKeyData();
        $p_data['SiteName'] = $site_name;
        $p_data['Day'] = $day;
        $result = $this->HttpPostCookie($url, $p_data);
        $data = json_decode($result, true);
        
        $this->debug_log('GetSiteTrafficMonitor API响应: ' . $result);
        
        // monitor插件返回的数据格式不同，需要转换
        if (isset($data['sent_bytes']) || isset($data['recv_bytes'])) {
            return array(
                'status' => true,
                'data' => array(
                    'sent_bytes' => isset($data['sent_bytes']) ? intval($data['sent_bytes']) : 0,
                    'recv_bytes' => isset($data['recv_bytes']) ? intval($data['recv_bytes']) : 0,
                    'request' => isset($data['request']) ? intval($data['request']) : 0,
                    'day' => $day
                )
            );
        }
        return null;
    }
    
    /**
     * 获取网站月度流量统计
     */
    public function GetMonthTraffic($id, $month) {
        $url = $this->BT_PANEL . '/site?action=GetMonthTraffic';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $p_data['month'] = $month;
        $result = $this->HttpPostCookie($url, $p_data);
        $data = json_decode($result, true);
        
        $this->debug_log('GetMonthTraffic API响应: ' . $result);
        
        if (isset($data['status']) && $data['status']) {
            return $data;
        }
        return null;
    }
    
    public function SetPHPVersion($siteName, $version) {
        $url = $this->BT_PANEL . '/site?action=SetPHPVersion';
        $p_data = $this->GetKeyData();
        $p_data['siteName'] = $siteName;
        $p_data['version'] = $version;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function AddDomain($id, $webname, $domain) {
        $url = $this->BT_PANEL . '/site?action=AddDomain';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $p_data['webname'] = $webname;
        $p_data['domain'] = $domain;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function DelDomain($id, $webname, $domain, $port = 80) {
        $url = $this->BT_PANEL . '/site?action=DelDomain';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $p_data['webname'] = $webname;
        $p_data['domain'] = $domain;
        $p_data['port'] = $port;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    /** 获取子目录绑定列表（宝塔API: GetDirBinding） */
    public function GetDirBinding($siteId) {
        $url = $this->BT_PANEL . '/site?action=GetDirBinding';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $siteId;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    /** 添加子目录绑定（宝塔API: AddDirBinding） */
    public function AddDirBinding($siteId, $domain, $dirName) {
        $url = $this->BT_PANEL . '/site?action=AddDirBinding';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $siteId;
        $p_data['domain'] = $domain;
        $p_data['dirName'] = $dirName;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    /** 删除子目录绑定（宝塔API: DelDirBinding） */
    public function DelDirBinding($bindingId) {
        $url = $this->BT_PANEL . '/site?action=DelDirBinding';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $bindingId;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function GetPHPVersion() {
        $url = $this->BT_PANEL . '/site?action=GetPHPVersion';
        $p_data = $this->GetKeyData();
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function GetSitePhp($siteName) {
        $url = $this->BT_PANEL . '/site?action=GetPHPVersion';
        $p_data = $this->GetKeyData();
        $p_data['siteName'] = $siteName;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function GetSites($limit = 15, $p = 1, $type = -1, $order = 'id desc') {
        $url = $this->BT_PANEL . '/data?action=getData&table=site';
        $p_data = $this->GetKeyData();
        $p_data['limit'] = $limit;
        $p_data['p'] = $p;
        $p_data['type'] = $type;
        $p_data['order'] = $order;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }


    public function DeployProgram($id, $bs) {
        $url = $this->BT_PANEL . '/site?action=SetupPackage';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $p_data['type'] = $bs['tb'];
        $p_data['version'] = 'latest';
        $p_data['php_version'] = '74';
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function GetFileList($path) {
        $url = $this->BT_PANEL . '/files?action=GetDir';
        $p_data = $this->GetKeyData();
        $p_data['path'] = $path;
        $p_data['disk'] = 'true';
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    // 别名，与GetFileList相同
    public function GetDir($path) {
        return $this->GetFileList($path);
    }

    public function DeleteFile($path) {
        $url = $this->BT_PANEL . '/files?action=DeleteFile';
        $p_data = $this->GetKeyData();
        $p_data['path'] = $path;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function DeleteDir($path) {
        $url = $this->BT_PANEL . '/files?action=DeleteDir';
        $p_data = $this->GetKeyData();
        $p_data['path'] = $path;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function CreateDir($path) {
        $url = $this->BT_PANEL . '/files?action=CreateDir';
        $p_data = $this->GetKeyData();
        $p_data['path'] = $path;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function SaveFile($path, $content) {
        $url = $this->BT_PANEL . '/files?action=SaveFileBody';
        $p_data = $this->GetKeyData();
        $p_data['path'] = $path;
        $p_data['data'] = $content;
        $p_data['encoding'] = 'utf-8';
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    public function ExecShell($command) {
        $url = $this->BT_PANEL . '/files?action=ExecShell';
        $p_data = $this->GetKeyData();
        $p_data['shell'] = $command;
        $result = $this->HttpPostCookie($url, $p_data);
        
        // 添加调试信息
        $log_file = __DIR__ . '/user/api/debug.log';
        $timestamp = date('Y-m-d H:i:s');
        file_put_contents($log_file, "[$timestamp] ExecShell原始响应: " . $result . "\n", FILE_APPEND);
        
        $decoded = json_decode($result, true);
        file_put_contents($log_file, "[$timestamp] ExecShell解析后: " . print_r($decoded, true) . "\n", FILE_APPEND);
        
        return $decoded;
    }

    public function BackupDatabase($name) {
        $url = $this->BT_PANEL . '/database?action=ToBackup';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $name;
        $p_data['name'] = $name;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function BackupSite($id) {
        $url = $this->BT_PANEL . '/site?action=ToBackup';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }



    public function webkjjs($path) {
        $url = $this->BT_PANEL . '/files?action=GetDir';
        $p_data = $this->GetKeyData();
        $p_data['path'] = $path;
        $p_data['disk'] = 'true';
        $result = $this->HttpPostCookie($url, $p_data);
        $data = json_decode($result, true);
        
        if (isset($data['data']) && isset($data['data']['disk_usage'])) {
            return $data['data']['disk_usage'];
        }
        
        return 0;
    }
    
    public function GetPanelStatus($timeout = 10) {
        $url = $this->BT_PANEL . '/system?action=GetSystemTotal';
        $p_data = $this->GetKeyData();
        $result = $this->HttpPostCookie($url, $p_data, $timeout);
        return $result;
    }
    
    /**
     * 获取磁盘信息
     */
    public function GetDiskInfo() {
        // 尝试多个可能的API端点
        $endpoints = array(
            '/system?action=GetDiskInfo',
            '/system?action=GetDisk',
            '/system?action=get_disk_info'
        );
        
        foreach ($endpoints as $endpoint) {
            $url = $this->BT_PANEL . $endpoint;
            $p_data = $this->GetKeyData();
            $result = $this->HttpPostCookie($url, $p_data);
            $data = json_decode($result, true);
            
            // 如果成功返回数据，直接返回
            if ($data && (isset($data['status']) || isset($data['data']) || isset($data[0]))) {
                return $data;
            }
        }
        
        // 如果所有API都失败，返回原始结果
        return json_decode($result, true);
    }
    
    /**
     * 获取网络信息
     */
    public function GetNetworkInfo() {
        // 尝试多个可能的API端点
        $endpoints = array(
            '/system?action=GetNetWork',
            '/system?action=GetNetwork',
            '/system?action=get_network_info',
            '/system?action=GetNetworkIo',
            '/system?action=GetNetWorkIo',
            '/system?action=network',
            '/data?action=getData&table=network',
            '/system?action=GetCpu',
            '/system?action=GetMem',
            '/system?action=GetDiskIo',
            '/system?action=get_system_total'
        );
        
        $last_result = null;
        
        foreach ($endpoints as $endpoint) {
            $url = $this->BT_PANEL . $endpoint;
            $p_data = $this->GetKeyData();
            $result = $this->HttpPostCookie($url, $p_data);
            $data = json_decode($result, true);
            
            $last_result = $data;
            
            // 如果成功返回数据且没有错误信息
            if ($data && isset($data['status']) && ($data['status'] === true || $data['status'] === 1)) {
                return $data;
            }
            // 如果返回有实际数据且没有错误
            if ($data && isset($data['upSpeed']) && empty($data['msg'])) {
                return $data;
            }
            // 如果返回有data数组
            if ($data && isset($data['data']) && is_array($data['data']) && !empty($data['data']) && empty($data['msg'])) {
                return $data;
            }
            // 如果返回有网络相关的实际数据
            if ($data && (isset($data['network_up']) || isset($data['network_down']) || isset($data['up']) || isset($data['down']))) {
                return $data;
            }
            // GetNetWork API 返回的数据包含 network 字段
            if ($data && isset($data['network']) && is_array($data['network'])) {
                return $data;
            }
        }
        
        // 如果所有API都失败，返回原始结果
        return $last_result;
    }
    
    public function GetServerIP() {
        // 通过执行shell命令获取服务器IP地址
        $shell = 'hostname -I';
        $result = $this->shell_yx($shell);
        
        if (isset($result['code']) && $result['code'] == 1 && isset($result['msg'])) {
            $ips = explode(' ', trim($result['msg']));
            // 返回第一个非回环地址的IP
            foreach ($ips as $ip) {
                if ($ip && $ip != '127.0.0.1' && filter_var($ip, FILTER_VALIDATE_IP)) {
                    return $ip;
                }
            }
        }
        
        // 如果shell命令失败，尝试从BT_PANEL URL中提取IP
        if (preg_match('/http:\/\/(.*?):/', $this->BT_PANEL, $matches)) {
            $host = $matches[1];
            if (filter_var($host, FILTER_VALIDATE_IP)) {
                return $host;
            }
        }
        
        return '未知IP';
    }
    
    public function WriteFileContent($path, $content) {
        $url = $this->BT_PANEL . '/files?action=SaveFileBody';
        $p_data = $this->GetKeyData();
        $p_data['path'] = $path;
        $p_data['data'] = $content;
        $p_data['encoding'] = 'utf-8';
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    // FTP用户管理相关方法
    public function AddFTPUser($username, $password, $path, $uid = 0, $gid = 0) {
        $url = $this->BT_PANEL . '/ftp?action=AddFtp';
        $p_data = $this->GetKeyData();
        $p_data['username'] = $username;
        $p_data['password'] = $password;
        $p_data['path'] = $path;
        $p_data['uid'] = $uid;
        $p_data['gid'] = $gid;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function DelFTPUser($id, $username) {
        $url = $this->BT_PANEL . '/ftp?action=DeleteFtp';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $p_data['username'] = $username;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function GetFTPUsers($limit = 100, $p = 1) {
        $url = $this->BT_PANEL . '/data?action=getData';
        $p_data = $this->GetKeyData();
        $p_data['table'] = 'ftps';
        $p_data['limit'] = $limit;
        $p_data['p'] = $p;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    // 文件操作相关方法
    public function UploadFile($path, $file, $filename = null) {
        // 参考宝塔API文档，使用 zunfile 作为文件参数名
        // 路径需要URL编码，避免特殊字符导致问题
        $url = $this->BT_PANEL . '/files?action=UploadFile&path=' . urlencode($path);
        $p_data = $this->GetKeyData();
        
        $real_file = realpath($file);
        if (!$real_file) {
            $real_file = $file;
        }

        // 获取文件名和MIME类型
        // 如果提供了原始文件名，使用原始文件名，否则使用临时文件名
        if ($filename === null) {
            $filename = basename($real_file);
        }
        
        // 获取MIME类型（兼容没有fileinfo扩展的情况）
        $mime_type = 'application/octet-stream'; // 默认值
        
        if (function_exists('mime_content_type') && file_exists($real_file)) {
            $mime_type = @mime_content_type($real_file);
        } elseif (function_exists('finfo_open') && file_exists($real_file)) {
            $finfo = @finfo_open(FILEINFO_MIME_TYPE);
            if ($finfo) {
                $mime_type = @finfo_file($finfo, $real_file);
                @finfo_close($finfo);
            }
        } else {
            // 根据文件扩展名判断MIME类型
            $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
            $mime_types = array(
                'zip' => 'application/zip',
                'tar' => 'application/x-tar',
                'gz' => 'application/gzip',
                'tgz' => 'application/gzip',
            );
            $mime_type = isset($mime_types[$ext]) ? $mime_types[$ext] : 'application/octet-stream';
        }
        
        if (empty($mime_type)) {
            $mime_type = 'application/octet-stream';
        }

        // 调试信息
        $debug_msg = "UploadFile: URL={$url}, File={$real_file}, Filename={$filename}, Mime={$mime_type}";
        $this->debug_log($debug_msg);

        // 检查文件是否存在
        if (!file_exists($real_file)) {
            $error_msg = "UploadFile: File does not exist: {$real_file}";
            $this->debug_log($error_msg);
            return array('status' => false, 'msg' => '文件不存在: ' . $filename);
        }

        if (class_exists('CURLFile')) {
            // 使用完整的CURLFile构造函数参数
            try {
                $p_data['zunfile'] = new CURLFile($real_file, $mime_type, $filename);
            } catch (Exception $e) {
                return array('status' => false, 'msg' => '创建CURLFile失败: ' . $e->getMessage());
            }
        } else {
            $p_data['zunfile'] = '@' . $real_file;
        }
        
        // 文件上传使用更长的超时时间（5分钟）
        $result = $this->HttpPostCookie($url, $p_data, 300);
        $result_msg = "UploadFile: Raw result=" . var_export($result, true);
        $this->debug_log($result_msg);
        
        // 如果返回的是数组（错误信息），直接返回
        if (is_array($result)) {
            return $result;
        }
        
        if ($result === false || $result === null || $result === '') {
            $error_msg = "UploadFile: Request failed or returned empty";
            $this->debug_log($error_msg);
            return array('status' => false, 'msg' => '请求宝塔API失败，请检查网络连接或宝塔面板状态');
        }
        
        $decoded = json_decode($result, true);
        if ($decoded === null && json_last_error() !== JSON_ERROR_NONE) {
            $error_msg = "UploadFile: JSON decode failed: " . json_last_error_msg();
            $this->debug_log($error_msg);
            return array('status' => false, 'msg' => '宝塔API返回格式错误: ' . $result);
        }
        
        return $decoded;
    }
    
    /**
     * 检查分片文件是否存在（用于断点续传）
     * @param string $filename 文件名（包括路径）
     * @return array API响应结果
     */
    public function CheckChunkExists($filename) {
        $url = $this->BT_PANEL . '/files?action=upload_file_exists';
        $p_data = $this->GetKeyData();
        $p_data['filename'] = $filename;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    /**
     * 分片上传文件
     * @param string $path 上传目录路径
     * @param string $fileChunk 临时文件路径（上传的文件块）
     * @param string $fileName 文件名
     * @param int $fileSize 文件总大小
     * @param int $chunkStart 分片起始位置
     * @param string $fileType 文件MIME类型
     * @return array API响应结果
     */
    public function UploadChunk($path, $fileChunk, $fileName, $fileSize, $chunkStart, $fileType = '') {
        $url = $this->BT_PANEL . '/files?action=upload';
        $p_data = $this->GetKeyData();
        $p_data['f_path'] = $path;
        $p_data['f_name'] = $fileName;
        $p_data['f_size'] = $fileSize;
        $p_data['f_start'] = $chunkStart;
        
        $real_file = realpath($fileChunk);
        if (!$real_file) {
            $real_file = $fileChunk;
        }
        
        if (class_exists('CURLFile')) {
            $p_data['blob'] = new CURLFile($real_file, $fileType, $fileName);
        } else {
            $p_data['blob'] = '@' . $real_file;
        }
        
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    /**
     * 下载文件（通过宝塔的 /download 接口）
     * 使用宝塔的直接下载接口，支持所有文件类型
     * @param string $path 文件完整路径
     * @return array 包含下载URL或错误信息
     */
    public function DownloadFile($path) {
        // 构建下载URL（使用宝塔的 /download 接口）
        // 添加认证参数
        $key_data = $this->GetKeyData();
        $download_url = $this->BT_PANEL . '/download?filename=' . urlencode($path);
        $download_url .= '&request_token=' . $key_data['request_token'];
        $download_url .= '&request_time=' . $key_data['request_time'];
        
        // 返回下载URL，让前端重定向
        return array(
            'status' => true,
            'url' => $download_url
        );
    }
    
    // 远程下载文件
    public function RemoteDownload($url, $path, $filename = '') {
        $api_url = $this->BT_PANEL . '/files?action=DownloadFile';
        $p_data = $this->GetKeyData();
        $p_data['url'] = $url;
        $p_data['path'] = dirname($path);
        $p_data['filename'] = $filename ?: basename($path);
        $result = $this->HttpPostCookie($api_url, $p_data);
        return json_decode($result, true);
    }
    
    // 创建符号链接
    public function CreateLink($path, $link_name, $type = 'soft') {
        $api_url = $this->BT_PANEL . '/files?action=CreateLink';
        $p_data = $this->GetKeyData();
        $p_data['path'] = $path;
        $p_data['link'] = $link_name;
        $p_data['type'] = $type; // soft=软链接, hard=硬链接
        $result = $this->HttpPostCookie($api_url, $p_data);
        return json_decode($result, true);
    }
    
    // 搜索文件内容
    public function SearchFiles($path, $keyword) {
        $api_url = $this->BT_PANEL . '/files?action=SearchFiles';
        $p_data = $this->GetKeyData();
        $p_data['path'] = $path;
        $p_data['keyword'] = $keyword;
        $result = $this->HttpPostCookie($api_url, $p_data);
        return json_decode($result, true);
    }
    
    public function RenameFile($oldPath, $newPath) {
        // 宝塔标准 API：MvFile，参数 sfile / dfile
        $url = $this->BT_PANEL . '/files?action=MvFile';
        $p_data = $this->GetKeyData();
        $p_data['sfile'] = $oldPath;
        $p_data['dfile'] = $newPath;
        $p_data['rename'] = '1';
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function MoveFile($oldPath, $newPath) {
        // 宝塔标准 API：MvFile，参数 sfile / dfile
        $url = $this->BT_PANEL . '/files?action=MvFile';
        $p_data = $this->GetKeyData();
        $p_data['sfile'] = $oldPath;
        $p_data['dfile'] = $newPath;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function CopyFile($oldPath, $newPath) {
        $url = $this->BT_PANEL . '/files?action=CopyFile';
        $p_data = $this->GetKeyData();
        $p_data['sfile'] = $oldPath;
        $p_data['dfile'] = $newPath;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function CreateDirectory($path) {
        $url = $this->BT_PANEL . '/files?action=CreateDir';
        $p_data = $this->GetKeyData();
        $p_data['path'] = $path;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    /** 宝塔标准 API：创建文件，path 为文件完整路径 */
    public function CreateFile($path) {
        $url = $this->BT_PANEL . '/files?action=CreateFile';
        $p_data = $this->GetKeyData();
        $p_data['path'] = $path;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function SetFileAccess($path, $access, $user = 'www', $all = 'False') {
        $url = $this->BT_PANEL . '/files?action=SetFileAccess';
        $p_data = $this->GetKeyData();
        $p_data['filename'] = $path;  // 宝塔API使用 filename 而不是 path
        $p_data['access'] = $access;
        $p_data['user'] = $user;  // 需要传递所有者
        $p_data['all'] = $all;  // 递归设置 'True' 或 'False'
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function DeleteDirectory($path) {
        $url = $this->BT_PANEL . '/files?action=DeleteDir';
        $p_data = $this->GetKeyData();
        $p_data['path'] = $path;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function Zip($path, $files, $dfile = '') {
        // 使用宝塔的 Zip 接口（根据本地宝塔面板代码）
        $url = $this->BT_PANEL . '/files?action=Zip';
        $p_data = $this->GetKeyData();
        
        // 源文件所在目录
        $p_data['path'] = $path;
        
        // 处理源文件列表，转换为用逗号分隔的字符串（宝塔API格式）
        if (is_array($files)) {
            $sfile = implode(',', array_values($files));
        } else {
            $sfile = $files;
        }
        $p_data['sfile'] = $sfile;
        
        // 目标压缩文件路径
        if (!empty($dfile)) {
            $p_data['dfile'] = $dfile;
        } else {
            // 默认生成压缩文件名
            $p_data['dfile'] = $path . '/archive_' . date('YmdHis') . '.zip';
        }
        
        // 压缩类型
        $p_data['z_type'] = 'zip';
        
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function UnZip($path, $file) {
        $url = $this->BT_PANEL . '/files?action=UnZip';
        $p_data = $this->GetKeyData();
        // sfile需要完整路径，dfile是目标目录
        $p_data['sfile'] = $path . '/' . $file;
        $p_data['dfile'] = $path;
        $p_data['coding'] = 'utf-8';
        $p_data['password'] = '';
        $p_data['type'] = 'zip';
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }

    /**
     * 解压文件到指定目录
     * @param string $sfile 源压缩文件完整路径
     * @param string $dfile 解压目标目录
     */
    public function UnZipFile($sfile, $dfile) {
        $url = $this->BT_PANEL . '/files?action=UnZip';
        $p_data = $this->GetKeyData();
        $p_data['sfile'] = $sfile;  // 源文件完整路径
        $p_data['dfile'] = $dfile;  // 目标目录
        $p_data['coding'] = 'utf-8';
        $p_data['password'] = '';
        $p_data['type'] = 'zip';
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    /** 获取路径大小（目录/文件） */
    public function GetPathSize($path) {
        $url = $this->BT_PANEL . '/files?action=get_path_size';
        $p_data = $this->GetKeyData();
        $p_data['path'] = $path;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    /** 获取文件属性 */
    public function GetFileAttribute($path) {
        $url = $this->BT_PANEL . '/files?action=get_file_attribute';
        $p_data = $this->GetKeyData();
        $p_data['path'] = $path;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    /** 获取文件哈希 */
    public function GetFileHash($path) {
        $url = $this->BT_PANEL . '/files?action=get_file_hash';
        $p_data = $this->GetKeyData();
        $p_data['path'] = $path;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    /** 创建下载链接（外链） */
    public function CreateDownloadUrl($filename, $ps = '', $password = '', $expire = 24) {
        $url = $this->BT_PANEL . '/files?action=create_download_url';
        $p_data = $this->GetKeyData();
        $p_data['filename'] = $filename;
        $p_data['ps'] = $ps;
        $p_data['password'] = $password;
        $p_data['expire'] = $expire;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    /** 关闭下载链接（外链） */
    public function RemoveDownloadUrl($id) {
        $url = $this->BT_PANEL . '/files?action=remove_download_url';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    /** 获取下载链接信息 */
    public function GetDownloadUrlFind($id) {
        $url = $this->BT_PANEL . '/files?action=get_download_url_find';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    /** 通过文件名获取下载链接ID */
    public function GetDownloadUrlId($filename) {
        // 先尝试直接通过数据库查询
        // 使用宝塔的 get_download_url_list 接口
        $url = $this->BT_PANEL . '/files?action=get_download_url_list';
        $p_data = $this->GetKeyData();
        $p_data['filename'] = $filename;
        $p_data['limit'] = 10;
        $p_data['p'] = 1;
        $result = $this->HttpPostCookie($url, $p_data);
        $data = json_decode($result, true);
        
        if (isset($data['data']) && is_array($data['data'])) {
            foreach ($data['data'] as $item) {
                if (isset($item['filename']) && $item['filename'] == $filename) {
                    return isset($item['id']) ? $item['id'] : 0;
                }
            }
        }
        return 0;
    }
    
    /** 压缩并下载 */
    public function ZipAndDownload($path, $files) {
        $url = $this->BT_PANEL . '/files?action=ZipAndDownload';
        $p_data = $this->GetKeyData();
        $p_data['path'] = $path;
        if (is_array($files)) {
            $p_data['files'] = json_encode(array_values($files));
        } else {
            $p_data['files'] = $files;
        }
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    public function InputSql($id, $file, $name = '') {
        $url = $this->BT_PANEL . '/database?action=InputSql';
        $p_data = $this->GetKeyData();
        $p_data['id'] = $id;
        $p_data['file'] = $file;
        if ($name !== '' && $name !== null) {
            $p_data['name'] = $name;
        }
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    /**
     * 获取禁止访问列表
     * API: get_file_deny
     * 模块: config
     */
    public function GetFileDeny() {
        $url = $this->BT_PANEL . '/config?action=get_file_deny';
        $p_data = $this->GetKeyData();
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    /**
     * 设置禁止访问
     * API: set_file_deny
     * 模块: config
     * @param string $filename 文件名或目录（如 .htaccess, data/, *.log）
     * @param int $status 状态：1=禁止访问, 0=允许访问
     */
    public function SetFileDeny($filename, $status = 1) {
        $url = $this->BT_PANEL . '/config?action=set_file_deny';
        $p_data = $this->GetKeyData();
        $p_data['filename'] = $filename;
        $p_data['status'] = $status;
        $result = $this->HttpPostCookie($url, $p_data);
        return json_decode($result, true);
    }
    
    /**
     * 解析流量大小字符串为字节数
     * 支持格式：1.5GB, 500MB, 1024KB, 1024B
     */
    public function parseTrafficSize($size) {
        if (empty($size)) {
            return 0;
        }
        
        // 如果是数字，直接返回
        if (is_numeric($size)) {
            return intval($size);
        }
        
        // 如果是数组，尝试获取值
        if (is_array($size)) {
            if (isset($size['value'])) {
                $size = $size['value'];
            } else {
                return 0;
            }
        }
        
        $size = strtoupper(trim($size));
        
        // 提取数字和单位
        preg_match('/([\d.]+)\s*([KMGTPE]?B?)/', $size, $matches);
        
        if (empty($matches)) {
            return 0;
        }
        
        $value = floatval($matches[1]);
        $unit = isset($matches[2]) ? $matches[2] : 'B';
        
        // 转换为字节
        switch ($unit) {
            case 'B':
                return intval($value);
            case 'KB':
                return intval($value * 1024);
            case 'MB':
                return intval($value * 1024 * 1024);
            case 'GB':
                return intval($value * 1024 * 1024 * 1024);
            case 'TB':
                return intval($value * 1024 * 1024 * 1024 * 1024);
            default:
                return intval($value);
        }
    }
    
    /**
     * 获取宝塔监控插件的网站流量统计数据
     * 调用 monitor 插件的 get_site_total_day 接口
     * 
     * @param string $siteName 网站名称
     * @param string $date 日期，格式 YYYY-MM-DD
     * @return array|null 流量数据或null
     */
    public function getMonitorTraffic($siteName, $date = null) {
        if (empty($siteName)) {
            return null;
        }
        
        if ($date === null) {
            $date = date('Y-m-d');
        }
        
        // 调用宝塔监控插件API
        $url = $this->BT_PANEL . '/plugin?action=get_site_total_day';
        $p_data = $this->GetKeyData();
        $p_data['SiteName'] = $siteName;
        $p_data['Day'] = $date;
        
        $result = $this->HttpPostCookie($url, $p_data);
        $data = json_decode($result, true);
        
        $this->debug_log('getMonitorTraffic API响应: ' . $result);
        
        if (isset($data['status']) && $data['status']) {
            return array(
                'sent_bytes' => isset($data['sent_bytes']) ? intval($data['sent_bytes']) : 0,
                'recv_bytes' => isset($data['recv_bytes']) ? intval($data['recv_bytes']) : 0,
                'request' => isset($data['request']) ? intval($data['request']) : 0,
                'pv_number' => isset($data['pv_number']) ? intval($data['pv_number']) : 0,
                'uv_number' => isset($data['uv_number']) ? intval($data['uv_number']) : 0,
                'ip_number' => isset($data['ip_number']) ? intval($data['ip_number']) : 0
            );
        }
        
        return null;
    }
    
    /**
     * 获取宝塔监控插件的全局统计信息
     * 调用 monitor 插件的 get_glabol_total 接口
     * 注意：此接口不需要SiteName参数，会自动获取所有网站的统计
     * 
     * @param string $siteName 网站名称（可选，仅用于日志）
     * @param string $startDate 开始日期 YYYY-MM-DD
     * @param string $endDate 结束日期 YYYY-MM-DD
     * @return array|null 详细流量统计数据或null
     */
    public function getMonitorGlobalTotal($siteName, $startDate = null, $endDate = null) {
        if ($startDate === null) {
            $startDate = date('Y-m-d', strtotime('-30 days'));
        }
        if ($endDate === null) {
            $endDate = date('Y-m-d');
        }
        
        // 调用宝塔监控插件API - get_glabol_total 不需要SiteName参数
        $url = $this->BT_PANEL . '/plugin?action=get_glabol_total';
        $p_data = $this->GetKeyData();
        $p_data['start_date'] = $startDate;
        $p_data['end_date'] = $endDate;
        
        $result = $this->HttpPostCookie($url, $p_data);
        $data = json_decode($result, true);
        
        $this->debug_log('getMonitorGlobalTotal API响应: ' . substr($result, 0, 500));
        
        if (isset($data['status']) && $data['status']) {
            return array(
                'sent_bytes' => isset($data['sent_bytes']) ? intval($data['sent_bytes']) : 0,
                'recv_bytes' => isset($data['recv_bytes']) ? intval($data['recv_bytes']) : 0,
                'request' => isset($data['request']) ? intval($data['request']) : 0,
                'pv_number' => isset($data['pv_number']) ? intval($data['pv_number']) : 0,
                'uv_number' => isset($data['uv_number']) ? intval($data['uv_number']) : 0,
                'ip_number' => isset($data['ip_number']) ? intval($data['ip_number']) : 0,
                'method_post' => isset($data['method_post']) ? intval($data['method_post']) : 0,
                'method_get' => isset($data['method_get']) ? intval($data['method_get']) : 0,
                'gzip' => isset($data['gzip']) ? intval($data['gzip']) : 0,
                'pc_count' => isset($data['pc_count']) ? intval($data['pc_count']) : 0,
                'mobile_count' => isset($data['mobile_count']) ? intval($data['mobile_count']) : 0,
                'spider_count' => isset($data['spider_count']) ? intval($data['spider_count']) : 0,
                'slow_count' => isset($data['slow_count']) ? intval($data['slow_count']) : 0,
                'status_200' => isset($data['status_200']) ? intval($data['status_200']) : 0,
                'status_404' => isset($data['status_404']) ? intval($data['status_404']) : 0,
                'status_500' => isset($data['status_500']) ? intval($data['status_500']) : 0,
                'status_502' => isset($data['status_502']) ? intval($data['status_502']) : 0,
                'status_504' => isset($data['status_504']) ? intval($data['status_504']) : 0
            );
        }
        
        return null;
    }
    
    /**
     * 获取宝塔监控插件的每日流量列表
     * 调用 monitor 插件的 get_site_total_list_day 接口
     * 
     * @param string $siteName 网站名称
     * @param string $date 日期，格式 YYYY-MM-DD
     * @return array|null 每日流量列表或null
     */
    public function getMonitorTrafficList($siteName, $date = null) {
        if (empty($siteName)) {
            return null;
        }
        
        if ($date === null) {
            $date = date('Y-m-d');
        }
        
        // 调用宝塔监控插件API
        $url = $this->BT_PANEL . '/plugin?action=get_site_total_list_day';
        $p_data = $this->GetKeyData();
        $p_data['SiteName'] = $siteName;
        $p_data['Day'] = $date;
        
        $result = $this->HttpPostCookie($url, $p_data);
        $data = json_decode($result, true);
        
        $this->debug_log('getMonitorTrafficList API响应: ' . substr($result, 0, 500));
        
        if (isset($data['status']) && $data['status']) {
            return $data;
        }
        
        return null;
    }
    
    /**
     * 获取宝塔监控插件的自定义时间范围流量统计
     * 调用 monitor 插件的 get_site_total_list_custom 接口
     * 
     * @param string $siteName 网站名称
     * @param string $startDate 开始日期 YYYY-MM-DD
     * @param string $endDate 结束日期 YYYY-MM-DD
     * @return array|null 自定义时间范围流量统计或null
     */
    public function getMonitorTrafficCustom($siteName, $startDate, $endDate) {
        if (empty($siteName) || empty($startDate) || empty($endDate)) {
            return null;
        }
        
        // 调用宝塔监控插件API
        $url = $this->BT_PANEL . '/plugin?action=get_site_total_list_custom';
        $p_data = $this->GetKeyData();
        $p_data['SiteName'] = $siteName;
        $p_data['start_date'] = $startDate;
        $p_data['end_date'] = $endDate;
        
        $result = $this->HttpPostCookie($url, $p_data);
        $data = json_decode($result, true);
        
        // 直接输出API响应以便调试
        
        $this->debug_log('getMonitorTrafficCustom API响应: ' . substr($result, 0, 500));
        
        if (isset($data['status']) && $data['status']) {
            return $data;
        }
        
        return null;
    }
    
    /**
     * 获取网站监控配置
     * 调用 monitor 插件的 get_site_config 接口
     * 
     * @param string $siteName 网站名称
     * @return array|null 网站监控配置或null
     */
    public function get_site_config($siteName) {
        if (empty($siteName)) {
            return null;
        }
        
        // 调用宝塔监控插件API
        $url = $this->BT_PANEL . '/plugin?action=get_site_config';
        $p_data = $this->GetKeyData();
        $p_data['SiteName'] = $siteName;
        
        $result = $this->HttpPostCookie($url, $p_data);
        $data = json_decode($result, true);
        
        $this->debug_log('get_site_config API响应: ' . substr($result, 0, 500));
        
        if (isset($data['status']) && $data['status']) {
            return $data;
        }
        
        return null;
    }
}
?>
