<?php
use WHMCS\Database\Capsule;

if (!defined("WHMCS")) {
    exit("This file cannot be accessed directly");
}
//ini_set('display_errors','On');
define('ZJMFCLOUD_FILE', ROOTDIR . '/modules/servers/zjmfcloud/');
define('ZJMFCLOUD_TOKEN_FILE', ZJMFCLOUD_FILE . 'data/token.php');


include "zjmf/function.php";
include "zjmf/login.php";
include "zjmf/action.php";

zjmfcloud_lang();//语言文件

function zjmfcloud_MetaData(){
    zjmfcloud_AddTable();
	return ["DisplayName" => "魔方云", "APIVersion" => "1.0.0", "DefaultNonSSLPort" => "80", "DefaultSSLPort" => "443"];
}

// 连接测试
function zjmfcloud_TestConnection($params){
	// 获取连接状态
	$res = zjmfcloud_Login($params, true);
    if($res['status'] == 'success'){
        $result = [
        	'success'=>true
        ];
    }else{
        $result = [
        	'error'=>$res['msg']
        ];
    }
	return $result;
}

//配置接口默认信息
function zjmfcloud_ConfigOptions() {
	global $_LANG;
	
    return [
        "system_disk_size" => [
            "FriendlyName" => "{$_LANG['zjmf_system_disk_size']}",//系统盘大小
            "Type" => "text", 
            "Size" => "25", 
            "Description" => "GB",
            "Default" => "50",
        ],
        "backup" => [
            "FriendlyName" => "{$_LANG['zjmf_backup_name']}",//备份数量
            "Type" => "text",
            "Size" => "25",
            "Description" => "{$_LANG['zjmf_configoptions_description']}",
            "Default" => "2",
        ],
		"snapshot" => [
            "FriendlyName" => "{$_LANG['zjmf_snapshot_name']}",//快照数量
            "Type" => "text",
            "Size" => "25",
            "Description" => "{$_LANG['zjmf_configoptions_description']}",
            "Default" => "2",
        ],
		"network_type" => [
            "FriendlyName" => "{$_LANG['zjmf_network_type']}",//网络类型
            "Type" => "dropdown",
            "Options" => "normal,vpc",
            "Description" => "{$_LANG['zjmf_network_type_description']}",
            "Default" => "vpc",
        ],	
		"in_bw" => [
            "FriendlyName" => "{$_LANG['zjmf_in_bw']}",//流入带宽
            "Type" => "text",
            "Size" => "25",
            "Description" => "{$_LANG['zjmf_in_bw_description']}",
            "Default" => "",
        ],	
		"nat_acl_limit" => [
            "FriendlyName" => "{$_LANG['zjmf_nat_acl_limit']}",//NAT转发数量
            "Type" => "text",
            "Size" => "25",
            "Description" => "{$_LANG['zjmf_configoptions_description']}",
            "Default" => "-1",
        ],	
		"nat_web_limit" => [
            "FriendlyName" => "{$_LANG['zjmf_nat_web_limit']}",//NAT建站数量
            "Type" => "text",
            "Size" => "25",
            "Description" => "{$_LANG['zjmf_configoptions_description']}",
            "Default" => "-1",
        ],
		"system_disk_io_limit" => [
            "FriendlyName" => "{$_LANG['zjmf_system_disk_io_limit'] }",//系统盘性能
            "Type" => "text",
            "Size" => "25",
            "Description" => "{$_LANG['zjmf_disk_io_limit_description']}",
            "Default" => "",
        ],	
		"data_disk_io_limit" => [
            "FriendlyName" => "{$_LANG['zjmf_data_disk_io_limit'] }",//数据盘性能
            "Type" => "text",
            "Size" => "25",
            "Description" => "{$_LANG['zjmf_disk_io_limit_description']}",
            "Default" => "",
        ],	
		"area" => [
            "FriendlyName" => "{$_LANG['zjmf_configoptions_area'] }",//数据中心
            "Type" => "text",
            "Size" => "25",
            "Description" => "{$_LANG['zjmf_configoptions_area_desc'] }",
            "Default" => "",
        ],
		"node_group" => [
            "FriendlyName" => "{$_LANG['zjmf_configoptions_node_group'] }",//节点分组
            "Type" => "text",
            "Size" => "25",
            "Description" => "{$_LANG['zjmf_configoptions_node_group_desc'] }",
            "Default" => "",
        ],
		"node" => [
            "FriendlyName" => "{$_LANG['zjmf_configoptions_node'] }",//节点
            "Type" => "text",
            "Size" => "25",
            "Description" => "{$_LANG['zjmf_configoptions_node_desc'] }",
            "Default" => "",
        ],
		"node_priority" => [
            "FriendlyName" => "{$_LANG['zjmf_configoptions_node_priority'] }",//节点选择优先级
            "Type" => "text",
            "Size" => "25",
            "Description" => "{$_LANG['zjmf_configoptions_node_priority_desc'] }",
            "Default" => "",
        ],
		"os" => [
            "FriendlyName" => "{$_LANG['zjmf_configoptions_os'] }",//操作系统
            "Type" => "text",
            "Size" => "25",
            "Description" => "{$_LANG['zjmf_configoptions_os_desc'] }",
            "Default" => "",
        ],
		"cpu" => [
            "FriendlyName" => "{$_LANG['zjmf_configoptions_cpu'] }",//CPU
            "Type" => "text",
            "Size" => "25",
            "Description" => "{$_LANG['zjmf_configoptions_cpu_desc'] }",
            "Default" => "",
        ],
		"memory" => [
            "FriendlyName" => "{$_LANG['zjmf_configoptions_memory'] }",//内存
            "Type" => "text",
            "Size" => "25",
            "Description" => "MB",
            "Default" => "",
        ],	
		"bw" => [
            "FriendlyName" => "{$_LANG['zjmf_configoptions_bw'] }",//带宽
            "Type" => "text",
            "Size" => "25",
            "Description" => "Mbps",
            "Default" => "",
        ],	
		"data_disk_size" => [
            "FriendlyName" => "{$_LANG['zjmf_configoptions_data_disk_size'] }",//数据盘
            "Type" => "text",
            "Size" => "25",
            "Description" => "GB",
            "Default" => "",
        ],
		"ip_group" => [
            "FriendlyName" => "{$_LANG['zjmf_configoptions_ip_group'] }",//IP分组
            "Type" => "text",
            "Size" => "25",
            "Description" => "{$_LANG['zjmf_configoptions_ip_group_desc'] }",
            "Default" => "",
        ],
		"ip_num" => [
            "FriendlyName" => "{$_LANG['zjmf_configoptions_ip_num'] }",//IP数量
            "Type" => "text",
            "Size" => "25",
            "Description" => "{$_LANG['zjmf_configoptions_ip_num_desc'] }",
            "Default" => "",
        ],	
		"flow_limit" => [
            "FriendlyName" => "{$_LANG['zjmf_configoptions_flow_limit'] }",//流量
            "Type" => "text",
            "Size" => "25",
            "Description" => "GB",
            "Default" => "",
        ],
        "bind_mac" => [
            "FriendlyName" => "{$_LANG['zjmf_configoptions_ip_mac_bind'] }",//IP-MAC绑定
            "Type" => "text",
            "Size" => "25",
            "Description" => "{$_LANG['zjmf_configoptions_ip_mac_bind_desc']}",
            "Default" => "1",
        ],
        "type" => [
            "FriendlyName" => "{$_LANG['zjmf_configoptions_type'] }",//类型
            "Type" => "dropdown",
            "Options"=>[
                'host'=>'KVM加强版',
                'lightHost'=>'KVM轻量版',
                'hyperv'=>'Hyper-V',
            ],
            "Description" => "",
            "Default" => "host",
        ],
    ];
}
// 后台输出
function zjmfcloud_AdminServicesTabFields($params){
	global $_LANG;
    // 进入后台时自动同步一次,把原来磁盘的关联匹配上
    if(zjmfcloud_NeedDiskSync($params)){
        zjmfcloud_Sync($params);
    }
	zjmfcloud_AdminAreaAllowedFunctions($params);
	
	$power_status = zjmfcloud_GetStatus($params);
	$params['zjmfcloud_power_status']=$power_status['data']['status'] ?: $power_status['status'];

	$clouds = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'], [], 30, 'GET');

    $params['cloud_rescue_status'] = $clouds['data']['rescue'] ?: 0;
    $params['remote_image_group_id'] = $clouds['data']['image_group_id'] ?: 1;
    $js = zjmfcloud_AdminPageJS($params);

	$powerStatus=$power_status['msg'] ?: $power_status['data']['des'];
	$result = [];
	$result[$_LANG['zjmf_layer_panel_pass']] = '<span>'.$clouds['data']['panel_pass'].'</span>'.$js;
	$result[$_LANG['zjmf_power_status']] = '<span id="powerStatus">'.$powerStatus.'</span>';

    // 获取数据盘关联数据
    $disk_link = zjmfcloud_GetDiskLink($params);
    $disk_link_arr = array_column($disk_link, 'disk_id', 'option_name');

    $data_disk_size = isset($params['configoptions']['data_disk_size'])?$params['configoptions']['data_disk_size']:$params['configoption18'];
    if(!empty($data_disk_size)){
        $result['data_disk_size_id'] = sprintf('<input type="text" name="zjmf_data_disk_size" value="%s" class="form-control input-500 input-inline">', $disk_link_arr['data_disk_size'] ?: '');
    }
    foreach($params['configoptions'] as $k=>$v){
        if(in_array($k, ['data1_disk_size','data2_disk_size','data3_disk_size','data4_disk_size'])){
            $result[$k.'_id'] = sprintf('<input type="text" name="zjmf_%s" value="%s" class="form-control input-500 input-inline">', $k, $disk_link_arr[$k] ?: '');
        }
    }
	return $result;
}

// 开通云服务器
function zjmfcloud_CreateAccount($params){
	//echo "<pre>";var_dump($params);exit;
	global $_LANG;
	if($params['customfields']['hostid'] > 0){
        return $_LANG['zjmf_ceate_account'];
    }
    $rid = (int)$params['configoptions']['resource_package'];
    $accesshash=zjmfcloud_AccessHash($params['serveraccesshash']);

    // 改为ID
    if($accesshash['username'] == 'uid'){
        $username = $params['clientsdetails']['id'];
    }else{
        $username = $params['clientsdetails']['email'] ?: $params['clientsdetails']['phonenumber'];
    }
    $username = $accesshash['user_prefix'].$username;
    if($accesshash['account_type'] == 'agent'){
        // 先创建对应用户
        $user_data = [
            'username'=>$username,
            'email'=>$params['clientsdetails']['email'] ?: '',
            'status'=>1,
            'real_name'=>$params['clientsdetails']['fullname'] ?: '',
            'password'=>zjmfcloud_RandStr(8),
            'rid'=>$rid,
        ];
    }else{
        // 先创建对应用户
        $user_data = [
            'username'=>$username,
            'email'=>$params['clientsdetails']['email'] ?: '',
            'status'=>1,
            'real_name'=>$params['clientsdetails']['fullname'] ?: '',
            'password'=>zjmfcloud_RandStr(8)
        ];
    }
    $res = zjmfcloud_Curl($params, '/user', $user_data);
    // 获取用户ID
    $res = zjmfcloud_Curl($params, '/user/check', ['username'=>$username]);
    if(empty($res['data']['id'])){
        return $res['msg'] ? : $_LANG['zjmf_ceate_account_user_error'];
    }

	$system_disk_size=isset($params['configoptions']['system_disk_size'])?$params['configoptions']['system_disk_size']:$params['configoption1'];//系统盘
	$backup_num=isset($params['configoptions']['backup_num'])?$params['configoptions']['backup_num']:$params['configoption2'];//备份数量
	$snap_num=isset($params['configoptions']['snap_num'])?$params['configoptions']['snap_num']:$params['configoption3'];//快照数量
	$network_type=isset($params['configoptions']['network_type'])?$params['configoptions']['network_type']:$params['configoption4'];//网络类型
	$in_bw=isset($params['configoptions']['in_bw'])?$params['configoptions']['in_bw']:$params['configoption5'];//流入带宽
	$nat_acl_limit=isset($params['configoptions']['nat_acl_limit'])?$params['configoptions']['nat_acl_limit']:$params['configoption6'];//NAT转发数量
	$nat_web_limit=isset($params['configoptions']['nat_web_limit'])?$params['configoptions']['nat_web_limit']:$params['configoption7'];//NAT建站数量
	$system_disk_io_limit=isset($params['configoptions']['system_disk_io_limit'])?$params['configoptions']['system_disk_io_limit']:$params['configoption8'];//系统盘性能
	$data_disk_io_limit=isset($params['configoptions']['data_disk_io_limit'])?$params['configoptions']['data_disk_io_limit']:$params['configoption9'];//数据盘性能
	$area=isset($params['configoptions']['area'])?$params['configoptions']['area']:$params['configoption10'];//区域数据中心
	$node_group=isset($params['configoptions']['node_group'])?$params['configoptions']['node_group']:$params['configoption11'];//节点分组
	$node=isset($params['configoptions']['node'])?$params['configoptions']['node']:$params['configoption12'];//节点
	$node_priority=isset($params['configoptions']['node_priority'])?$params['configoptions']['node_priority']:$params['configoption13'];//节点优先级
	$os=isset($params['configoptions']['os'])?$params['configoptions']['os']:$params['configoption14'];//操作系统
	$cpu=isset($params['configoptions']['cpu'])?$params['configoptions']['cpu']:$params['configoption15'];//CPU
	$memory=isset($params['configoptions']['memory'])?$params['configoptions']['memory']:$params['configoption16'];//内存
	$bw=isset($params['configoptions']['bw'])?$params['configoptions']['bw']:$params['configoption17'];//带宽
	$data_disk_size=isset($params['configoptions']['data_disk_size'])?$params['configoptions']['data_disk_size']:$params['configoption18'];//数据盘
	$ip_group=isset($params['configoptions']['ip_group'])?$params['configoptions']['ip_group']:$params['configoption19'];//IP分组
	$ip_num=isset($params['configoptions']['ip_num'])?$params['configoptions']['ip_num']:$params['configoption20'];//IP数量
	$flow_limit=isset($params['configoptions']['flow_limit'])?$params['configoptions']['flow_limit']:$params['configoption21'];//流量
    $bind_mac=isset($params['configoptions']['IP_MACBond'])?$params['configoptions']['IP_MACBond']:$params['configoption22'];//IP-MAC绑定
    $store=isset($params['configoptions']['store'])?$params['configoptions']['store']:'';//存储
    $cpu_limit=isset($params['configoptions']['cpu_limit'])?$params['configoptions']['cpu_limit']:'';//CPU限制
    $traffic_bill_type=isset($params['configoptions']['traffic_bill_type'])?$params['configoptions']['traffic_bill_type']:'month';//流量计费方式
    $type=isset($params['configoptions']['type'])?$params['configoptions']['type']:$params['configoption23'];//节点类型
    $advanced_cpu = isset($params['configoptions']['advanced_cpu']) ? intval($params['configoptions']['advanced_cpu']) : null;
    $advanced_bw = isset($params['configoptions']['advanced_bw']) ? intval($params['configoptions']['advanced_bw']) : null;
    $flow_way = isset($params['configoptions']['flow_way']) ? $params['configoptions']['flow_way'] : 'all';
    $port = isset($params['configoptions']['port']) ? $params['configoptions']['port'] : 0;
    $ipv6_num=isset($params['configoptions']['ipv6_num'])?intval($params['configoptions']['ipv6_num']):0;//IPv6数量
    $data1_disk_size=$params['configoptions']['data1_disk_size'];
    $data2_disk_size=$params['configoptions']['data2_disk_size'];
    $data3_disk_size=$params['configoptions']['data3_disk_size'];
    $data4_disk_size=$params['configoptions']['data4_disk_size'];
    $simulate_physical_machine = isset($params['configoptions']['simulate_physical_machine']) ? intval($params['configoptions']['simulate_physical_machine']) : null;
    $niccard = isset($params['configoptions']['niccard']) ? intval($params['configoptions']['niccard']) : null;
    $gpu_num = isset($params['configoptions']['gpu_num']) ? intval($params['configoptions']['gpu_num']) : null;

    $traffic_type_arr = [
        'in'=>1,
        'out'=>2,
        'all'=>3
    ];
    $flow_way = $traffic_type_arr[$flow_way] ?: 3;

    $system_disk_size = zjmfcloud_FormatSystemDiskSize($system_disk_size);

	if(is_numeric($area)){
    	$post_data['area'] = $area;
    }
    if(is_numeric($node)){
    	$post_data['node'] = $node;
    }
	if(strpos($os,"|")!==false){
		$os=explode("|",$os);
		$os=$os[0];
	}
    // 兼容未升级魔方云也能使用
    if(is_array($system_disk_size)){
        // 获取镜像
        $os_info = zjmfcloud_Curl($params, '/images/'.$os, [], 30, 'GET');
        if($os_info['data']['image_group_id'] == 1){
            $system_disk_size = $system_disk_size[0];
        }else{
            $system_disk_size = $system_disk_size[1];
        }
    }
    $post_data['os'] = $os;
    $post_data['cpu'] = $cpu;
    $post_data['memory'] = $memory;
	$post_data['ip_num'] = $ip_num;
	$post_data['bw'] = $bw;
    $post_data['advanced_cpu'] = $advanced_cpu;
    $post_data['advanced_bw'] = $advanced_bw;
    $post_data['traffic_type'] = $flow_way;
    $post_data['port'] = $port;
    $post_data['simulate_physical_machine'] = $simulate_physical_machine;
	if(is_numeric($bw)){
		$post_data['in_bw'] = (int)$bw;
        $post_data['out_bw'] = (int)$bw;
	}
	if(is_numeric($in_bw)){
		$post_data['in_bw'] = (int)$in_bw;
	}
    $post_data['other_data_disk'] = [];
    $data_disk = [];
    if(!empty($data_disk_size)){
        $disk_info = zjmfcloud_GetDataDiskSize($params, $data_disk_size, 'data_disk_size');
        if($disk_info['size']>0){
            $post_data['other_data_disk'][] = $disk_info;
            $data_disk[] = 'data_disk_size';
        }
    }
    if(!empty($data1_disk_size)){
        $disk_info = zjmfcloud_GetDataDiskSize($params, $data1_disk_size, 'data1_disk_size');
        if($disk_info['size']>0){
            $post_data['other_data_disk'][] = $disk_info;
            $data_disk[] = 'data1_disk_size';
        }
    }
    if(!empty($data2_disk_size)){
        $disk_info = zjmfcloud_GetDataDiskSize($params, $data2_disk_size, 'data2_disk_size');
        if($disk_info['size']>0){
            $post_data['other_data_disk'][] = $disk_info;
            $data_disk[] = 'data2_disk_size';
        }
    }
    if(!empty($data3_disk_size)){
        $disk_info = zjmfcloud_GetDataDiskSize($params, $data3_disk_size, 'data3_disk_size');
        if($disk_info['size']>0){
            $post_data['other_data_disk'][] = $disk_info;
            $data_disk[] = 'data3_disk_size';
        }
    }
    if(!empty($data4_disk_size)){
        $disk_info = zjmfcloud_GetDataDiskSize($params, $data4_disk_size, 'data4_disk_size');
        if($disk_info['size']>0){
            $post_data['other_data_disk'][] = $disk_info;
            $data_disk[] = 'data4_disk_size';
        }
    }
	if($flow_limit){
		$post_data['traffic_quota'] = (int)$flow_limit;
    }
	if(!empty($ip_group)){
		$post_data['ip_group'] = $ip_group;
	}
	if(!empty($node_group)){
		$post_data['node_group'] = $node_group;
	}
	if(!empty($node_priority)){
		$post_data['node_priority'] = $node_priority;
	}
	//var_dump($system_sec);exit;
	if($system_disk_io_limit){
		$system_sec=explode(",",str_replace("，",",",$system_disk_io_limit));//系统盘性能
		if(count($system_sec)!=4){
			return $_LANG['zjmf_ceate_account_disk_system_error'].count($system_sec);
		}
		$post_data['system_read_bytes_sec']=$system_sec[0];
		$post_data['system_write_bytes_sec']=$system_sec[1];
		$post_data['system_read_iops_sec']=$system_sec[2];
		$post_data['system_write_iops_sec']=$system_sec[3];
	}
	if($data_disk_io_limit){
		$data_sec=explode(",",str_replace("，",",",$data_disk_io_limit));//数据盘性能
		if(count($data_sec)!=4){
			return $_LANG['zjmf_ceate_account_disk_data_error'].count($data_sec);
		}
		$post_data['data_read_bytes_sec']=$data_sec[0];
		$post_data['data_write_bytes_sec']=$data_sec[1];
		$post_data['data_read_iops_sec']=$data_sec[2];
		$post_data['data_write_iops_sec']=$data_sec[3];
	}
    if(is_numeric($system_disk_size) && $system_disk_size > 0){
        $post_data['system_disk_size'] = $system_disk_size;//系统盘
    }
    $post_data['backup_num'] = $backup_num;//备份数量
    $post_data['snap_num'] = $snap_num;//快照数量
	$post_data['network_type'] = $network_type;		
    if($network_type == 'vpc'){
        // 随机生成一个网络名称
        $post_data['vpc_name'] = 'VPC-'.zjmfcloud_RandStr(8);
    }
	$post_data['nat_acl_limit'] = $nat_acl_limit;	
	$post_data['nat_web_limit'] = $nat_web_limit;
	
    $post_data['client'] = $res['data']['id'];
    // 让魔方云自动生成
    // if(!empty($params['domain'])){
    // 	$post_data['hostname'] = $params['domain'];
    // }
    if(!empty($params['password'])){
		// if(preg_match('/[|!@#$%&*\\/=?,;\'"{}<>().:\\-_+~`^\\\\]/', $params['password'])){
		// 	$post_data['rootpass'] =zjmfcloud_RandStr();
			//$updatePassword['password']=encrypt($post_data['rootpass']);
			//Capsule::table("tblhosting")->where('id', '=', $params['serviceid'])->update($updatePassword);
		// }else{
			$post_data['rootpass'] = $params['password'];
		// }    	
    }
	if(isset($bind_mac) && in_array($bind_mac, [0,1])){
        $post_data['bind_mac'] = $bind_mac;
    }
    if(is_numeric($store)){
        $post_data['store'] = $store;
    }
    if(is_numeric($cpu_limit) && $cpu_limit>=0 && $cpu_limit <= 100){
        $post_data['cpu_limit'] = (int)$cpu_limit;
    }
    if($traffic_bill_type == 'last_30days'){
        $post_data['reset_flow_day'] = date('j');
    }
    $post_data['type'] = $type;

    if($accesshash['account_type'] == 'agent' && !empty($rid)){
        $post_data['rid'] = $rid;
    }
    if(!empty($ipv6_num)){
        $post_data['ipv6_num'] = $ipv6_num;
    }
    if(in_array($niccard, [1,2,3])){
        $post_data['niccard'] = $niccard;
    }
    $post_data['gpu_num'] = $gpu_num;
	//echo "<pre>";var_dump($post_data);exit;
    $res = zjmfcloud_Curl($params, '/clouds', $post_data);
    if($res['status'] == 'success') {
        $hostid = $res['data']['id'];

        $detail = zjmfcloud_Curl($params, '/clouds/'.$hostid, [], 20, 'GET');
        if($detail['status'] == 'success'){
        	$update['dedicatedip'] = $detail['data']['mainip'];

            $assignedips = array_merge(array_column($detail['data']['ip'], 'ipaddress') ?: [], array_column($detail['data']['ipv6'], 'ipv6') ?: []);
	        $update['assignedips'] = implode("\r\n", array_filter($assignedips, function($x) use ($detail) {
	            return $x != $detail['data']['mainip'];
	        }));
	        $update['domainstatus'] = 'Active';
	        $update['username'] = $detail['data']['osuser'];
	        $update['password'] = encrypt($detail['data']['rootpassword']);
	        // 刚开通时没有临时流量
	        $update['bwlimit'] = $detail['data']['traffic_quota'] * 1024;
	        $update['domain'] = $detail['data']['hostname'];

	        Capsule::table("tblhosting")->where('id', '=', $params['serviceid'])->update($update);
	        $description = $_LANG['zjmf_ceate_account_success'];

            $remote_port = !empty($detail['data']['port']) ? $detail['data']['port'] : ($detail['data']['image_group_id'] == 1 ? 3389 : 22);
            zjmfcloud_SetRemotePort($params, $remote_port);

            // 存储数据盘关联,创建时一定是按顺序创建的
            foreach($detail['data']['disk'] as $v){
                if($v['type'] == 'system'){
                    continue;
                }
                zjmfcloud_AddDiskLink(array_shift($data_disk), $params['serviceid'], $v['id']);
            }
        }else{
        	$description = $_LANG['zjmf_ceate_account_success_sync_error'];
        }
        $msg = 'success';
        zjmfcloud_SetHostID($params, $hostid);
        zjmfcloud_SetExtraOs($params, $params['configoptions']['os'] ?: '');
    } else if ($res['status'] == 'error') {
        $msg = $_LANG['zjmf_ceate_account_error'].$res['msg'];
    } else {
        $msg = $_LANG['zjmf_ceate_account_error_api'] ;
    }
    return $msg;
}

// 暂停
function zjmfcloud_SuspendAccount($params){
	global $_LANG;
	if(empty($params['customfields']['hostid'])){
		return $_LANG['zjmf_api_host_id_error'] ;
	}
	$res = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'].'/suspend');
	if($res['status'] == 'success'){
		$result = 'success';
	}else{
		$result = $_LANG['zjmf_suspend_account_error'] .$res['msg'];
	}
	return $result;
}

// 解除暂停
function zjmfcloud_UnsuspendAccount($params){
	global $_LANG;
	if(empty($params['customfields']['hostid'])){
		return $_LANG['zjmf_api_host_id_error'] ;
	}
	$res = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'].'/unsuspend');
	if($res['status'] == 'success'){
		$result = 'success';
	}else{
		$result = $_LANG['zjmf_unsuspend_account_error'].$res['msg'];
	}
	return $result;
}

// 删除
function zjmfcloud_TerminateAccount($params){
	//echo "<pre>";var_dump($params);exit;
	global $_LANG;
	if(empty($params['customfields']['hostid'])){
		return $_LANG['zjmf_api_host_id_error'] ;
	}
	$res = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'], [], 30, 'DELETE');
	if($res['status'] == 'success' || $res['http_code'] == 404){
		$update = [
			'domain'=>'',
			'dedicatedip'=>'',
			'assignedips'=>'',
			'username'=>'',
			'password'=>''
		];
		Capsule::table('tblhosting')->where('id', '=', $params['serviceid'])->update($update);
		$id = Capsule::table('tblcustomfields')
					->where('type', '=', 'product')
					->where('relid', '=', $params['packageid'])
					->where('fieldname', '=', 'hostid')
					->value('id');
		Capsule::table('tblcustomfieldsvalues')
		->where('fieldid','=', $id)
		->where('relid','=', $params['serviceid'])
		->where('value','=', $params['customfields']['hostid'])
		->update(['value'=>'']);
		$result = 'success';

        $sql = "DELETE FROM `zjmfcloud_disk_link` WHERE `host_id`=".intval($params['serviceid']);
        full_query($sql);
	}else{
		$result = $_LANG['zjmf_terminate_account_error'].$res['msg'];
	}
	return $result;
}

//升级
function zjmfcloud_ChangePackage($params){
	global $_LANG;
	if(empty($params['customfields']['hostid'])){
		return $_LANG['zjmf_api_host_id_error'] ;
	}
	$clouds = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'], [], 30, 'GET');	
	if($clouds['status'] != 'success'){
		return $_LANG['zjmf_admin_result_changePackage_error'];
	}

	$backup_num=isset($params['configoptions']['backup_num'])?$params['configoptions']['backup_num']:$params['configoption2'];//备份数量
	$snap_num=isset($params['configoptions']['snap_num'])?$params['configoptions']['snap_num']:$params['configoption3'];//快照数量
	$in_bw=isset($params['configoptions']['in_bw'])?$params['configoptions']['in_bw']:$params['configoption5'];//流入带宽
    $system_disk_io_limit=isset($params['configoptions']['system_disk_io_limit'])?$params['configoptions']['system_disk_io_limit']:$params['configoption8'];//系统盘性能
    $data_disk_io_limit=isset($params['configoptions']['data_disk_io_limit'])?$params['configoptions']['data_disk_io_limit']:$params['configoption9'];//数据盘性能
	$cpu=isset($params['configoptions']['cpu'])?$params['configoptions']['cpu']:$params['configoption15'];//CPU
	$memory=isset($params['configoptions']['memory'])?$params['configoptions']['memory']:$params['configoption16'];//内存
	$bw=isset($params['configoptions']['bw'])?$params['configoptions']['bw']:$params['configoption17'];//带宽
	$data_disk_size=isset($params['configoptions']['data_disk_size'])?$params['configoptions']['data_disk_size']:$params['configoption18'];//数据盘
	$ip_num=isset($params['configoptions']['ip_num'])?$params['configoptions']['ip_num']:$params['configoption20'];//IP数量
	$flow_limit=isset($params['configoptions']['flow_limit'])?$params['configoptions']['flow_limit']:$params['configoption21'];//流量	
	$ipv6_num=isset($params['configoptions']['ipv6_num'])?intval($params['configoptions']['ipv6_num']):null;//IP数量
	$data1_disk_size=$params['configoptions']['data1_disk_size'];
    $data2_disk_size=$params['configoptions']['data2_disk_size'];
    $data3_disk_size=$params['configoptions']['data3_disk_size'];
    $data4_disk_size=$params['configoptions']['data4_disk_size'];

    $log_detail = [];
    $post_data = [];
	// cpu  内存 流量 备份数量  快照数量
	if($backup_num >-1 && $clouds['data']['backup_num'] != $backup_num){
        $post_data['backup_num'] = $backup_num;
    }
	if($snap_num >-1 && $clouds['data']['snap_num'] != $snap_num){
        $post_data['snap_num'] = $snap_num;
    }
    if($cpu > 0 && $cpu != $clouds['data']['cpu']){
        $post_data['cpu'] = $cpu;
    }
    if($memory > 0 && $memory != $clouds['data']['memory'] * 1024){
        $post_data['memory'] = $memory;
    }
    if(is_numeric($flow_limit) && $flow_limit >= 0 && $flow_limit != $clouds['data']['traffic_quota']){
        $post_data['traffic_quota'] = (int)$flow_limit;
    }

    $auto_boot = false;
    if(isset($post_data['cpu']) || isset($post_data['memory']) || !empty($system_disk_io_limit) || !empty($data_disk_io_limit)){
        $auto_boot = true;
    }
    if($clouds['data']['status'] != 'on' && $clouds['data']['status'] != 'wait_reboot'){
        $auto_boot = false;
    }
    if($auto_boot){
        zjmfcloud_Curl($params,'/clouds/'.$params['customfields']['hostid'].'/hardoff', [], 10, 'POST');
        // 检查是否关机成功,检查3分钟
        for($i = 0; $i<18; $i++){
            $cloud_status = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'], [], 30, 'GET');   
            if($cloud_status['data']['status'] == 'off'){
                break;
            }
            sleep(10);
        }
    }
    
    if(!empty($post_data)){
        $res = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'], $post_data, 30, 'PUT');

        $config_desc_arr = [
            'backup_num'    => $_LANG['zjmf_backup_name'],
            'snap_num'      => $_LANG['zjmf_snapshot_name'],
            'cpu'           => 'CPU',
            'memory'        => $_LANG['zjmf_configoptions_memory'],
            'traffic_quota' => $_LANG['zjmf_traffic_quota'],
        ];
        $config_desc = '';
        foreach($post_data as $k=>$v){
            $config_desc .= sprintf(',%s:%d', $config_desc_arr[$k], $v);
        }
        if($res['status'] == 'success'){
            $log_detail[] = zjmfcloud_Langset('zjmf_log_upgrade_config_success', [
                'detail'=>$config_desc,
            ]);
        }else{
            $log_detail[] = zjmfcloud_Langset('zjmf_log_upgrade_config_fail', [
                'detail' => $config_desc,
                'reason' => $res['msg'],
            ]);
        }
    }
    // 有流量上限变动才尝试
    if(isset($post_data['traffic_quota'])){
        // 可能升级完流量限制,解除超流暂停
        if($clouds['data']['status'] == 'suspend' && $clouds['data']['suspend_type'] == 'traffic'){
            // 检查流量
            $traffic_usage = zjmfcloud_TrafficTotal($params);
            if(is_numeric($traffic_usage['data']['percent']) && $traffic_usage['data']['percent'] < 100){
                // 解除暂停
                $res = zjmfcloud_UnsuspendAccount($params);
                if($res == 'success'){
                    $log_detail[] = zjmfcloud_Langset('zjmf_log_upgrade_unsuspend_success');
                }else{
                    $log_detail[] = zjmfcloud_Langset('zjmf_log_upgrade_unsuspend_fail', [
                        'reason' => $res,
                    ]);
                }
            }
        }else if($clouds['data']['internet'] == 0){
            // 断网
            $traffic_usage = zjmfcloud_TrafficTotal($params);
            if(is_numeric($traffic_usage['data']['percent']) && $traffic_usage['data']['percent'] < 100){
                // 解除暂停
                $res = zjmfcloud_RestoreNetwork($params);
                if($res['status'] == 'success'){
                    $log_detail[] = zjmfcloud_Langset('zjmf_log_upgrade_recover_network_success');
                }else{
                    $log_detail[] = zjmfcloud_Langset('zjmf_log_upgrade_recover_network_fail', [
                        '{reason}' => $res['msg'],
                    ]);
                }
            }
        }else if(isset($clouds['data']['over_flow_limit_bw']) && $clouds['data']['over_flow_limit_bw'] == 1){
            // 超额限流
            $traffic_usage = zjmfcloud_TrafficTotal($params);
            if(is_numeric($traffic_usage['data']['percent']) && $traffic_usage['data']['percent'] < 100){
                // 解除暂停
                $res = zjmfcloud_RecoverOriginBw($params);
                if($res['status'] == 'success'){
                    $log_detail[] = zjmfcloud_Langset('zjmf_log_upgrade_recover_bw_success');
                }else{
                    $log_detail[] = zjmfcloud_Langset('zjmf_log_upgrade_recover_bw_fail', [
                        '{reason}' => $res['msg'],
                    ]);
                }
            }
        }
    }
    if(is_numeric($ip_num) && $ip_num != $clouds['data']['ip_num']){
        $res_ip = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'].'/ip', ['num'=>$ip_num], 30, 'PUT');
        if($res_ip['status'] == 'success'){
            $log_detail[] = zjmfcloud_Langset('zjmf_log_upgrade_ip_num_success', [
                'ip_num' => $ip_num,
            ]);
        }else{
            $log_detail[] = zjmfcloud_Langset('zjmf_log_upgrade_ip_num_fail', [
                'ip_num' => $ip_num,
                'reason' => $res['msg'],
            ]);
        }
    }
	// 带宽
	if(is_numeric($bw)){
        if($bw != $clouds['data']['bw_group'][0]['out_bw']){
            $post_bw['out_bw'] = (int)$bw;
        }
        if($bw != $clouds['data']['bw_group'][0]['in_bw']){
            $post_bw['in_bw'] = (int)$bw;
        }
	}
	if(is_numeric($in_bw) && $in_bw != $clouds['data']['bw_group'][0]['in_bw']){
		$post_bw['in_bw'] = (int)$in_bw;
	}
    if(!empty($post_bw)){
        $res_bw = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'].'/bw', $post_bw, 30, 'PUT');
        if($res_bw['status'] == 'success'){
            $log_detail[] = zjmfcloud_Langset('zjmf_log_upgrade_bw_success', [
                'in_bw'  => $post_bw['in_bw'] ?: $_LANG['zjmf_no_change'],
                'out_bw' => $post_bw['out_bw'] ?: $_LANG['zjmf_no_change'],
            ]);
        }else{
            $log_detail[] = zjmfcloud_Langset('zjmf_log_upgrade_bw_fail', [
                'in_bw'  => $post_bw['in_bw'] ?: $_LANG['zjmf_no_change'],
                'out_bw' => $post_bw['out_bw'] ?: $_LANG['zjmf_no_change'],
                'reason' => $res['msg'],
            ]);
        }
    }

    // 系统盘存储ID
    $system_disk_store = 0;

    // 当前数据盘id,size关系
    $real_data_disk = $clouds['data']['disk'];
    array_shift($real_data_disk);
    $real_disk_size = array_column($real_data_disk, 'size', 'id');

    $data_disk_arr = [
        'data_disk_size'=>$data_disk_size,
        'data1_disk_size'=>$data1_disk_size,
        'data2_disk_size'=>$data2_disk_size,
        'data3_disk_size'=>$data3_disk_size,
        'data4_disk_size'=>$data4_disk_size,
    ];
    $new_disk = [];

    // 数据盘扩容
    foreach($data_disk_arr as $k=>$v){
        if(empty($v)){
            continue;
        }
        $disk_info = zjmfcloud_GetDataDiskSize($params, $v, $k);
        if(empty($disk_info['size'])){
            continue;
        }
        $disk_id = zjmfcloud_GetDiskId($k, $params['serviceid']);
        $store_id = $disk_info['store'];
        
        if($disk_id>0){
            // 数据盘ID不属于该实例
            if(empty($real_disk_size[$disk_id])){
                $log_detail[] = zjmfcloud_Langset('zjmf_log_upgrade_disk_size_fail', [
                    'diskid' => $disk_id,
                    'size'   => $disk_info['size'],
                    'reason' => $_LANG['zjmf_data_disk_not_belong_to_this_host'],
                ]);
                continue;
            }
            if($disk_info['size'] > $real_disk_size[$disk_id]){

            }else if($disk_info['size'] == $real_disk_size[$disk_id]){
                // 未改变,下一个
                continue;
            }
            $res_disk = zjmfcloud_Curl($params, '/disks/'.$disk_id, ['size'=>$disk_info['size']], 30, 'PUT');
            if($res_disk['status'] != 'success'){
                $log_detail[] = zjmfcloud_Langset('zjmf_log_upgrade_disk_size_fail', [
                    'diskid' => $disk_id,
                    'size'   => $disk_info['size'],
                    'reason' => $res_disk['msg'],
                ]);
            }else{
                $log_detail[] = zjmfcloud_Langset('zjmf_log_upgrade_disk_size_success', [
                    'diskid' => $disk_id,
                    'size'   => $disk_info['size'],
                ]);
            }
        }else{
            if(empty($store_id)){
                if(empty($system_disk_store)){
                    $stores=zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'].'/stores', '', 30, 'GET');         
                    $store_name=$clouds['data']['disk'][0]['store_name'];
                    foreach($stores['data'] as $v){
                        if($v['name']==$store_name){
                            $system_disk_store=$v['id'];
                        }
                    }
                }
                $store_id = $system_disk_store;
            }
            if($store_id>0){
                $disk = [];
                $disk['id']=$params['customfields']['hostid'];
                $disk['store']=$store_id;
                $disk['driver'] = 'virtio';
                $disk['size'] = $disk_info['size'];
                $res_disk = zjmfcloud_Curl($params,'/clouds/'.$params['customfields']['hostid'].'/disks', $disk, 30, 'POST');
                if($res_disk['status'] != 'success'){
                    $log_detail[] = zjmfcloud_Langset('zjmf_log_upgrade_add_disk_fail', [
                        'size'  => $disk_info['size'],
                        'reason'=> $res_disk['msg'],
                    ]);
                }else{
                    zjmfcloud_AddDiskLink($k, $params['serviceid'], $res_disk['data']['diskid']);
                    $new_disk[] = $res_disk['data']['diskid'];

                    $log_detail[] = zjmfcloud_Langset('zjmf_log_upgrade_add_disk_success', [
                        'size' => $disk_info['size'],
                    ]);
                }
            }
        }
    }
    // ipv6数量
    if(is_numeric($ipv6_num) && $ipv6_num != $clouds['data']['ipv6_num']){
        $res_ipv6 = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'].'/ipv6', ['num'=>$ipv6_num], 30, 'PUT');
        if($res_ipv6['status'] != 'success'){
            $log_detail[] = zjmfcloud_Langset('zjmf_log_upgrade_ipv6_num_fail', [
                'num'   => $ipv6_num,
                'reason'=> $res_ipv6['msg'],
            ]);
        }else{
            $log_detail[] = zjmfcloud_Langset('zjmf_log_upgrade_ipv6_num_success', [
                'num' => $ipv6_num,
            ]);
        }
    }

    if(!empty($system_disk_io_limit)){
        $arr = explode(',', $system_disk_io_limit);
        $post_data_for_disk['read_bytes_sec'] = $arr[0] > 0 ? (int)$arr[0] : 0;
        $post_data_for_disk['write_bytes_sec'] = $arr[1] > 0 ? (int)$arr[1] : 0;
        $post_data_for_disk['read_iops_sec'] = $arr[2] > 0 ? (int)$arr[2] : 0;
        $post_data_for_disk['write_iops_sec'] = $arr[3] > 0 ? (int)$arr[3] : 0;

        foreach($clouds['data']['disk'] as $v){
            if($v['type'] == 'system'){
                if($post_data_for_disk['read_bytes_sec'] == $v['read_bytes_sec'] && $post_data_for_disk['write_bytes_sec'] == $v['write_bytes_sec'] && $post_data_for_disk['read_iops_sec'] == $v['read_iops_sec'] && $post_data_for_disk['write_iops_sec'] == $v['write_iops_sec']){
                    break;
                }
                $res_system_disk_io_limit = zjmfcloud_Curl($params, '/disks/'.$v['id'], $post_data_for_disk, 30, 'PUT');
                if($res_system_disk_io_limit['status'] != 'success'){
                    $log_detail[] = zjmfcloud_Langset('zjmf_log_upgrade_system_disk_io_limit_fail', [
                        'limit'  => $system_disk_io_limit,
                        'reason' => $res_system_disk_io_limit['msg'],
                    ]);
                }else{
                    $log_detail[] = zjmfcloud_Langset('zjmf_log_upgrade_system_disk_io_limit_success', [
                        'limit' => $system_disk_io_limit,
                    ]);
                }
                break;
            }
        }
    }
    if(!empty($data_disk_io_limit)){
        $arr = explode(',', $data_disk_io_limit);
        $post_data_for_disk['read_bytes_sec'] = $arr[0] > 0 ? (int)$arr[0] : 0;
        $post_data_for_disk['write_bytes_sec'] = $arr[1] > 0 ? (int)$arr[1] : 0;
        $post_data_for_disk['read_iops_sec'] = $arr[2] > 0 ? (int)$arr[2] : 0;
        $post_data_for_disk['write_iops_sec'] = $arr[3] > 0 ? (int)$arr[3] : 0;

        foreach($clouds['data']['disk'] as $v){
            if($v['type'] == 'data'){
                if($post_data_for_disk['read_bytes_sec'] == $v['read_bytes_sec'] && $post_data_for_disk['write_bytes_sec'] == $v['write_bytes_sec'] && $post_data_for_disk['read_iops_sec'] == $v['read_iops_sec'] && $post_data_for_disk['write_iops_sec'] == $v['write_iops_sec']){
                    continue;
                }
                $res_data_disk_io_limit = zjmfcloud_Curl($params, '/disks/'.$v['id'], $post_data_for_disk, 30, 'PUT');
                if($res_data_disk_io_limit['status'] != 'success'){
                    $log_detail[] = zjmfcloud_Langset('zjmf_log_upgrade_data_disk_io_limit_fail', [
                        'diskid' => $v['id'],
                        'limit'  => $data_disk_io_limit,
                        'reason' => $res_data_disk_io_limit['msg'],
                    ]);
                }else{
                    $log_detail[] = zjmfcloud_Langset('zjmf_log_upgrade_data_disk_io_limit_success', [
                        'diskid' => $v['id'],
                        'limit'  => $data_disk_io_limit,
                    ]);
                }
            }
        }
        foreach($new_disk as $v){
            // 重试3次
            for($i = 0; $i<3; $i++){
                $res_data_disk_io_limit = zjmfcloud_Curl($params, '/disks/'.$v, $post_data_for_disk, 30, 'PUT');
                if($res_data_disk_io_limit['status'] == 'success'){
                    break;
                }
                sleep(5);
            }
            if($res_data_disk_io_limit['status'] != 'success'){
                $log_detail[] = zjmfcloud_Langset('zjmf_log_upgrade_data_disk_io_limit_fail', [
                    'diskid' => $v,
                    'limit'  => $data_disk_io_limit,
                    'reason' => $res_data_disk_io_limit['msg'],
                ]);
            }else{
                $log_detail[] = zjmfcloud_Langset('zjmf_log_upgrade_data_disk_io_limit_success', [
                    'diskid' => $v,
                    'limit'  => $data_disk_io_limit,
                ]);
            }
        }
    }
    if($auto_boot){
        zjmfcloud_Curl($params,'/clouds/'.$params['customfields']['hostid'].'/on', [], 10, 'POST');
    }
    if(!empty($log_detail)){
        $description = zjmfcloud_Langset('zjmf_log_upgrade_complete', [
            'detail'    => implode(',', $log_detail),
            'serviceid' => $params['serviceid'],
        ]);
        logActivity($description);
    }

	zjmfcloud_Sync($params, false);
	return 'success';
}



// 后台模块自定义按钮
function zjmfcloud_AdminCustomButtonArray($params) {
    global $_LANG;
	if(empty($params)){
        $params['serviceid'] = $_GET['id'];
    }
    $button = [];
    if(!empty($params['customfields']['hostid'])){
    	$button[$_LANG['zjmf_api_power_status_unpaused']] = 'Unpaused';
    	$button[$_LANG['zjmf_api_on'] ] = 'On';
    	$button[$_LANG['zjmf_api_off'] ] = 'Off';
    	$button[$_LANG['zjmf_api_reboot']] = 'Reboot';
    	$button[$_LANG['zjmf_api_hardoff']] = 'HardOff';
    	$button[$_LANG['zjmf_api_hardreboot']] = 'HardReboot';
    	$button['reinstall'] = '';
        $button['crackpass'] = '';
    	$button['rescue'] = ''; // 救援系统
    	$button['vnc'] = '';
    	$button[$_LANG['zjmf_api_sync']] = 'Sync';
    	$button['panel'] = '';
    }
    return $button;
}

// 后台允许的方法
function zjmfcloud_AdminAreaAllowedFunctions($params){
	global $_LANG;
    $method = $_POST['zjmfcloud_method'] ?: $_GET['zjmfcloud_method'];
    if(isset($method)){
    	switch($method){
    		case 'vnc':
    			$result = zjmfcloud_Vnc($params);
    			break;
	        case 'vnc_page':
	        	zjmfcloud_VncPage($params);
	            break;
            case 'reinstall':
                $result = zjmfcloud_Reinstall($params);
                break;
            case 'crack_pass':
                $result = zjmfcloud_CrackPass($params);
                break;
			case 'powerStatus':
                $result = zjmfcloud_GetStatus($params, 'admin');
                break;
            case 'rescue':
                $result = zjmfcloud_Rescue($params);
                break;
            case 'exit_rescue':
                $result = zjmfcloud_ExitRescue($params);
                break;
	        default:
                $result['status'] = 'error';
                $result['msg'] = $_LANG['zjmf_admin_result_invalid'];
	            break;
	    }
	    ob_clean();
	    echo json_encode($result);exit;
    }
}

function zjmfcloud_AdminServicesTabFieldsSave($params){
    if(!empty($params['customfields']['hostid']) && isset($params['configoptions']['traffic_bill_type'])){
        $res = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'], [], 15, 'GET');

        $detail = $res['data'];
        if($res['status'] == 'success' && isset($detail['reset_flow_day'])){
            if($params['configoptions']['traffic_bill_type'] == 'last_30days'){
                $reset_flow_day = date('j', strtotime($detail['create_time']));
            }else{
                $reset_flow_day = 1;
            }
            if($reset_flow_day != $detail['reset_flow_day']){
                zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'], ['reset_flow_day'=>$reset_flow_day], 5, 'PUT');
            }
        }
    }
    // 允许手动调整
    $data_disk = [
        'data_disk_size',
        'data1_disk_size',
        'data2_disk_size',
        'data3_disk_size',
        'data4_disk_size',
    ];
    foreach($data_disk as $v){
        if(isset($_POST['zjmf_'.$v])){
            zjmfcloud_AddDiskLink($v, $params['serviceid'], (int)$_POST['zjmf_'.$v]);
        }
    }
}

//前台页面输出
function zjmfcloud_ClientArea($params){
	global $_LANG;
	if($params['status']!="Active") return false;
	$ac = $_GET['ac'];
    $id =$_GET['id'];
	if($ac=="default" || $ac=="snapshots" || $ac=="safe" || $ac=="setting" || $ac=="nat" || $ac == 'ssh_key'){
		$str=file_get_contents('php://input');
		if(zjmfcloud_IsNotJson($str)){
			parse_str($str,$requestData);
			$func =$requestData['func'];
		}else if($str){
			$requestData=json_decode($str,true);
			$func =$requestData['func'];
		}
	} 
	if($ac=="product"){
        // 进入前台时自动同步一次,把原来磁盘的关联匹配上
        if(zjmfcloud_NeedDiskSync($params)){
            zjmfcloud_Sync($params);
        }
        $serveraccesshash = zjmfcloud_AccessHash($params['serveraccesshash']);
		$pdo = Capsule::connection()->getPdo();
		$sql="select dedicatedip,assignedips from tblhosting 
		where id={$params['serviceid']}
		";
		$hosting = $pdo->query($sql)->fetch(PDO::FETCH_ASSOC);
		//$tblhosting = Capsule::select($sql);
		//$hosting=zjmfcloud_ObjectToArray($tblhosting);
		$data=array(
			"domain"=>$params['domain'],
			"dedicatedip"=>$hosting['dedicatedip'],
			"username"=>$params['username'],
			"password"=>$params['password'],
			"productname"=>$params['templatevars']['product'],
            "bwusage"=>0,//$hosting['bwusage'],
            "bwlimit"=>0,//$hosting['bwlimit'],
            "assignedips"=>explode("\r\n", $hosting['assignedips']) ?: [],
		);
        $data['assignedips'] = array_filter($data['assignedips']);
        if(strpos($data['assignedips'][0], $data['dedicatedip']) === false){
            array_unshift($data['assignedips'], $data['dedicatedip']);
        }
        // if(!in_array($data['dedicatedip'], $data['assignedips'])){
        //     array_unshift($data['assignedips'], $data['dedicatedip']);
        // }
        $data['assignedips'] = array_values($data['assignedips']);
		$sql="select ops.optionname from tblhosting as h
		left Join tblproductconfiglinks as link on link.pid=h.packageid
		left Join tblproductconfigoptions as ops on ops.gid=link.gid
		where h.id={$params['serviceid']}
		";
		$optionname = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
		//$tblproductconfigoptionssub = Capsule::select($sql);
		//$optionname=zjmfcloud_ObjectToArray($tblproductconfigoptionssub);
		$optionname=array_column($optionname,"optionname");
		foreach($optionname as $v){
			$opname=explode("|",$v);
			$optionname_array[$opname[1]]=$opname[0];
		}
		$optionssub=array(); $dant=[];
		foreach($params['templatevars']['configurableoptions'] as $k=>$v){
			if($optionname_array[$v['optionname']]=="os"){
				$optionssub[$k]['option_type']=5;
				$optionssub[$k]['sub_name']=(strpos($v['selectedname'],"^"))?substr($v['selectedname'],strpos($v['selectedname'],"^")+1):$v['selectedname'];
				$optionssub[$k]['name']=$_LANG['zjmf_layer_content_os'] ;
				$optionssub[$k]['sub_img_name']=strtolower(substr($v['selectedname'],0,strpos($v['selectedname'],"^")));
				$dant["os"]="os";
			}else if($optionname_array[$v['optionname']]=="cpu"){
				$optionssub[$k]['option_type']=6;
				$optionssub[$k]['sub_name']=$v['selectedname'];
				$optionssub[$k]['name']="CPU";
				$dant["cpu"]="cpu";
			}else if($optionname_array[$v['optionname']]=="memory"){
				$optionssub[$k]['option_type']=8;
				$optionssub[$k]['sub_name']=$v['selectedname'];
				$optionssub[$k]['name']=$_LANG['zjmf_clientarea_memory'];
				$dant["memory"]="memory";
			}
		}
		
		$second=array(
			'allow_second_verify'=>1,
			'second_verify'=>0,
			'second_verify_action_home'=>array("ikvm","kvm","off","reboot","bmc","crack_pass","rescue","on","hard_off","hard_reboot","vnc","get_api_pwd","modify_api_pwd","reinstall"),
		);
		$clouds = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'], array(), 30, 'GET');
        $data['type'] = $clouds['data']['type'] ?: 'host';
        $data['reset_flow_day'] = $clouds['data']['reset_flow_day'] ?: 1;
        $data['port'] = (int)$clouds['data']['port'];
        $data['rescue'] = $clouds['data']['rescue'] ?: 0;
        $data['image_group_id'] = $clouds['data']['image_group_id'];
        $data['ssh_key_id'] = $clouds['data']['ssh_key']['id'] ?: 0;

        if($data['type'] == 'hyperv'){
            $data['bwlimit'] = 0;
        }
/* 		if($_GET['bug']){
			
			echo "<pre>"; var_dump($clouds);exit;
		} */
		$dant_k=count($optionssub);
		if(!$dant["os"]){
			$optionssub[$dant_k+1]['option_type']=5;
			$optionssub[$dant_k+1]['sub_name']=$clouds['data']['operate_system'];
			$optionssub[$dant_k+1]['name']=$_LANG['zjmf_layer_content_os'] ;
		}
		if(!$dant["cpu"]){
			$optionssub[$dant_k+2]['option_type']=6;
			$optionssub[$dant_k+2]['sub_name']=$clouds['data']['cpu'].$_LANG['zjmf_configoptions_cpu_desc'];
			$optionssub[$dant_k+2]['name']="CPU";
		}
		if(!$dant["memory"]){
			$optionssub[$dant_k+3]['option_type']=8;
			$optionssub[$dant_k+3]['sub_name']=$clouds['data']['memory']."GB";
			$optionssub[$dant_k+3]['name']=$_LANG['zjmf_clientarea_memory'];
		}
		//NAT转发
		$nat_acl = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid']."/nat_acl", array('sort'=>'asc','list_type'=>'all'), 30, 'GET');
		if($nat_acl['data']['data'][0]['ext_port']){
			end($optionssub); $subk=key($optionssub);
			$optionssub[$subk+1]['option_type']=9;
			$optionssub[$subk+1]['sub_name']=$nat_acl['data']['nat_host_ip'].":".$nat_acl['data']['data'][0]['ext_port'];
			$optionssub[$subk+1]['name']=$_LANG['zjmf_clientarea_nat_ext'] ;
			$optionssub[$subk+2]['option_type']=10;
			$optionssub[$subk+2]['sub_name']=$nat_acl['data']['nat_host_ip'];
			$optionssub[$subk+2]['name']=$_LANG['zjmf_clientarea_nat_host_ip'];
		}
		$optionssub=array_merge($optionssub);
		$data['panel_pass']=$clouds['data']['panel_pass'];
		if(is_array($clouds['data'])){
			$nat=array(
				'backup_num'=>$clouds['data']['backup_num'],//备份数量限制(0不限-1不允许)
				'snap_num'=>$clouds['data']['snap_num'],//快照数量限制(0不限-1不允许)
				'nat_acl'=>$clouds['data']['nat_acl_limit'],//NAT转发数量
				'nat_web'=>$clouds['data']['nat_web_limit'],//NAT建站数量
			);
            if($data['type'] == 'hyperv'){
                $nat['snap_num'] = -1;
            }
		}
		$lang['zjmf_client_ipaddressNum']=$_LANG['zjmf_client_ipaddressNum'];
		$lang['zjmf_client_username']=$_LANG['zjmf_client_username'] ;
		$lang['zjmf_layer_content_password']=$_LANG['zjmf_layer_content_password']  ;
		$lang['zjmf_api_crackpass']=$_LANG['zjmf_api_crackpass']  ;
		$lang['zjmf_client_port']=$_LANG['zjmf_client_port']  ;
		$lang['zjmf_client_default']=$_LANG['zjmf_client_default']  ;
		$lang['zjmf_client_changedate']=$_LANG['zjmf_client_changedate']  ;
		$lang['zjmf_client_usage']=$_LANG['zjmf_client_usage']  ;
		$lang['zjmf_client_usage_chart']=$_LANG['zjmf_client_usage_chart']  ;
		$lang['zjmf_client_snap_backup']=$_LANG['zjmf_client_snap_backup']  ;
		$lang['zjmf_client_security']=$_LANG['zjmf_client_security']  ;
		$lang['zjmf_client_setting']=$_LANG['zjmf_client_setting']  ;
		$lang['zjmf_client_nat_acl']=$_LANG['zjmf_client_nat_acl']  ;
		$lang['zjmf_client_nat_web']=$_LANG['zjmf_client_nat_web']  ;
		$lang['zjmf_api_reinstall']=$_LANG['zjmf_api_reinstall']  ;
		$lang['zjmf_client_os']=$_LANG['zjmf_client_os']  ;
		$lang['zjmf_client_backup_ok']=$_LANG['zjmf_client_backup_ok']  ;
		$lang['zjmf_layer_confirm']=$_LANG['zjmf_layer_confirm']  ;
		$lang['zjmf_layer_cancel']=$_LANG['zjmf_layer_cancel']  ;
		$lang['zjmf_check_password']=$_LANG['zjmf_check_password']  ;
		$lang['zjmf_api_on']=$_LANG['zjmf_api_on']  ;
		$lang['zjmf_api_off']=$_LANG['zjmf_api_off']  ;
		$lang['zjmf_api_reboot']=$_LANG['zjmf_api_reboot']  ;
		$lang['zjmf_api_hardoff']=$_LANG['zjmf_api_hardoff']  ;
		$lang['zjmf_api_hardreboot']=$_LANG['zjmf_api_hardreboot']  ;
		$lang['zjmf_api_power_status_unknown']=$_LANG['zjmf_api_power_status_unknown']  ;
		$lang['zjmf_client_copy_success']=$_LANG['zjmf_client_copy_success']  ;
		$lang['zjmf_client_copy_error']=$_LANG['zjmf_client_copy_error']  ;
		$lang['zjmf_client_data_no']=$_LANG['zjmf_client_data_no']  ;
		$lang['zjmf_client_traffic_usage']=$_LANG['zjmf_client_traffic_usage']  ;
		$lang['zjmf_client_password']=$_LANG['zjmf_client_password']  ;
		$lang['zjmf_client_password_error']=$_LANG['zjmf_client_password_error']  ;
		$lang['zjmf_client_chart']=$_LANG['zjmf_client_chart']  ;
		$lang['zjmf_client_tips']=$_LANG['zjmf_client_tips']  ;
		$lang['zjmf_api_power_status_unpaused']=$_LANG['zjmf_api_power_status_unpaused']  ;
		$lang['zjmf_layer_panel_pass']=$_LANG['zjmf_layer_panel_pass']  ;
		$lang['zjmf_clients_repassword_1']=$_LANG['zjmf_clients_repassword_1']  ;
		$lang['zjmf_clients_repassword_2']=$_LANG['zjmf_clients_repassword_2']  ;
		$lang['zjmf_clients_repassword_3']=$_LANG['zjmf_clients_repassword_3']  ;
		$lang['zjmf_clients_repassword_4']=$_LANG['zjmf_clients_repassword_4']  ;
		$lang['zjmf_clients_repassword_5']=$_LANG['zjmf_clients_repassword_5']  ;
        $lang['zjmf_backup_restore_will_delete_snap']=$_LANG['zjmf_backup_restore_will_delete_snap']  ;
        $lang['zjmf_reinstall_confirm']=$_LANG['zjmf_reinstall_confirm'];
        $lang['zjmf_traffic_reset_day']=$_LANG['zjmf_traffic_reset_day'];
        $lang['zjmf_used_traffic']=$_LANG['zjmf_used_traffic'];
        $lang['zjmf_surplus']=$_LANG['zjmf_surplus'];
        $lang['zjmf_traffic_reset_day_month']=$_LANG['zjmf_traffic_reset_day_month'];
        $lang['zjmf_traffic_reset_day_day']=$_LANG['zjmf_traffic_reset_day_day'];
        $lang['zjmf_format_data_disk']=$_LANG['zjmf_format_data_disk'];
        $lang['zjmf_api_rescue']=$_LANG['zjmf_api_rescue'];
        $lang['zjmf_api_rescue_exit']=$_LANG['zjmf_api_rescue_exit'];
        $lang['zjmf_layer_rescue_type']=$_LANG['zjmf_layer_rescue_type'];
        $lang['zjmf_onetime_password_please_save']=$_LANG['zjmf_onetime_password_please_save'];
        $lang['zjmf_layer_temp_pass']=$_LANG['zjmf_layer_temp_pass'];
        $lang['zjmf_client_ssh']=$_LANG['zjmf_ssh_key'];

        $configoptions = [];
        $pid = $params['pid'];
        $pdo = Capsule::connection()->getPdo();
        $sql="select ops.id,ops.optionname from tblhosting as h
            left Join tblproductconfiglinks as link on link.pid=h.packageid
            left Join tblproductconfigoptions as ops on ops.gid=link.gid
            where h.id={$params['serviceid']}
            ";
        $optionname = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
        $optionname_array = [];
        foreach($optionname as $v){
            $opname=explode("|",$v['optionname']);
            $optionname_array[$v['id']]=$opname;
        }
        $sql="select sub.configid,sub.optionname,ops.optiontype from tblhosting as h
            left Join tblproductconfiglinks as link on link.pid=h.packageid
            left Join tblproductconfigoptions as ops on ops.gid=link.gid
            left Join tblproductconfigoptionssub as sub on ops.id=sub.configid
            where h.id={$params['serviceid']}
            ";
        $suboptionname = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
        foreach ($suboptionname as $v){
            $subopname=explode("|",$v['optionname']);
            $opname = $optionname_array[$v['configid']];
            if($v['optiontype']==4){
                $configoptions[$opname[0]] = ['name' => $opname[1], 'value' => $params['configoptions'][$opname[0]]];
            }else{
               if(isset($params['configoptions'][$opname[0]]) && $subopname[0]==$params['configoptions'][$opname[0]]){
                    $configoptions[$opname[0]] = ['name' => $opname[1], 'value' => $subopname[1]];
                } 
            }
            
        }
        $sql="select fieldname from tblcustomfields where type='product' AND relid={$params['pid']} AND adminonly!='on'";
        $customfields = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
        $customfields = array_column($customfields, 'fieldname');
        foreach ($params['customfields'] as $key => $value) {
            if(!in_array($key, $customfields)){
                unset($params['customfields'][$key]);
            }
        }

        $sql="SELECT a.configid,a.optionid,a.qty,b.optiontype FROM tblhostingconfigoptions a LEFT JOIN tblproductconfigoptions b on a.configid=b.id WHERE a.relid = {$params['serviceid']}";
        $hostconfigoptions = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
        $oldconfigoptions = [];
        foreach ($hostconfigoptions as $key => $value) {
            if(in_array($value['optiontype'], ['1', '2'])){
                $oldconfigoptions[$value['configid']] = $value['optionid'];
            }else{
                $oldconfigoptions[$value['configid']] = $value['qty'];
            }
        }
        $data['configoptionsupgrade'] = $params['model']['product']['configoptionsupgrade'];
		$json=array(
			'status'=>200,
			'is_aff'=>1,
			'data'=>array(
				'host_data'=>$data,
				'config_options'=>$optionssub,
                'configoptions'=>$configoptions,
                'oldconfigoptions'=>$oldconfigoptions,
                'customfields'=>$params['customfields'],
				'second'=>$second,
				'nat'=>$nat,
				'lang'=>$lang,
                'setting'=>[
                    'format_data_disk'=>$serveraccesshash['format_data_disk'],
                ],
			),
		);
		echo json_encode($json);exit;
	}else if($ac=="moudle"){
		$control_view=array(
			'module_power_status'=>true,
			'show_traffic_usage'=>true,
		);
		$module_button=array(
			"console"=>array(
				0=>array("func"=>'vnc',"name"=>'VNC',"type"=>'default')
			)
		);
		$json=array(
			'status'=>200,
			'is_aff'=>1,
			'data'=>array(
				'control_view'=>$control_view,
				'module_button'=>$module_button,
				
			),
		);
		echo json_encode($json);exit;
	}else if($ac=="cloudos_layer"){
		$cloud_os = zjmfcloud_GetOs($params);
		
		$json=array(
			'status'=>200,
			'is_aff'=>1,
			'data'=>array(
				'cloud_os'=>$cloud_os['os'],	
				'cloud_os_group'=>$cloud_os['os_group'],	
			),
		);
		echo json_encode($json);exit;
	}else if($ac=="chart"){
		$type =$_GET['type'];
		$start =$_GET['start'];
		$end =$_GET['end'];
		$checkid =$_GET['disk']?:$_GET['network'];
		$result =zjmfcloud_Chart($params,$type,$start,$end,$checkid);
		echo json_encode($result);exit;
	}else if($ac=="trafficusage"){
		$result =zjmfcloud_Trafficusage($params);
		echo json_encode($result);exit;
	}else if($ac=="default"){	
		if($func=="status"){
			$result =zjmfcloud_GetStatus($params);//主机状态			
		}else if($func=="unpaused"){
			$re =zjmfcloud_Unpaused($params);//解除挂起
		}else if($func=="on"){
			$re =zjmfcloud_On($params);//开机
		}else if($func=="off"){
			$re =zjmfcloud_Off($params);//关机
		}else if($func=="reboot"){
			$re =zjmfcloud_Reboot($params);//重启			
		}else if($func=="hard_off"){
			$re =zjmfcloud_HardOff($params);//硬关机
		}else if($func=="hard_reboot"){
			$re =zjmfcloud_HardReboot($params);//硬重启
		}else if($func=="crack_pass"){
            $_POST['new_pass']=$requestData['password'];
			$_POST['password_type']=$requestData['password_type'];
            $_POST['ssh_key_id']=$requestData['ssh_key_id'];
			$result =zjmfcloud_CrackPass($params);//重置密码
		}else if($func=="reinstall"){
			$_POST['os']=$requestData['os'];
			$_POST['new_pass']=$requestData['password'];
            $_POST['format_data_disk']=$requestData['format_data_disk'];
            $_POST['password_type']=$requestData['password_type'];
            $_POST['ssh_key_id']=$requestData['ssh_key_id'];
			$result =zjmfcloud_Reinstall($params);//重装系统
		}else if($func=="vnc"){
			$result =zjmfcloud_Vnc($params);//获取vnc
			if(!$result['data']['url'])$result['data']['url']='clientarea.php?action=productdetails&id='.$id.'&ac=vnc_page&token='.$result['data']['token'].'&pass='.$result['data']['vnc_pass'].'&path='.$result['data']['path'];
		}else if($func == 'rescue'){
            $_POST['type']=$requestData['type'];
            $_POST['temp_pass']=$requestData['temp_pass'];
            $result = zjmfcloud_Rescue($params);
        }else if($func == 'exit_rescue'){
            $result = zjmfcloud_ExitRescue($params);
        }
		
		if($re) $result['msg']=$re;
		
		if(($re!="success" && !empty($re)) || ($result['status']!="success" &&  !empty($result['status']))) $result['status']=404; else $result['status']=200;
		echo json_encode($result);exit;
	}else if($ac=="vnc_page"){
		zjmfcloud_VncPage($params);//vnc 页面
	}else if($ac=="snapshots"){		
		$snapshots_id=$requestData['snapshots_id'];
		if($func=="createSnap"){			
			$result =zjmfcloud_CreateSnap($params,$requestData['disk_id'],$requestData['remarks']);//创建快照					
		}else if($func=="restore"){			
			$result =zjmfcloud_RestoreBySnap($params,$snapshots_id);//恢复快照			
		}else if($func=="deleteSnap"){
			$result =zjmfcloud_DeleteSnap($params,$snapshots_id);//删除快照
		}else if($func=="createBackup"){
			$result =zjmfcloud_CreateBackup($params,$requestData['disk_id'],$requestData['remarks']);//创建备份
		}else if($func=="restoreBackup"){
			$result =zjmfcloud_RestoreByBackup($params,$snapshots_id);//恢复备份
		}else if($func=="deleteBackup"){
			$result =zjmfcloud_DeleteBackup($params,$snapshots_id);//删除备份
		}else if($func=='listSnapBackup'){
            $result =zjmfcloud_ListSnapBackup($params);//删除备份
        }else if($func=="getSnapBackup"){
            $result =zjmfcloud_GetSnapBackup($params);//获取快照备份
        }
		echo json_encode($result);exit;
	}else if($ac=="safe"){
		if($func=="createSecurityGroup"){			
			$result =zjmfcloud_CreateSecurityGroup($params);//创建安全组				
		}else if($func=="linkSecurityGroup"){
			$result =zjmfcloud_LinkSecurityGroup($params,$requestData['SecurityGroupId']);//应用安全组			
		}else if($func=="delSecurityGroup"){
			$result =zjmfcloud_DeleteSecurityGroup($params,$requestData['SecurityGroupId']);//删除安全组			
		}else if($func=="showSecurityRules"){
			$result =zjmfcloud_SecurityRulesList($params,$requestData['SecurityGroupId']);//查看安全组规则	
		}else if($func=="createSecurityRule"){
			$result =zjmfcloud_CreateSecurityRule($params,$requestData['SecurityGroupId']);//创建安全组规则			
		}else if($func=="delSecurityRule"){
			$result =zjmfcloud_DeleteSecurityGroupRule($params,$requestData['SecurityRuleId']);//删除策略			
		}else if($func=="getSecurity"){
            $result =zjmfcloud_GetSecurity($params);//获取安全组
        }
		echo json_encode($result);exit;
	}else if($ac=="setting"){
		if($func=="mountIso"){			
			$result =zjmfcloud_MountIso($params,$requestData['isoId']);//挂载ISO				
		}else if($func=="unmountIso"){
			$result =zjmfcloud_UnMountIso($params,$requestData['unmountIsoId']);//卸载ISO			
		}else if($func=="setBootOrder"){
			$result =zjmfcloud_SetBootOrder($params,$requestData['bootOrderId']);//启动项				
		}else if($func=="getSetting"){
            $result =zjmfcloud_GetSetting($params);//设置              
        }
		echo json_encode($result);exit;
	}else if($ac=="nat"){		
		$nat_id=$requestData['NatId'];
		if($func=="createNatAcl"){			
			$result =zjmfcloud_CreateNatAcl($params,$requestData);//创建nat转发								
		}else if($func=="delNatAcl"){
			$result =zjmfcloud_DeleteNatAcl($params,$nat_id);//删除NAT转发
		}else if($func=="createNatWeb"){
			$result =zjmfcloud_CreateNatWeb($params,$requestData);//创建NAT建站
		}else if($func=="delNatWeb"){
			$result =zjmfcloud_DeleteNatWeb($params,$nat_id);//删除NAT建站
		}else if($func=="getNatAcl"){
            $result = zjmfcloud_GetNatAcl($params); 
        }else if($func=="getNatWeb"){
            $result = zjmfcloud_GetNatWeb($params); 
        }
		echo json_encode($result);exit;
	}else if($ac=='traffictotal'){
        $result = zjmfcloud_TrafficTotal($params);
        echo json_encode($result);exit;
    }else if($ac == 'ssh_key'){
        if($func == 'createSSHKey'){
            $result = zjmfcloud_CreateSSHKey($params, $requestData);
        }else if($func == 'deleteSSHKey'){
            $result = zjmfcloud_DeleteSSHKey($params, $requestData['ssh_key_id']);
        }else if($func == 'getSSHKey'){
            $result = zjmfcloud_GetSSHKey($params);
        }else if($func == 'bindSSHKey'){
            $result = zjmfcloud_BindSSHKey($params, $requestData['ssh_key_id']);
        }
        echo json_encode($result);exit;
    }
	if($_GET['tpl']=="index"){
		$tpl=file_get_contents(ZJMFCLOUD_FILE ."templates/server_innerpage/index.html");

        $lang = [];
        $lang['zjmf_client_ipaddressNum']=$_LANG['zjmf_client_ipaddressNum'];
        $lang['zjmf_client_username']=$_LANG['zjmf_client_username'] ;
        $lang['zjmf_layer_content_password']=$_LANG['zjmf_layer_content_password']  ;
        $lang['zjmf_api_crackpass']=$_LANG['zjmf_api_crackpass']  ;
        $lang['zjmf_client_port']=$_LANG['zjmf_client_port']  ;
        $lang['zjmf_client_default']=$_LANG['zjmf_client_default']  ;
        $lang['zjmf_client_changedate']=$_LANG['zjmf_client_changedate']  ;
        $lang['zjmf_client_usage']=$_LANG['zjmf_client_usage']  ;
        $lang['zjmf_client_usage_chart']=$_LANG['zjmf_client_usage_chart']  ;
        $lang['zjmf_client_snap_backup']=$_LANG['zjmf_client_snap_backup']  ;
        $lang['zjmf_client_security']=$_LANG['zjmf_client_security']  ;
        $lang['zjmf_client_setting']=$_LANG['zjmf_client_setting']  ;
        $lang['zjmf_client_nat_acl']=$_LANG['zjmf_client_nat_acl']  ;
        $lang['zjmf_client_nat_web']=$_LANG['zjmf_client_nat_web']  ;
        $lang['zjmf_api_reinstall']=$_LANG['zjmf_api_reinstall']  ;
        $lang['zjmf_client_os']=$_LANG['zjmf_client_os']  ;
        $lang['zjmf_client_backup_ok']=$_LANG['zjmf_client_backup_ok']  ;
        $lang['zjmf_layer_confirm']=$_LANG['zjmf_layer_confirm']  ;
        $lang['zjmf_layer_cancel']=$_LANG['zjmf_layer_cancel']  ;
        $lang['zjmf_check_password']=$_LANG['zjmf_check_password']  ;
        $lang['zjmf_api_on']=$_LANG['zjmf_api_on']  ;
        $lang['zjmf_api_off']=$_LANG['zjmf_api_off']  ;
        $lang['zjmf_api_reboot']=$_LANG['zjmf_api_reboot']  ;
        $lang['zjmf_api_hardoff']=$_LANG['zjmf_api_hardoff']  ;
        $lang['zjmf_api_hardreboot']=$_LANG['zjmf_api_hardreboot']  ;
        $lang['zjmf_api_power_status_unknown']=$_LANG['zjmf_api_power_status_unknown']  ;
        $lang['zjmf_client_copy_success']=$_LANG['zjmf_client_copy_success']  ;
        $lang['zjmf_client_copy_error']=$_LANG['zjmf_client_copy_error']  ;
        $lang['zjmf_client_data_no']=$_LANG['zjmf_client_data_no']  ;
        $lang['zjmf_client_traffic_usage']=$_LANG['zjmf_client_traffic_usage']  ;
        $lang['zjmf_client_password']=$_LANG['zjmf_client_password']  ;
        $lang['zjmf_client_password_error']=$_LANG['zjmf_client_password_error']  ;
        $lang['zjmf_client_chart']=$_LANG['zjmf_client_chart']  ;
        $lang['zjmf_client_tips']=$_LANG['zjmf_client_tips']  ;
        $lang['zjmf_api_power_status_unpaused']=$_LANG['zjmf_api_power_status_unpaused']  ;
        $lang['zjmf_layer_panel_pass']=$_LANG['zjmf_layer_panel_pass']  ;
        $lang['zjmf_clients_repassword_1']=$_LANG['zjmf_clients_repassword_1']  ;
        $lang['zjmf_clients_repassword_2']=$_LANG['zjmf_clients_repassword_2']  ;
        $lang['zjmf_clients_repassword_3']=$_LANG['zjmf_clients_repassword_3']  ;
        $lang['zjmf_clients_repassword_4']=$_LANG['zjmf_clients_repassword_4']  ;
        $lang['zjmf_clients_repassword_5']=$_LANG['zjmf_clients_repassword_5']  ;
        $lang['zjmf_clients_repassword_6']=$_LANG['zjmf_clients_repassword_6']  ;
        $lang['zjmf_backup_restore_will_delete_snap']=$_LANG['zjmf_backup_restore_will_delete_snap']  ;
        $lang['zjmf_reinstall_confirm']=$_LANG['zjmf_reinstall_confirm'];
        $lang['zjmf_traffic_reset_day']=$_LANG['zjmf_traffic_reset_day'];
        $lang['zjmf_used_traffic']=$_LANG['zjmf_used_traffic'];
        $lang['zjmf_surplus']=$_LANG['zjmf_surplus'];
        $lang['zjmf_traffic_reset_day_month']=$_LANG['zjmf_traffic_reset_day_month'];
        $lang['zjmf_traffic_reset_day_day']=$_LANG['zjmf_traffic_reset_day_day'];
        $lang['zjmf_format_data_disk']=$_LANG['zjmf_format_data_disk'];
        $lang['zjmf_api_rescue']=$_LANG['zjmf_api_rescue'];
        $lang['zjmf_api_rescue_exit']=$_LANG['zjmf_api_rescue_exit'];
        $lang['zjmf_layer_rescue_type']=$_LANG['zjmf_layer_rescue_type'];
        $lang['zjmf_onetime_password_please_save']=$_LANG['zjmf_onetime_password_please_save'];
        $lang['zjmf_layer_temp_pass']=$_LANG['zjmf_layer_temp_pass'];
        $lang['zjmf_client_ssh']=$_LANG['zjmf_ssh_key'];
        $lang['zjmf_select_time']=$_LANG['zjmf_select_time'];
        $lang['zjmf_task_rescue_success']=$_LANG['zjmf_task_rescue_success'];
        $lang['zjmf_task_exit_rescue_success']=$_LANG['zjmf_task_exit_rescue_success'];
        $lang['zjmf_client_loading']=$_LANG['zjmf_client_loading'];
        $lang['zjmf_please_select_ssh_key']=$_LANG['zjmf_please_select_ssh_key'];
        $lang['zjmf_input_reason']=$_LANG['zjmf_input_reason'];
        
        $zjmf_lang = $_LANG['zjmf_lang'] ?: 'zh-cn';
        $user_lang = str_replace("'", "\'", json_encode($lang, true));
        // 获取语言文件
        $js = <<<JS
        var zjmf_lang = JSON.parse('{$user_lang}');
JS;
		echo str_replace(['{$id}', '{$js}', '{$zjmf_lang}'], [$id, $js, $zjmf_lang], $tpl);
        exit;
		
	}else if($_GET['tpl']=="snap"){
		zjmfcloud_SnapBackup($params);
		
	}else if($_GET['tpl']=="safe"){
		zjmfcloud_Security($params);
	}else if($_GET['tpl']=="nat"){
		zjmfcloud_NatAcl($params);
		
	}else if($_GET['tpl']=="build"){
		zjmfcloud_NatWeb($params); 
		
	}else if($_GET['tpl']=="setting"){
		zjmfcloud_setting($params);
		
	}else if($_GET['tpl'] == 'ssh'){
        zjmfcloud_ssh($params);

    }else{
		$templateFile = 'templates/server_innerpage.tpl';
		return array(
			'templatefile' => $templateFile,
			'templateVariables' => array(
                'id' => $params['serviceid'],
            ),
		);
	}
}

/*
function zjmfcloud_UsageUpdate($params){
    $pdo = Capsule::connection()->getPdo();
    $serverid = (int)$params['serverid'];
    $server_info = $pdo->query("SELECT * FROM tblservers WHERE id='{$serverid}'")->fetch(PDO::FETCH_ASSOC);
    if(empty($server_info)){
        return false;
    }
    $sql = "SELECT h.id,cf.value FROM tblhosting h LEFT JOIN tblcustomfields c ON h.packageid=c.relid AND c.type='product' AND fieldname='hostid' LEFT JOIN tblcustomfieldsvalues cf ON c.id=cf.fieldid AND h.id=cf.relid WHERE h.server='{$serverid}'";

    $host = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
    
    $params['serverhostname'] = $server_info['hostname'];
    $params['serverip'] = $server_info['ipaddress'];
    $params['serverusername'] = $server_info['username'];
    $params['serverpassword'] = decrypt($server_info['password']);
    $params['serversecure'] = $server_info['secure'];
    $params['serveraccesshash'] = $server_info['accesshash'];
    if($params['serversecure'] == 'on'){
        $params['serverhttpprefix'] = 'https';
    }else{
        $params['serverhttpprefix'] = 'http';
    }
    $params['serverport'] = $server_info['port'];
    foreach($host as $v){
        if(empty($v['value'])){
            continue;
        }
        $res = zjmfcloud_Curl($params, '/net_info', ['host_id'=>$v['value']], 15, 'GET');
        if($res['status'] == 'success'){
            if($res['data']['meta']['traffic_quota'] != 0){
                $res['data']['meta']['traffic_quota'] += $info['data']['meta']['tmp_traffic'];
            }
            $update = [];
            $update['bwlimit'] = intval($res['data']['meta']['traffic_quota'] * 1024);
            $usage = 0;
            if($res['data']['meta']['traffic_type'] == 1){
                $usage = intval($res['data']['info']['to_month']['accept']/pow(1024, 2));
            }else if($res['data']['meta']['traffic_type'] == 2){
                $usage = intval($res['data']['info']['to_month']['send']/pow(1024, 2));
            }else if($res['data']['meta']['traffic_type'] == 3){
                $usage = intval($res['data']['info']['to_month']['total']/pow(1024, 2));
            }
            $update['bwusage'] = $usage;
            $update['lastupdate'] = date('Y-m-d H:i:s');
            // var_dump($update);
            Capsule::table('tblhosting')->where('id', '=', $v['id'])->update($update);
        }
    }
    return true;
}
*/
