<?php

require(dirname(__FILE__)."/config.php");
require_once(dirname(__FILE__)."/../include/oxwindow.class.php");

$ac = empty($ac)?"":$ac;

switch($ac){
	case "adminchk":
		$dsql->Query("me", "select * from #@__admin order by id asc");
		$adminrow = $dsql->GetTotalRow();
		$adminrs = $dsql->GetArray();
		if($adminrow>1) $rs['msg'] = "您当前的管理员帐号有<font color=red>$adminrow</font>个";
		if($adminrs['userid']=="admin"){
			$rs['msg'] = (empty($rs['msg'])?"":$rs['msg']."，")."使用默认登录名（admin）";
		}
		$md5chk = @file_get_contents("http://openapi.dedeapps.com/?m=dedesafer&c=md5chk&data=".$adminrs['pwd']);
		if($md5chk!="pass"){
			$rs['msg'] = (empty($rs['msg'])?"":$rs['msg']."，")."密码过于简单";
		}
		if(empty($rs['msg'])){
			$rs['msg'] = "检查管理员帐号安全性";
			$rs['tip'] = "";
			$rs['act'] = "没有风险[安全]";
			$rs['sc'] = 0;
		}else{
			$rs['tip'] = "建议检查";
			$rs['act'] = '<a href="sys_admin_user.php" class="np coolbg">立即查看</a>';
			$rs['sc'] = 9;
		}
		$rs["ac"] = $ac;
		echo json_encode(array_gb2utf8($rs));
	break;
	
	case "updatechk":
			$verLockFile = DEDEDATA.'/admin/ver.txt';
			$fp = fopen($verLockFile,'r');
			$upTime = trim(fread($fp,64));
			fclose($fp);
			
			$vers = explode("_", $cfg_version);
			$ver = str_replace("V", "", $vers[0]);
			$updateHost = 'http://updatenew.dedecms.com/base-v'.$ver.'/';
			include_once( DEDEINC.'/dedehttpdown.class.php');
			$dhd = new DedeHttpDown();
			$dhd->OpenUrl($updateHost.'/verinfo.txt');
			$verlist = trim($dhd->GetHtml());
			$dhd->Close();
			if($cfg_soft_lang=='utf-8') 
			{
				$verlist = gb2utf8($verlist);
			}
			$verlist = preg_replace("#[\r\n]{1,}#", "\n", $verlist);
			$verlists = explode("\n", $verlist);
			
			$tmp = explode(",", end($verlists));
			$lasttime = trim($tmp[0]);
			
			if($upTime==$lasttime){
				$rs['msg'] = "检查系统是否需要更新";
				$rs['tip'] = "";
				$rs['act'] = "没有风险[安全]";
				$rs['sc'] = 0;
			}else{
				$rs['msg'] = "您的系统需要升级，有安全更新可用";
				$rs['tip'] = "建议更新";
				$rs['act'] = '<a href="javascript:void(0);" class="np coolbg" onclick="$(\'.trhide\').show();LoadUpdateInfos();">立即更新</a>（<a href="?ac=checkserv&tab=2&stype=sj">联系技术工程师协助您升级？</a>）';
				$rs['sc'] = 13;
			}
			$rs["ac"] = $ac;
			echo json_encode(array_gb2utf8($rs));
	break;
	
	case "dbzendchk":
			$dsql->query("me","SHOW TABLE STATUS");
			$tables = array();
			while($row = $dsql->GetArray()){
				$tables[$row['Name']] = $row;
			}
			$allfreesize = 0;
			foreach($tables as $k=>$r){
				$allfreesize += $r['Data_free'];
			}
			if($allfreesize>0){
				$rs['msg'] = "当前数据库有碎片（".formatsize($allfreesize)."）可以优化";
				$rs['tip'] = "建议优化";
				$rs['act'] = '<a href="?ac=dbzendchk_do" class="np coolbg">立即优化</a>';
				$rs['sc'] = 5;
			}else{
				$rs['msg'] = "扫描数据库是否需要优化";
				$rs['tip'] = "";
				$rs['act'] = "没有风险[安全]";
				$rs['sc'] = 0;
			}
			$rs["ac"] = $ac;
			echo json_encode(array_gb2utf8($rs));
	break;
	
	case "dbzendchk_do":
			$dsql->query("me","SHOW TABLE STATUS");
			$tables = array();
			while($row = $dsql->GetArray()){
				if($row['Data_free']>0){
					$dsql->ExecuteNoneQuery("OPTIMIZE TABLE `{$row['Name']}` ");
				}
			}
			showmsg("数据库优化成功", $_SERVER['HTTP_REFERER']);
	break;
	
	case "filechk":
			$files = filechk(DEDEROOT);
			if(count($files)>0){
				$rs['msg'] = "扫描到<font color=red>".count($files)."</font>个可疑文件";
				$rs['tip'] = "建议检查";
				$rs['act'] = '<a href="javascript:void(0);" class="np coolbg" onclick="$(\'.trhide\').show();Loadfilechk();">全面扫描</a>';
				$rs['sc'] = 17;
			}else{
				$rs['msg'] = "系统木马文件扫描";
				$rs['tip'] = "";
				$rs['act'] = "没有风险[安全]";
				$rs['sc'] = 0;
			}
			$rs["ac"] = $ac;
			echo json_encode(array_gb2utf8($rs));
	break;

	case "Loadfilechk":
		AjaxHead();
		$files = filechk(DEDEROOT);
		if($files){
			foreach($files as $val){
				$val = str_replace(DEDEROOT, '', $val);
				echo "<div style='clear:both;border-bottom:1px dotted #B8E6A2;line-height:24px'>
				<div style='width:350px;float:left'>可疑文件：{$val}</div>
				<div style='float:left'>[<a href='file_manage_view.php?fmdo=del&filename=$val&activepath=' target='_blank'><u>删除</u></a>]
				[<a href='file_manage_view.php?fmdo=edit&filename=$val&activepath=' target='_blank'><u>查看源码</u></a>]
				[<a href='?ac=checkserv&f=$val'><u>安全鉴定</u></a>]
				</div></div>\r\n";
			}
		}else{
			echo "本次扫描没有找到可疑文件";
		}
	break;

	case "delerr";
		$mysql_error_trace = DEDEDATA.'/mysql_error_trace.inc';
		$mysqli_error_trace = DEDEDATA.'/mysqli_error_trace.inc';
		@unlink($mysql_error_trace);
		@unlink($mysqli_error_trace);
		showmsg("清理成功", $_SERVER['HTTP_REFERER']);
	break;
	
	case "adclear":
		$dir = DEDEDATA.'/cache';
        $dh = dir($dir);
        while($filename = $dh->read())
        {
            if(!preg_match("#myad-#", $filename))
            {
                continue;
            }
            $filename = $dir."/$filename";
            if(!is_dir($filename))
            {
                @unlink($filename);
            }
        }
		showmsg("清理成功", 'dedesafer.php?adc=1');
	break;
	
	case "tplclear":
		$d = DEDEROOT.$cfg_tplcache_dir;
		if(preg_match("#data\/#", $cfg_tplcache_dir) && file_exists($d) && is_dir($d))
		{
			$dh = dir($d);
			while($filename = $dh->read())
			{
				if($filename=='.'||$filename=='..'||$filename=='index.html') continue;
				@unlink($d.'/'.$filename);
			}
		}
		showmsg("清理成功", $_SERVER['HTTP_REFERER']);
	break;
	
	case "delinject":
		$log_file = DEDEDATA.'/'.md5($cfg_cookie_encode).'_safe.txt';
		@unlink($log_file);
		showmsg("清理成功", $_SERVER['HTTP_REFERER']);
	break;

	case "checkserv":
		$cc = "";
		if(!empty($f)){
			$fs = explode(",", $f);
			foreach($fs as $r){
				$rf = DEDEROOT.$r;
				if(is_file($rf)){
					$str = htmlspecialchars( cn_substr( file_get_contents($rf), 50000 ) );
					$cc = "文件：{$r}\r\n{$str}\r\n";
				}
			}
		}
		
		include DedeInclude('templets/dedesafer/checkserv.htm');
	break;
	
	case "plus":
		//根据dedecms版本获取最新插件列表
		@session_start();
		if(empty($_SESSION['pluslist'])){
			$uptime = file_get_contents(DEDEDATA.'/admin/ver.txt');
			$host = empty($_SERVER['HTTP_HOST'])?str_replace("http://", "", $cfg_basehost):$_SERVER['HTTP_HOST'];
			
			$pluslist = @file_get_contents("http://openapi.dedeapps.com/?m=dedesafer&c=plus&version=".$cfg_version."&uptime=".$uptime."&host=".$host);
			if(empty($pluslist) || strpos($pluslist, 'invalid')!==false){
				showmsg("连接云接口获取插件列表失败，请稍后再试", 1, 2);
				exit;
			}
			$pluslist = array_utf82gb( std_class_object_to_array( @json_decode($pluslist) ) );
			if(!empty($pluslist)){
				$_SESSION['pluslist'] = $pluslist;
			}
		}else{
			$pluslist = $_SESSION['pluslist'];
		}
		$mstr = "";
		foreach($pluslist as $key => $r){
			$actname = "";
			switch($r['act']){
				case "close":
					$actname = $cfg_mb_open=='Y'?"<font color=red>关闭</font>":"<font color=green>开启</font>";
				break;
				case "unstall":
					if(is_file(DEDEROOT.$r['mlist'][0]) || is_dir(DEDEROOT.$r['mlist'][0])){
						$actname = "<font color=red>卸载</font>";
					}else	if(!empty($r['hash']) && is_file(DEDEDATA.'/module/'.$r['hash'].".xml")){
						$actname = "<font color=green>安装</font>";
					}
				break;
				case "del":
					if(is_file(DEDEROOT.$r['mlist'][0]) || is_dir(DEDEROOT.$r['mlist'][0])){
						$actname = "<font color=red>删除</font>";
					}
				break;
				case "move":
					if(is_file(DEDEROOT.$r['mlist'][0]) || is_dir(DEDEROOT.$r['mlist'][0])){
						$actname = "<font color=red>移除</font>";
					}else if(is_file(DEDEDATA.'/safebackup'.$r['mlist'][0].'.bak') || is_dir(DEDEDATA.'/safebackup'.$r['mlist'][0])){
						$actname = "<font color=green>安装</font>";
					}
				break;
			}
			if(!empty($actname)){ //debug 判断是否存在备份或者插件
				$mstr .= "<div style='clear:both;border-bottom:1px dotted #B8E6A2;line-height:24px'>
					<div style='width:450px;float:left'>{$r['name']}</div>
					<div style='float:left'><a href='?ac=plus_do&plus={$key}'  class='np coolbg'>$actname</a></div>
				</div>";
			}
		}
		include DedeInclude('templets/dedesafer/plus.htm');
	break;

	case "plus_do":
		//根据dedecms版本获取最新插件详情
		$uptime = file_get_contents(DEDEDATA.'/admin/ver.txt');
		$host = empty($_SERVER['HTTP_HOST'])?str_replace("http://", "", $cfg_basehost):$_SERVER['HTTP_HOST'];
		$plus = @file_get_contents("http://openapi.dedeapps.com/?m=dedesafer&c=plus&a=getbyname&plus=".$plus."&version=".$cfg_version."&uptime=".$uptime."&host=".$host);
		if(empty($plus)){
			showmsg("连接云接口获取插件详情失败，请稍后再试");
			exit;
		}
		if(strpos($plus, 'invalid')!==false){
				$win = new OxWindow();
				$win->Init("module_main.php?action=uninstall", "js/blank.js", "post");
				$wecome_info = "织梦安全卫士";
				$win->AddMsgItem("<div style='padding-left:10px;line-height:150%;color:red;'>请先授权</div><div style='padding-left:10px;line-height:150%;'>本功能需要授权才能使用，详情请联系客服 QQ:<a href='http://wpa.qq.com/msgrd?v=3&amp;uin=79702151&amp;site=qq&amp;menu=yes' target='_blank'>79702151</a><br>活动：现在购买授权可赠送一次文件鉴定及其它服务9折优惠</div>");
				$winform = $win->GetWindow("hand","");
				$win->Display();
				exit;
		}
		$plus = array_utf82gb( std_class_object_to_array( @json_decode($plus) ) );
		
		switch($plus['act']){
			case "unstall":
					if(is_file(DEDEROOT.$plus['mlist'][0]) || is_dir(DEDEROOT.$plus['mlist'][0])){
						$win = new OxWindow();
						$win->Init("module_main.php?action=uninstall", "js/blank.js", "post");
						$wecome_info = "织梦安全优化";
						$win->AddTitle("<a href='dedesafer.php'>织梦安全优化</a> &gt;&gt; 卸载模块： ");
						$win->AddHidden('hash', $plus['hash']);
						$win->AddMsgItem("<div style='padding-left:10px;line-height:150%;color:red;'>点击确认进入正常卸载流程，请在下一步“对于模块的文件处理方法”中选择“删除模块的所有文件”！</div>");
						$winform = $win->GetWindow("ok","");
						$win->Display();
					}else	if(!empty($plus['hash']) && is_file(DEDEDATA.'/module/'.$plus['hash'].".xml")){
						showmsg("正在安装，请稍后", "module_main.php?action=setup&hash=".$plus['hash']);
					}
			break;
			case "del":
				foreach($plus['mlist'] as $r){
					RmDirFiles(DEDEROOT.$r);
				}
				showmsg("操作成功", $_SERVER['HTTP_REFERER']);
			break;
			case "move":
					if(is_file(DEDEROOT.$plus['mlist'][0]) || is_dir(DEDEROOT.$plus['mlist'][0])){
						if(!is_dir(DEDEDATA.'/safebackup')) mkdir(DEDEDATA.'/safebackup');
						foreach($plus['mlist'] as $file){
							$dirname = dirname(DEDEDATA.'/safebackup'.$file.'.bak');
							if(!is_dir($dirname)) mkdir($dirname);
							rename(DEDEROOT.$file, DEDEDATA.'/safebackup'.$file.'.bak');
						}
						showmsg("操作成功", "dedesafer.php?ac=plus");
					}else if(is_file(DEDEDATA.'/safebackup'.$plus['mlist'][0].'.bak') || is_dir(DEDEDATA.'/safebackup'.$plus['mlist'][0])){
						foreach($plus['mlist'] as $file){
							rename(DEDEDATA.'/safebackup'.$file.'.bak', DEDEROOT.$file);
						}
						showmsg("操作成功", "dedesafer.php?ac=plus");
					}
			break;
			case "close":
				if($cfg_mb_open=='Y'){
					$dsql->ExecuteNoneQuery("update #@__sysconfig set `value`='N' where varname='cfg_mb_open'");
				}else{
					$dsql->ExecuteNoneQuery("update #@__sysconfig set `value`='Y' where varname='cfg_mb_open'");
				}
				ReWriteConfig();
				showmsg("操作成功", "dedesafer.php?ac=plus");
			break;
		}
	break;

	default:
		$mysql_error_trace = DEDEDATA.'/mysql_error_trace.inc';
		$mysqli_error_trace = DEDEDATA.'/mysqli_error_trace.inc';
		$mysql_error_size = 0;
		if(is_file($mysql_error_trace)) $mysql_error_size += filesize($mysql_error_trace);
		if(is_file($mysqli_error_trace)) $mysql_error_size += filesize($mysqli_error_trace);
		
		$log_file = DEDEDATA.'/'.md5($cfg_cookie_encode).'_safe.txt';
		
		$bkdir = DEDEDATA.'/'.$cfg_backup_dir;
        $dh = dir($bkdir);
        while($filename = $dh->read())
        {
            if(preg_match("#txt$#", $filename))
            {
                $filename = $bkdir."/$filename";
				$filemtime = filemtime($filename);
				$bkday = intval((time()-$filemtime)/(3600*24));
				break;
            }
        }
        $dh->close();
		
		$tplcachesize = 0;
		$tpldir = DEDEROOT.$cfg_tplcache_dir;
        $dh = dir($tpldir);
        while($filename = $dh->read())
        {
            if(!preg_match("#inc#", $filename))
            {
                continue;
            }
            $filename = $tpldir."/$filename";
            if(!is_dir($filename))
            {
                $tplcachesize += filesize($filename);
            }
        }
        $dh->close();

		$cururl = GetCurUrl();
		$datadir = str_replace(DEDEROOT, "", DEDEDATA);
		
		include DedeInclude('templets/dedesafer/main.htm');
}

function formatsize($size) {
	$prec=3;
	$size = round(abs($size));
	$units = array(0=>" B ", 1=>" KB", 2=>" MB", 3=>" GB", 4=>" TB");
	if ($size==0) return str_repeat(" ", $prec)."0$units[0]";
	$unit = min(4, floor(log($size)/log(2)/10));
	$size = $size * pow(2, -10*$unit);
	$digi = $prec - 1 - floor(log($size)/log(10));
	$size = round($size * pow(10, $digi)) * pow(10, -$digi);
	return $size.$units[$unit];
}

function array_gb2utf8($arr){
	global $cfg_soft_lang;
	if($cfg_soft_lang!='utf-8'){
		if(is_array($arr)){
			foreach($arr as $k => $v) {
				$arr[$k] = array_gb2utf8( $v );
			}
		}else{
			$arr = gb2utf8( $arr );
		}
	}
	return $arr;
}

function array_utf82gb($arr){
	global $cfg_soft_lang;
	if($cfg_soft_lang=='gb2312'){
		if(is_array($arr)){
			foreach($arr as $k => $v) {
				$arr[$k] = array_utf82gb( $v );
			}
		}else{
			$arr = utf82gb( $arr );
		}
	}
	return $arr;
}

function filechk($indir, $floor=0){
		if($floor>2) return array();
		$dh = dir($indir);
		$i = 0;
		$files = array();
		while($filename = $dh->read())
		{
			$i++;
			if($i>1000) break;
			if($filename == "." || $filename == "..")
			{
				continue;
			}
			else if(is_file("$indir/$filename"))
			{
				if(strpos($indir, '/uploads')!==false && strpos($filename, '.php')!==false){
					$files[] = "$indir/$filename";
				}
				elseif(strpos($filename, '.php')!==false){
					$str = file_get_contents("$indir/$filename");
					if(preg_match("/ev"."al.*(base6"."4_decode|_G"."ET[ ]*\[|_PO"."ST[ ]*\[)/i", $str)){
						$files[] = "$indir/$filename";
					}
				}
				if(strpos($filename, '.asp')!==false){
					$files[] = "$indir/$filename";
				}
			}
			else
			{
				$arr = filechk("$indir/$filename", $floor+1);
				$files = array_merge($files, $arr);
			}
		}
		$dh->close();
		return $files;
}

function std_class_object_to_array($stdclassobject)
{
    $_array = is_object($stdclassobject) ? get_object_vars($stdclassobject) : $stdclassobject;
    foreach ($_array as $key => $value) {
        $value = (is_array($value) || is_object($value)) ? std_class_object_to_array($value) : $value;
        $array[$key] = $value;
    }
    return $array;
}

function RmDirFiles($indir)
{
	if(!is_dir($indir))
	{
		return ;
	}
	$dh = dir($indir);
	while($filename = $dh->read())
	{
		if($filename == "." || $filename == "..")
		{
			continue;
		}
		else if(is_file("$indir/$filename"))
		{
			@unlink("$indir/$filename");
		}
		else
		{
			RmDirFiles("$indir/$filename");
		}
	}
	$dh->close();
	@rmdir($indir);
}

//更新配置函数
function ReWriteConfig()
{
    global $dsql;
	$configfile = DEDEDATA.'/config.cache.inc.php';
    if(!is_writeable($configfile))
    {
        echo "配置文件'{$configfile}'不支持写入，无法修改系统配置参数！";
        exit();
    }
    $fp = fopen($configfile,'w');
    flock($fp,3);
    fwrite($fp,"<"."?php\r\n");
    $dsql->SetQuery("SELECT `varname`,`type`,`value`,`groupid` FROM `#@__sysconfig` ORDER BY aid ASC ");
    $dsql->Execute();
    while($row = $dsql->GetArray())
    {
        if($row['type']=='number')
        {
            if($row['value']=='') $row['value'] = 0;
            fwrite($fp,"\${$row['varname']} = ".$row['value'].";\r\n");
        }
        else
        {
            fwrite($fp,"\${$row['varname']} = '".str_replace("'",'',$row['value'])."';\r\n");
        }
    }
    fwrite($fp,"?".">");
    fclose($fp);
}