<?php
use WHMCS\Database\Capsule;

if (!defined("WHMCS")) {
    exit("This file cannot be accessed directly");
}
// 解除挂起
function zjmfcloud_Unpaused($params){
	global $_LANG;
	if(empty($params['customfields']['hostid'])){
		return $_LANG['zjmf_api_host_id_error'] ;
	}
	$res = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'].'/resume');
    if($res['status'] == 'success'){
        $result = 'success';

        $description = zjmfcloud_Langset('zjmf_log_unpaused_success', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
        ]);
    }else{
        $result = $_LANG['zjmf_api_host_on_error'].$res['msg'];

        $description = zjmfcloud_Langset('zjmf_log_unpaused_fail', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
            'reason'    => $res['msg'],
        ]);
    }
    logActivity($description);
    return $result;
}
// 开机
function zjmfcloud_On($params){
	global $_LANG;
	if(empty($params['customfields']['hostid'])){
		return $_LANG['zjmf_api_host_id_error'] ;
	}
	$res = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'].'/on');
    if($res['status'] == 'success'){
        $result = 'success';

        $description = zjmfcloud_Langset('zjmf_log_on_success', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
        ]);
    }else{
        $result = $_LANG['zjmf_api_host_on_error'].$res['msg'];

        $description = zjmfcloud_Langset('zjmf_log_on_fail', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
            'reason'    => $res['msg'],
        ]);
    }
    logActivity($description);
    return $result;
}

// 关机
function zjmfcloud_Off($params){
	global $_LANG;
	if(empty($params['customfields']['hostid'])){
		return $_LANG['zjmf_api_host_id_error'] ;
	}
	$res = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'].'/off');
    if($res['status'] == 'success'){
        $result = 'success';

        $description = zjmfcloud_Langset('zjmf_log_off_success', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
        ]);
    }else{
        $result = $_LANG['zjmf_api_host_off_error'].$res['msg'];

        $description = zjmfcloud_Langset('zjmf_log_off_fail', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
            'reason'    => $res['msg'],
        ]);
    }
    logActivity($description);
    return $result;
}

// 重启
function zjmfcloud_Reboot($params){
	global $_LANG;
	if(empty($params['customfields']['hostid'])){
		return $_LANG['zjmf_api_host_id_error'] ;
	}
	$res = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'].'/reboot');
    if($res['status'] == 'success'){
        $result = 'success';

        $description = zjmfcloud_Langset('zjmf_log_reboot_success', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
        ]);
    }else{
        $result = $_LANG['zjmf_api_host_reboot_error'].$res['msg'];

        $description = zjmfcloud_Langset('zjmf_log_reboot_fail', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
            'reason'    => $res['msg'],
        ]);
    }
    logActivity($description);
    return $result;
}

// 硬关机
function zjmfcloud_HardOff($params){
	global $_LANG;
	if(empty($params['customfields']['hostid'])){
		return $_LANG['zjmf_api_host_id_error'] ;
	}
	$res = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'].'/hardoff');
    if($res['status'] == 'success'){
        $result = 'success';

        $description = zjmfcloud_Langset('zjmf_log_hard_off_success', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
        ]);
    }else{
        $result = $_LANG['zjmf_api_host_hardoff_error'] .$res['msg'];

        $description = zjmfcloud_Langset('zjmf_log_hard_off_fail', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
            'reason'    => $res['msg'],
        ]);
    }
    logActivity($description);
    return $result;
}

// 硬重启
function zjmfcloud_HardReboot($params){
	global $_LANG;
	if(empty($params['customfields']['hostid'])){
		return $_LANG['zjmf_api_host_id_error'] ;
	}
	$res = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'].'/hard_reboot');
    if($res['status'] == 'success'){
        $result = 'success';

        $description = zjmfcloud_Langset('zjmf_log_hard_reboot_success', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
        ]);
    }else{
        $result = $_LANG['zjmf_api_host_hardreboot_error'] .$res['msg'];

        $description = zjmfcloud_Langset('zjmf_log_hard_reboot_fail', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
            'reason'    => $res['msg'],
        ]);
    }
    logActivity($description);
    return $result;
}

// 获取云主机状态
function zjmfcloud_GetStatus($params, $plat = ''){
	global $_LANG;
	if(empty($params['customfields']['hostid'])){
		$result['status'] = 'error';
		$result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
		return $result;
	}
	$res = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'].'/status', [], 30, 'GET');
    if($res['status'] == 'success'){
        $result['status'] = 'success';
		
        if($res['data']['status'] == 'on'){
            $result['data']['status'] = 'on';
            $result['data']['des'] = $_LANG['zjmf_api_power_status_on'] ;
        }else if($res['data']['status'] == 'off'){
            $result['data']['status'] = 'off';
            $result['data']['des'] = $_LANG['zjmf_api_power_status_off'] ;
        }else if($res['data']['status'] == 'suspend'){
            $result['data']['status'] = 'suspend';
            $result['data']['des'] = $_LANG['zjmf_api_power_status_suspend'];
        }else if($res['data']['status'] == 'wait_reboot'){
            $result['data']['status'] = 'waiting';
            $result['data']['des'] = $_LANG['zjmf_api_power_status_waiting'];
        }else if($res['data']['status'] == 'task'){
			$task=include "task.php";
			if(!empty($task[$res['data']['task']])){
				$result['data']['status'] = 'process';
				$result['data']['des'] = $_LANG['zjmf_api_power_task_'.$res['data']['task']].$_LANG['zjmf_api_power_status_task'];
                if($plat == 'admin'){
                    $result['data']['task'] = $res['data']['task'];
                }
			}
			/* if($res['data']['task']=='on') $task_name=$_LANG['zjmf_api_power_status_on'];
			else if($res['data']['task']=="off") $task_name=$_LANG['zjmf_api_power_status_off'];
			else if($res['data']['task']=="suspend") $task_name=$_LANG['zjmf_api_power_status_suspend'];
			else if($res['data']['task']=="waiting") $task_name=$_LANG['zjmf_api_power_status_waiting'];
			else if($res['data']['task']=="paused") $task_name=$_LANG['zjmf_api_power_status_paused'];
			else if($res['data']['task']=="unknown") $task_name=$_LANG['zjmf_api_power_status_unknown'];
			else if($res['data']['task']=="reboot") $task_name=$_LANG['zjmf_api_reboot'];
            $result['data']['status'] = 'process';
            $result['data']['des'] = $task_name.$_LANG['zjmf_api_power_status_task']; */
		}else if($res['data']['status'] == 'paused'){
            $result['data']['status'] = 'paused';
            $result['data']['des'] = $_LANG['zjmf_api_power_status_paused'];
        }else{
            $result['data']['status'] = 'unknown';
            $result['data']['des'] = $_LANG['zjmf_api_power_status_unknown'];
        }
    }else{
        $result['status'] = 'error';
        $result['msg'] = $res['msg'];
    }
    return $result;
}

// 拉取信息
function zjmfcloud_Sync($params, $is_sync_disk = true){
	global $_LANG;
	if(empty($params['customfields']['hostid'])){
		return $_LANG['zjmf_api_host_id_error'];
	}
	$res = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'], [], 30, 'GET');
    if($res['status'] == 'success'){
        $update['dedicatedip'] = $res['data']['mainip'];

        $assignedips = array_merge(array_column($res['data']['ip'], 'ipaddress') ?: [], array_column($res['data']['ipv6'], 'ipv6') ?: []);
        $update['assignedips'] = implode("\r\n", array_filter($assignedips, function($x) use ($res) {
            return $x != $res['data']['mainip'];
        }));
        $update['username'] = $res['data']['osuser'];
        $update['password'] = encrypt($res['data']['rootpassword']);
        if($res['data']['traffic_quota'] == 0){
            $update['bwlimit'] = 0;
        }else{
            $update['bwlimit'] = ($res['data']['traffic_quota'] + $res['data']['tmp_traffic']) * 1024;
        }
        $update['domain'] = $res['data']['hostname'];
        
        Capsule::table('tblhosting')->where('id', $params['serviceid'])->update($update);

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

        // 升降级不需要同步
        if($is_sync_disk){
            // 处理数据盘关联
            $data_disk = [];
            $data_disk_size = isset($params['configoptions']['data_disk_size'])?$params['configoptions']['data_disk_size']:$params['configoption18'];
            if(!empty($data_disk_size)){
                $one = zjmfcloud_GetDataDiskSize($params, $data_disk_size, 'data_disk_size');
                $one['key'] = 'data_disk_size';
                $data_disk[] = $one;
            }
            // 其他磁盘
            foreach($params['configoptions'] as $k=>$v){
                if(in_array($k, ['data1_disk_size','data2_disk_size','data3_disk_size','data4_disk_size'])){
                    $one = zjmfcloud_GetDataDiskSize($params, $v, $k);
                    $one['key'] = $k;
                    // 有存储的放在前面
                    if(!empty($one['store'])){
                        array_unshift($data_disk, $one);
                    }else{
                        $data_disk[] = $one;
                    }
                }
            }
            $disk_link = zjmfcloud_GetDiskLink($params);
            $disk_link_disk_id = array_column($disk_link, 'disk_id', 'option_name');
            $real_disk_id = array_column($res['data']['disk'], 'id');
            
            // 匹配磁盘记录ID 
            foreach($res['data']['disk'] as $v){
                // 已经关联过了
                // if(!empty($disk_link_disk_id[$v['id']])){
                //     continue;
                // }
                if($v['type'] == 'system'){
                    continue;
                }
                foreach($data_disk as $kk=>$vv){
                    // 已经关联过了,确认下关联的ID是否正确
                    if(!empty($disk_link_disk_id[$vv['key']])){
                        if(in_array($disk_link_disk_id[$vv['key']], $real_disk_id)){
                            unset($data_disk[$kk]);
                            continue;
                        }
                    }
                    if( (!empty($vv['store']) && $vv['store'] == $v['store_id'] && $vv['size'] == $v['size']) || (empty($vv['store']) && $vv['size'] == $v['size'])){
                        // 匹配成功
                        zjmfcloud_AddDiskLink($vv['key'], $params['serviceid'], $v['id']);
                        unset($data_disk[$kk]);
                    }
                }
            }
        }
        $result = 'success';
    }else{
        $result = $_LANG['zjmf_api_host_sync_error'] .$res['msg'];
    }
    return $result;
}
// VNC
function zjmfcloud_Vnc($params){
	global $_LANG;
	if(empty($params['customfields']['hostid'])){
		return $_LANG['zjmf_api_host_id_error'] ;
	}
	$res = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'].'/vnc');
    if($res['status'] == 'success'){
        $result['status'] = 'success';
        $result['data'] = $res['data'];
		if($res['data']['vnc_url_http'] || $res['data']['vnc_url_https']){
			$result['data']['url']=$res['data']['vnc_url_http'];
			if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']==='on'){
				$result['data']['url']=$res['data']['vnc_url_https'];
			}
		}

        $description = zjmfcloud_Langset('zjmf_log_vnc_success', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
        ]);
    }else{
    	$result['status'] = 'error';
		$result['msg'] = $_LANG['zjmf_api_host_vnc_error'].$res['msg'];

        $description = zjmfcloud_Langset('zjmf_log_vnc_fail', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
            'reason'    => $res['msg'],
        ]);
    }
    logActivity($description);
    return $result;
}

// VNC页面
function zjmfcloud_VncPage($params){
	global $_LANG;
	ob_clean();
	$url = zjmfcloud_GetUrl($params);
	$link_url = '';
	if(strpos($url, 'https://') !== false){
        $link_url = str_replace('https://', 'wss://', $url);
    }else{
        $link_url = str_replace('http://', 'ws://', $url);
    }
	$accesshash=zjmfcloud_AccessHash($params['serveraccesshash']);
	if(!empty($accesshash['dir'])){
		$link_url=str_replace($accesshash['dir'],"",$link_url);
	}
	$path = (int)$_GET['path'] ?: 1;
	$link_url .= '/cloud_ws'.$path.'?token='.$_GET['token'];
	$password = $params['password'];
	$web_root = DI::make("asset")->getWebRoot();
	require_once ZJMFCLOUD_FILE .'noVNC/vnc_lite.php';
	exit;
}
// 重装系统
function zjmfcloud_Reinstall($params){
	global $_LANG;
    if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
        return $result;
    }
    $os = (int)$_POST['os'];
    $new_pass = $_POST['new_pass'];
    $format_data_disk = (int)$_POST['format_data_disk'];
    if(empty($os)){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_check_os'];
        return $result;
    }
    $os_arr = zjmfcloud_GetOs($params);
	$os_arr =$os_arr['os'];
	$os_id=array_column($os_arr,'osid', 'id');
    if(empty($os_id[$os])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_check_os_error'] ;
        return $result;
    }
	
    $post_data['password_type'] = (int)$_POST['password_type'];
    $post_data['os'] = $os_id[$os];
    $post_data['password'] = $new_pass;
    $post_data['ssh_key'] = (int)$_POST['ssh_key_id'];
    $post_data['format_data_disk'] = $format_data_disk;
    $system_disk_size=isset($params['configoptions']['system_disk_size'])?$params['configoptions']['system_disk_size']:$params['configoption1'];//系统盘
    $post_data['system_disk_size'] = zjmfcloud_FormatSystemDiskSize($system_disk_size);

    $res = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'].'/reinstall', $post_data, 30, 'PUT');
    if($res['status'] == 'success'){
        $result['status'] = 'success';
        $result['msg'] = $_LANG['zjmf_check_os_success'] ;
        if(!empty($res['data']['password'])){
			$pdo = Capsule::connection()->getPdo();
			//$tblproductconfigoptionssub = Capsule::select("select `id`,`configid` from tblproductconfigoptionssub where id = $os limit 1");
			//$optionssub=zjmfcloud_ObjectToArray($tblproductconfigoptionssub[0]);
			$optionssub = $pdo->query("select `id`,`configid` from tblproductconfigoptionssub where id = $os limit 1")->fetch(PDO::FETCH_ASSOC);
            if(!empty($optionssub)){
                $id=(int)$optionssub['id'];
                $configid=(int)$optionssub['configid'];
                Capsule::table('tblhosting')->where('id', '=', $params['serviceid'])->update(['username'=>$res['data']['user'],'password'=>encrypt($res['data']['password'])]);
                Capsule::table('tblhostingconfigoptions')
                ->where('relid', '=', $params['serviceid'])
                ->where('configid', '=', $configid)
                ->update(['optionid'=>$id]);

                $currency = zjmfcloud_getCurrency($params);
                $charge = $pdo->query("select `id` from `tblpricing` where `type`='tblpricing' AND `currency`=$currency AND `relid` = $id AND (`msetupfee`>0 OR `qsetupfee`>0 OR `ssetupfee`>0 OR `asetupfee`>0 OR `bsetupfee`>0 OR `tsetupfee`>0 OR `monthly`>0 OR `quarterly`>0 OR `semiannually`>0 OR `annually`>0 OR `biennially`>0 OR `triennially`>0)")->fetch(PDO::FETCH_ASSOC);
                if(!empty($charge)){
                    $extra_os = $params['customfields']['extra_os'];
                    if(!empty($extra_os)){
                        $extra_os = explode(',', $extra_os) ?: [];
                        $extra_os[] = $os_id[$os];
                        $extra_os = array_unique($extra_os);
                        $extra_os = implode(',', $extra_os);
                    }else{
                        $extra_os = $os_id[$os];
                    }
                    zjmfcloud_SetExtraOs($params, $extra_os);
                }
            }
        }

        $description = zjmfcloud_Langset('zjmf_log_reinstall_success', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
        ]);
    }else{
        $result['status'] = 'error';
        $result['msg'] = $res['msg'];

        $description = zjmfcloud_Langset('zjmf_log_reinstall_fail', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
            'reason'    => $res['msg'],
        ]);
    }
    logActivity($description);
    return $result;
}

// 破解密码
function zjmfcloud_CrackPass($params){
	global $_LANG;
    if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
        return $result;
    }
    $password_type = (int)$_POST['password_type'];
    $new_pass = $_POST['new_pass'];
    if($password_type == 0 && empty($new_pass)){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_check_password'];
        return $result;
    }
    $post = [
        'password_type' => $password_type,
        'password'      => $new_pass,
        'ssh_key'       => $_POST['ssh_key_id'],
    ];

    $res = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'].'/password', $post, 30, 'PUT');
    if($res['status'] == 'success'){
        $result['status'] = 'success';
        $result['msg'] = $_LANG['zjmf_check_password_success'];
        Capsule::table('tblhosting')->where('id', '=', $params['serviceid'])->update(['password'=>encrypt($new_pass)]);

        $description = zjmfcloud_Langset('zjmf_log_reset_password_success', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
        ]);
    }else{
        $result['status'] = 'error';
        $result['msg'] = $res['msg'];

        $description = zjmfcloud_Langset('zjmf_log_reset_password_fail', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
            'reason'    => $res['msg'],
        ]);
    }
    logActivity($description);
    return $result;
}
// 后台产品弹出层模板
function zjmfcloud_AdminPageJS($params){
	global $_LANG;
	$userid = $params['userid'];
    $serviceid = $params['serviceid'];
    $hostid = $params['customfields']['hostid'];
    $api_url = zjmfcloud_GetUrl($params);

    $os = zjmfcloud_GetOs($params);
    $os_group = '';
    foreach($os['os_group'] as $v){
        $os_group .= "<option value='{$v['id']}'>{$v['name']}</option>";
    }
    $ssh_key = zjmfcloud_GetSSHKey($params);
    $ssh_key_list = '';
    if($ssh_key['data']['type'] != 'hyperv' && !empty($ssh_key['data']['list'])){
        foreach($ssh_key['data']['list'] as $v){
            $ssh_key_list .= "<option value='{$v['id']}'>{$v['name']}</option>";
        }
    }

	$admin_action_layer=file_get_contents(ZJMFCLOUD_FILE . "templates/admin_action_layer.php");
	$tpl_array=array(
		'{$os}'=>json_encode($os['os']),
        '{$os_group}'=>$os_group,
		'{$ssh_key_list}'=>$ssh_key_list,
		'{$zjmfcloud_power_status}'=>$params['zjmfcloud_power_status'],
		'{$hostid}'=>$params['customfields']['hostid'],
		'{$user_id}'=>$params['userid'],
		'{$serviceid}'=>$serviceid,
		'{$api_url}'=>$api_url,
		'{$username}'=>$params['username'],
		'{$password}'=>$params['password'],
		'{$zjmf_api_reinstall}'=>$_LANG['zjmf_api_reinstall'],
		'{$zjmf_api_crackpass}'=>$_LANG['zjmf_api_crackpass'] ,
		'{$zjmf_api_panel}'=>$_LANG['zjmf_api_panel'] ,
		'{$zjmf_layer_close}'=>$_LANG['zjmf_layer_close'] ,
		'{$zjmf_layer_confirm}'=>$_LANG['zjmf_layer_confirm'],
		'{$zjmf_layer_cancel}'=>$_LANG['zjmf_layer_cancel'],
		'{$zjmf_check_password}'=>$_LANG['zjmf_check_password'],
		'{$zjmf_check_os}'=>$_LANG['zjmf_check_os'],
		'{$zjmf_check_vnc_loading}'=>$_LANG['zjmf_check_vnc_loading'],
		'{$zjmf_layer_content_password}'=>$_LANG['zjmf_layer_content_password'],
		'{$zjmf_layer_content_newpassword}'=>$_LANG['zjmf_layer_content_newpassword'],
        '{$zjmf_layer_content_os}'=>$_LANG['zjmf_layer_content_os'],
        '{$zjmf_layer_rescue_type}'=>$_LANG['zjmf_layer_rescue_type'],
        '{$zjmf_layer_temp_pass}'=>$_LANG['zjmf_layer_temp_pass'],
        '{$zjmf_api_rescue}'=>$_LANG['zjmf_api_rescue'],
        '{$zjmf_api_rescue_exit}'=>$_LANG['zjmf_api_rescue_exit'],
        '{$zjmf_please_wait_act}'=>$_LANG['zjmf_please_wait_act'],
        '{$zjmf_onetime_password_please_save}'=>$_LANG['zjmf_onetime_password_please_save'],
        '{$zjmf_please_receive_hard_off}'=>$_LANG['zjmf_please_receive_hard_off'],
        '{$cloud_rescue_status}'=>$params['cloud_rescue_status'],
        '{$remote_image_group_id}'=>$params['remote_image_group_id'],
        '{$zjmf_please_select_ssh_key}'=>$_LANG['zjmf_please_select_ssh_key'],
        '{$zjmf_ssh_key}'=>$_LANG['zjmf_ssh_key'],
        '{$zjmf_clients_repassword_4}'=>$_LANG['zjmf_clients_repassword_4'],
        '{$zjmf_clients_repassword_5}'=>$_LANG['zjmf_clients_repassword_5'],
	);
	foreach($tpl_array as $k=>$v){
		$admin_action_layer=str_replace($k,$v,$admin_action_layer);
	}
	return $admin_action_layer;
}
// 获取可配置选项里面的操作系统
function zjmfcloud_GetOs($params){
    if(empty($params['customfields']['hostid'])){
    	return [];
    }
	$pdo = Capsule::connection()->getPdo();
    $configid = Capsule::table('tblhosting')
    		->leftJoin('tblproductconfiglinks', 'tblhosting.packageid', '=', 'tblproductconfiglinks.pid')
    		->leftJoin('tblproductconfigoptions', 'tblproductconfiglinks.gid', '=', 'tblproductconfigoptions.gid')
    		->where('tblproductconfigoptions.optionname', 'LIKE', '%os|%')
    		->where('tblhosting.id', '=', $params['serviceid'])
    		->value('tblproductconfigoptions.id');
    $data = [];
	$other=false;
    if(!empty($configid)){
    	/* $res = Capsule::table('tblproductconfigoptionssub')
    			->where('configid', '=', $configid)
    			->orderBy('sortorder', 'asc')
    			->get(['id', 'optionname']); */
    	$group=[];
    	$extra_os = explode(',', $params['customfields']['extra_os']) ?: [];

    	$currency = zjmfcloud_getCurrency($params);
    	// 隐藏收费镜像
		$res = $pdo->query('select t1.`id`,t1.`optionname`,t2.`msetupfee`,t2.`qsetupfee`,t2.`ssetupfee`,t2.`asetupfee`,t2.`bsetupfee`,t2.`tsetupfee`,t2.`monthly`,t2.`quarterly`,t2.`semiannually`,t2.`annually`,t2.`biennially`,t2.`triennially` from tblproductconfigoptionssub t1 LEFT JOIN tblpricing t2 ON t1.id=t2.relid AND t2.currency='.$currency.' AND t2.type="configoptions" where t1.configid = ' . $configid .' GROUP BY t1.id ORDER BY sortorder asc')->fetchAll(PDO::FETCH_ASSOC);
		//echo "<pre>";var_dump($res);exit;
		//$res=zjmfcloud_ObjectToArray($res);

		//echo "<pre>";var_dump($res);exit;
    	foreach($res as $k=>$v){
    		$optionname = explode('|', $v['optionname']);
    		if($v['msetupfee']>0||$v['qsetupfee']>0||$v['ssetupfee']>0||$v['asetupfee']>0||$v['bsetupfee']>0||$v['tsetupfee']>0||$v['monthly']>0||$v['quarterly']>0||$v['semiannually']>0||$v['annually']>0||$v['biennially']>0||$v['triennially']>0){
    			if(empty($extra_os)){
    				continue;
    			}else{
    				if(!in_array($optionname[0], $extra_os)){
    					continue;
    				}
    			}
    		}
			if(strpos($optionname[1],"^")===false){
				$optionname[1]="other^".$optionname[1];
			}
			$osname = explode('^', $optionname[1]);
			if(!empty($osname[0])){
				$group_name=strtolower($osname[0]);				
				if(!in_array($group_name, $group)){
					if($osname[0]=="other") $other=true;
					$data['os_group'][] = [
						'id'=>$osname[0],
						'name'=>$group_name
					];
				}
				$group[$k]=$group_name;
				$data['os'][$k] = [
					'group'=>$osname[0],
					'id'=>$v['id'],
					'osid'=>$optionname[0],
					'name'=>$osname[1]
				];
			}else{
				$data['os'][$k] = [
					'id'=>$v['id'],
					'osid'=>$optionname[0],
					'name'=>$optionname[1]
				];
			}
    	}
    }else{
    	$accesshash = zjmfcloud_AccessHash($params['serveraccesshash']);

		$configoption14 = Capsule::table('tblhosting')
    		->leftJoin('tblproducts', 'tblproducts.id', '=', 'tblhosting.packageid')
    		->where('tblhosting.id', '=', $params['serviceid'])
    		->value('tblproducts.configoption14');
		$os=explode("|",$configoption14);
		//$os=zjmfcloud_ObjectToArray($os);
		
		$os=array_filter($os);

		if($accesshash['account_type'] == 'agent'){
			$get = ['rid'=>(int)$params['configoptions']['resource_package']];
			$image_res = zjmfcloud_Curl($params, '/node_images', $get, 30, 'GET');
			$image = [];
			foreach($image_res['data'] as $v){
				foreach($v['image'] as $vv){
					$image[$vv['id']] = $vv['name'];
				}
			}
			//var_dump($os);
			//echo "<pre>";var_dump($image);exit;
			foreach($os as $k=>$v){
				if(empty($image[$v])) continue;
				
				$data['os'][$k] = [
					'id'=>$v,
					'osid'=>$v,
					'name'=>$image[$v]
				];
			}
		}else{
			$get=['per_page'=>1000,'page'=>1];
			$image = zjmfcloud_Curl($params, '/image',$get, 30, 'GET');
			$image =array_column($image['data']['data'],"name","id");
			//var_dump($os);
			//echo "<pre>";var_dump($image);exit;
			foreach($os as $k=>$v){
				if(empty($image[$v])) continue;
				
				$data['os'][$k] = [
					'id'=>$v,
					'osid'=>$v,
					'name'=>$image[$v]
				];
			}
		}
	}
	if($other){
		unset($data['os_group']);
	}
	$data['os']=array_merge($data['os']);
	//var_dump($data);exit;
    return $data;
}

//chart 
function zjmfcloud_Chart($params,$type="",$start="",$end="",$checkid=""){
	global $_LANG;
	if(empty($params['customfields']['hostid'])){
		$result['status'] = 'error';
		$result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
		return $result;
	}	
	//读取主机详细
	$clouds = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'], [], 30, 'GET');		
	if($clouds['status'] == 'success'){
		$cloudsData=$clouds['data'];
		foreach($cloudsData['disk'] as $k=>$v){
			$disk[$k]['name']=$v['name'];
			$disk[$k]['disk_id']=$v['dev'];
		}
		foreach($cloudsData['network'] as $k=>$v){
			$flow[$k]['name']=$v['mac'];
			$flow[$k]['network_id']=$v['name'];
		}
		
	}else{
		$result['status'] = 'error';
		$result['msg'] = $_LANG['zjmf_api_host_error'];
		return $result;
	}
	if(!empty($type)){			
		if($clouds['status'] == 'success'){			
			$statistics['node_id']=$cloudsData['node_id'];
			$statistics['kvm']=$cloudsData['kvmid'];
			$statistics['st']=$start?:strtotime("-3 day")*1000;
			$statistics['et']=$end?:time()*1000;							
			if($type=="cpu"){
				$statistics['type']="kvm_info";
				
				$data['chart_type']="area";
				$data['label']=$_LANG['zjmf_chart_label_cpu'] ;				
				$data['unit']="%";				
			}else if($type=="memory"){
				$statistics['type']="kvm_info";
				
				$data['chart_type']="bar";
			}else if($type=="disk"){
				$statistics['dev_name']=$checkid?:$cloudsData['disk'][0]['dev'];
				$statistics['type']="disk_io";
				
				$data['chart_type']="line";
			}else if($type=="flow"){
				$statistics['kvm_ifname']=$checkid?:$cloudsData['network'][0]['name'];
				$statistics['type']="net_adapter";
				
				$data['chart_type']="line";
			}
		}
		$res = zjmfcloud_Curl($params, '/statistics', $statistics, 30, 'GET');
		$memory_unit_KB=0;$memory_unit_MB=0;
		$disk_unit_KB=0;$disk_unit_MB=0;
		$flow_unit_bps=0;$flow_unit_Kbps=0;$flow_unit_Mbps=0;
		foreach($res['data'] as $k=>$v){
			$v[0]=date("Y-m-d H:i:s",strtotime($v[0]));
			if($type=="cpu"){
				$list[0][$k]['time']=$v[0];
				$list[0][$k]['value']=sprintf("%.2f",$v[1]);
			}else if($type=="memory"){
				$list[0][$k]['time']=$v[0];
				$list[0][$k]['value']=sprintf("%.2f",($v[2]/(1024)));
				$list[1][$k]['time']=$v[0];
				$list[1][$k]['value']=sprintf("%.2f",($v[3]/(1024)));
				if($list[0][$k]['value']<1024 && $list[1][$k]['value']<1024) $memory_unit_KB++;
				if($list[0][$k]['value']>1024 || $list[1][$k]['value']>1024) $memory_unit_MB++;
			}else if($type=="disk"){
				$list[0][$k]['time']=$v[0];
				$list[0][$k]['value']=sprintf("%.2f",($v[1]/(1024)));
				$list[1][$k]['time']=$v[0];
				$list[1][$k]['value']=sprintf("%.2f",($v[2]/(1024)));
				if($list[0][$k]['value']<1024 && $list[1][$k]['value']<1024) $disk_unit_KB++;
				if($list[0][$k]['value']>1024 || $list[1][$k]['value']>1024) $disk_unit_MB++;
			}else if($type=="flow"){
				$list[0][$k]['time']=$v[0];
				$list[0][$k]['value']=sprintf("%.2f",($v[1]));
				$list[1][$k]['time']=$v[0];
				$list[1][$k]['value']=sprintf("%.2f",($v[2]));
				if($list[0][$k]['value']<1024 && $list[1][$k]['value']<1024) $flow_unit_bps++;
				if($list[0][$k]['value']>1024 || $list[1][$k]['value']>1024) $flow_unit_Kbps++;
				if(($list[0][$k]['value']/1024)>1024 || ($list[1][$k]['value']/1024)>1024) $flow_unit_Mbps++;
			}
		}
		
		if($memory_unit_MB>0){			
			$data['label']=array($_LANG['zjmf_chart_label_memory_1'].'(MB)', $_LANG['zjmf_chart_label_memory_2'].'(MB)' );				
			$data['unit']="MB";
		}else if($memory_unit_KB>0){
			$data['label']=array($_LANG['zjmf_chart_label_memory_1']."(KB)", $_LANG['zjmf_chart_label_memory_2']."(KB)");				
			$data['unit']="KB";
		} 
		if($disk_unit_MB>0){
			$data['label']=array($_LANG['zjmf_chart_label_disk_1'] ."(MB/s)", $_LANG['zjmf_chart_label_disk_2']."(MB/s)");				
			$data['unit']="MB/s";
		}else if($disk_unit_KB>0){
			$data['label']=array($_LANG['zjmf_chart_label_disk_1'] ."(KB/s)", $_LANG['zjmf_chart_label_disk_2']."(KB/s)");				
			$data['unit']="KB/s";
		} 
		if($flow_unit_Mbps>0){
			$data['label']=array($_LANG['zjmf_chart_label_flow_1'] ."(Mbps)", $_LANG['zjmf_chart_label_flow_2']."(Mbps)");				
			$data['unit']="Mbps";			
		}else if($flow_unit_Kbps>0){
			$data['label']=array($_LANG['zjmf_chart_label_flow_1'] ."(Kbps)", $_LANG['zjmf_chart_label_flow_2']."(Kbps)");				
			$data['unit']="Kbps";
		}else if($flow_unit_bps>0){
			$data['label']=array($_LANG['zjmf_chart_label_flow_1'] ."(bps)", $_LANG['zjmf_chart_label_flow_2']."(bps)");				
			$data['unit']="bps";
		} 
		$number=1024;
		if($memory_unit_MB>0 || $disk_unit_MB>0 || $flow_unit_Mbps>0 || $flow_unit_Kbps>0){
			if($flow_unit_Mbps>0)$number=1024*1024;
			foreach($list as $k=>$v){
				foreach($v as $kk=>$vv){
					$list[$k][$kk]['value']=sprintf("%.2f",($vv['value']/($number)));
				}
			}
		}
		$data['list']=$list;
		$json=array(
			'status'=>200,
			'is_aff'=>1,
			'data'=>$data
		);
		return $json;exit;
	}
	$module_chart=array(
		0=>array(
			'title'=>$_LANG['zjmf_chart_title_cpu'] ,
			'type'=>'cpu',
		),
		1=>array(
			'title'=>$_LANG['zjmf_chart_title_disk'] ,
			'type'=>'disk',
			'disk'=>$disk,
		),
		2=>array(
			'title'=>$_LANG['zjmf_chart_title_memory'],
			'type'=>'memory',
		),
		3=>array(
			'title'=>$_LANG['zjmf_chart_title_flow'],
			'type'=>'flow',
			'flow'=>$flow,
		),
	);
	$json=array(
		'status'=>200,
		'is_aff'=>1,
		'data'=>array(
			'create_time'=>$clouds['data']['create_time'],
			'module_chart'=>$module_chart,	
		),
	);
	return $json;
}
//用量
function zjmfcloud_Trafficusage($params){
	global $_LANG;
	if(empty($params['customfields']['hostid'])){
		$result['status'] = 'error';
		$result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
		return $result;
	}	
	$clouds = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'], [], 30, 'GET');	
	if($clouds['status'] == 'success'){
		$cloudsData=$clouds['data'];
		$statistics['node_id']=$cloudsData['node_id'];
		$statistics['kvm']=$cloudsData['kvmid'];	
		$statistics['kvm_ifname']=$cloudsData['network'][0]['name'];
		$statistics['type']="net_adapter";
		$statistics['status']="1";
        if(!empty($_GET['start'])){
            $statistics['st'] = strtotime($_GET['start'].' 08:00:00').'000';
        }
        if($_GET['end'] != date('Ymd')){
            $statistics['et'] = strtotime($_GET['end'].' 23:59:59').'000';
        }
        if(!empty($_GET['start']) && !empty($_GET['end']) && $_GET['start'] == $_GET['end']){
            $statistics['st'] = strtotime($_GET['start'].' 00:00:00').'000';
        }
		
		$res = zjmfcloud_Curl($params, '/statistics', $statistics, 30, 'GET');
		$flow_unit_bps=0;$flow_unit_Kbps=0;$flow_unit_Mbps=0;

        $show_time = true;
        if(isset($res['data'][0]) && isset($res['data'][1]) && date('Ymd', strtotime($res['data'][0][0])) != date('Ymd', strtotime($res['data'][1][0])) ){
            $show_time = false;
        }

		foreach($res['data'] as $k=>$v){
            if($show_time){
                $v[0]=date("Y-m-d H:i",strtotime($v[0]));
            }else{
                $v[0]=date("Y-m-d",strtotime($v[0]));
            }
			$list[$k]['time']=$v[0];
			$list[$k]['value']=$v[1]+$v[2];
			if($list[$k]['value']<1024) $flow_unit_bps++;
			if($list[$k]['value']>1024) $flow_unit_Kbps++;
			if(($list[$k]['value']/1024)>1024) $flow_unit_Mbps++;
		}
		if($flow_unit_Mbps>0){				
			$data['unit']="MB";			
		}else if($flow_unit_Kbps>0){				
			$data['unit']="KB";
		}else if($flow_unit_bps>0){				
			$data['unit']="B";
		} 
		$number=1024;
		if($flow_unit_Mbps>0 || $flow_unit_Kbps>0){
			if($flow_unit_Mbps>0)$number=1024*1024;
			foreach($list as $k=>$v){
				$list[$k]['value']=sprintf("%.2f",($v['value']/($number)));
			}
		}
		$data['list']=$list;
		$json=array(
			'status'=>200,
			'data'=>$data,
            'show_time'=>$show_time,
		);
		return $json;exit;
	}else{
		$result['status'] = 'error';
		$result['msg'] = $_LANG['zjmf_api_host_error'];
		return $result;
	}
	
}
//获取快照/备份 和磁盘
function zjmfcloud_SnapBackup($params){
	global $_LANG;
	if(empty($params['customfields']['hostid'])){
		$result['status'] = 'error';
		$result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
		return $result;
	}	
	$snapshots = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid']."/snapshots", [], 30, 'GET');
	if($snapshots['status'] == 'success'){
		$snapshots=$snapshots['data']['data'];	
	}
	//读取主机详细
	$clouds = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'], [], 30, 'GET');

	$host_type = 'host';
	$snap_num = 1;
	$backup_num = 1;
	if($clouds['status'] == 'success'){
		$data=$clouds['data'];
		foreach($data['disk'] as $k=>$v){
			$disk[$k]['name']=$v['name'];
			$disk[$k]['disk_id']=$v['id'];
		}
		$host_type = $data['type'] ?: 'host';
		$snap_num = $data['snap_num'];
		$backup_num = $data['backup_num'];
	}
	if($host_type == 'hyperv'){
		$snap_num = -1;
	}
 	include ZJMFCLOUD_FILE ."templates/server_innerpage/snap.php";exit;
}

function zjmfcloud_GetSnapBackup($params){
    global $_LANG;
    if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
        return $result;
    }   
    $snapshots = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid']."/snapshots", [], 30, 'GET');
    if($snapshots['status'] == 'success'){
        $snapshots=$snapshots['data']['data'];  
    }
    //读取主机详细
    $clouds = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'], [], 30, 'GET');

    $host_type = 'host';
    $snap_num = 1;
    $backup_num = 1;
    if($clouds['status'] == 'success'){
        $data=$clouds['data'];
        foreach($data['disk'] as $k=>$v){
            $disk[$k]['name']=$v['name'];
            $disk[$k]['disk_id']=$v['id'];
        }
        $host_type = $data['type'] ?: 'host';
        $snap_num = $data['snap_num'];
        $backup_num = $data['backup_num'];
    }
    if($host_type == 'hyperv'){
        $snap_num = -1;
    }
    $result = ['status' => 200, 'data' => ['snapshots' => $snapshots, 'host_type' => $host_type, 'snap_num' => $snap_num, 'backup_num' => $backup_num, 'disk' => $disk]];
    return $result;
}

// 创建快照
function zjmfcloud_CreateSnap($params,$disk_id,$remarks){
	global $_LANG;
    if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
        return $result;
    }
    $id = (int)$disk_id;
    if(empty($id)){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_check_disk']  ;
        return $result;
    }
    $res = zjmfcloud_Curl($params, '/disks/'.$id.'/snapshots?hostid='.$params['customfields']['hostid'], ['type'=>'snap', 'name'=>$remarks]);
    if($res['status'] == 'success'){
        $result['status'] = 200;
        $result['msg'] = $_LANG['zjmf_check_snap_create'];

        $description = zjmfcloud_Langset('zjmf_log_create_snap_success', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
            'name'      => $remarks,
        ]);
    }else{
        $result['status'] = 'error';
        $result['msg'] = $res['msg'];

        $description = zjmfcloud_Langset('zjmf_log_create_snap_fail', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
            'name'      => $remarks,
            'reason'    => $res['msg'],
        ]);
    }
    logActivity($description);
    return $result;
}

// 创建备份
function zjmfcloud_CreateBackup($params,$disk_id,$remarks){
    global $_LANG;
	if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
        return $result;
    }
    $id = (int)$disk_id;
    if(empty($id)){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_check_disk']  ;
        return $result;
    }

    $res = zjmfcloud_Curl($params, '/disks/'.$id.'/snapshots?hostid='.$params['customfields']['hostid'], ['type'=>'backup', 'name'=>$remarks]);
    if($res['status'] == 'success'){
        $result['status'] = 200;
        $result['msg'] = $_LANG['zjmf_check_backup_create'];

        $description = zjmfcloud_Langset('zjmf_log_create_backup_success', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
            'name'      => $remarks,
        ]);
    }else{
        $result['status'] = 'error';
        $result['msg'] = $res['msg'];

        $description = zjmfcloud_Langset('zjmf_log_create_backup_fail', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
            'name'      => $remarks,
            'reason'    => $res['msg'],
        ]);
    }
    logActivity($description);
    return $result;
}

// 删除快照
function zjmfcloud_DeleteSnap($params,$id){
    global $_LANG;
	if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
        return $result;
    }
    if(empty($id)){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_check_snap'] ;
        return $result;
    }

    $res = zjmfcloud_Curl($params, '/snapshots/'.$id.'?hostid='.$params['customfields']['hostid'], [], 30, 'DELETE');
    if($res['status'] == 'success'){
        $result['status'] = 200;
        $result['msg'] = $_LANG['zjmf_check_snap_delete_success'];

        $description = zjmfcloud_Langset('zjmf_log_delete_snap_success', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
            'snapid'    => $id,
        ]);
    }else{
        $result['status'] = 'error';
        $result['msg'] = $res['msg'];
        
        $description = zjmfcloud_Langset('zjmf_log_delete_snap_fail', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
            'snapid'    => $id,
            'reason'    => $res['msg'],
        ]);
    }
    logActivity($description);
    return $result;
}

// 删除备份
function zjmfcloud_DeleteBackup($params,$id){
    global $_LANG;
	if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
        return $result;
    }
    if(empty($id)){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_check_backup'];
        return $result;
    }

    $res = zjmfcloud_Curl($params, '/snapshots/'.$id.'?hostid='.$params['customfields']['hostid'], [], 30, 'DELETE');
    if($res['status'] == 'success'){
        $result['status'] = 200;
        $result['msg'] = $_LANG['zjmf_check_backup_delete_success'] ;

        $description = zjmfcloud_Langset('zjmf_log_delete_backup_success', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
            'snapid'    => $id,
        ]);
    }else{
        $result['status'] = 'error';
        $result['msg'] = $res['msg'];

        $description = zjmfcloud_Langset('zjmf_log_delete_backup_fail', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
            'snapid'    => $id,
            'reason'    => $res['msg'],
        ]);
    }
    logActivity($description);
    return $result;
}

// 快照还原
function zjmfcloud_RestoreBySnap($params,$id){
    global $_LANG;
	if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
        return $result;
    }
    if(empty($id)){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_check_snap'];
        return $result;
    }
    $res = zjmfcloud_Curl($params, '/snapshots/'.$id.'/restore?hostid='.$params['customfields']['hostid']);
    if($res['status'] == 'success'){
        $result['status'] =200;
        $result['msg'] = $_LANG['zjmf_check_snap_restore_success'];

        $description = zjmfcloud_Langset('zjmf_log_snap_restore_success', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
            'snapid'    => $id,
        ]);
    }else{
        $result['status'] = 'error';
        $result['msg'] = $res['msg'];

        $description = zjmfcloud_Langset('zjmf_log_snap_restore_fail', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
            'snapid'    => $id,
            'reason'    => $res['msg'],
        ]);
    }
    logActivity($description);
    return $result;
}

// 备份还原
function zjmfcloud_RestoreByBackup($params,$id){
    global $_LANG;
	if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
        return $result;
    }
    if(empty($id)){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_check_backup'];
        return $result;
    }
    $res = zjmfcloud_Curl($params, '/snapshots/'.$id.'/restore?hostid='.$params['customfields']['hostid']);
    if($res['status'] == 'success'){
        $result['status'] = 200;
        $result['msg'] = $_LANG['zjmf_check_backup_restore_success'];

        $description = zjmfcloud_Langset('zjmf_log_backup_restore_success', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
            'snapid'    => $id,
        ]);
    }else{
        $result['status'] = 'error';
        $result['msg'] = $res['msg'];

        $description = zjmfcloud_Langset('zjmf_log_backup_restore_fail', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
            'snapid'    => $id,
            'reason'    => $res['msg'],
        ]);
    }
    logActivity($description);
    return $result;
}

function zjmfcloud_ListSnapBackup($params){
    global $_LANG;
    if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'];
        return $result;
    }
    $snapshots = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid']."/snapshots", ['page'=>1,'per_page'=>9999], 30, 'GET');
    if($snapshots['status'] == 'success'){
        $snapshots=$snapshots['data']['data'];

        // 隐藏不要的数据
        foreach($snapshots as $k=>$v){
            unset($snapshots[$k]['disk_remarks'], $snapshots[$k]['diskid'], $snapshots[$k]['real_file'], $snapshots[$k]['size']);
        }
    }
    $result['status'] = 200;
    $result['data'] = $snapshots;
    return $result;
}


//获取安全组
function zjmfcloud_Security($params){
	 global $_LANG;
	if(empty($params['customfields']['hostid'])){
		$result['status'] = 'error';
		$result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
		include ZJMFCLOUD_FILE ."templates/server_innerpage/safe.php";exit;
	}	
	$snapshots = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'], [], 30, 'GET');
	if($snapshots['status']!='success'){
		$result['status'] = 'error';
		$result['msg'] = $snapshots['msg'];
		include ZJMFCLOUD_FILE ."templates/server_innerpage/safe.php";exit;
	}
	$host_type = $snapshots['data']['type'] ?: 'host';

	$data['user']=$snapshots['data']['user_id'];	
	$data['list_type']="all";
	$data['type'] = $host_type;
	$security_groups = zjmfcloud_Curl($params, '/security_groups', $data, 30, 'GET');
	$securityGroups=$security_groups['data']['data'];
	$hostid=$params['customfields']['hostid'];
	$security_group_rule_protocols = [
        ["name"=>$_LANG['security_group_rule_protocols_all'],"value"=>"all","port"=>"1-65535"],
        ["name"=>$_LANG['security_group_rule_protocols_all_tcp'],"value"=>"all_tcp","port"=>"1-65535"],
        ["name"=>$_LANG['security_group_rule_protocols_all_udp'],"value"=>"all_udp","port"=>"1-65535"],
        ["name"=>$_LANG['security_group_rule_protocols_custom_tcp'],"value"=>"tcp","port"=>""],
        ["name"=>$_LANG['security_group_rule_protocols_custom_udp'],"value"=>"udp","port"=>""],
        ["name"=>"ICMP","value"=>"icmp","port"=>"1-65535"],
        ["name"=>"GRE","value"=>"gre","port"=>"1-65535"],
        ["name"=>"SSH (22)","value"=>"ssh","port"=>"22"],
        ["name"=>"telnet (23)","value"=>"telnet","port"=>"23"],
        ["name"=>"HTTP (80)","value"=>"http","port"=>"80"],
        ["name"=>"HTTPS (443)","value"=>"https","port"=>"443"],
        ["name"=>"MS SQL(1433)","value"=>"mssql","port"=>"1433"],
        ["name"=>"Oracle (1521)","value"=>"oracle","port"=>"1521"],
        ["name"=>"MySQL (3306)","value"=>"mysql","port"=>"3306"],
        ["name"=>"RDP (3389)","value"=>"rdp","port"=>"3389"],
        ["name"=>"PostgreSQL (5432)","value"=>"postgresql","port"=>"5432"],
        ["name"=>"Redis (6379)","value"=>"redis","port"=>"6379"],
    ];
 	include ZJMFCLOUD_FILE ."templates/server_innerpage/safe.php";exit;
}
function zjmfcloud_GetSecurity($params){
     global $_LANG;
    if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
        return $result;
    }   
    $snapshots = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'], [], 30, 'GET');
    if($snapshots['status']!='success'){
        $result['status'] = 'error';
        $result['msg'] = $snapshots['msg'];
        return $result;
    }
    $host_type = $snapshots['data']['type'] ?: 'host';

    $data['user']=$snapshots['data']['user_id'];    
    $data['list_type']="all";
    $data['type'] = $host_type;
    $security_groups = zjmfcloud_Curl($params, '/security_groups', $data, 30, 'GET');
    $securityGroups=$security_groups['data']['data'];
    $hostid=$params['customfields']['hostid'];
    $security_group_rule_protocols = [
        ["name"=>$_LANG['security_group_rule_protocols_all'],"value"=>"all","port"=>"1-65535"],
        ["name"=>$_LANG['security_group_rule_protocols_all_tcp'],"value"=>"all_tcp","port"=>"1-65535"],
        ["name"=>$_LANG['security_group_rule_protocols_all_udp'],"value"=>"all_udp","port"=>"1-65535"],
        ["name"=>$_LANG['security_group_rule_protocols_custom_tcp'],"value"=>"tcp","port"=>""],
        ["name"=>$_LANG['security_group_rule_protocols_custom_udp'],"value"=>"udp","port"=>""],
        ["name"=>"ICMP","value"=>"icmp","port"=>"1-65535"],
        ["name"=>"GRE","value"=>"gre","port"=>"1-65535"],
        ["name"=>"SSH (22)","value"=>"ssh","port"=>"22"],
        ["name"=>"telnet (23)","value"=>"telnet","port"=>"23"],
        ["name"=>"HTTP (80)","value"=>"http","port"=>"80"],
        ["name"=>"HTTPS (443)","value"=>"https","port"=>"443"],
        ["name"=>"MS SQL(1433)","value"=>"mssql","port"=>"1433"],
        ["name"=>"Oracle (1521)","value"=>"oracle","port"=>"1521"],
        ["name"=>"MySQL (3306)","value"=>"mysql","port"=>"3306"],
        ["name"=>"RDP (3389)","value"=>"rdp","port"=>"3389"],
        ["name"=>"PostgreSQL (5432)","value"=>"postgresql","port"=>"5432"],
        ["name"=>"Redis (6379)","value"=>"redis","port"=>"6379"],
    ];
    $result = ['status' => 200, 'data' => ['securityGroups' => $securityGroups, 'security_group_rule_protocols' => $security_group_rule_protocols, 'host_type' => $host_type, 'hostid' => $hostid]];
    return $result;
}
// 创建安全组
function zjmfcloud_CreateSecurityGroup($params){
    global $_LANG;
	if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
        return $result;
    }
    $detail = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'], [], 30, 'GET');
    if($detail['status'] != 'success'){
        $result['status'] = 'error';
        $result['msg'] = $detail['msg'] ?: $_LANG['zjmf_check_security_error'] ;
        return $result;
    }
    $post_data['uid'] = $detail['data']['user_id'];
    $post_data['name'] = $_POST['name'];
    $post_data['description'] = $_POST['description'];
    $post_data['type'] = $detail['data']['type'];

    $res = zjmfcloud_Curl($params, '/security_groups', $post_data, 30, 'POST');
    if($res['status'] == 'success'){
        $result['status'] = 200;
        $result['msg'] = $_LANG['zjmf_check_security_success'] ;

        $description = zjmfcloud_Langset('zjmf_log_create_security_group_success', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
            'name'      => $post_data['name'],
        ]);
    }else{
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_check_security_error'] ;

        $description = zjmfcloud_Langset('zjmf_log_create_security_group_fail', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
            'name'      => $post_data['name'],
            'reason'    => $res['msg'],
        ]);
    }
    logActivity($description);
    return $result;
}

// 安全组规则列表
function zjmfcloud_SecurityRulesList($params,$SecurityGroupId){
    global $_LANG;
	if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
        return $result;
    }
    $id = (int)$SecurityGroupId;
    $res = zjmfcloud_Curl($params, '/security_groups/'.$id.'/rules', ['per_page'=>9999], 30, 'GET');
    if($res['status'] == 'success'){
        $result['status'] = 'success';
        $result['list'] = $res['data']['data'];
        // 去掉已锁定的规则
        $is_delete = false;
        foreach($result['list'] as $k=>$v){
        	if($v['lock'] == 1){
        		unset($result['list'][$k]);
        		$is_delete = true;
        	}
        }
        if($is_delete){
        	$result['list'] = array_values($result['list']);
        }
    }else{
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_check_security_rules_list_error'];
    }
    return $result;
}

// 创建安全组规则
function zjmfcloud_CreateSecurityRule($params,$SecurityGroupId){
    global $_LANG;
	if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
        return $result;
    }
    $id = (int)$SecurityGroupId;
    $post_data = [
        'port'=>$_POST['port'],
        'ip'=>$_POST['ip'],
        'protocol'=>$_POST['protocol'],
        'direction'=>$_POST['direction'],
        'description'=>$_POST['description'],
        'start_port'=>$_POST['start_port'],
        'end_port'=>$_POST['end_port'],
        'start_ip'=>$_POST['start_ip'],
        'end_ip'=>$_POST['end_ip'],
        'action'=>$_POST['_action'],
        'priority'=>$_POST['priority'],
    ];
    $detail = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'], [], 30, 'GET');
    if($detail['status'] != 'success'){
        $result['status'] = 'error';
        $result['msg'] = $detail['msg'] ?: $_LANG['zjmf_check_security_error'] ;
        return $result;
    }
    $res = zjmfcloud_Curl($params, '/security_groups/'.$id.'/rules?uid='.$detail['data']['user_id'], $post_data);
    if($res['status'] == 'success'){
        $result['status'] = 200;
        $result['msg'] = $_LANG['zjmf_check_security_success'];
    }else{
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_check_security_error'] ;
    }
    return $result;
}

// 删除安全组
function zjmfcloud_DeleteSecurityGroup($params,$SecurityGroupId){
    global $_LANG;
	if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
        return $result;
    }
    $id = (int)$SecurityGroupId;
    $detail = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'], [], 30, 'GET');
    if($detail['status'] != 'success'){
        $result['status'] = 'error';
        $result['msg'] = $detail['msg'] ?: $_LANG['zjmf_check_security_delete_error']  ;
        return $result;
    }
    $res = zjmfcloud_Curl($params, '/security_groups/'.$id.'?uid='.$detail['data']['user_id'], [], 30, 'DELETE');
    if($res['status'] == 'success'){
        $result['status'] = 200;
        $result['msg'] = $_LANG['zjmf_check_security_delete_success'];
    }else{
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_check_security_delete_error']  ;
    }
    return $result;
}

// 删除安全组规则
function zjmfcloud_DeleteSecurityGroupRule($params,$SecurityRuleId){
    global $_LANG;
	if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
        return $result;
    }
    $id = (int)$SecurityRuleId;
    $detail = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'], [], 30, 'GET');
    if($detail['status'] != 'success'){
        $result['status'] = 'error';
        $result['msg'] = $detail['msg'] ?: $_LANG['zjmf_check_security_delete_error'];
        return $result;
    }
    $res = zjmfcloud_Curl($params, '/security_group_rules/'.$id.'?uid='.$detail['data']['user_id'], [], 30, 'DELETE');
    if($res['status'] == 'success'){
        $result['status'] = 200;
        $result['msg'] = $_LANG['zjmf_check_security_delete_success'];
    }else{
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_check_security_delete_error'];
    }
    return $result;
}

// 应用安全组
function zjmfcloud_LinkSecurityGroup($params,$SecurityGroupId){
   global $_LANG;
   if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
        return $result;
    }
    $id = (int)$SecurityGroupId;
    $res = zjmfcloud_Curl($params, '/security_groups/'.$id.'/links', ['cloud'=>$params['customfields']['hostid'], 'type'=>1]);
    if($res['status'] == 'success'){
        $result['status'] = 200;
        $result['msg'] = $_LANG['zjmf_check_security_link_success'];
    }else{
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_check_security_link_error'] ;
    }
    return $result;
}

//设置
function zjmfcloud_setting($params){
	 global $_LANG;
	if(empty($params['customfields']['hostid'])){
		$result['status'] = 'error';
		$result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
		return $result;
	}	
	$clouds = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'], [], 30, 'GET');

	$data=array(
		'id'=>$clouds['data']['node_id'],
		'type'=>'node',
	);
	$node_isos = zjmfcloud_Curl($params, '/node_isos', $data, 30, 'GET');
	
	$useIso=$clouds['data']['iso'];
	$useBootorder=$clouds['data']['bootorder'];
	$bootorder=array(
		'dc'=>'(1) Hard Disk (2) CDROM',
		'cd'=>'(1) CDROM (2) Hard Disk',
		'd'=>'Hard Disk Only',
		'c'=>'CDROM Only'
	);
	$host_type = $clouds['data']['type'] ?: 'host';
	include ZJMFCLOUD_FILE ."templates/server_innerpage/setting.php";exit;
}

function zjmfcloud_ssh($params){
    global $_LANG;
    
    $sshKeyList = zjmfcloud_GetSSHKey($params);

    $host_type = $sshKeyList['data']['type'] ?: 'host';
    $sshKeyList = $sshKeyList['data']['list'] ?: [];
    include ZJMFCLOUD_FILE ."templates/server_innerpage/ssh.php";exit;
}

function zjmfcloud_GetSetting($params){
     global $_LANG;
    if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
        return $result;
    }   
    $clouds = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'], [], 30, 'GET');

    $data=array(
        'id'=>$clouds['data']['node_id'],
        'type'=>'node',
    );
    $node_isos = zjmfcloud_Curl($params, '/node_isos', $data, 30, 'GET');
    
    $useIso=$clouds['data']['iso'];
    $useBootorder=$clouds['data']['bootorder'];
    $bootorder=array(
        'dc'=>'(1) Hard Disk (2) CDROM',
        'cd'=>'(1) CDROM (2) Hard Disk',
        'd'=>'Hard Disk Only',
        'c'=>'CDROM Only'
    );
    $host_type = $clouds['data']['type'] ?: 'host';
    $result = ['status' => 200, 'data' => ['node_isos' => $node_isos, 'useIso' => $useIso, 'useBootorder' => $useBootorder, 'bootorder'=>$bootorder, 'host_type' => $host_type]];
    return $result;
}

//挂载
function zjmfcloud_MountIso($params,$isoId){
	global $_LANG;
	if(empty($params['customfields']['hostid'])){
		$result['status'] = 'error';
		$result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
		return $result;
	}	
	$id = (int)$isoId;
	$data['iso']=$id;
	$res = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'].'/iso', $data, 30, 'POST');
	if($res['status'] == 'success'){
        $result['status'] = 200;
        $result['msg'] = $_LANG['zjmf_check_mount_success'];
    }else{
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_check_mount_error'];
    }
    return $result;
}
//卸载挂载
function zjmfcloud_UnMountIso($params,$unmountIsoId){
	global $_LANG;
	if(empty($params['customfields']['hostid'])){
		$result['status'] = 'error';
		$result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
		return $result;
	}	
	$id = (int)$unmountIsoId;
	$data['iso']=$id;
	$res = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'].'/iso', $data, 30, 'DELETE');
	if($res['status'] == 'success'){
        $result['status'] = 200;
        $result['msg'] = $_LANG['zjmf_check_unmount_success'];
    }else{
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_check_unmount_error'] ;
    }
    return $result;	
}
//启动项
function zjmfcloud_SetBootOrder($params,$bootOrderId){
	global $_LANG;
	if(empty($params['customfields']['hostid'])){
		$result['status'] = 'error';
		$result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
		return $result;
	}	
	$id = $bootOrderId;
	$data['bootorder']=$id;
	$res = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'], $data, 30, 'PUT');
	if($res['status'] == 'success'){
        $result['status'] = 200;
        $result['msg'] = $_LANG['zjmf_check_setboot_success'] ;
    }else{
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_check_setboot_error'] ;
    }
    return $result;	
}
//NAT转发页面
function zjmfcloud_NatAcl($params){
	 global $_LANG;
	if(empty($params['customfields']['hostid'])){
		$result['status'] = 'error';
		$result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
		return $result;
	}	
	//协议( 1tcp 2udp 3tcp+udp )
	$protocol=array(1=>'tcp',2=>'udp',3=>'tcp+udp');
	$clouds = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid']."/nat_acl", array('sort'=>'asc','list_type'=>'all'), 30, 'GET');
	$nat_acl=$clouds['data']['data'];
	$nat_host_ip=$clouds['data']['nat_host_ip'];
	include ZJMFCLOUD_FILE ."templates/server_innerpage/nat_acl.php";exit;
}
function zjmfcloud_GetNatAcl($params){
     global $_LANG;
    if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
        return $result;
    }   
    //协议( 1tcp 2udp 3tcp+udp )
    $protocol=array(1=>'tcp',2=>'udp',3=>'tcp+udp');
    $clouds = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid']."/nat_acl", array('sort'=>'asc','list_type'=>'all'), 30, 'GET');
    $nat_acl=$clouds['data']['data'];
    $nat_host_ip=$clouds['data']['nat_host_ip'];
    $result = ['status' => 200, 'data' => ['protocol' => $protocol, 'nat_acl' => $nat_acl, 'nat_host_ip' => $nat_host_ip]];
    return $result;
}
// 创建NAT转发
function zjmfcloud_CreateNatAcl($params,$requestData){
    global $_LANG;
	if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
        return $result;
    }
    $data['name'] = $requestData['name'];
	$data['ext_port'] = $requestData['ext_port'];
	$data['int_port'] = $requestData['int_port'];
	$data['protocol'] = $requestData['protocol'];
    $res = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid']."/nat_acl", $data, 30, 'POST');
    if($res['status'] == 'success'){
        $result['status'] = 200;
        $result['msg'] = $_LANG['zjmf_check_createnatacl_success'];
    }else{
        $result['status'] = 'error';
        $result['msg'] = $res['msg'];
    }
    return $result;
}
// 删除NAT转发
function zjmfcloud_DeleteNatAcl($params,$id){
    global $_LANG;
	if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
        return $result;
    }
    $res = zjmfcloud_Curl($params, '/nat_acl/'.$id.'?hostid='.$params['customfields']['hostid'], [], 30, 'DELETE');
    if($res['status'] == 'success'){
        $result['status'] = 200;
        $result['msg'] = $_LANG['zjmf_check_deletenatacl_success'] ;
    }else{
        $result['status'] = 'error';
        $result['msg'] = $res['msg'];
        
    }
    return $result;
}
//NAT建站页面 
function zjmfcloud_NatWeb($params){
	global $_LANG;
	if(empty($params['customfields']['hostid'])){
		$result['status'] = 'error';
		$result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
		return $result;
	}	
	$clouds = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid']."/nat_web", array('list_type'=>'all'), 30, 'GET');
	$nat_web=$clouds['data']['data'];
	$nat_host_ip=$clouds['data']['nat_host_ip'];
	include ZJMFCLOUD_FILE ."templates/server_innerpage/nat_web.php";exit;
}
function zjmfcloud_GetNatWeb($params){
    global $_LANG;
    if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
        return $result;
    }   
    $clouds = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid']."/nat_web", array('list_type'=>'all'), 30, 'GET');
    $nat_web=$clouds['data']['data'];
    $nat_host_ip=$clouds['data']['nat_host_ip'];
    $result = ['status' => 200, 'data' => ['nat_web' => $nat_web, 'nat_host_ip' => $nat_host_ip]];
    return $result;
}
// 创建NAT建站
function zjmfcloud_CreateNatWeb($params,$requestData){
    global $_LANG;
	if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
        return $result;
    }
    $data['domain'] = $requestData['domain'];
	$data['ext_port'] = $requestData['ext_port'];
	$data['int_port'] = $requestData['int_port'];
    $res = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid']."/nat_web", $data, 30, 'POST');
    if($res['status'] == 'success'){
        $result['status'] = 200;
        $result['msg'] = $_LANG['zjmf_check_createnatweb_success'];
    }else{
        $result['status'] = 'error';
        $result['msg'] = $res['msg'];
    }
    return $result;
}
// 删除NAT建站
function zjmfcloud_DeleteNatWeb($params,$id){
    global $_LANG;
	if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
        return $result;
    }

    $res = zjmfcloud_Curl($params, '/nat_web/'.$id.'?hostid='.$params['customfields']['hostid'], [], 30, 'DELETE');
    if($res['status'] == 'success'){
        $result['status'] = 200;
        $result['msg'] = $_LANG['zjmf_check_deletenatweb_success'];
    }else{
        $result['status'] = 'error';
        $result['msg'] = $res['msg'];
        
    }
    return $result;
}

function zjmfcloud_TrafficTotal($params){
	if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
        return $result;
    }
	$res = zjmfcloud_Curl($params, '/net_info', ['host_id'=>$params['customfields']['hostid']], 15, 'GET');
	$data = [];
	// $data['bwlimit'] = 0;
	// $data['bwusage'] = 0;
    if($res['status'] == 'success'){
        if($res['data']['meta']['traffic_quota'] != 0){
            $res['data']['meta']['traffic_quota'] += $info['data']['meta']['tmp_traffic'];
        }
        $data = [];
        $data['bwlimit'] = intval($res['data']['meta']['traffic_quota'] * 1024);
        $usage = 0;
        if($res['data']['meta']['traffic_type'] == 1){
            $usage = intval($res['data']['info']['30_day']['accept']/pow(1024, 2));
        }else if($res['data']['meta']['traffic_type'] == 2){
            $usage = intval($res['data']['info']['30_day']['send']/pow(1024, 2));
        }else if($res['data']['meta']['traffic_type'] == 3){
            $usage = intval($res['data']['info']['30_day']['total']/pow(1024, 2));
        }
        $data['bwusage'] = $usage;
        $data['percent'] = $res['data']['info']['30_day']['float'];
        // $data['lastupdate'] = date('Y-m-d H:i:s');
        // var_dump($update);
        //Capsule::table('tblhosting')->where('id', '=', $v['id'])->update($update);
        
        $result['status'] = 'success';
        $result['data'] = $data;
    }else{
    	$result['status'] = 'error';
    	$result['msg'] = '';
    }
    return $result;

}

function zjmfcloud_getCurrency($params){
	$currency = $params['clientsdetails']['currency'];
	if(empty($currency)){
		$pdo = Capsule::connection()->getPdo();
		$currency = $pdo->query('SELECT `id` FROM `tblcurrencies` WHERE `default`=1')->fetch(PDO::FETCH_ASSOC);
		$currency = (int)$currency['id'];
	}
	return $currency;
}

function zjmfcloud_RestoreNetwork($params){
    global $_LANG;
    if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
        return $result;
    }
    $res = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'].'/internet', [], 30, 'PUT');
    if($res['status'] == 'success'){
        $result['status'] = 200;
        $result['msg'] = $_LANG['zjmf_restore_network_success'];
    }else{
        $result['status'] = 'error';
        $result['msg'] = $res['msg'];
        
    }
    return $result;
}

function zjmfcloud_Rescue($params){
    global $_LANG;
    if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
        return $result;
    }
    $post_data = [
        'type' => $_POST['type'] ?: 0,
        'temp_pass' => $_POST['temp_pass'],
    ];
    $res = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'].'/rescue', $post_data, 30, 'POST');
    if($res['status'] == 'success'){
        $result['status'] = 'success';
        $result['msg'] = $_LANG['zjmf_task_rescue_success'] ;

        $description = zjmfcloud_Langset('zjmf_log_rescue_success', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
        ]);
    }else{
        $result['status'] = 'error';
        $result['msg'] = $res['msg'];

        $description = zjmfcloud_Langset('zjmf_log_rescue_fail', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
            'reason'    => $res['msg'],
        ]);
    }
    logActivity($description);
    return $result;
}

function zjmfcloud_ExitRescue($params){
    global $_LANG;
    if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
        return $result;
    }
    $res = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'].'/rescue', [], 30, 'DELETE');
    if($res['status'] == 'success'){
        $result['status'] = 'success';
        $result['msg'] = $_LANG['zjmf_task_exit_rescue_success'] ;

        $description = zjmfcloud_Langset('zjmf_log_exit_rescue_success', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
        ]);
    }else{
        $result['status'] = 'error';
        $result['msg'] = $res['msg'];

        $description = zjmfcloud_Langset('zjmf_log_exit_rescue_fail', [
            'domain'    => $params['domain'],
            'serviceid' => $params['serviceid'],
            'reason'    => $res['msg'],
        ]);
    }
    logActivity($description);
    return $result;
}

function zjmfcloud_RecoverOriginBw($params){
    global $_LANG;
    if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'] ;
        return $result;
    }
    $res = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'].'/recover_origin_bw', [], 30, 'PUT');
    if($res['status'] == 'success'){
        $result['status'] = 200;
        $result['msg'] = $_LANG['zjmf_restore_network_success'];
    }else{
        $result['status'] = 'error';
        $result['msg'] = $res['msg'];
        
    }
    return $result;
}

// 密钥列表
function zjmfcloud_GetSSHKey($params){
    global $_LANG;
    if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'];
        return $result;
    }
    $clouds = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'], [], 30, 'GET');
    if($clouds['status'] != 'success'){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_now_cannot_do_this_please_wait_retry'];
        return $result;
    }
    $data = [];

    $res = zjmfcloud_Curl($params, '/ssh_keys', ['uid'=>$clouds['data']['user_id'], 'page'=>1, 'per_page'=>50 ], 30, 'GET');
    if($res['status'] == 'success'){
        $result['status'] = 200;
        $result['msg'] = $_LANG['zjmf_request_success'];
        
        foreach($res['data']['data'] as $v){
            $is_bind = false;
            if($v['id'] == $clouds['data']['ssh_key']['id']){
                $is_bind = true;
            }
            $data[] = [
                'id'        => $v['id'],
                'name'      => $v['name'],
                'bind'      => $is_bind,
                'can_delete'=> empty($v['host']),
            ];
        }

        $result['data']['list'] = $data;
        $result['data']['type'] = $clouds['data']['type'];
    }else{
        $result['status'] = 'error';
        $result['msg'] = $res['msg'];
    }
    return $result;
}

// 创建密钥
function zjmfcloud_CreateSSHKey($params, $post = []){
    global $_LANG;
    $max = 50;
    if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'];
        return $result;
    }
    $clouds = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'], [], 30, 'GET');
    if($clouds['status'] != 'success'){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_now_cannot_do_this_please_wait_retry'];
        return $result;
    }
    $res = zjmfcloud_Curl($params, '/ssh_keys', ['uid'=>$clouds['data']['user_id'], 'page'=>1, 'per_page'=>1 ], 30, 'GET');
    if($res['data']['meta']['total'] >= $max){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_ssh_key_num_max'];
        return $result;
    }
    $data = [
        'type'      => $post['type'],
        'uid'       => $clouds['data']['user_id'],
        'name'      => $post['name'],
        'public_key'=> $post['public_key'],
    ];

    $res = zjmfcloud_Curl($params, '/ssh_keys', $data, 30, 'POST');
    if($res['status'] == 'success'){
        $result['status'] = 200;
        $result['msg'] = $_LANG['zjmf_check_security_success'];
        $result['data'] = $res['data'];
    }else{
        $result['status'] = 'error';
        $result['msg'] = $res['msg'];
    }
    return $result;
}

// 删除密钥
function zjmfcloud_DeleteSSHKey($params, $ssh_key_id = 0){
    global $_LANG;
    if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'];
        return $result;
    }
    $clouds = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'], [], 30, 'GET');
    if($clouds['status'] != 'success'){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_now_cannot_do_this_please_wait_retry'];
        return $result;
    }
    $list = zjmfcloud_Curl($params, '/ssh_keys', [ 'uid'=>$clouds['data']['user_id'], 'page'=>1, 'per_page'=>100 ], 30, 'GET');

    $ssh_key = [];
    foreach($list['data']['data'] as $k=>$v){
        if($v['id'] == $ssh_key_id){
            $ssh_key = $v;
            break;
        }
    }
    if(empty($ssh_key)){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_now_cannot_do_this_please_wait_retry'];
        return $result;
    }
    if(!empty($ssh_key['host'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_ssh_key_used_cannot_delete'];
        return $result;
    }

    $res = zjmfcloud_Curl($params, '/ssh_keys/'.$ssh_key_id, [], 30, 'DELETE');
    if($res['status'] == 'success'){
        $result['status'] = 200;
        $result['msg'] = $_LANG['zjmf_check_security_delete_success'];
    }else{
        $result['status'] = 'error';
        $result['msg'] = $res['msg'];
    }
    return $result;
}

// 绑定密钥
function zjmfcloud_BindSSHKey($params, $ssh_key_id = 0){
    global $_LANG;
    if(empty($params['customfields']['hostid'])){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_api_host_id_error'];
        return $result;
    }
    $clouds = zjmfcloud_Curl($params, '/clouds/'.$params['customfields']['hostid'], [], 30, 'GET');
    if($clouds['status'] != 'success'){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_now_cannot_do_this_please_wait_retry'];
        return $result;
    }
    if($clouds['data']['image_group_id'] == 1){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_ssh_key_windows_cannot_use'];
        return $result;
    }

    $list = zjmfcloud_Curl($params, '/ssh_keys', [ 'uid'=>$clouds['data']['user_id'], 'page'=>1, 'per_page'=>100 ], 30, 'GET');

    $ssh_key = [];
    foreach($list['data']['data'] as $k=>$v){
        if($v['id'] == $ssh_key_id){
            $ssh_key = $v;
            break;
        }
    }
    if(empty($ssh_key)){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_now_cannot_do_this_please_wait_retry'];
        return $result;
    }
    if($clouds['data']['status'] != 'off'){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['zjmf_ssh_key_bind_must_shutdown'];
        return $result;
    }

    $res = zjmfcloud_Curl($params, '/ssh_keys/'.$ssh_key_id.'/clouds', ['hostid'=>[$clouds['data']['id']]], 30, 'POST');
    if($res['status'] == 'success'){
        $result['status'] = 200;
        $result['msg'] = $_LANG['zjmf_ssh_key_bind_success'];
    }else{
        $result['status'] = 'error';
        $result['msg'] = $res['msg'];
    }
    return $result;
}








