<?php 
use WHMCS\Database\Capsule;

if (!defined("WHMCS")) {
    exit("This file cannot be accessed directly");
}
//ini_set('display_errors','On');
define('IPMI_FILE', ROOTDIR . '/modules/servers/ipmi/');

include "ipmi/loginCurl.php";
include "ipmi/adminArea.php";
include "ipmi/publicFunction.php";
include "ipmi/systemFunction.php";
include "ipmi/actionFunction.php";
include "ipmi/clientArea.php";

ipmi_lang();//语言文件
// 元数据
function ipmi_MetaData(){
    return ["DisplayName" => "ipmi", "APIVersion" => "2.0.1", "DefaultNonSSLPort" => "80", "DefaultSSLPort" => "443"];
}

// 初始化配置
function ipmi_ConfigOptions(){
    $sql = "CREATE TABLE IF NOT EXISTS `mod_custom_ipmi` (
        `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
        `serviceid` int(10) unsigned NOT NULL,
        `ipmi_id` int(10) NOT NULL,
        `value` text NOT NULL,
        `value2` text NOT NULL,
        `value3` varchar(255) NULL,
        PRIMARY KEY (`id`),
        KEY `serviceid` (`serviceid`)
	) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8";
    full_query($sql);

    // 添加字段 value3   v1.0 - v2.0.1
    $alterSql = "select count(*) as count from information_schema.columns where table_name = 'mod_custom_ipmi' and column_name = 'value3'";
    $res = full_query($alterSql);
    $isExisten = mysql_fetch_array($res);
    if(empty($isExisten['count'])){
        full_query("ALTER TABLE `mod_custom_ipmi` ADD COLUMN `value3` varchar(255) NULL AFTER `value2`");
    }

    $configarray = array(
        '类型' => array('Type' => 'dropdown', 'Options' => '服务器租用,服务器托管,机柜租用')
    );
    return $configarray;
}

// 管理区输出自定义按钮
function ipmi_AdminCustomButtonArray($params) {
	global $_LANG;
    if(empty($params)){
        $params['serviceid'] = $_GET['id'];
    }
    $serviceid = $params['serviceid'];
    $customData = ipmi_GetCustomIpmi($serviceid);
    $ipmi_id = $customData['ipmi_id'];
    $hosting = getHosting($serviceid);
    $ipmiType = $hosting['configoption1'];
    if(empty($ipmi_id))
        return [];
    if('服务器租用' != $ipmiType)
        return [$_LANG['ipmi_client_sync'] => 'Sync'];
    $accesshash = serverAccessHash($hosting['server'], $hosting['accesshash']);
    $buttonarray = [];
    // 开机
    if ($accesshash['onadmin'] == 'on') {
        $buttonarray[$_LANG['ipmi_client_on']] = 'On';
    }
    //关机
    if ($accesshash['offadmin'] == 'on') {
        $buttonarray[$_LANG['ipmi_client_off']] = 'Off';
    }
    //重启
    if ($accesshash['rebootadmin'] == 'on') {
        $buttonarray[$_LANG['ipmi_client_reboot']] = 'Reboot';
    }
    $buttonarray[$_LANG['ipmi_client_sync']] = 'Sync';
    //重置BMC
    if ($accesshash['resetbmcadmin'] == 'on' || empty($accesshash['resetbmcadmin'])) {
        $buttonarray[$_LANG['ipmi_client_resetbmc']] = 'ResetBmc';
    }
    //kvm
    if ($accesshash['kvmadmin'] == "on") {
        $buttonarray['KVM'] = '';
    }
    //ikvm
    if ($accesshash['ikvmadmin'] == 'on') {
        $buttonarray['IKVM'] = "";
    }
    //vnc
    if ($accesshash['vncadmin'] == 'on') {
        $buttonarray['VNC'] = '';
    }
    //重装系统
    if ($accesshash['reinstalladmin'] != 'off') {
        $buttonarray['Reinstall'] = '';
    }
    //救援系统
    if($accesshash['rescueadmin'] == 'on'){
        $buttonarray['Rescue'] = '';
    }
    //破解密码
    if($accesshash['crackadmin'] == 'on'){
        $buttonarray['Crack'] = '';
    }
    if($accesshash['idcimadmin'] == 'on'){
        $buttonarray['Idcim'] = '';
    }
    return $buttonarray;
}

// 管理区信息输出
function ipmi_AdminServicesTabFields($params) {
	return ipmi_admin_area($params);
}

// 客户区输出
function ipmi_ClientArea($params){
	return ipmi_client_area($params);
}

// 管理区自定义信息保存
function ipmi_AdminServicesTabFieldsSave($params) {
    update_query('mod_custom_ipmi', array(
        'ipmi_id' => $_POST['ipmi_id'],
        'value3' => $_POST['ipmi_panel_pass'] ?: '',
    ), array("serviceid" => $params['serviceid']));
}

// 开通
function ipmi_CreateAccount($params){
	return ipmi_create($params);
}

// 暂停
function ipmi_SuspendAccount($params){
	return ipmi_suspend($params);
}

// 解除暂停
function ipmi_UnsuspendAccount($params){
	return ipmi_unsuspend($params);
}

// 删除
function ipmi_TerminateAccount($params){
   return ipmi_terminate($params);
}

// 直接获取端口
function ipmi_Detail($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'];
    }
    if('机柜租用' ==  $ipmiType) {
        return $_LANG['ipmi_admin_cabinet_error'] ;
    }
    $postfields['id'] = $ipmi_id;
    # 调用api
    $result = ipmi_req('serverDetailed', $postfields, $params, 60);
    return $result;
}
// 获取流量
function ipmi_serverFlow($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['type'] = 'custom';
        $res = ipmi_req('serverFlow&start='.$params['startDate'], $postfields, $params, 120);
    }else{
        $res['status'] = 'error';
        $res['msg']    = $_LANG['ipmi_middle_handle_no'];
    }
    return $res;
}

// 获取操作系统
function ipmi_os($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;
    } 
    $sql = "SELECT a.id,a.packageid,c.gid,c.id AS groupid FROM tblhosting AS a LEFT JOIN tblproductconfiglinks AS b ON a.packageid=b.pid LEFT JOIN tblproductconfigoptions AS c ON b.gid=c.gid WHERE c.optionname LIKE 'os|%' AND a.id='{$serviceid}'";
    $tblhosting = full_query($sql);
    $hosting = mysql_fetch_assoc($tblhosting);
    $gid = $hosting['groupid'];
    $sql = "SELECT * FROM tblproductconfigoptionssub WHERE configid='{$gid}' ORDER BY sortorder ASC";
    $sql_result = full_query($sql);
    $res = [];
    while ($value = mysql_fetch_assoc($sql_result)) {
        $temp = explode('|', $value['optionname']);
        $res[] = [
            'id'=>$temp[0],
            'name'=>$temp[1]
        ];
    }
    $postfields['id'] = $ipmi_id;
    $result = ipmi_req("getMirrorOsConfig", $postfields, $params);
    if (!empty($res)) {
        $result['os'] = $res;
    }
    return $result;
}

// 流量图页面
function ipmi_Traffic($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;
    }
    $postfields['id'] = $ipmi_id;
    $web_root = DI::make("asset")->getWebRoot();
    if('服务器租用' ==  $ipmiType || '服务器托管' == $ipmiType) {
        $result = ipmi_req('serverDetailed', $postfields, $params, 30);
        if($result['status'] == 'success'){
            $real_server_type = $result['server']['stype'];
            $switch = $result['switch'];
            $server = $result['server'];
            require_once IPMI_FILE.'templates/traffic.php';
        }
    }else{
        $result = ipmi_req('ipmiCabinetRentDetailed', $postfields, $params, 30);
        if($result['status'] == 'success'){
            $real_server_type = 6;
            $switch = $result['link_switch'];
            $server = $result['server'];
            require_once IPMI_FILE.'templates/traffic.php';
        }
    }
    exit;
}   

// 获取单个端口的流量图数据
function ipmi_getTraffic($params){
    $postfields['switch_id'] = $params['switch_id']; 
    $postfields['port_name'] = $params['port_name']; 
    $postfields['start_time'] = $params['start']; 
    $postfields['end_time'] = $params['end']; 
    $postfields['type'] = $params['type']; 
    $postfields['reverse'] = $params['reverse'];
    $res = ipmi_req('traffic', $postfields, $params, 30);
    echo json_encode($res);exit;
}



//更新流量
function ipmi_UsageUpdate($params){
    $serverid = $params['serverid'];
    $server_info = mysql_fetch_assoc(full_query("SELECT s.secure,s.port AS serverport,s.hostname,s.ipaddress,s.username,s.password FROM tblservers AS s WHERE s.id='{$serverid}'"));
    $tblhosting = full_query("SELECT a.id AS serviceid,a.regdate,b.configoption1 FROM tblhosting AS a LEFT JOIN tblproducts AS b ON a.packageid=b.id WHERE a.server='{$serverid}'");
    $limit = 1024*1024;
    $month_start = date('Y-m-01');

    $param['serverhostname'] = $server_info['hostname'];
    $param['serverip'] = $server_info['ipaddress'];
    $param['serverusername'] = $server_info['username'];
    $param['serverpassword'] = decrypt($server_info['password']);
    $param['serversecure'] = $server_info['secure'];
    $param['serverport'] = $server_info['serverport'];
    while(($host = mysql_fetch_assoc($tblhosting)) != false){
        $param['configoption1'] = $host['configoption1'];
        $param['serviceid'] = $host['serviceid'];
        // 直接同步
        ipmi_Sync($param);
    }
}

// 获取用量信息
function ipmi_trafficUsage($params){
	global $_LANG;
    if(!ipmi_showTrafficUsage()){
        $result['status'] = 'error';
        $result['msg'] = $_LANG['ipmi_admin_jurisdiction_error'];
        return $result;
    }
    $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['start'] = $params['start'];
        $postfields['end'] = $params['end'];
        $result = ipmi_req('trafficUsage', $postfields, $params, 120);
        if($result['status'] == 'success'){
            $x = array_keys($result['data']);
            $data = [];
            foreach($x as $v){
                $data[] = $result['data'][$v][$result['direction']];
            }
            $res['status'] = 'success';
            $res['x'] = $x;
            $res['data'] = $data;
        }else{
            $res = $result;
        }
    }else{
        $res['status'] = 'error';
        $res['msg']    = $_LANG['ipmi_middle_handle_no'] ;
    }
    return $res;
}


// 前台允许的操作
function ipmi_ClientAreaAllowedFunctions($params){
    global $_LANG;
	$method = $_POST['method'];
    if(isset($method)){
        switch($method){
            case 'buyFlowPacket':
                $result = ipmi_CreateFlowPackageInvoice($params);
                break;
            case 'buyReinstallTimes':
                $result = ipmi_BuyReinstallTimes($params);
                break;
            case 'on':
                $res = ipmi_On($params);
                if($res == 'success'){
                    $result['status'] = 'success';
                    $result['msg'] = $_LANG['ipmi_hooks_powerup_success'] ;
                }else{
                    $result['status'] = 'error';
                    $result['msg'] = $res ?: $_LANG['ipmi_hooks_powerup_error'];
                }
                break;
            case 'off':
                $res = ipmi_Off($params);
                if($res == 'success'){
                    $result['status'] = 'success';
                    $result['msg'] = $_LANG['ipmi_hooks_powerdown_success'];
                }else{
                    $result['status'] = 'error';
                    $result['msg'] = $res ?: $_LANG['ipmi_hooks_powerdown_error'] ;
                }
                break;
            case 'reboot':
                $res = ipmi_Reboot($params);
                if($res == 'success'){
                    $result['status'] = 'success';
                    $result['msg'] = $_LANG['ipmi_hooks_reboot_success'];
                }else{
                    $result['status'] = 'error';
                    $result['msg'] = $res ?: $_LANG['ipmi_hooks_reboot_error'];
                }
                break;
            case 'bmc':
                $res = ipmi_ResetBmc($params);
                if($res == 'success'){
                    $result['status'] = 'success';
                    $result['msg'] = $_LANG['ipmi_hooks_bmc_success'];
                }else{
                    $result['status'] = 'error';
                    $result['msg'] = $res ?: $_LANG['ipmi_hooks_bmc_error'];
                }
                break;
            case 'getMirrorScripts':
                $params['mos'] = $_POST['mos'];
                $result = ipmi_getMirrorScripts($params);
                break;
            default:
                $result['status'] = 'error';
                $result['msg'] = $_LANG['ipmi_error'];
                break;
        }
        echo json_encode($result);exit;
    }
}


// 供上下游请求
function ipmi_CustomFunctions($params){
    global $_LANG;
    $method = $_POST['method'];
    if(isset($method)){
        switch($method){
            case 'buyFlowPacket':
                $result = ipmi_CreateFlowPackageInvoice($params);
                break;
            case 'buyReinstallTimes':
                $result = ipmi_BuyReinstallTimes($params);
                break;
            case 'status':
                $result = ipmi_GetPowerStatus($params);
                break;
            case 'reinstall':
                $params = array_merge($params, $_POST);
                $result = ipmi_reinstall($params);
                break;
            case 'reinstallStatus':
                $result = ipmi_reinstallStatus($params);
                break;
            case 'cancellReinstall':
                $result = ipmi_cancellReinstall($params);
                break;
            case 'unsuspendReload':
                $result = ipmi_unsuspendReload($params);
                break;
            case 'rescue':
                $result = ipmi_rescue($params);
                break;
            case 'crack':
                $result = ipmi_crack($params);
                break;
            case 'trafficUsage':
                $result = ipmi_trafficUsage($params);
                break;
            case 'getTraffic':
                $customData = ipmi_GetCustomIpmi($params['serviceid']);
                $params['switch_id'] = $customData['ipmi_id'];
                $params['type'] = 'server';
                $result = ipmi_getTraffic($params);
                break;
            case 'os':
                $result = ipmi_os($params);
                if(!isset($result['status'])){
                    $result['status'] = 'success';
                }
                break;
            case 'serverFlow':
                $result = ipmi_serverFlow($params);
                break;
            case 'detail':
                $result = ipmi_Detail($params);
                if($result['status']=='success'){
                    $customData = ipmi_GetCustomIpmi($params['serviceid']);
                    $ipmi_panel_pass = $customData['value3'];
                    $result['server'] = [
                        'id' => $result['server']['id'],
                        'wltag' => $result['server']['wltag'],
                        'osname' => $result['server']['osname'],
                        'power' => $result['server']['power'],
                        'power_msg' => $result['server']['power_msg'],
                        'osusername' => $result['server']['osusername'],
                        'ospassword' => $result['server']['ospassword'],
                        'crack_success_info' => $result['server']['crack_success_info'],
                        'crack_user' => $result['server']['crack_user'],
                        'default_user' => $result['server']['default_user'],
                        'ippassword' => $ipmi_panel_pass,
                        'port' => $result['server']['port'],
                        'main_ip' => $result['server']['zhuip'],
                        'configoptionsupgrade' => $params['model']['product']['configoptionsupgrade'],
                    ];
                    foreach ($result['switch'] as $key => $value) {
                        unset($result['switch'][$key]['port_info']);
                    }
                    unset($result['cabinetRent'], $result['intranet'], $result['system_custom_fields']);
                    $result['configoptions'] = [];
                    $pid = $params['pid'];
                    $pdo = Capsule::connection()->getPdo();
                    $sql="select ops.id,ops.optionname from tblhosting as h
                        left Join tblproductconfiglinks as link on link.pid=h.packageid
                        left Join tblproductconfigoptions as ops on ops.gid=link.gid
                        where h.id={$params['serviceid']}
                        ";
                    $optionname = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
                    $optionname_array = [];
                    foreach($optionname as $v){
                        $opname=explode("|",$v['optionname']);
                        $optionname_array[$v['id']]=$opname;
                    }
                    $sql="select sub.configid,sub.optionname,ops.optiontype from tblhosting as h
                        left Join tblproductconfiglinks as link on link.pid=h.packageid
                        left Join tblproductconfigoptions as ops on ops.gid=link.gid
                        left Join tblproductconfigoptionssub as sub on ops.id=sub.configid
                        where h.id={$params['serviceid']}
                        ";
                    $suboptionname = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
                    foreach ($suboptionname as $v){
                        $subopname=explode("|",$v['optionname']);
                        $opname = $optionname_array[$v['configid']];
                        if($v['optiontype']==4){
                            $result['configoptions'][$opname[0]] = ['name' => $opname[1], 'value' => $params['configoptions'][$opname[0]]];
                        }else{
                           if(isset($params['configoptions'][$opname[0]]) && $subopname[0]==$params['configoptions'][$opname[0]]){
                                $result['configoptions'][$opname[0]] = ['name' => $opname[1], 'value' => $subopname[1]];
                            } 
                        }
                    }
                    $sql="select fieldname from tblcustomfields where type='product' AND relid={$params['pid']} AND adminonly!='on'";
                    $customfields = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
                    $customfields = array_column($customfields, 'fieldname');
                    foreach ($params['customfields'] as $key => $value) {
                        if(!in_array($key, $customfields)){
                            unset($params['customfields'][$key]);
                        }
                    }
                    $result['customfields'] = $params['customfields'];

                    $sql="SELECT a.configid,a.optionid,a.qty,b.optiontype FROM tblhostingconfigoptions a LEFT JOIN tblproductconfigoptions b on a.configid=b.id WHERE a.relid = {$params['serviceid']}";
                    $hostconfigoptions = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
                    $oldconfigoptions = [];
                    foreach ($hostconfigoptions as $key => $value) {
                        if(in_array($value['optiontype'], ['1', '2'])){
                            $oldconfigoptions[$value['configid']] = $value['optionid'];
                        }else{
                            $oldconfigoptions[$value['configid']] = $value['qty'];
                        }
                    }
                    $result['oldconfigoptions'] = $oldconfigoptions;
                }
                break;
            case 'vnc':
                $result = ipmi_vnc($params);
                break;
            case 'on':
                $res = ipmi_On($params);
                if($res == 'success'){
                    $result['status'] = 'success';
                    $result['msg'] = $_LANG['ipmi_hooks_powerup_success'] ;
                }else{
                    $result['status'] = 'error';
                    $result['msg'] = $res ?: $_LANG['ipmi_hooks_powerup_error'];
                }
                break;
            case 'off':
                $res = ipmi_Off($params);
                if($res == 'success'){
                    $result['status'] = 'success';
                    $result['msg'] = $_LANG['ipmi_hooks_powerdown_success'];
                }else{
                    $result['status'] = 'error';
                    $result['msg'] = $res ?: $_LANG['ipmi_hooks_powerdown_error'] ;
                }
                break;
            case 'reboot':
                $res = ipmi_Reboot($params);
                if($res == 'success'){
                    $result['status'] = 'success';
                    $result['msg'] = $_LANG['ipmi_hooks_reboot_success'];
                }else{
                    $result['status'] = 'error';
                    $result['msg'] = $res ?: $_LANG['ipmi_hooks_reboot_error'];
                }
                break;
            case 'bmc':
                $res = ipmi_ResetBmc($params);
                if($res == 'success'){
                    $result['status'] = 'success';
                    $result['msg'] = $_LANG['ipmi_hooks_bmc_success'];
                }else{
                    $result['status'] = 'error';
                    $result['msg'] = $res ?: $_LANG['ipmi_hooks_bmc_error'];
                }
                break;
            default:
                $result['status'] = 'error';
                $result['msg'] = $_LANG['ipmi_error'];
                break;
        }
        if($result['status']=='success'){
            $result['status'] = 200;
        }else{
            $result['status'] = 400;
        }
        echo json_encode($result);exit;
    }
}


function ipmi_checkTemplateIsMcSpace(){
    // 当前模板
    $template = $_SESSION['Template'] ? : $GLOBALS['CONFIG']['Template'];
    $path = ROOTDIR . "/templates/" . $template . "/idcsmart.tpl";
    if(file_exists($path)){
        return true;
    }
    return false;
}



