<?php 

// 重启
function ipmi_Reboot($params){
	global $_LANG;
    $ipmiType = $params['configoption1'];
    $serviceid = $params['serviceid'];
    $customData = ipmi_GetCustomIpmi($serviceid);
    $ipmi_id = $customData['ipmi_id'];
    $is_debug = ipmi_IsDebug();
    $hosting = getHosting($serviceid);
    $accesshash = serverAccessHash($hosting['server'], $hosting['accesshash']);
    if(empty($ipmi_id)){
        return $_LANG['ipmi_admin_server_error'];
    }
    if('机柜租用' ==  $ipmiType) {
        return $_LANG['ipmi_admin_cabinet_error'];
    }
    if(!$is_debug && in_array('reboot', $accesshash['sms_check']) && !ipmi_checkSms()){  //前台
        return $_LANG['ipmi_action_check_error1'];
    }
    $postfields['id'] = $ipmi_id;
    $postfields['hostid'] = $serviceid;
    # 调用api
    $result = ipmi_req('ipmiReboot', $postfields, $params, 30);
    if('success' == $result['status']){
        $res = 'success';
        
        $description = "Module {$_LANG['ipmi_client_reboot']} REBOOT Success - Service ID: {$serviceid}";
        ipmi_addLog($description);
    }else{
        if($is_debug){  //后台
            $res = $result['msg'];
        }else{ //前台
            $res = $_LANG['ipmi_action_check_error2'];
        }
        
        $description = "Module {$_LANG['ipmi_client_reboot']} REBOOT Failed - Service ID: {$serviceid} - Error: ".$result['msg'];
        ipmi_addLog($description);
    }
    return $res;
}

// 关机
function ipmi_Off($params){
    global $_LANG;
	$ipmiType = $params['configoption1'];
    $serviceid = $params['serviceid'];
    $customData = ipmi_GetCustomIpmi($serviceid);
    $ipmi_id = $customData['ipmi_id'];
    $is_debug = ipmi_IsDebug();
    $hosting = getHosting($serviceid);
    $accesshash = serverAccessHash($hosting['server'], $hosting['accesshash']);
    if(empty($ipmi_id)){
        return $_LANG['ipmi_admin_server_error'];
    }
    if('机柜租用' ==  $ipmiType) {
        return $_LANG['ipmi_admin_cabinet_error'];
    }
    if(!$is_debug && in_array('off', $accesshash['sms_check']) && !ipmi_checkSms()){  //前台
        return $_LANG['ipmi_action_check_error1']; 
    }
    $postfields['id'] = $ipmi_id;
    $postfields['hostid'] = $serviceid;
    # 调用api
    $result = ipmi_req('ipmiOff', $postfields, $params, 30);
    if('success' == $result['status']){
        $res = 'success';
        
        $description = "Module {$_LANG['ipmi_action_power_off']} POWER_OFF Success - Service ID: {$serviceid}";
        ipmi_addLog($description);
    }else{
        if($is_debug){  //后台
            $res = $result['msg'];
        }else{ //前台
            $res = $_LANG['ipmi_action_check_error3'];
        }
        
        $description = "Module {$_LANG['ipmi_action_power_off']} POWER_OFF Failed - Service ID: {$serviceid} - Error: ".$result['msg'];
        ipmi_addLog($description);
    }
    return $res;
}

// 开机
function ipmi_On($params){
    global $_LANG;
	$ipmiType = $params['configoption1'];
    $serviceid = $params['serviceid'];
    $customData = ipmi_GetCustomIpmi($serviceid);
    $ipmi_id = $customData['ipmi_id'];
    $is_debug = ipmi_IsDebug();
    $hosting = getHosting($serviceid);
    $accesshash = serverAccessHash($hosting['server'], $hosting['accesshash']);
    if(empty($ipmi_id)){
        return $_LANG['ipmi_admin_server_error'];
    }
    if('机柜租用' ==  $ipmiType) {
        return $_LANG['ipmi_admin_cabinet_error'];
    }
    if(!$is_debug && in_array('on', $accesshash['sms_check']) && !ipmi_checkSms()){  //前台
        return 'ipmi_client'; 
    }
    $postfields['id'] = $ipmi_id;
    $postfields['hostid'] = $serviceid;
    # 调用api
    $result = ipmi_req('ipmiOn', $postfields, $params, 30);
    if('success' == $result['status']){
        $res = 'success';
        
        $description = "Module {$_LANG['ipmi_action_power_on']} POWER_ON Success - Service ID: {$serviceid}";
        ipmi_addLog($description);
    }else{
        if($is_debug){  //后台
            $res = $result['msg'];
        }else{ //前台
            $res = $_LANG['ipmi_action_check_error4'];
        }
        
        $description = "Module {$_LANG['ipmi_action_power_on']} POWER_ON Failed - Service ID: {$serviceid} - Error: ".$result['msg'];
        ipmi_addLog($description);
    }
    return $res;
}

// 重置bmc
function ipmi_ResetBmc($params){
    global $_LANG;
	$ipmiType = $params['configoption1'];
    $serviceid = $params['serviceid'];
    $customData = ipmi_GetCustomIpmi($serviceid);
    $ipmi_id = $customData['ipmi_id'];
    $is_debug = ipmi_IsDebug();
    $hosting = getHosting($serviceid);
    $accesshash = serverAccessHash($hosting['server'], $hosting['accesshash']);
    if(empty($ipmi_id)){
        return $_LANG['ipmi_admin_server_error'];
    }
    if('机柜租用' ==  $ipmiType) {
        return $_LANG['ipmi_admin_cabinet_error'];
    }
    if(!$is_debug && in_array('bmc', $accesshash['sms_check']) && !ipmi_checkSms()){  //前台
        return $_LANG['ipmi_action_check_error1']; 
    }
    $postfields['id'] = $ipmi_id;
    $postfields['hostid'] = $serviceid;
    # 调用api
    $result = ipmi_req('ipmiMcresetcold', $postfields, $params, 30);
    if('success' == $result['status']){
        $res = 'success';
        
        $description = "Module {$_LANG['ipmi_client_resetbmc']} Success - Service ID: {$serviceid}";
        ipmi_addLog($description);
    }else{
        if($is_debug){  //后台
            $res = $result['msg'];
        }else{ //前台
            $res = $_LANG['ipmi_action_check_error5'];
        }
        
        $description = "Module {$_LANG['ipmi_client_resetbmc']} Failed - Service ID: {$serviceid} - Error: ".$result['msg'];
        ipmi_addLog($description);
    }
    return $res;
}
// 同步
function ipmi_Sync($params){
    global $_LANG;
	$ipmiType = $params['configoption1'];
    $serviceid = $params['serviceid'];
    $customData = ipmi_GetCustomIpmi($serviceid);
    $ipmi_id = $customData['ipmi_id'];
    if(empty($ipmi_id)){
        return $_LANG['ipmi_admin_server_error'];
    }
    $hosting = getHosting($serviceid);
    $accesshash = serverAccessHash($hosting['server'], $hosting['accesshash']);
    $user_info = mysql_fetch_assoc(full_query("select id,email from tblclients where id='{$params["userid"]}'"));
    $postfields['id'] = $ipmi_id;
    $postfields['hostid'] = $serviceid;
	if($accesshash['post_emailorid_pre']){
		$post_emailorid_pre= ($accesshash['post_emailorid_pre'])?$accesshash['post_emailorid_pre']."_":'';
	}
    $postfields['user_id'] = ($accesshash['post_emailorid'] == "email") ? $user_info['email'] : $params['userid'];
    $postfields['user_id']=$post_emailorid_pre.$postfields['user_id'];
    $postfields['domainstatus'] = $hosting['domainstatus'];
    $postfields['starttime'] = $hosting['regdate'].' 00:00:00';
    // dcim4.6添加到期时间传递
    $postfields['expiretime'] = $hosting['nextduedate'];
    $params['serversecure'] = $hosting['secure']; 
    $params['serverip'] = $hosting['hostname'] ?: $hosting['ipaddress'];
    $params['serverport'] = $hosting['serverport'];
    $params['serverusername'] = $hosting['username'];
    $params['serverpassword'] = decrypt($hosting['password']);
    $result = ipmi_req('ipmiSync', $postfields, $params, 30);
    if('success' == $result['status']){
        if ($accesshash['changehostname'] == 'hostname') {
            $arr['domain'] = $result['wltag'];
        }else if ($accesshash['changehostname'] == 'ip') {
            $arr['domain'] = $result['zhuip'];
        }else if ($accesshash['changehostname'] == 'hostnameip') {
            $arr['domain'] = $result['wltag'].'-'.$result['zhuip'];
        } 
        if('机柜租用' ==  $ipmiType){
            $arr['domain'] = $result['name'];
        }
        if($accesshash['changehostname'] == 'none'){
            unset($arr['domain']);
        }
        if($accesshash['changemainip'] == 'on'){
            $arr['dedicatedip'] = $result['zhuip'];
        }
        if($accesshash['changeassignip'] == 'on'){
            $newarr = explode("\r\n", $result['ips']);
            $arr['assignedips'] = '';
            foreach ($newarr as $value) {
                 if ($value != $result['zhuip'] && !empty($value)) {         
                    $arr['assignedips'] .= $value."\r\n";    
                 }
            }
            $arr['assignedips'] = rtrim($arr['assignedips'], "\r\n"); 
        }           
        if (!empty($result['username'])){
            $arr['username'] = $result['username'];
        }
        if (!empty($result['password'])){
            $arr['password'] = encrypt($result['password']);
        }
        // 记录流量数据,是否启用插件?
        if(ipmi_addonFlowPacket()){
            $bill_type = mysql_fetch_assoc(full_query("SELECT * FROM idcsmart_flowpacket_config WHERE name='bill_type'"));
            $bill_type = $bill_type['value'] ?: 'month';
            if(!empty($result['traffic_usage'][$bill_type][$result['traffic_type']])){
                $arr['bwusage'] = ceil(str_replace('MB', '', $result['traffic_usage'][$bill_type][$result['traffic_type']]));
                $arr['lastupdate'] = 'now()';
            }
        }
        if(isset($result['traffic'])){
            $arr['bwlimit'] = ceil($result['traffic']);
        }
        update_query('mod_custom_ipmi', ['value2'=>$result['wltag'], 'value3'=>$result['ippassword']], ['serviceid' => $serviceid]);
        if(!empty($arr)){
            update_query('tblhosting', $arr, ['id'=>$serviceid]);
        }
        $res = 'success';
        if(!empty($customData['admin'])){
            $description = "Module {$_LANG['ipmi_client_sync']} SYNC Success - Service ID: {$serviceid}";
            localAPI('LogActivity', ['description'=>$description], $customData["admin"]);
        }
    }else{
        $res = $result['msg'] ?: 'error';
        if(!empty($customData['admin'])){
            $description = "Module {$_LANG['ipmi_client_sync']} SYNC Failed - Service ID: {$serviceid} - Error: ".$result['msg'];
            localAPI('LogActivity', ['description'=>$description], $customData["admin"]);
        }
    }
    return $res;
}

// 获取vnc
function ipmi_vnc($params){
    global $_LANG;
	$ipmiType = $params['configoption1'];
    $serviceid = $params['serviceid'];
    $customData = ipmi_GetCustomIpmi($serviceid);
    $ipmi_id = $customData['ipmi_id'];
    if(empty($ipmi_id)){
        $res['status'] = 'error';
        $res['msg']    = $_LANG['ipmi_admin_server_error'];
        return $res;
    }
    if('机柜租用' ==  $ipmiType) {
        $res['status'] = 'error';
        $res['msg']    = $_LANG['ipmi_admin_cabinet_error'];
        return $res;
    }
    $postfields['id'] = $ipmi_id;
    $postfields['hostid'] = $serviceid;
    if($params['restart'] == 1){
        $result = ipmi_req('ipmiVncRestart', $postfields, $params, 150);
    }else{
        $result = ipmi_req('ipmiVnc', $postfields, $params, 150);
    }
    if('success' == $result['status']){
        $hosting = getHosting($serviceid);
        $res['status'] = 'success';
        $host = $params['serverhostname'] ? $params['serverhostname'] : $params['serverip'];  
        $serverport = $params['serverport'];
        if(!empty($serverport)){
            $host = $host.':'.$serverport;
        }
        $res['host'] = $host;  //$result['vnc_url'];
        $res['ssl'] = $params['serversecure'];
        $res['house'] = $result['house_id'];
        $res['token'] = $result['token'];
        $res['pass'] = decrypt($hosting['operate_password']);
        $res['vnc_pass'] = $result['pass'];
        
        $description = "Module {$_LANG['ipmi_action_vnc_open']} VNC Success - Service ID: {$serviceid}";
        ipmi_addLog($description);
    }else{
        $res['status'] = 'error';
        $res['msg']    = $_LANG['ipmi_action_check_error6'];
        
        $description = "Module {$_LANG['ipmi_action_vnc_open']} VNC Failed - Service ID: {$serviceid} - Error: ".$result['msg'];
        ipmi_addLog($description);
    }
    return $res;
}
// kvm
function ipmi_kvm($params){
   global $_LANG;
   $ipmiType = $params['configoption1'];
    $serviceid = $params['serviceid'];
    $customData = ipmi_GetCustomIpmi($serviceid);
    $ipmi_id = $customData['ipmi_id'];
    if(empty($ipmi_id)){
        $res['status'] = 'error';
        $res['msg']    = $_LANG['ipmi_admin_server_error'];
        return $res;
    }
    if('机柜租用' ==  $ipmiType) {
        $res['status'] = 'error';
        $res['msg']    = $_LANG['ipmi_admin_cabinet_error'];
        return $res;
    }
    $postfields['id'] = $ipmi_id;
    $postfields['hostid'] = $serviceid;
    # 调用api
    $result = ipmi_req('ipmiKvm', $postfields, $params, 150);
    if('success' == $result['status']){
        $data = ipmi_httpGetContent($result['url']);
        $name = array_pop(explode('/', $result['url']));
        $save_path = IPMI_FILE.'download/'.$name;
        file_put_contents($save_path, $data);
        $res['status']   = 'success';
        $res['filename'] = $name;
        
        $description = "Module KVM Success - Service ID: {$serviceid}";
        ipmi_addLog($description);
    }else{
        $res = $result;
        $res['status'] = 'error';
        
        $description = "Module KVM Failed - Service ID: {$serviceid} - Error: {$_LANG['ipmi_client_ikvm_down_error'] }";
        ipmi_addLog($description);
    }
    return $res;
}

// ikvm
function ipmi_ikvm($params){
    global $_LANG;
	$ipmiType = $params['configoption1'];
    $serviceid = $params['serviceid'];
    $customData = ipmi_GetCustomIpmi($serviceid);
    $ipmi_id = $customData['ipmi_id'];
    if(empty($ipmi_id)){
        $res['status'] = 'error';
        $res['msg']    = $_LANG['ipmi_admin_server_error'];
        return $res;
    }
    if('机柜租用' ==  $ipmiType) {
        $res['status'] = 'error';
        $res['msg']    = $_LANG['ipmi_admin_cabinet_error'];
        return $res;
    }
    $postfields['id'] = $ipmi_id;
    $postfields['hostid'] = $serviceid;
    # 调用api
    $result = ipmi_req('ipmiIKvm', $postfields, $params, 150);
    if('success' == $result['status']){
        $data = ipmi_httpGetContent($result['url']);
        $name = array_pop(explode('/', $result['url']));
        $save_path = IPMI_FILE.'download/'.$name;
        file_put_contents($save_path, $data);
        $res['status']   = 'success';
        $res['filename'] = $name;
        
        $description = "Module IKVM Success - Service ID: {$serviceid}";
        ipmi_addLog($description);
    }else{
        $res = $result;
        
        $description = "Module IKVM Failed - Service ID: {$serviceid} - Error: {$_LANG['ipmi_client_ikvm_down_error'] }";
        ipmi_addLog($description);
    }
    return $res;
}

// 获取电源状态
function ipmi_GetPowerStatus($params){
   global $_LANG;
   $ipmiType = $params['configoption1'];
    $serviceid = $params['serviceid'];
    $customData = ipmi_GetCustomIpmi($serviceid);
    $ipmi_id = $customData['ipmi_id'];
    if( empty($ipmi_id) ){
        $res['status'] = 'error';
        $res['msg']    = $_LANG['ipmi_admin_server_error'];
        return $res;
    }
    if('服务器租用' ==  $ipmiType || '服务器托管' == $ipmiType) {
        $postfields['id'] = $ipmi_id;
        # 调用api
        $result = ipmi_req('ipmiPowerSync', $postfields, $params, 60);
        if ($result['msg'] == 'on'){
            $msg = $_LANG['ipmi_client_on'];
        } else if ($result['msg'] == 'off'){
            $msg = $_LANG['ipmi_client_off'];
        }else if ($result['msg'] == 'error'){
            $msg = $_LANG['ipmi_middle_error'];
        }else if ($result['msg'] == 'nonsupport'){
            $result['msg'] = $_LANG['ipmi_middle_power_no'];
        } 
        if ($result['status'] == 'success') {
            $res['status'] = 'success';
            $res['power'] = $result['msg'];
            $res['msg'] = $msg;
        }else{
            $res['status'] = 'error';
            $res['msg'] = empty($result['msg']) ? $result['power_msg'] : $result['msg'];
        } 
    }else{
        $res['status'] = 'error';
        $res['msg']    = $_LANG['ipmi_middle_power_no'];
    }
    return $res;
}

// 重装系统
function ipmi_reinstall($params){
    global $_LANG;
	$ipmiType = $params['configoption1'];
    $serviceid = $params['serviceid'];
    $customData = ipmi_GetCustomIpmi($serviceid);
    $ipmi_id = $customData['ipmi_id'];
    if( empty($ipmi_id) ){
        $res['status'] = 'error';
        $res['msg']    = $_LANG['ipmi_admin_server_error'];
        return $res;
    }
    if('服务器租用' ==  $ipmiType || '服务器托管' == $ipmiType) {
        $postfields['id'] = $ipmi_id;
        //$postfields['hostid'] = $serviceid;
        $postfields['rootpass'] = $params['password'];
        $postfields['action'] = $params['action'];
        $postfields['wltag'] = $params['wltag'];
        $postfields['mos'] = $params['mos'];
        $postfields['mcon'] = $params['mcon'];
        $postfields['mscripts'] = $params['mscripts'];
        $postfields['port'] = $params['port'];
        $postfields['xml'] = $params['xml'];
        $postfields['part_type'] = $params['part_type'];
        $postfields['disk'] = $params['disk'];
        $postfields['check_disk_size'] = $params['check_disk_size'];
        $postfields['highgrade'] = $params['highgrade'] ?? 0;
        $res = ipmi_req('reinstallSystem', $postfields, $params, 120);
        
        if ($res['status'] == "success") {
            $description = "Module {$_LANG['ipmi_admin_area_reinstall_getinfo4']} reinstall Success - Service ID: {$serviceid}";
        } else {
            $description = "Module {$_LANG['ipmi_admin_area_reinstall_getinfo4']} reinstall Failed - Service ID: {$serviceid} - Error: ".$res['msg'];
        }
        ipmi_addLog($description);
    }else{
        $res['status'] = 'error';
        $res['msg']    = $_LANG['ipmi_middle_handle_no'];
    }
    ipmi_Sync($params); 
    return $res;  
}
// 获取重装状态
function ipmi_reinstallStatus($params){
    global $_LANG;
	$ipmiType = $params['configoption1'];
    $serviceid = $params['serviceid'];
    $customData = ipmi_GetCustomIpmi($serviceid);
    $ipmi_id = $customData['ipmi_id'];
    if( empty($ipmi_id) ){
        $res['status'] = 'error';
        $res['msg']    = $_LANG['ipmi_admin_server_error'];
        return $res;
    }
    if('服务器租用' ==  $ipmiType || '服务器托管' == $ipmiType) {
        $postfields['id'] = $ipmi_id;
        $res = ipmi_req('getReinstallStatus', $postfields, $params, 120);
    }else{
        $res['status'] = 'error';
        $res['msg']    = $_LANG['ipmi_middle_handle_no'];
    }
    return $res;
}
// 取消重装
function ipmi_cancellReinstall($params){
    global $_LANG;
	$serviceid = $params['serviceid'];
    $ipmiType = $params['configoption1'];
    $customData = ipmi_GetCustomIpmi($serviceid);
    $ipmi_id = $customData['ipmi_id'];
    if(empty($ipmi_id)){
        $res['status'] = 'error';
        $res['msg']    = $_LANG['ipmi_admin_server_error'];
        return $res;
    }
    if('服务器租用' ==  $ipmiType || '服务器托管' == $ipmiType) {
        $postfields['id'] = $params["mirror_task_id"];
        $res = ipmi_req('cancellReinstall', $postfields, $params, 120);
    }else{
        $res['status'] = 'error';
        $res['msg']    = $_LANG['ipmi_middle_handle_no'];
    }
    return $res;
}
// 解除暂停重装
function ipmi_unsuspendReload($params){
    global $_LANG;
	$serviceid = $params['serviceid'];
    $ipmiType = $params['configoption1'];
    $customData = ipmi_GetCustomIpmi($serviceid);
    $ipmi_id = $customData['ipmi_id'];
    if(empty($ipmi_id)){
        $res['status'] = 'error';
        $res['msg']    = $_LANG['ipmi_admin_server_error'];
        return $res;
    }
    if('服务器租用' ==  $ipmiType || '服务器托管' == $ipmiType) {
        $postfields['id'] = $params["mirror_task_id"];
        $postfields['disk_part'] = $params["disk_part"];
        $res = ipmi_req('unsuspendReload', $postfields, $params, 120);
    }else{
        $res['status'] = 'error';
        $res['msg']    = $_LANG['ipmi_middle_handle_no'];
    }
    return $res;
}

// 救援系统
function ipmi_rescue($params){
    global $_LANG;
	$ipmiType = $params['configoption1'];
    $serviceid = $params['serviceid'];
    $customData = ipmi_GetCustomIpmi($serviceid);
    $ipmi_id = $customData['ipmi_id'];
    if( empty($ipmi_id) ){
        $res['status'] = 'error';
        $res['msg']    = $_LANG['ipmi_admin_server_error'];
        return $res;
    }
    if('服务器租用' ==  $ipmiType || '服务器托管' == $ipmiType) {
        $postfields['id'] = $ipmi_id;
        $postfields['hostid'] = $serviceid;
        $postfields['system'] = $params['system'];
        $postfields['rescue'] = $params['rescue'];
        $res = ipmi_req('ipmiRescueSystem', $postfields, $params, 120);
        
        if ($res['status'] == "success") {
            $description = "Module {$_LANG['ipmi_admin_area_reinstall_getinfo3']} rescue Success - Service ID: {$serviceid}";
        } else {
            $description = "Module {$_LANG['ipmi_admin_area_reinstall_getinfo3']} rescue Failed - Service ID: {$serviceid} - Error: ".$res['msg'];
        }
        ipmi_addLog($description);
    }else{
        $res['status'] = 'error';
        $res['msg']    = $_LANG['ipmi_middle_handle_no'];
    }
    return $res;  
}

// 破解密码
function ipmi_crack($params){
    global $_LANG;
	$ipmiType = $params['configoption1'];
    $serviceid = $params['serviceid'];
    $customData = ipmi_GetCustomIpmi($serviceid);
    $ipmi_id = $customData['ipmi_id'];
    if( empty($ipmi_id) ){
        $res['status'] = 'error';
        $res['msg']    = $_LANG['ipmi_admin_server_error'];
        return $res;
    }
    if('服务器租用' ==  $ipmiType || '服务器托管' == $ipmiType) {
        $postfields['id'] = $ipmi_id;
        $postfields['hostid'] = $serviceid;
        $postfields['action'] = $params['action'];
        $postfields['crack_password'] = $params['password'];
        $postfields['user'] = $params['user'];
        $postfields['other_user'] = $params['other_user'];
        $res = ipmi_req('ipmiCrackPwd', $postfields, $params, 120);
        
        if ($res['status'] == "success") {
            $description = "Module {$_LANG['ipmi_admin_area_reinstall_getinfo2']} crack Success - Service ID: {$serviceid}";
        } else {
            $description = "Module {$_LANG['ipmi_admin_area_reinstall_getinfo2']} crack Failed - Service ID: {$serviceid} - Error: ".$res['msg'];
        }
        ipmi_addLog($description);
    }else{
        $res['status'] = 'error';
        $res['msg']    = $_LANG['ipmi_middle_handle_no'];
    }
    return $res;  
}

// 创建流量包订购账单
function ipmi_CreateFlowPackageInvoice($params){
    global $_LANG;
	if(!ipmi_addonFlowPacket()){
        $jsonMsg['status'] = 'error';
        $jsonMsg['msg'] = $_LANG['ipmi_action_flow_close'];
        return $jsonMsg;
    }
    $flowid = intval($_POST['flowid']);
    $res = full_query("SELECT * FROM idcsmart_flowpacket WHERE id='$flowid' AND status=1 AND FIND_IN_SET('{$params['packageid']}', allow_products)");
    $flowPacket = mysql_fetch_array($res);
    if( empty($flowPacket) ){
        $jsonMsg['status'] = 'error';
        $jsonMsg['msg'] = $_LANG['ipmi_action_flow_notfound'];
        return $jsonMsg;
    }
    $capacity = $flowPacket['capacity'];
    $price = $flowPacket['price'];

    # 生成自定义账单
    $command = 'CreateInvoice';
    $postData = array(
        'userid' => $params['userid'],
        'sendinvoice' => '1',
        'date' => date("Y-m-d"),
        'duedate' => date("Y-m-d"),
        'itemdescription1' => $_LANG['ipmi_action_flow_buy_big'] .'：' . $capacity . "Gb",
        'itemamount1' => $price,
    );
    $res = select_query("tbladmins","*",array(),"","");
    $admin_res = mysql_fetch_array($res);
    $adminUsername = $admin_res['username']; // Optional for WHMCS 7.2 and later

    $results = localAPI($command, $postData, $adminUsername);
    if( $results['result'] != "success" ) {
        $jsonMsg['status'] = 'error';
        $jsonMsg['msg'] = $_LANG['ipmi_action_check_error7'];
        return $jsonMsg;
    }
    # $results['status'] = "Paid";的情况需要测试
    $invoiceid = $results['invoiceid'];
    # 添加该记录到流量包列表
    $idata = [
        'uid' => $params['userid'],
        'fid' => $flowid,
        'serviceid' => $params['serviceid'],
        'invoiceid' => $invoiceid,
        'capacity' => $capacity,
        'price'=>$price,
        'create_time'   => date('Y-m-d H:i:s'),
    ];
    $recordid = insert_query("idcsmart_flowpacket_record", $idata);
    if( $recordid ) {
        $jsonMsg['status'] = "success";
        $jsonMsg['msg'] = $_LANG['ipmi_action_flow_bill_success'];
        $jsonMsg['url'] = "viewinvoice.php?id=" . $invoiceid;
        insert_query("idcsmart_flowpacket_log", array('serviceid'=>$params['serviceid'], "description"=>$_LANG['ipmi_action_flow_bill1']."：<a target=\"_blank\" href=\"/admin/invoices.php?action=edit&id={$invoiceid}\">{$invoiceid}</a>", "create_time"=>date('Y-m-d H:i:s')));
    }else{
        $jsonMsg['status'] = "error";
        $jsonMsg['msg'] = $_LANG['ipmi_action_flow_bill_error1']."：" . $invoiceid;
    }
    return $jsonMsg;
}

// 创建重装次数订单
function ipmi_BuyReinstallTimes($params){
    global $_LANG;
	if(!ipmi_addonFlowPacket()){
        $jsonMsg['status'] = 'error';
        $jsonMsg['msg'] = $_LANG['ipmi_action_flow_close'];
        return $jsonMsg;
    }
    $hosting = getHosting($params['serviceid']);
    // 获取配置
    $accesshash = serverAccessHash($hosting['server'], $hosting['accesshash']);
    $t2 = microtime(true);
    if($accesshash['reinstalltimes'] == 0 || $accesshash['reinstallprice'] <= 0 || $accesshash['buyreinstalltimes'] != 'on'){
        $jsonMsg['status'] = 'error';
        $jsonMsg['msg'] = $_LANG['ipmi_action_flow_buy_no'];
        return $jsonMsg;
    }
    $price = $accesshash['reinstallprice'];

    # 生成自定义账单
    $command = 'CreateInvoice';
    $postData = array(
        'userid' => $params['userid'],
        'sendinvoice' => '1',
        'date' => date("Y-m-d"),
        'duedate' => date("Y-m-d"),
        'itemdescription1' => $_LANG['ipmi_action_flow_buy_num'],
        'itemamount1' => $price,
    );
    $res = select_query("tbladmins","*",array(),"","");
    $admin_res = mysql_fetch_array($res);
    $adminUsername = $admin_res['username']; // Optional for WHMCS 7.2 and later
    $t1 = microtime(true);
    $results = localAPI($command, $postData, $adminUsername);
    $t2 = microtime(true);
    if( $results['result'] != "success" ) {
        $jsonMsg['status'] = 'error';
        $jsonMsg['msg'] = $_LANG['ipmi_action_check_error7'];
        return $jsonMsg;
    }
    # $results['status'] = "Paid";的情况需要测试
    $invoiceid = $results['invoiceid'];
    # 添加该记录到流量包列表
    $idata = [
        'uid' => $params['userid'],
        'serviceid' => $params['serviceid'],
        'invoiceid' => $invoiceid,
        'price'=>$price,
        'create_time'   => date('Y-m-d H:i:s'),
    ];
    $recordid = insert_query("idcsmart_flowpacket_reinstalltimes_record", $idata);
    if( $recordid ) {
        $jsonMsg['status'] = "success";
        $jsonMsg['msg'] = $_LANG['ipmi_action_flow_bill_success'];
        $jsonMsg['url'] = "viewinvoice.php?id=" . $invoiceid;
        $jsonMsg['t'] = $t2 - $t1;
        insert_query("idcsmart_flowpacket_log", array('serviceid'=>$params['serviceid'], "description"=>$_LANG['ipmi_action_flow_bill2']."：<a target=\"_blank\" href=\"/admin/invoices.php?action=edit&id={$invoiceid}\">{$invoiceid}</a>", "create_time"=>date('Y-m-d H:i:s')));
    }else{
        $jsonMsg['status'] = "error";
        $jsonMsg['msg'] = $_LANG['ipmi_action_flow_bill_error2']."：" . $invoiceid;
    }
    return $jsonMsg;
}
// 获取本周购买重装次数
function ipmi_buyTimes($serviceid){
    if(!ipmi_addonFlowPacket()){
        return 0;
    }
    $uid = $_SESSION['uid'];
    // 获取本周开始时间
    $start = date('Y-m-d 00:00:00',strtotime('this week Monday',time()));
    $end = date('Y-m-d 23:59:59',strtotime('this week Sunday',time()));
    $r = mysql_fetch_assoc(full_query("SELECT count(*) AS sum FROM `idcsmart_flowpacket_reinstalltimes_record` WHERE serviceid='{$serviceid}' AND uid='{$uid}' AND status=1 AND pay_time>='{$start}' AND pay_time<='{$end}'"));
    if(!empty($r)){
        return $r['sum'];
    }else{
        return 0;
    }
}

function ipmi_getMirrorScripts($params){
    $res = [
        'status' => 'success',
        'data'   => [],
    ];

    global $_LANG;
    $ipmiType = $params['configoption1'];
    $serviceid = $params['serviceid'];
    $customData = ipmi_GetCustomIpmi($serviceid);
    $ipmi_id = $customData['ipmi_id'];
    if( empty($ipmi_id) ){
        return $res;
    }
    if('服务器租用' ==  $ipmiType || '服务器托管' == $ipmiType) {
        $postfields['id'] = $ipmi_id;
        $postfields['mos'] = $params['mos'];
        
        $data = ipmi_req('getMirrorScripts', $postfields, $params, 120);
        if(!empty($data)){
            $res['data']   = $data;
        }
    }
    return $res;  
}
