<?php
use WHMCS\Database\Capsule;
// 2020-06-30 添加前台操作日志
function ipmi_addLog($description = ''){
    if(empty($description)){
        return false;
    }
    global $remote_ip;
    $uid = $_SESSION['uid'];
    $adminid = $_SESSION['adminid'];

    if(!empty($adminid)){
        $user_info = mysql_fetch_array(select_query("tbladmins", "username", ["id" =>$adminid]));
        $id = (int)$adminid;
        $name = $user_info['username'];
    }else if(!empty($uid)){
        $user_info = mysql_fetch_array(select_query("tblclients", "firstname,lastname,phonenumber,email", ["id" =>$uid]));
        $id = (int)$uid;
        $name = ($user_info['firstname'].$user_info['lastname'] ?: $user_info['phonenumber']) ?: $user_info['email'];
    }else{
        return false;
    }
    $data = [
        'date'=>"now()",
        'description'=>$description,
        'user'=>$name,
        'userid'=>$id,
        'ipaddr'=>$remote_ip
    ];
    insert_query("tblactivitylog", $data);
}
# 获取模块配置
function ipmi_GetConfig(){
    $config = require(IPMI_FILE . 'config.php');
    return $config;
}
//购买主机日期计算
function ipmi_regdate($regdate){
    $regdate = strtotime($regdate);
    $reg_d = date("d", $regdate);
    $firstDate = date("Y-m-01", $regdate);
    $latDate = date("d", strtotime("$firstDate +1 month -1 day"));
    $d = date("d");
    $date = ($reg_d > $d) ? date("Y-m-$reg_d", strtotime("-1 month")) : date("Y-m-$reg_d");
    $startDate = ($reg_d == $latDate) ? date("Y-m-01") : $date;
    $endDate = date("Y-m-d");
    return array("startDate" => $startDate, "endDate" => $endDate);
}
# 1.是否为调试模式
# 2.后台默认显示错误信息
function ipmi_IsDebug(){
    $CONFIG = ipmi_GetConfig();
    $isAdmin = $_SESSION['adminid'];
    if($CONFIG['is_debug'] || $isAdmin){
        return true;
    }
    return false;
}

#　获取该服务器 mod_custom_ipmi 表中数据，没有则创建一基础数据
function ipmi_GetCustomIpmi($serviceid){
    if ( empty($serviceid) ) return false;
    $adminUsersql = select_query("tbladmins", "", array("id" => $_SESSION['adminid']));
    $adminUser = mysql_fetch_array($adminUsersql);
    $custom_ipmi = select_query("mod_custom_ipmi", "", array("serviceid" => $serviceid));
    $data = mysql_fetch_array($custom_ipmi);
    if( !empty($data) ){
        $data['admin'] = $adminUser['username'];
        return $data;
    }
    insert_query("mod_custom_ipmi", array("serviceid" => $serviceid));
    $custom_ipmi = select_query("mod_custom_ipmi", "", array("serviceid" => $serviceid));
    $data = mysql_fetch_array($custom_ipmi);
    $data['admin'] = $adminUser['username'];
    return $data;
}

function getHosting($serviceid){
    $sql = "select p.configoption1,p.configoption2,h.packageid,h.userid,h.dedicatedip,h.assignedips,h.regdate,h.domainstatus,h.username AS operate_user,h.password AS operate_password,h.regdate,h.nextduedate,h.server,h.bwusage,h.bwlimit,c.email,c.phonenumber,s.type,s.accesshash,s.secure,s.port AS serverport,s.hostname,s.ipaddress,s.username,s.password  
    from tblhosting AS h 
    left join tblproducts AS p ON p.id=h.packageid 
    left join tblclients AS c ON c.id=h.userid 
    left join tblservers AS s ON s.id=h.server 
    WHERE h.id='{$serviceid}'";
    $tblhosting = full_query($sql);
    $hosting = mysql_fetch_assoc($tblhosting);
    return $hosting;
}
// 获取用户自定义字段ID,如果没有便创建
function impi_GetIpmiCustomNameId($relid, $fieldname, $type='product'){
    global $_LANG;
	$sql = "SELECT v.* FROM tblcustomfields AS f
        LEFT JOIN tblcustomfieldsvalues AS v ON f.id=v.fieldid 
        WHERE f.fieldname='$fieldname' AND f.type='$type' AND v.relid='$relid' ";
    $customData = publicFunc::pdo_query($sql)[0];
    $id = $customData['id'];
    if(empty($customData)){
        #获取产品ID
        $productid = publicFunc::pdo_select("tblhosting", "","id='$relid'")['packageid'];
        if(empty($productid)){
            throw new Exception($_LANG['ipmi_middle_product_no'], 1);
        }
        $customId = publicFunc::pdo_select("tblcustomfields","","fieldname='$fieldname' AND relid='$productid'")['id'];
        if(empty($customId)){
            throw new Exception($_LANG['ipmi_middle_custom_no'], 1);
        }
        $id = publicFunc::pdo_insert("tblcustomfieldsvalues",array("fieldid"=>$customId, "relid"=>$relid));
    }
    return $id;
}


//处理hash数据
function serverAccessHash($serverid, $serveraccesshash)
{
    // 启用了流量包插件
    if(ipmi_addonFlowPacket()){
        $res = mysql_fetch_assoc(full_query("SELECT * FROM idcsmart_flowpacket_config WHERE name='server_{$serverid}'"));
        $array = json_decode($res['value'], true) ?: [];
    }else{
        $xmlstring = "<xml>".htmlspecialchars_decode($serveraccesshash)."</xml>";
        $array = json_decode(json_encode((array)simplexml_load_string($xmlstring, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        $array['sms_check'] = explode(',', $array['sms_check']);
    }
    $array['reinstalladmin'] = $array['reinstalladmin'] ?: 'on';
    $array['resetbmcadmin'] = $array['resetbmcadmin'] ?: 'on';
    $array['changemainip'] = $array['changemainip'] ?: 'on';
    $array['changeassignip'] = $array['changeassignip'] ?: 'on';
    $array['reinstalltimes'] = $array['reinstalltimes'] ? floor($array['reinstalltimes']) : 0;
    $array['buyreinstalltimes'] = $array['buyreinstalltimes'] ?: 'off';
    $array['reinstallprice'] = $array['reinstallprice'] ?: 0;
    return $array;       
}

// 转换流量
function dataUnitConversion($data=''){
    if($data>1024){
        $data=bcdiv($data,'1024',2);
        $data.='GB';
    }else{
        $data=bcdiv($data,'1',2).'MB';
    }
    return $data;
}

function ipmi_ipnum($ip_num = ''){
    if(strpos($ip_num, ',') !== false){
        $arr = explode(',', $ip_num);
        $res = [];
        foreach($arr as $v){
            $r = ipmi_ipnum($v);
            if($r === false){
                return false;
            }
            foreach($r as $kk=>$vv){
                $res[$kk] = $vv;
            }
        }
    }else if(strpos($ip_num, '_') !== false){
        $arr = explode('_', $ip_num);
        if(count($arr) != 2 || !is_numeric($arr[0]) || !is_numeric($arr[1])){
            return false;
        }
        return [$arr[1]=>$arr[0]];
    }else{
        $res = false;
    }
    return $res;
}

function ipmi_checkSms(){
    $message = mysql_fetch_assoc(full_query("SELECT * FROM tbladdonmodules WHERE setting='access' AND module='idcsmart_message'"));
    if(empty($message)){  //不需要验证
        return true;
    }
    //判断是否验证过
    $time = time();
    $ipmiSmsTime = $_SESSION['ipmiSmsTime'] ? : 0;
    if($time - $ipmiSmsTime < 3600 ) {
        return true;
    }
    return false;
}
// 优化获取多个数据
function ipmi_get_adminAreaData($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) {
        $host = $params['serverhostname'] ? $params['serverhostname'] : $params['serverip'];
        if(empty($host)){
            $res['ipmiPowerSync']['status'] = 'error';
            $res['ipmiPowerSync']['msg'] = $_LANG['ipmi_middle_power_no'];

            $res['reinstallStatus']['status'] = 'error';
            $res['reinstallStatus']['msg'] = $_LANG['ipmi_middle_handle_no'];

            $res['detail'] = [];
            return $res;
        }
        $postfields['username'] = $params['serverusername'];
        $postfields['password'] = $params['serverpassword'];
        $usessl = $params['serversecure'];
        $serverport = $params['serverport'];
        if ($usessl) {
            $urldomain = "https://".$host;
        }else {
            $urldomain = "http://".$host;
        }
        if(!empty($serverport)){
            $urldomain .= ":".$serverport;
        }
        $url = $urldomain.'/index.php?m=api&a=';
        $data['ipmiPowerSync']['url'] = $url.'ipmiPowerSync';
        $data['ipmiPowerSync']['data'] = $postfields;
        $data['ipmiPowerSync']['data']['id'] = $ipmi_id;

        $data['reinstallStatus']['url'] = $url.'getReinstallStatus';
        $data['reinstallStatus']['data'] = $postfields;
        $data['reinstallStatus']['data']['id'] = $ipmi_id;

        $data['detail']['url'] = $url.'serverDetailed';
        $data['detail']['data'] = $postfields;
        $data['detail']['data']['id'] = $ipmi_id;

        // 获取使用流量
        $data['traffic']['url'] = $url.'serverDetailflowData';
        $data['traffic']['data'] = $postfields;
        $data['traffic']['data']['id'] = $ipmi_id;
        $data['traffic']['data']['unit'] = 'GB';
        
        $responses = ipmi_batch_curl_post($data, 120, ipmi_IsDebug());
        
        //电源结果
        if ($responses['ipmiPowerSync']['msg'] == 'on'){
            $msg = $_LANG['ipmi_client_on'] ;
        } else if ($responses['ipmiPowerSync']['msg'] == 'off'){
            $msg = $_LANG['ipmi_client_off'];
        }else if ($responses['ipmiPowerSync']['msg'] == 'error'){
            $msg = $_LANG['ipmi_middle_error'];
        }else if ($responses['ipmiPowerSync']['msg'] == 'nonsupport'){
            $responses['ipmiPowerSync']['msg'] = $_LANG['ipmi_middle_power_no'];
        } 
        if ($responses['ipmiPowerSync']['status'] == 'success') {
            $res['ipmiPowerSync']['status'] = 'success';
            $res['ipmiPowerSync']['power'] = $responses['ipmiPowerSync']['msg'];
            $res['ipmiPowerSync']['msg'] = $msg;
        }else{
            $res['ipmiPowerSync']['status'] = 'error';
            $res['ipmiPowerSync']['msg'] = empty($responses['ipmiPowerSync']['msg']) ? $responses['ipmiPowerSync']['power_msg'] : $responses['ipmiPowerSync']['msg'];
        } 
        // 重装状态
        $res['reinstallStatus'] = $responses['reinstallStatus'];
        // 详情
        $res['detail'] = $responses['detail'];
        // 用量
        $res['traffic'] = $responses['traffic'];
    }else{
        $res['ipmiPowerSync']['status'] = 'error';
        $res['ipmiPowerSync']['msg'] = $_LANG['ipmi_middle_power_no'];

        $res['reinstallStatus']['status'] = 'error';
        $res['reinstallStatus']['msg'] = $_LANG['ipmi_middle_handle_no'];

        $res['detail'] = [];

        $res['traffic'] = [];
    }
    return $res;
}

// 是否启用了流量包插件
function ipmi_addonFlowPacket(){
    $activemodules = mysql_fetch_assoc(full_query("SELECT * FROM tblconfiguration WHERE setting='ActiveAddonModules'"));
    $activemodules = explode(',', $activemodules['value']);
    return in_array('idcsmart_flowpacket', $activemodules);
}

// 是否显示用量图
function ipmi_showTrafficUsage(){
    if(!ipmi_addonFlowPacket()){
        return false;
    }
    $res = mysql_fetch_assoc(full_query("SELECT * FROM idcsmart_flowpacket_config WHERE name='show_daily_chart'"));
    return $res['value'] == 1;
}
// 获取当前产品能使用的流量包
function ipmi_GetFlowPack($params) {
    if(!ipmi_addonFlowPacket()){
        return [];
    }
    // 查找当前符合该产品的流量包产品
    $serviceid = $params['serviceid'];
    $pid = $params['packageid'];
    $sql = "SELECT * FROM idcsmart_flowpacket WHERE status=1 AND FIND_IN_SET('$pid', allow_products)";
    $res = full_query($sql);
    while( $row = mysql_fetch_assoc($res) ){
        $flowpacket[] = $row;
    }
    return $flowpacket;
}
// 获取本周期订购的流量包数据, 和使用情况
function ipmi_getTrafficUsageTable($serviceid, $uid, $arr){
    if(!ipmi_addonFlowPacket()){
        return [];
    }
    $bill_type = mysql_fetch_assoc(full_query("SELECT * FROM idcsmart_flowpacket_config WHERE name='bill_type'"));
    $bill_type = $bill_type['value'] ?: 'month';
    // 获取购买记录使用区间
    if($bill_type == 'month'){
        $start_date = date('Y-m-01 00:00:00');
    }else{
        // 获取开通日期
        $hosting = mysql_fetch_assoc(full_query("SELECT id,regdate FROM tblhosting WHERE id='{$serverid}'"));
        $start_time = (int)strtotime($hosting['regdate'].' 00:00:00');
        $now = time();
        $diff = floor(($now - $start_time)/(30*24*3600));
        $start_time = $start_time + $diff*30*24*3600;
        $start_date = date('Y-m-d 00:00:00', $start_time);
    }
    $res = full_query("SELECT * FROM `idcsmart_flowpacket_record` WHERE serviceid='{$serviceid}' AND uid='{$uid}' AND status=1 AND show_status=0 AND pay_time>'{$start_date}' ORDER BY pay_time ASC");
    $data = [];
    $limit = $arr['limit']; //限额,不包含临时
    $used = str_replace('GB', '', $arr['data'][$bill_type][$arr['type']]);
    $over = $used - $limit;  //超出流量 
    while(($r = mysql_fetch_assoc($res)) != false){
        $r['usage'] = 0;
        if($limit>0 && $over >= 0){
            $over = $over - $r['capacity'];
            if($over>=0){
                $r['usage'] = $r['capacity'];
            }else{
                $r['usage'] = $over + $r['capacity'];
            }
        }
        $data[] = $r;
    }
    return $data;
}
// 下载文件
function ipmi_Download($filename, $showname = '', $expire = 1800){
    global $_LANG;
	$filename = str_replace('/', '', $filename);
    $filename = IPMI_FILE.'download/'.$filename;  //文件目录 
    if(file_exists($filename) && is_file($filename)) {
        $length = filesize($filename);
    }else {
        die($_LANG['ipmi_middle_down_notfound']);
    }
    header("Pragma: public");
    header("Cache-control: max-age=".$expire);
    //header('Cache-Control: no-store, no-cache, must-revalidate');
    header("Expires: " . gmdate("D, d M Y H:i:s",time()+$expire) . "GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s",time()) . "GMT");
    header("Content-Disposition: attachment; filename=".$showname);
    header("Content-Length: ".$length);
    header("Content-type: text/x-java-source");
    header('Content-Encoding: none');
    header("Content-Transfer-Encoding: binary");
    readfile($filename);
    sleep(2);
    unlink($filename);
    return true;
}
//加载语言文件
function ipmi_lang(){
	global $_LANG,$CONFIG;	
	$langDir=IPMI_FILE. 'lang/';
	$langFile = glob ($langDir. '*.php');
	if(strpos($_SERVER['REQUEST_URI'],"clientarea.php")!==false || strpos($_SERVER['REQUEST_URI'],"cart.php")!==false){
		$uid=$_SESSION['uid'];
		if($uid>0){
			$tblclients = Capsule::table('tblclients')
					->where('id', '=', $uid)
					->get(['language']);
			$language =$tblclients[0]->language;	
		}else{	
			$language =(isset($_SESSION['Language']))? $_SESSION['Language']:$CONFIG['Language'];
		}
	}else{
		$adminid=$_SESSION['adminid'];
		$tbladmins = Capsule::table('tbladmins')
    			->where('id', '=', $adminid)
    			->get(['language']);
		$language =$tbladmins[0]->language;	
	}	
	$language = strtolower( $language ) . '.php';
	if ( ! in_array( $langDir.$language, $langFile ) ) {
		$language = 'chinese.php';
	}

	require_once( $langDir . $language );
}
//语言参数替换
function ipmi_langReplace($str='',$arr=array()){
	foreach($arr as $k=>$v){
		$str=str_replace($k, $v, $str);
	}
	return $str;	
}

// 保存远程端口到自定义字段
function ipmi_SetRemotePort($params, $port = 0){
    if(empty($params['packageid']) || empty($params['serviceid']) || empty($port)){
        return false;
    }
    $id = Capsule::table('tblcustomfields')
                    ->where('type', '=', 'product')
                    ->where('relid', '=', $params['packageid'])
                    ->where('fieldname', '=', 'remote_port')
                    ->value('id');
    if(empty($id)){
        // 自动创建
        $insert = [
            'type'=>'product',
            'relid'=>$params['packageid'],
            'fieldname'=>'remote_port',
            'fieldtype'=>'text',
            'adminonly'=>'on'
        ];
        $id = Capsule::table('tblcustomfields')->insertGetId($insert);
    }
    if(!empty($id)){
        $value = Capsule::table('tblcustomfieldsvalues')
                ->where('fieldid', $id)
                ->where('relid', $params['serviceid'])
                ->first();
        if(empty($value)){
            $insert = [
                'fieldid'=>$id,
                'relid'=>$params['serviceid'],
                'value'=>$port,
                'created_at'=>date('Y-m-d H:i:s')
            ];
            $res = Capsule::table('tblcustomfieldsvalues')->insertGetId($insert);
        }else{
            $res = Capsule::table('tblcustomfieldsvalues')->where('id', $value->id)->update(['value'=>$port]);
        }
    }else{
        $res = false;
    }
    return $res;
}
