<?php 

// 订单支付
function ipmi_InvoicePaid($params){
	// 根据订单id查找主机id和产品类型
	$invoiceid = $params['invoiceid'];
	$sql = "SELECT p.servertype,h.id FROM tblproducts AS p 
		LEFT JOIN tblhosting AS h ON h.packageid=p.id 
		LEFT JOIN tblinvoiceitems AS im ON h.id=im.relid 
		WHERE im.invoiceid='{$invoiceid}'";
	$tblproducts = full_query($sql);
	$result = mysql_fetch_assoc($tblproducts);
	if ($result['servertype'] == 'ipmi') {
		include_once "ipmi.php";
		$sql2 = "SELECT relid FROM tblinvoiceitems WHERE invoiceid='{$invoiceid}'";
		$tblinvoiceitems = full_query($sql2);
		//调用同步
		while ($re = mysql_fetch_assoc($tblinvoiceitems)) {
			$params['serviceid'] = $re['relid'];
			ipmi_Sync($params);
		}
	}
}
add_hook('InvoicePaid', 1, 'ipmi_InvoicePaid');

// 处理后台
function ipmi_AdminAreaPage($params){	

	if($params['filename'] == 'clientsservices'){		
		include_once "ipmi.php";		
		global $_LANG; 
		
	    $serviceid = intval($_GET['id'] ?: $_GET['productselect']);
		$hosting = getHosting($serviceid);
		$accesshash = serverAccessHash($hosting['server'], $hosting['accesshash']);		
		if($hosting['type'] != 'ipmi'){
			return ;
		}
		
		$param['serversecure'] = $hosting['secure'];    
		$param['serverip'] = $hosting['hostname'] ?: $hosting['ipaddress'];
		$param['serverport'] = $hosting['serverport'];
		$param['serverusername'] = $hosting['username'];
		$param['serverpassword'] = decrypt($hosting['password']);
		if($_GET['download'] == 'true' && $_GET['java'] == 'true'){
	        $file = $_GET['name'];
	        ipmi_Download($file, $file);
	        exit;
	    }
	    if (!empty($_GET['switch_email'])) {  //跳转
			$email = $_GET['euid']; 
			$pdsid = $_GET['pdsid'];
			if (strpos($email, '@') === false || filter_var($email, FILTER_VALIDATE_EMAIL) === false) return false;

			$sql = "SELECT `id` FROM `tblclients` WHERE `email` = '$email' LIMIT 1;";
			$user = full_query($sql);
			$user = mysql_fetch_assoc($user);
			if ($user['id']) {  
	        	$url = '<script>window.location.href="?userid='.$user['id'].'&productselect='.$pdsid.'"</script>'; 	
	        	unset($query_arr,$email,$user,$sql);
	        	echo $url;exit;
	        }
		}
		if($_GET['vnc'] == 'true'){
			if($accesshash['vncadmin'] != 'on'){
				exit($_LANG['ipmi_hooks_vnc_nostart'] );
			}
			$param['configoption1'] = $hosting['configoption1'];
		    $param['serviceid'] = $serviceid;
		    if($_POST['restart'] == 1){
		    	$param['restart'] = 1;
		    }
		    $result = ipmi_vnc($param);
		    if($result['status'] == 'success'){
		    	$host = $result['host'];
		    	$ssl = $result['ssl'];
		    	$token = $result['token'];
		    	$house = $result['house'];
		    	$pass = $result['pass'];
		    	$vnc_pass = $result['vnc_pass'];
		    }else{
		    	$msg = $_LANG['ipmi_hooks_vnc_start_error'];
		    }
		    $web_root = DI::make("asset")->getWebRoot();
		    require_once IPMI_FILE.'noVNC/vnc_lite.php';
			exit;
		}
		if($_GET['traffic'] == 'true'){
			if($_GET['get_traffic'] == 1){
				$start = $_GET['start'];
				$regtime = strtotime($hosting['regdate'].' 00:00:00').'000';
				if($start < $regtime){
					$start = $regtime;
				}
				$param['switch_id'] = $_GET['switch_id'];
			    $param['port_name'] = $_GET['switch_num'];
			    $param['start'] = $start;
			    $param['end'] = $_GET['end'];
			    $param['type'] = $_GET['type'];
			    $param['reverse'] = $_GET['reverse'];
				ipmi_getTraffic($param);
			}else{
				$param['configoption1'] = $hosting['configoption1'];
		        $param['serviceid'] = $serviceid;
				ipmi_Traffic($param);
			}
			exit;
		}
	    if ($_POST['adminipmiac'] == 'kvm') {  //KVM
	        if ($accesshash['kvmadmin'] != 'on') {
	            $res['status'] = 'error';
	            $res['msg'] = $_LANG['ipmi_client_kvm_off'];
	        }else{
	        	$param['configoption1'] = $hosting['configoption1'];
	        	$param['serviceid'] = $serviceid;
	            $res = ipmi_kvm($param);
	        }
	        echo json_encode($res);exit;
	    } 
	    if ($_POST['adminipmiac'] == 'ikvm') {  //IKVM
	        if ($accesshash['ikvmadmin'] != 'on') {
	            $res['status'] = 'error';
	            $res['msg'] = $_LANG['ipmi_client_ikvm_off'];
	        }else{
	        	$param['configoption1'] = $hosting['configoption1'];
	        	$param['serviceid'] = $serviceid;
	            $res = ipmi_ikvm($param);
	        }
	        echo json_encode($res);exit;
	    } 
	    if($_GET['ipmi_serverFlow'] == 'true'){
	    	$start = $_GET['startDate'];
	    	$month_start = date('Y-m-01');
	    	$last_30days = date('Y-m-d', strtotime('-30 days'));
	    	if(empty($start)){
	    		if(str_replace('-', '', $month_start) > str_replace('-', '', $last_30days)){
	    			$start = $last_30days;
	    		}else{
	    			$start = $month_start;
	    		}
	    	}
	    	if(str_replace('-', '', $month_start) < str_replace('-', '', $start)){
	    		$month_start = $start;
	    	}
	    	if(str_replace('-', '', $last_30days) < str_replace('-', '', $start)){
	    		$last_30days = $start;
	    	}
			$param['configoption1'] = $hosting['configoption1'];
        	$param['serviceid'] = $serviceid;
			$param['startDate'] = $start;
			$result = ipmi_serverFlow($param);
			if($result['status'] == 'success' && !empty($result['data'])){
				$month_flow = 0;
				$last_30days_flow = 0;
				$all_flow = 0;
				foreach($result['data'] as $k=>$v){
					foreach($v as $kk=>$vv){
						if($kk >= $_GET['startDate']){
							$all_flow += $vv['in_bw_add'] + $vv['out_bw_add'];
						}
						if($kk >= $last_30days){
							$last_30days_flow += $vv['in_bw_add'] + $vv['out_bw_add'];
						}
						if($kk >= $month_start){
							$month_flow += $vv['in_bw_add'] + $vv['out_bw_add'];
						}
					}
					break;
				}
				$month_flow += round($result['data']['today']['all']/1024/1024,2);
				$last_30days_flow += round($result['data']['today']['all']/1024/1024,2);
				$all_flow += round($result['data']['today']['all']/1024/1024,2);
				$month_flow = dataUnitConversion($month_flow);
				$last_30days_flow = dataUnitConversion($last_30days_flow);
				$all_flow = dataUnitConversion($all_flow);
				$res['status'] = 'success';
				$res['msg'] = "{$_LANG['ipmi_hooks_serverflow1'] }：{$month_flow}; {$_LANG['ipmi_hooks_serverflow2'] }：{$last_30days_flow}; {$_LANG['ipmi_hooks_serverflow3'] }{$_GET['startDate']}~{$_GET['endDate']}:{$all_flow}";
			}else{
				$res = $result;
			}
			echo json_encode($res);exit;
	    }
	    if($_POST['ipmi_reinstall'] == 'true' && !empty($_POST['mos'])){  //重装
	    	if ($accesshash['reinstalladmin'] != "on") {
				$res['status'] = "error";
				$res['msg'] = $_LANG['ipmi_hooks_reinstall_off'] ;
				echo json_encode($res);exit;
			} 
	    	$param['configoption1'] = $hosting['configoption1'];
        	$param['serviceid'] = $serviceid;
	    	$param['password'] = $_POST['passwords'];
			$param['action'] = $_POST['ipmiaction'];
			$param['wltag'] = $_POST['wltag'];
			$param['mos'] = $_POST['mos'];
			$param['mcon'] = $_POST['mcon'];
			$param['highgrade'] = 1;
			$param['mscripts'] = (int)$_POST['mscripts'];
			$param['port'] = $_POST['port'];
			$param['part_type'] = $_POST['part_type'];
			$param['xml'] = $_POST['xml'];
			$param['disk'] = $_POST['disk'];
			$param['check_disk_size'] = $_POST['check_disk_size'];
			$res = ipmi_reinstall($param);
			echo json_encode($res);exit;
	    }
		if ($_POST['ipmi_cancellReinstall'] == 'true') {  //取消重装系统
			$param['serviceid'] = $serviceid;
			$param['configoption1'] = $hosting['configoption1'];
			$param['mirror_task_id'] = $_POST['mirror_task_id'];
			$res = ipmi_cancellReinstall($param);
			echo json_encode($res);exit;
		}
		if ($_POST['adminipmiac'] == "reload_status") {  //KVM
			$param['configoption1'] = $hosting['configoption1'];
        	$param['serviceid'] = $serviceid;
			$result = ipmi_reinstallStatus($param);
	        if (!empty($result['data'])) {
	        	if($result['data']['windows_finish']){
	        		$res['status'] = 'success';
	        		$res['msg'] = "<span class='reload_status'> {$_LANG['ipmi_admin_area_reinstall_windows_finish']}</span>";
	        		$res['windows_finish'] = true;
	            }else{
		        	if($result['data']['task_type'] == 3){
		        		$info = $_LANG['ipmi_admin_area_reinstall_getinfo1'];
		        		$cancel = $_LANG['ipmi_admin_area_reinstall_cancelinfo1'] ;
		        		$span = '';
		        	}else if($result['data']['task_type'] == 2){
		        		$info = $_LANG['ipmi_admin_area_reinstall_getinfo2'];
		        		$cancel = $_LANG['ipmi_admin_area_reinstall_cancelinfo2'] ;
		        		$span = '';
		        	}else if($result['data']['task_type'] == 1){
		        		$info = $_LANG['ipmi_admin_area_reinstall_getinfo3'];
		        		$cancel = $_LANG['ipmi_admin_area_reinstall_cancelinfo3'] ;
		        		$span = '';
		        	}else{
		        		$info = $_LANG['ipmi_admin_area_reinstall_getinfo4'];
		        		$cancel = $_LANG['ipmi_admin_area_reinstall_cancelinfo4'] ;
		        		$part_info = [$_LANG['ipmi_admin_area_reinstall_part_info1'], $_LANG['ipmi_admin_area_reinstall_part_info2']];
		        		$span = $result['data']['name'].','.$_LANG['ipmi_admin_area_reinstall_info1'].'：disk'.$result['data']['disk'].','.$_LANG['ipmi_admin_area_reinstall_info2'].':'.$part_info[$result['data']['part_type']];
		        	}
		        	$res['status'] = "success";
		            $res['msg'] = "<span style='color:red;'> {$info}：</span>".$span."  ".$_LANG['ipmi_admin_area_reinstall_info3']."：".$result['data']['progress']."% ".$result['data']['step']."  ".$_LANG['ipmi_admin_area_reinstall_info4']."：".$result['data']['time']."  <a href=\"javascript:;\" data-id=\"".$result['data']['id']."\" class=\"stopReload\">{$cancel}</a>";
		            $res['crackPwd'] = $result['crackPwd'];
		            $res['disk_check'] = json_decode($result['data']['disk_check'], true) ?: [];
		            $res['error_type'] = $result['data']['error_type'];
		            $res['error_msg'] = $result['data']['error_msg'];
		            $res['disk_info'] = json_decode($result['data']['disk_info'], true) ?: [];
		            $res['progress'] = $result['data']['progress'];
		            $res['id'] = $result['data']['id'];
		            $res['windows_finish'] = false;
		        }
	        }else{
	        	$res['status'] = "error";
	        }  
			echo json_encode($res);exit;  
	    }
	    if($_POST['ipmi_rescue'] == 'true'){
	    	if ($accesshash['rescueadmin'] != "on") {
				$res['status'] = "error";
				$res['msg'] = $_LANG['ipmi_hooks_rescue_off'] ;
				echo json_encode($res);exit;
			} 
	    	$param['configoption1'] = $hosting['configoption1'];
        	$param['serviceid'] = $serviceid;
        	$param['rescue'] = $_POST['rescue'];
        	$param['system'] = $_POST['system'];
        	$result = ipmi_rescue($param);
        	echo json_encode($result);exit;
	    }
	    if($_POST['ipmi_crack'] == 'true'){
	    	if ($accesshash['crackadmin'] != "on") {
				$res['status'] = "error";
				$res['msg'] = $_LANG['ipmi_hooks_crack_off'];
				echo json_encode($res);exit;
			} 
	    	$param['configoption1'] = $hosting['configoption1'];
        	$param['serviceid'] = $serviceid;
        	$param['action'] = $_POST['action'];
        	$param['password'] = $_POST['password'];
        	$param['user'] = $_POST['user'];
        	$param['other_user'] = $_POST['other_user'];
        	$result = ipmi_crack($param);
        	echo json_encode($result);exit;
	    }
	    if ($_POST['adminipmiac'] == 'ipmion') {  //开机
	        if ($accesshash['onadmin'] != 'on') {
	            $res['status'] = 'error';
	            $res['msg'] = $_LANG['ipmi_hooks_powerup_off'];
	        }else{
	        	$param['configoption1'] = $hosting['configoption1'];
	        	$param['serviceid'] = $serviceid;
	            $result = ipmi_on($param);
	            if($result == 'success'){
	            	$res['status'] = 'success';
	            	$res['msg'] = $_LANG['ipmi_hooks_powerup_success'];
	            }else{
	            	$res['status'] = 'error';
	            	$res['msg'] = $_LANG['ipmi_hooks_powerup_error'];
	            }
	        }
	        echo json_encode($res);exit;
	    } 
	    if ($_POST['adminipmiac'] == 'ipmioff') {  //关机
	        if ($accesshash['offadmin'] != 'on') {
	            $res['status'] = 'error';
	            $res['msg'] = $_LANG['ipmi_hooks_powerdown_off'];
	        }else{
	        	$param['configoption1'] = $hosting['configoption1'];
	        	$param['serviceid'] = $serviceid;
	            $result = ipmi_off($param);
	            if($result == 'success'){
	            	$res['status'] = 'success';
	            	$res['msg'] = $_LANG['ipmi_hooks_powerdown_success'];
	            }else{
	            	$res['status'] = 'error';
	            	$res['msg'] = $_LANG['ipmi_hooks_powerdown_error'] ;
	            }
	        }
	        echo json_encode($res);exit;
	    } 
	    if ($_POST['adminipmiac'] == 'ipmireboot') {  //重启
	        if ($accesshash['rebootadmin'] != 'on') {
	            $res['status'] = 'error';
	            $res['msg'] = $_LANG['ipmi_hooks_reboot_off'] ;
	        }else{
	        	$param['configoption1'] = $hosting['configoption1'];
	        	$param['serviceid'] = $serviceid;
	            $result = ipmi_reboot($param);
	            if($result == 'success'){
	            	$res['status'] = 'success';
	            	$res['msg'] = $_LANG['ipmi_hooks_reboot_success'];
	            }else{
	            	$res['status'] = 'error';
	            	$res['msg'] = $_LANG['ipmi_hooks_reboot_error'] ;
	            }
	        }
	        echo json_encode($res);exit;
	    } 
	    if($_POST['adminipmiac'] == 'unsuspendReload'){
        	$param['configoption1'] = $hosting['configoption1'];
        	$param['serviceid'] = $serviceid;
        	$param['disk_part'] = $_POST['disk_part'];
        	$param['mirror_task_id'] = $_POST['mirror_task_id'];
            $result = ipmi_unsuspendReload($param);
	        echo json_encode($result);exit;
	    }
	    if($_POST['ipmi_traffic_usage'] == 1){
	    	$param['configoption1'] = $hosting['configoption1'];
        	$param['serviceid'] = $serviceid;
        	$param['start'] = !empty($_POST['start']) ? toMySQLDate($_POST['start']) : date('Y-m-d', strtotime('-30 days'));
        	$param['end'] = !empty($_POST['end']) ? toMySQLDate($_POST['end']) : date('Y-m-d');
        	if(str_replace('-', '', $param['start']) < str_replace('-', '', $hosting['regdate'])){
        		$param['start'] = $hosting['regdate'];
        	}
        	if(str_replace('-', '', $param['end']) > date('Ymd')){
        		$param['end'] = date('Y-m-d');
        	}
        	if(str_replace('-', '', $param['start']) > str_replace('-', '', $param['end'])){
        		$result['status'] = 'error';
        		$result['msg'] = $_LANG['ipmi_hooks_serverflow4'];
        		echo json_encode($result);exit;
        	}
            $result = ipmi_trafficUsage($param);
	        echo json_encode($result);exit;
	    }
	    if($_POST['adminipmiac'] == 'getMirrorScripts'){
	    	$param['configoption1'] = $hosting['configoption1'];
		    $param['serviceid'] = $serviceid;
	    	$param['mos'] = (int)$_POST['mos'];
            $result = ipmi_getMirrorScripts($param);
            echo json_encode($result);exit;
	    }

	}
}

add_hook("AdminAreaPage", 1, "ipmi_AdminAreaPage");

// 客户页加载时运行
function ipmi_ClientAreaPage($params){
	 
	if($params['filename'] == "clientarea" && $params['action'] == "productdetails"){
		include_once "ipmi.php";
		global $_LANG;
	    $serviceid = $params['serviceid'] ?: intval($_GET['id'] ?: $_GET['productselect']);
		$hosting = getHosting($serviceid);
		$accesshash = serverAccessHash($hosting['server'], $hosting['accesshash']);
		if($hosting['type'] != 'ipmi'){
			return ;
		}else if($hosting['domainstatus'] != 'Active'){
			return ;
		}
		if(empty($_SESSION['uid']) || $_SESSION['uid'] != $hosting['userid']){
			return ;
		}
		
		$sms_check_on = ipmi_checkSms();
		$param['serversecure'] = $hosting['secure'];
		$param['serverip'] = $hosting['hostname'] ?: $hosting['ipaddress'];
		$param['serverport'] = $hosting['serverport'];
		$param['serverusername'] = $hosting['username'];
		$param['serverpassword'] = decrypt($hosting['password']);
		$param['serviceid'] = $serviceid;
		$param['configoption1'] = $hosting['configoption1'];
		if($_GET['download'] == 'true' && $_GET['java'] == 'true'){
	        $file = $_GET['name'];
	        ipmi_Download($file, $file);
	        exit;
	    }
	    if($_GET['vnc'] == 'true'){
			if($accesshash['vnc'] != 'on'){
				exit($_LANG['ipmi_hooks_vnc_nostart'] );
			}
			if(!$sms_check_on && in_array('vnc', $accesshash['sms_check'])){
				exit($_LANG['ipmi_client_code_error'] );
			}
			$param['configoption1'] = $hosting['configoption1'];
		    $param['serviceid'] = $serviceid;
		    if($_POST['restart'] == 1){
		    	$param['restart'] = 1;
		    }
		    $result = ipmi_vnc($param);
		    if($result['status'] == 'success'){
		    	$host = $result['host'];
		    	$ssl = $result['ssl'];
		    	$token = $result['token'];
		    	$house = $result['house'];
		    	$pass = $result['pass'];
		    	$vnc_pass = $result['vnc_pass'];
		    }else{
		    	$msg = $_LANG['ipmi_hooks_vnc_start_error'] ;
		    }
		    $web_root = DI::make("asset")->getWebRoot();
		    require_once IPMI_FILE.'noVNC/vnc_lite.php';
			exit;
		}
	    if($_GET['traffic'] == 'true'){
	    	if($accesshash['flowchart'] != 'on'){
				exit($_LANG['ipmi_hooks_serverflow_off'] );
			}
			if($_GET['get_traffic'] == 1){
				$start = $_GET['start'];
				$regtime = strtotime($hosting['regdate'].' 00:00:00').'000';
				if($start < $regtime){
					$start = $regtime;
				}
				$param['switch_id'] = $_GET['switch_id'];
			    $param['port_name'] = $_GET['switch_num'];
			    $param['start'] = $start;
			    $param['end'] = $_GET['end'];
			    $param['type'] = $_GET['type'];
			    $param['reverse'] = $_GET['reverse'];
				ipmi_getTraffic($param);
			}else{
				$param['configoption1'] = $hosting['configoption1'];
		        $param['serviceid'] = $serviceid;
				ipmi_Traffic($param);
			}
			exit;
		}
		if($_POST['check_reinstall'] == "true"){
			if($accesshash['reinstalltimes'] == 0){
				$result['status'] = 'success';
				echo json_encode($result);exit;
			}
			$tblcustomfields = select_query("tblcustomfields", "", array("type" => "ipmi","relid" => 0));
			$customfields = mysql_fetch_array($tblcustomfields);
			if (empty($customfields['id'])) {
				$fields = array(
					"type" => "ipmi",
					"relid" => 0,
					"fieldname" => $_LANG['ipmi_hooks_reinstall_num'] ,
					"fieldtype" => "text",
				);
				insert_query("tblcustomfields", $fields);
			}
			$tblcustomfieldsvalues = select_query("tblcustomfieldsvalues", "", array("fieldid" => $customfields['id'], "relid" => $serviceid));
			$customfieldsvalues = mysql_fetch_array($tblcustomfieldsvalues);
			$value = unserialize($customfieldsvalues['value']);
			$num = intval($value['num']);
			if(empty($customfields['id']) || strtotime('this week Monday') > strtotime($value['date'])){
				$num = 0;
			}
			if($accesshash['buyreinstalltimes'] == 'on'){
				$buy_times = ipmi_buyTimes($serviceid);
			}else{
				$buy_times = 0;
			}
			if ($num >= $accesshash['reinstalltimes'] + $buy_times && $accesshash['reinstalltimes'] > 0) {
				if($accesshash['buyreinstalltimes'] == 'on' && $accesshash['reinstallprice']>0){
					// 获取默认货币后缀
					$suffix = '';
					foreach($params['currencies'] as $v){
						if($v['default'] == 1){
							$suffix = $v['suffix'];
							break;
						}
					}
					$result['status'] = 'confirm_buy';
					//$result['msg'] = "您本周已重装{$num}次，已达最大限额，重装将收取{$accesshash['reinstallprice']}{$suffix}每次，确认支付？";
					$result['msg'] = ipmi_langReplace($_LANG['ipmi_hooks_reinstallprice'],array('{$num}'=>$num,'{$suffix}'=>$accesshash['reinstallprice'].$suffix));
					echo json_encode($result);exit;
				}else{
					echo json_encode(array("status" => "error", "msg" => $_LANG['ipmi_hooks_reinstall_max'] ));exit;
				}
			}else{
				$result['status'] = "confirm";
				//$result['msg'] = "您本周共允许重装".($accesshash['reinstalltimes'] + $buy_times)."次，已重装{$num}次，是否继续？";
				//$result['msg'] = '您本周共允许重装{$reinstalltimes}次，已重装{$num}次，是否继续？';
				$result['msg'] = ipmi_langReplace($_LANG['ipmi_hooks_reinstalltimes_num'],array('{$reinstalltimes}'=>($accesshash['reinstalltimes'] + $buy_times),'{$num}'=>$num));
				echo json_encode($result);exit;
			}
		}
		if ($_POST['ipmi_reinstall'] == "true") {
			if (!$_POST['reinstall_confirm'] || $_POST['reinstall_confirm'] != 1) {
				$res = [
					'status' => 'error',
					'msg' => $_LANG['ipmi_layer_content_os_reload_backups_confirm']   
				];
				echo json_encode($res);exit;
			}
			if ($accesshash['reinstall'] != "on") {
				$jsonMsg['status'] = "error";
				$jsonMsg['msg'] = $_LANG['ipmi_hooks_reinstall_off'];
				echo json_encode($jsonMsg);exit;
			}
			if($accesshash['custompartition'] != 'on' && $_POST['ipmiaction'] == 2){
				$jsonMsg['status'] = "error";
				$jsonMsg['msg'] = $_LANG['ipmi_hooks_custom_off'];
				echo json_encode($ipmi_reinstall);exit;
			}
			$tblcustomfields = select_query("tblcustomfields", "", array("type" => "ipmi","relid" => 0));
			$customfields = mysql_fetch_array($tblcustomfields);
			if (empty($customfields['id'])) {
				$fields = array(
					"type" => "ipmi",
					"relid" => 0,
					"fieldname" => $_LANG['ipmi_hooks_reinstall_num'],
					"fieldtype" => "text",
				);
				insert_query("tblcustomfields", $fields);
			}
			$tblcustomfieldsvalues = select_query("tblcustomfieldsvalues", "", array("fieldid" => $customfields['id'], "relid" => $serviceid));
			$customfieldsvalues = mysql_fetch_array($tblcustomfieldsvalues);
			$value = unserialize($customfieldsvalues['value']);
			$num = intval($value['num']);
			if(empty($customfields['id']) || strtotime('this week Monday') > strtotime($value['date'])){
				$num = 0;
			}
			if($accesshash['buyreinstalltimes'] == 'on'){
				$buy_times = ipmi_buyTimes($serviceid);
			}else{
				$buy_times = 0;
			}
			if ($num >= $accesshash['reinstalltimes'] + $buy_times && $accesshash['reinstalltimes'] > 0) {
				// if($accesshash['buyreinstalltimes'] == 'on' && $accesshash['reinstallprice']>0){
				// 	// 获取默认货币后缀
				// 	$suffix = '';
				// 	foreach($params['currencies'] as $v){
				// 		if($v['default'] == 1){
				// 			$suffix = $v['suffix'];
				// 			break;
				// 		}
				// 	}
				// 	$result['status'] = 'confirm_buy';
				// 	$result['msg'] = "您本周已重装{$num}次，已达最大限额，重装将收取{$accesshash['reinstallprice']}{$suffix}每次，确认支付？";
				// 	echo json_encode($result);exit;
				// }else{
					echo json_encode(array("status" => "not", "msg" => $_LANG['ipmi_hooks_reinstall_max']));exit;
				//}
			}
			if(!$sms_check_on && in_array('reinstall', $accesshash['sms_check'])){
				$res['status'] = 'nocheck';
                $res['msg'] = $_LANG['ipmi_client_code_error'];
                echo json_encode($res);exit;
			}
			$param['password'] = $_POST['password'];
			$param['action'] = $_POST['ipmiaction'];
			$param['wltag'] = $_POST['wltag'];
			$param['mos'] = $_POST['mos'];
			$param['mcon'] = $_POST['mcon'];
			$param['part_type'] = $_POST['part_type'];
			$param['disk'] = $_POST['disk'];
			$param['check_disk_size'] = $_POST['check_disk_size'];
			$param['mscripts'] = (int)$_POST['mscripts'];
			$param['highgrade'] = (int)$_POST['highgrade'];
			if($accesshash['custompartition'] == 'on'){
				$param['xml'] = $_POST['xml'];
			}
			if($accesshash['customport'] == 'on'){
				$param['port'] = $_POST['port'];
			}
			$ipmi_reinstall = ipmi_reinstall($param);
			if ($ipmi_reinstall['status'] == "success") {
				if($accesshash['reinstalltimes'] > 0){
					if (empty($customfieldsvalues['fieldid'])) {					
						$fieldsvalues = array(
							"fieldid" => $customfields['id'],
							"relid" => $serviceid,
							"value" => serialize(array("num"=>1, "date"=>date("Y-m-d"))),
						);
						insert_query("tblcustomfieldsvalues", $fieldsvalues);
					} else {
						if (strtotime('this week Monday') > strtotime($value['date'])) {
							$num = 1;
						} else {
							$num = $value['num']+1;
						}
						$fieldsvalues = array(
							"value" => serialize(array("num" => $num,"date" => date("Y-m-d"))),
						);
						update_query("tblcustomfieldsvalues", $fieldsvalues, array("fieldid" => $customfields['id'],"relid" => $serviceid));
					}
				}
			}
			echo json_encode($ipmi_reinstall);
			exit;
		}
		if ($_GET['ipmi_cancellReinstall'] == "true") {
			$param['mirror_task_id'] = $_GET['mirror_task_id'];
			$ipmi_reinstall = ipmi_cancellReinstall($param);
			// 重装
			if($ipmi_reinstall['status'] == 'success' && isset($ipmi_reinstall['task_type']) && $ipmi_reinstall['task_type'] == 0){
				// 取消重装，使用次数-1
				if($accesshash['reinstalltimes']>0){
					$tblcustomfields = select_query("tblcustomfields", "", array("type" => "ipmi","relid" => 0));
					$customfields = mysql_fetch_array($tblcustomfields);
					if (empty($customfields['id'])) {
						$fields = array(
							"type" => "ipmi",
							"relid" => 0,
							"fieldname" => $_LANG['ipmi_hooks_reinstall_num'] ,
							"fieldtype" => "text",
						);
						insert_query("tblcustomfields", $fields);
					}
					$tblcustomfieldsvalues = select_query("tblcustomfieldsvalues", "", array("fieldid" => $customfields['id'], "relid" => $serviceid));
					$customfieldsvalues = mysql_fetch_array($tblcustomfieldsvalues);
					$value = unserialize($customfieldsvalues['value']);
					if (!empty($customfieldsvalues['fieldid'])) {					
						if (strtotime('this week Monday') > strtotime($value['date'])) {
							$num = 0;
						} else {
							$num = $value['num']-1;
						}
						if($num>=0){
							$fieldsvalues = array(
								"value" => serialize(array("num" => $num,"date" => $value['date'])),
							);
							update_query("tblcustomfieldsvalues", $fieldsvalues, array("fieldid" => $customfields['id'], "relid" => $serviceid));
						}
					}
				}
			}
			echo json_encode($ipmi_reinstall);
			exit;
		}
		if ($_POST['adminipmiac'] == "reload_status") {  
			$param['configoption1'] = $hosting['configoption1'];
        	$param['serviceid'] = $serviceid;
			$result = ipmi_reinstallStatus($param);
	        if (!empty($result['data'])) {
	        	if($result['data']['windows_finish']){
	        		$res['status'] = 'success';
	        		$res['msg'] = "<span class='reload_status'> {$_LANG['ipmi_admin_area_reinstall_windows_finish']}</span>";
	        		$res['windows_finish'] = true;
	            }else{
		        	if($result['data']['task_type'] == 3){
		        		$info = $_LANG['ipmi_admin_area_reinstall_getinfo1'] ;
		        		$cancel = $_LANG['ipmi_admin_area_reinstall_cancelinfo1'];
		        		$span = '';
		        	}else if($result['data']['task_type'] == 2){
		        		$info = $_LANG['ipmi_admin_area_reinstall_getinfo2'] ;
		        		$cancel = $_LANG['ipmi_admin_area_reinstall_cancelinfo2'];
		        		$span = '';
		        	}else if($result['data']['task_type'] == 1){
		        		$info = $_LANG['ipmi_admin_area_reinstall_getinfo3'] ;
		        		$cancel = $_LANG['ipmi_admin_area_reinstall_cancelinfo3'];
		        		$span = '';
		        	}else{
		        		$info = $_LANG['ipmi_admin_area_reinstall_getinfo4'] ;
		        		$cancel = $_LANG['ipmi_admin_area_reinstall_cancelinfo4'];
		        		$part_info = [$_LANG['ipmi_admin_area_reinstall_part_info1'],$_LANG['ipmi_admin_area_reinstall_part_info2']];
		        		$span = $result['data']['name'].','.$_LANG['ipmi_admin_area_reinstall_info1'].'：disk'.$result['data']['disk'].','.$_LANG['ipmi_admin_area_reinstall_info2'].':'.$part_info[$result['data']['part_type']];
		        	}
		        	$res['status'] = "success";
		        	$res['msg'] = "<span class='reload_status'><span style='color:red;'> {$info}：</span>".$span."  ".$_LANG['ipmi_admin_area_reinstall_info3']."：".$result['data']['progress']."% ".$result['data']['step']."</span>";
		            $res['crackPwd'] = $result['crackPwd'];
		            $res['disk_check'] = json_decode($result['data']['disk_check'], true) ?: [];
		            $res['error_type'] = $result['data']['error_type'];
		            $res['error_msg'] = $result['data']['error_msg'];
		            $res['disk_info'] = json_decode($result['data']['disk_info'], true) ?: [];
		            $res['progress'] = $result['data']['progress'];
		            $res['id'] = $result['data']['id'];
		            $res['windows_finish'] = false;
		        }
	        }else{
	        	$res['status'] = "error";
	        }  
			echo json_encode($res);exit;  
	    }
		if($_POST['ipmi_rescue'] == 'true'){
	    	if ($accesshash['rescue'] != "on") {
				$res['status'] = "error";
				$res['msg'] = $_LANG['ipmi_hooks_rescue_off'];
				echo json_encode($res);exit;
			} 
			if(!$sms_check_on && in_array('rescue', $accesshash['sms_check'])){
				$res['status'] = 'nocheck';
                $res['msg'] = $_LANG['ipmi_client_code_error'];
                echo json_encode($res);exit;
			}
	    	$param['configoption1'] = $hosting['configoption1'];
        	$param['serviceid'] = $serviceid;
        	$param['rescue'] = $_POST['rescue'];
        	$param['system'] = $_POST['system'];
        	$result = ipmi_rescue($param);
        	echo json_encode($result);exit;
	    }
	    if($_POST['ipmi_crack'] == 'true'){
	    	if ($accesshash['crack'] != "on") {
				$res['status'] = "error";
				$res['msg'] = $_LANG['ipmi_hooks_crack_off'];
				echo json_encode($res);exit;
			} 
			if(!$sms_check_on && in_array('crack', $accesshash['sms_check'])){
				$res['status'] = 'nocheck';
                $res['msg'] = $_LANG['ipmi_client_code_error'];
                echo json_encode($res);exit;
			}
	    	$param['configoption1'] = $hosting['configoption1'];
        	$param['serviceid'] = $serviceid;
        	$param['action'] = $_POST['crack_action'];
        	$param['password'] = $_POST['password'];
        	$param['user'] = $_POST['user'];
        	$param['other_user'] = $_POST['other_user'];
        	$result = ipmi_crack($param);
        	echo json_encode($result);exit;
	    }
	    if ($_POST['adminipmiac'] == 'ipmion') {  //开机
	        if ($accesshash['on'] != 'on') {
	            $res['status'] = 'error';
	            $res['msg'] = $_LANG['ipmi_hooks_powerup_off'] ;
	        }else{
	        	$param['configoption1'] = $hosting['configoption1'];
	        	$param['serviceid'] = $serviceid;
	            $result = ipmi_on($param);
	            if($result == 'success'){
	            	$res['status'] = 'success';
	            	$res['msg'] = $_LANG['ipmi_hooks_powerup_success'];
	            }else{
	            	$res['status'] = 'error';
	            	$res['msg'] = $result;
	            }
	        }
	        echo json_encode($res);exit;
	    } 
	    if ($_POST['adminipmiac'] == 'ipmioff') {  //关机
	        if ($accesshash['off'] != 'on') {
	            $res['status'] = 'error';
	            $res['msg'] = $_LANG['ipmi_hooks_powerdown_off'];
	        }else{
	        	$param['configoption1'] = $hosting['configoption1'];
	        	$param['serviceid'] = $serviceid;
	            $result = ipmi_off($param);
	            if($result == 'success'){
	            	$res['status'] = 'success';
	            	$res['msg'] = $_LANG['ipmi_hooks_powerdown_success'];
	            }else{
	            	$res['status'] = 'error';
	            	$res['msg'] = $result;
	            }
	        }
	        echo json_encode($res);exit;
	    } 
	    if ($_POST['adminipmiac'] == 'ipmireboot') {  //重启
	        if ($accesshash['reboot'] != 'on') {
	            $res['status'] = 'error';
	            $res['msg'] = $_LANG['ipmi_hooks_reboot_off'] ;
	        }else{
	        	$param['configoption1'] = $hosting['configoption1'];
	        	$param['serviceid'] = $serviceid;
	            $result = ipmi_reboot($param);
	            if($result == 'success'){
	            	$res['status'] = 'success';
	            	$res['msg'] = $_LANG['ipmi_hooks_reboot_success'];
	            }else{
	            	$res['status'] = 'error';
	            	$res['msg'] = $result;
	            }
	        }
	        echo json_encode($res);exit;
	    }
	    if($_POST['adminipmiac'] == 'unsuspendReload'){
        	$param['configoption1'] = $hosting['configoption1'];
        	$param['serviceid'] = $serviceid;
        	$param['disk_part'] = $_POST['disk_part'];
        	$param['mirror_task_id'] = $_POST['mirror_task_id'];
            $result = ipmi_unsuspendReload($param);
	        echo json_encode($result);exit;
	    }
	    if($_POST['ipmi_traffic_usage'] == 1){
	    	$param['configoption1'] = $hosting['configoption1'];
        	$param['serviceid'] = $serviceid;
        	$param['start'] = !empty($_POST['start']) ? $_POST['start'] : date('Y-m-d', strtotime('-30 days'));
        	$param['end'] = !empty($_POST['end']) ? $_POST['end'] : date('Y-m-d');
        	if(str_replace('-', '', $param['start']) < str_replace('-', '', $hosting['regdate'])){
        		$param['start'] = $hosting['regdate'];
        	}
        	if(str_replace('-', '', $param['end']) > date('Ymd')){
        		$param['end'] = date('Y-m-d');
        	}
        	if(str_replace('-', '', $param['start']) > str_replace('-', '', $param['end'])){
        		$result['status'] = 'error';
        		$result['msg'] = $_LANG['ipmi_hooks_serverflow4'];
        		echo json_encode($result);exit;
        	}
            $result = ipmi_trafficUsage($param);
	        echo json_encode($result);exit;
	    }
	}
}
add_hook("ClientAreaPage", 1, "ipmi_ClientAreaPage");


add_hook('ClientAreaProductDetailsOutput', 1, function($params) {
	include_once "ipmi.php";
	global $_LANG;
	$serviceid = $params['service']->id;
	$hosting = getHosting($serviceid);
	$accesshash = serverAccessHash($hosting['server'], $hosting['accesshash']);
	if ($hosting['type'] != "ipmi"){
	 	return false;
	}elseif ($hosting['domainstatus'] != 'Active' && $hosting['domainstatus'] != 'Suspended'){
	 	return false;
	}
	if(empty($_SESSION['uid']) || $_SESSION['uid'] != $hosting['userid']){
		return ;
	}
	 
    /* if(ipmi_checkTemplateIsMcSpace()){
        return ;
    } */
	
	$_html = '';
	$userid = $_SESSION['uid'];

	$param['serversecure'] = $hosting['secure'];
	$param['serverip'] = $hosting['ipaddress'];
	$param['serverport'] = $hosting['serverport'];
	$param['serverusername'] = $hosting['username'];
	$param['serverpassword'] = decrypt($hosting['password']);
	$param['serviceid'] = $serviceid;
	$param['configoption1'] = $hosting['configoption1'];
    $param['packageid'] = $params['service']->packageid;
	
	$flowpacket = ipmi_GetFlowPack($param);
	$flowpacket_html = '';
	foreach($flowpacket as $v){
        $flowpacket_html .= '<option value="'.$v['id'].'">'.$_LANG['ipmi_hooks_flowpacket_big'].'：'.$v['capacity'].'GB，'.$_LANG['ipmi_hooks_flowpacket_price'] .'：'.$v['price'].'</option>';
	}
	if(!empty($flowpacket)){
		if(!ipmi_checkTemplateIsMcSpace()){
			$_button = '<div id="ipmi_buy_flowpacket" style="margin-bottom: 10px;padding:20px;border: 1px solid #dfe3e9;">
				<button class="btn btn-success btn-large m-l-5" data-toggle="modal" data-target="#modalBuyFlowpacket">'.$_LANG['ipmi_hooks_flowpacket_buy'].'</button>
			</div>';
		}else{
			$_buttonjs = ' $(function(){
            $(".content section>.row").eq(1).find(".card-body").append("<button class=\"btn btn-success btn-large m-l-5\" data-toggle=\"modal\" data-target=\"#modalBuyFlowpacket\">'.$_LANG['ipmi_hooks_flowpacket_buy'].'</button>");
        })';
		}
		$_html =$_button. '
<div class="modal fade" id="modalBuyFlowpacket" tabindex="-1" role="dialog" aria-labelledby="ModuleReinstall" aria-hidden="false" style="display: none;">
    <div class="modal-dialog">
        <div class="modal-content panel panel-primary">
            <div class="modal-header panel-heading">
                <h4 class="modal-title">'.$_LANG['ipmi_hooks_flowpacket_buy'].'</h4>
                <button type="button" class="close" data-dismiss="modal">
                    <span aria-hidden="true">×</span>
                    <span class="sr-only">'.$_LANG['ipmi_layer_close'].'</span>
                </button>
            </div>
            <div class="modal-body panel-body">
                <div class="margin-top-bottom-20 text-center">
                    <div class="form-group row" style="width: 100%;float: left;">
                        <label class="col-xs-12 col-md-3 form-control-label" style="line-height:30px;height:30px;text-align:center;">'.$_LANG['ipmi_hooks_flowpacket'].'</label>
                        <div class="col-xs-12 col-md-9" style="text-align:left;">
                            <select class="form-control" name="input_flow" id="input_flow">
                                '.$flowpacket_html.'
                            </select>
                        </div>
                    </div>
                    <div class="clearfix"></div>            
                </div>
            </div>
            <div class="modal-footer panel-footer">
                <button type="button" id="btnBuyFlowPacket" class="btn btn-primary" style="background:#3979f1;border-color:#3979f1;outline:none;box-shadow:none;font-family: “Microsoft YaHei”">
                    '.$_LANG['ipmi_client_os_buy'] .'
                </button>
                <button type="button" class="btn btn-default" data-dismiss="modal" style="font-family: “Microsoft YaHei”">
                    '.$_LANG['ipmi_layer_cancel'].'
                </button>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
'.$_buttonjs.'
		// 购买流量包
	    $("#btnBuyFlowPacket").on("click", function(){
	        var _this = $(this);
	        var _name = $(this).text()
	        var flowid = $("select[name=\"input_flow\"]").val();
	        if( flowid == ""){
	            if(typeof toastr !== "undefined"){
	                toastr.error("'.$_LANG['ipmi_hooks_flowpacket_select'].'");
	            }else{
	                alert("'.$_LANG['ipmi_hooks_flowpacket_select'].'");
	            }
	            return false;
	        }

	        if($(this).data("submit") == "submit"){
	            return false;
	        }else{
	            _this.text(_name + "...")
	            $(this).data("submit","submit");
	            $.post("clientarea.php?action=productdetails&id='.$serviceid.'",{method:"buyFlowPacket",flowid:flowid} , function(res){
	                if("success" == res.status){
	                    if(typeof toastr !== "undefined"){
	                        toastr.success(res.msg)
	                    }else{
	                        alert(res.msg)
	                    }
	                    $("#modalBuyFlowpacket").modal("hide")
	                    setTimeout(function(){
	                        window.open(res.url);
	                    }, 1000)
	                }else{
	                    if(typeof toastr !== "undefined"){
	                        toastr.error(res.msg);
	                    }else{
	                        alert(res.msg)
	                    }
	                }
	                _this.text("'.$_LANG['ipmi_client_os_buy'].'")
	                _this.removeData("submit");
	            }, "json")
	        }
	    });
	//})
</script>';
	}
	return $_html;
});

