<?php
require(dirname(__FILE__) .'/check.php');


switch ($mudi){
	case 'updateWebCache':
		UpdateWebCache();
		break;

	case 'clearWebCache':
		ClearWebCache();
		break;

	case 'updateBackupCall':
		UpdateBackupCall();
		break;

	case 'checkEditorMode':
		CheckEditorMode();
		break;

	case 'readQrCode':
		ReadQrCode();
		break;

	case 'checkHomeHtml':
		CheckHomeHtml();
		break;

	default:
		die('err');
}

$DB->Close();





function UpdateWebCache(){
	global $DB,$mudi,$dbName,$systemArr;

	$mode = OT::GetStr('mode');
	$step = OT::GetStr('step');
	if ($mode == 'verCodeNum'){
		$DB->query('update '. OT_dbPref .'system set SYS_verCodeMode=1 where SYS_ID=1');

	}elseif ($mode == 'defTpl'){
		$DB->query('update '. OT_dbPref .'system set SYS_templateDir="default/" where SYS_ID=1');

	}elseif ($mode == 'showDb'){
		$ver = $DB->GetOne('select VERSION()');
		$mysqlAddi = 'MySQL版本：'. $ver . (version_compare($ver, '5.5.3') < 0 ? '<span style="color:red;">（建议版本≥5.5.3）</span>' : '');

		/* 获取数据库lower_case_table_names信息
		$rs = $DB->GetRow('select @@lower_case_table_names');
		if (isset($rs['@@lower_case_table_names'])){
			die('lower_case_table_names = '. $rs['@@lower_case_table_names']);
		} */
		$rs = $DB->GetRow('show variables like "lower_case_table_names"');	// 大小写敏感
		if (isset($rs['Value'])){
			$tabNameStr = '';
			if ($rs['Value'] == 0){
				$tabNameStr = '区分大小写('. $rs['Value'] .')';
			}elseif ($rs['Value'] == 1){
				$tabNameStr = '不区分大小写，自动小写化['. $rs['Value'] .']';
			}elseif ($rs['Value'] == 2){
				$tabNameStr = '不区分大小写，保留大小写['. $rs['Value'] .']';
			}
			$mysqlAddi .= '&ensp;<span style="color:blue;" title="lower_case_table_names='. $rs['Value'] .'；0 Linux默认值，大小写敏感；1 Windows默认值，大小写不敏感，自动小写化；2 MacOS默认值，大小写不敏感，保持大小写">（表名'. $tabNameStr .'）</span>';
		}

		echo('
		<div style="margin-bottom:6px;">服务器类型：'. PHP_OS .'</div>
		<div style="margin-bottom:6px;">服务器端信息：'. $_SERVER['SERVER_SOFTWARE'] .'</div>
		<div style="margin-bottom:6px;">PHP版本：'. PHP_VERSION . (PHP_VERSION < 5.3 ? '&ensp;<span style="color:red;">（建议PHP版本≥5.3）</span>' : '') .'</div>
		<div style="margin-bottom:6px;">'. $mysqlAddi .'</div>
		<div style="margin-bottom:6px;">程序版本：V'. OT_VERSION .''. OT_VERSION2 .' <span class="font3_2">build '. OT_UPDATETIME .'</span></div>
		<div style="margin-bottom:6px;">数据库版本：[当前]'. $systemArr['SYS_dbTimeStr'] . ($systemArr['SYS_dbTimeStr'] != OT_DBTIME ? ' ≠ [程序]'. OT_DBTIME : '') .'</div>
		');

		$tabNum = 0;
		$tabArr = array();
		$sizeexe = $DB->query("select TABLE_NAME from information_schema.tables where TABLE_SCHEMA = '". $dbName ."'");
			while ($row = $sizeexe->fetch()){
				$tabNum ++;
				$tabArr[] = '`'. $row['TABLE_NAME'] .'`';
				echo('<div>'. str_replace(OT_dbPref,'前缀_',$row['TABLE_NAME']) .'（'. $DB->GetOne('select count(1) from '. $row['TABLE_NAME'] .'') .'）</div>');
			}
		unset($sizeexe);
		$whereStr = implode(',', $tabArr);

		echo('<div>共 <b>'. $tabNum .'</b> 张表</div>');

		$itemName = $sqlStr = '';
		switch ($step){
			case 'check':
				$itemName = '检查';
				$sqlStr = 'CHECK TABLE ';
				break;

			case 'optimize':
				$itemName = '优化';
				$sqlStr = 'OPTIMIZE TABLE ';
				break;

			case 'repair':
				$itemName = '修复';
				$sqlStr = 'REPAIR TABLE ';
				break;

			case 'analyze':
				$itemName = '分析';
				$sqlStr = 'ANALYZE TABLE ';
				break;
		}

		if (strlen($itemName) > 0){
			$showStr = '';
			$judRes = $DB->query($sqlStr . $whereStr);
			if ($judRes){
				if ($row = $judRes->fetchAll()){
					$number = 0;
					$titleStr = '
						<table cellpadding="3" cellspacing="2" class="tabList1 padd8td" style="margin-top:5px;">
						<tr>
							<td align="center">编号</td>
							';
					foreach($row as $val){
						$number ++;
						$showStr .= '
							<tr>
								<td align="center">'. $number .'</td>
								';
						foreach($val as $key => $val2){
							if ($number == 1){ $titleStr .= '<td align="center">'. $key .'</td>'; }
							$showStr .= '<td>'. $val2 .'</td>';
						}
						if ($number == 1){ $titleStr .= '</tr>'; }
						$showStr .= '</tr>';
					}
					$showStr = $titleStr . $showStr .'</table>';
				}
			}else{
				$showStr = $itemName .' '. $whereStr .' 执行失败！';
			}

			if (strlen($showStr) > 5){
				echo('
				<div style="padding:10px;font-size:14px;">
				返回结果：'. $showStr .'<br />
				<div style="margin-top:15px;"><b>'. $itemName .'表 执行完毕</b>。</div>
				</div>
				');
			}
		}

	}elseif ($mode == 'revTabName'){
		$mudi2 = OT::GetStr('mudi2');

		$DB->SetAttr('noErr');	// 执行SQL语句关闭错误提示

		$tabArr = array(
			'ad', 'addiData', 'apiItem', 'apiRecord', 'apiSys', 'apiUsers', 'apiUsersLog', 'appField', 'appSys', 'audioVideo', 'authSoft', 'authSys', 'authUsers', 'autoRunLog', 'autoRunSys', 
			'agentPrice', 'agentUserOnline', 'agentUsers', 
			'banner', 'bbsData', 'bbsReply', 'bbsSys', 'bbsType', 'buyOrders', 'buySys', 
			'caData', 'caGroup', 'caType', 'collHistory', 'collItem', 'collResult', 'collSys', 'collType', 
			'dashang', 'dbBak', 'dbErr', 'diyPayData', 'diyPayList', 'diyPaySys', 
			'dialingCity', 'dialingData', 'dialingProv', 'dialingTixing', 'dialingUsers', 'domainApi', 'domainCart', 'domainData', 'domainPrice', 'domainSys', 'domainTpl', 
			'fileData', 'fileVer', 'formField', 'formType', 'formUsers', 
			'gainHistory', 'gainItem', 'gainMoney', 'getGift', 'getUsers', 'giftData', 'giftSys', 'giftUsers', 'goUrl', 'goUrlBrowser', 'goUrlUsers', 
			'htmlFile', 
			'homePro', 'hostData', 'hostTixing', 'hostUsers', 
			'info', 'infoContent1', 'infoContent2', 'infoContent3', 'infoContent4', 'infoContent5', 'infoContent6', 'infoContent7', 'infoContent8', 'infoContent9', 'infoContent10', 'infoContent11', 'infoContent12', 'infoContent13', 'infoContent14', 'infoContent15', 'infoContent16', 'infoContent17', 'infoContent18', 'infoContent19', 'infoContent20', 'infoContent21', 'infoContent22', 'infoContent23', 'infoContent24', 'infoContent25', 'infoContent26', 'infoContent27', 'infoContent28', 'infoContent29', 'infoContent30', 'infoDown', 'infoImport', 'infoMessage', 'infoMove', 'infoPayData', 'infoSys', 'infoTheme', 'infoType', 'infoView', 'infoWeb', 
			'idcLoginCode', 'idcMoneyData', 'idcProData', 'idcProGroup', 'idcProSys', 'idcProType', 'idcServData', 'idcServIp', 'idcServList', 'idcServLog', 'idcServOs', 'idcServPro', 'idcServSys', 'idcServVps', 'idcUsers', 'idcVpsDel', 
			'jingancode', 
			'keyWord', 
			'mailCode', 'mailInfo', 'mailTpl', 'mailUsers', 'makeDiy', 'member', 'memberGroup', 'memberLog', 'memberOnline', 'menuFile', 'menuTree', 'message', 'moneyGive', 'moneyLog', 'moneyPay', 'moneyQuick', 'moneyRecord', 'moneySys', 'moneyTime', 
			'onePage', 'oneWebTpl', 'oneWebType', 'oneWebUsers', 
			'paySoft', 'paySoftPack', 'phoneCode', 'phoneSys', 'phoneTpl', 'phoneUsers', 'photoLog', 'photoRecord', 'photoSize', 'photoSys', 'planData', 'postLogin', 'provCity', 
			'pptpData', 'pptpTixing', 'pptpUsers', 
			'qiandaoSys', 'qrcode', 'qrcodeImg', 'quanData', 'quanSell', 'quanSys', 'qunData', 'qunType', 
			'report', 'robotData', 'robotList', 'robotSys', 
			'siteLogin', 'siteMessage', 'siteMessageReply', 'sysAdmin', 'sysImages', 'sysParam', 'system', 
			'servData', 'servTixing', 'servUsers', 'siteIpDomain', 'sslData', 'sslTixing', 'sslUsers', 
			'tabField', 'tag', 'template', 'tplSys', 'type', 
			'tixing', 
			'upFile', 'urlNav', 
			'userApi', 'userFile', 'userGroup', 'userIp', 'userLevel', 'userLog', 'userMark', 'userMoney', 'userOnline', 'users', 'userScore', 'userSys', 'userTemp', 'userView', 
			'vpsApi', 'vpsApiData', 'vpsApiTixing', 'vpsApiUsers', 'vpsClass', 'vpsCompany', 'vpsDealerList', 'vpsDelUsers', 'vpsProData', 'vpsProTixing', 'vpsProUsers', 'vpsRecord', 'vpsSys', 'vpsType', 
			'workOrder', 'workOrderReply', 'xingwaiServ', 
			'wap', 'weixinAdmin', 'weixinFormField', 'weixinFormType', 'weixinFormUsers', 'weixinInfo', 'weixinLog', 'weixinMenu', 'weixinNews', 'weixinOther', 'weixinQrcode', 'weixinSys', 'weixinTpl', 'weixinTplSend', 'weixinTplSet', 'weixinUserGroup', 'weixinUserLog', 'weixinUsers', 'weixinWordContent', 'weixinWordKey', 'workData', 'workUsers', 
			'xcxAdOrder', 'xcxAdSys', 'xcxAdWord', 'xcxApiUsers', 'xcxBaby', 'xcxBabyDeve', 'xcxBabyFeed', 'xcxBabyNote', 'xcxDingyue', 'xcxDingyueSet', 'xcxFamily', 'xcxLog', 'xcxMessage', 'xcxPhotoSys', 'xcxShopGoods', 'xcxShopOrder', 'xcxShopOrderGoods', 'xcxShopType', 'xcxSys', 'xcxTixing', 'xcxUsers', 'xcxUsersBaby', 'xcxYaopin'
			);

			// 'actSys', 'job', 'jobUser', 'robotData', 'robotNum', 'robotPR', 'robotRank', 'robotSys', '', '', '', '', '', '', '', '', ''
		if ((strpos(PHP_OS, 'WINNT') !== false && strpos($_SERVER['SERVER_SOFTWARE'], 'IIS') !== false) || in_array($step,array('one','two'))){
			echo("<div>【分两步修改表名】</div>");
			if ($step != 'two'){
				foreach ($tabArr as $val){
					$DB->query("ALTER TABLE ". strtolower(OT_dbPref . $val) ." RENAME TO ". OT_dbPref . $val ."_gai");
					/* echo("<div>ALTER TABLE ". strtolower(OT_dbPref . $val) ." RENAME TO ". OT_dbPref . $val ."_gai;</div>"); */
				}
				JS::HrefTimeoutEnd('?mudi='. $mudi .'&mode='. $mode .'&step=two',3);
			}else{
				foreach ($tabArr as $val){
					$DB->query("ALTER TABLE ". OT_dbPref . $val ."_gai RENAME TO ". OT_dbPref . $val);
					/* echo("<div>ALTER TABLE ". OT_dbPref . $val ."_gai RENAME TO ". OT_dbPref . $val .";</div>"); */
				}
			}
		}else{
			echo("<div>【直接修改表名】</div>");
			foreach ($tabArr as $val){
				$DB->query("ALTER TABLE ". strtolower(OT_dbPref . $val) ." RENAME TO ". OT_dbPref . $val);
			}
		}
		echo('<div>修改表名大小写完成，现在到数据库管理里看看。'. ($mudi2 == 'db' ? '<a href="sysCheckFile.php?mudi=db" style="color:red;">【返回】</a>' : '') .'</div>');

	}

	$Cache = new Cache();
	$Cache->Php('appSys');
	$Cache->Js('appSys');
	$Cache->Php('autoRunSys');
	$Cache->Js('autoRunSys');
	$Cache->Php('infoSys');
	$Cache->Js('infoSys');
	$Cache->Php('idcProSys');
	$Cache->Php('sysAdmin');
	$Cache->Php('sysImages');
	$Cache->Php('system');
	$Cache->Js('system');
	$Cache->Php('tplSys');
	$Cache->Js('tplSys');
	$Cache->Php('userSys');
	$Cache->Js('userSys');
	$Cache->Php('vpsSys');

	$fileResStr = '';
	// 节日倒计时
	if ( AppJieri::Jud() ){
		if ( AppJieri::UpdateJsCache() ){
			$fileResStr .= '，jieri.js 生成成功！';
		}else{
			$fileResStr .= '，jieri.js 生成失败！';
		}
	}
	// 前台js集缓存
	if ( Cache::UpdateConfigJs() ){
		$fileResStr .= '，configJs.js 生成成功！';
	}else{
		$fileResStr .= '，configJs.js 生成失败！';
	}

	$pluStr = '';
	if (AreaApp::Jud(9)){
		$pluStr .= '【简易小论坛】';
		$Cache->Php('bbsSys');
	}
	if (AreaApp::Jud(42)){
		$pluStr .= '【会员订单记录】';
		$Cache->Php('buySys');
	}
	if (AreaApp::Jud(5)){
		$pluStr .= '【采集基础包】';
		$Cache->Php('collSys');
	}
	if (AreaApp::Jud(105)){
		$pluStr .= '【扫码充值手动录入】';
		$Cache->Php('diyPaySys');
	}
	if (AreaApp::Jud(28)){
		$pluStr .= '【积分商城】';
		$Cache->Php('giftSys');
	}
	$appArr = AreaApp::IdNameArr('money');
	if (AreaApp::Jud($appArr['id'])){
		$pluStr .= '【财务基础包】';
		$Cache->Php('moneySys');
	}
	if (AreaApp::Jud(56)){
		$pluStr .= '【短信验证通知】';
		$Cache->Php('phoneSys');
	}
	if (AreaApp::Jud(47)){
		$pluStr .= '【会员打卡签到】';
		$Cache->Php('qiandaoSys');
	}
	if (AreaApp::Jud(54)){
		$pluStr .= '【卡密卡券】';
		$Cache->Php('quanSys');
	}
	if (AreaApp::Jud(10)){
		$pluStr .= '【淘宝客基础包】';
		$Cache->Php('taokeSys');
	}
	if (AppWap::Jud()){
		$pluStr .= '【WAP手机版】';
		$DB->query('update '. OT_dbPref .'wap set WAP_htmlCacheTime='. $DB->ForTime(TimeDate::Get()));
		$Cache->Php('wap');
	}
	if (strlen($pluStr) > 0){
		$pluStr = '，其中插件更新缓存有：'. $pluStr;
	}

	File::DelDir(OT_ROOT .'cache/smarty/templates_c/', false);	// 删除smarty模板缓存
	Ca::MakeJs();	// 生成广告缓存
	// AdmArea::MakeSiteCss();	// 生成 cache/web/site.css 文件

	JS::AlertEnd('更新配置缓存文件完成'. $fileResStr);	//  . $pluStr
}



// 清空缓存
function ClearWebCache(){
	$mode = OT::GetStr('mode');

	$webCacheNum = File::Count(OT_ROOT .'cache/html/',array('html','png'));

	if ($webCacheNum>0){
		$retNum = File::MoreDel(OT_ROOT .'cache/html/',array('html','png'));

		if ($mode != 'noAlert'){
			echo('alert("共清空了'. $retNum .'个缓存。");');
		}
	}else{
		if ($mode != 'noAlert'){
			echo('alert("暂无页面缓存，无需清理。");');
		}
	}
/*
	global $DB;

	$todayTime = TimeDate::Get();
	$DB->query('update '. OT_dbPref .'system set SYS_htmlCacheTime='. $DB->ForTime($todayTime));

	$Cache = new Cache();
	$Cache->Php('system');

	if ($mode != 'noAlert'){
		echo('alert("页面缓存已更新'. $todayTime .'.");');
	}
*/

}



function UpdateBackupCall(){
	global $DB,$sysAdminArr;

	$num = OT::GetInt('num');

	$newDate = '';
	switch ($num){
		case -1:
			$newDate=TimeDate::Get('date');
			break;

		case 1:
			$newDate=TimeDate::Add('d',1-$sysAdminArr['SA_backupCallDay'],TimeDate::Get('date'));
			break;

		case 7:
			$newDate=TimeDate::Add('d',7-$sysAdminArr['SA_backupCallDay'],TimeDate::Get('date'));
			break;

	}
	if (strtotime($newDate)){
		$DB->query('update '. OT_dbPref .'sysAdmin set SA_backupCallTime='. $DB->ForTime($newDate) .' where SA_ID=1');
	}
	
	$Cache = new Cache();
	$Cache->Php('sysAdmin');
}



function CheckEditorMode(){
	$editorMode = OT::GetStr('editorMode');

	switch ($editorMode){
		case 'tinymce':
			$fileStr = File::Read(OT_adminROOT .'tools/tinymce/tinymce.min.js');
			if (strlen($fileStr)<=15){
				die(''.
				'alert("未检测到tinyMCE编辑器，请确定存在【后台目录/tools/tinymce/】该目录");'.
				'$id("editorMode1").checked=true;'.
				'');
			}
			break;

		case 'tinymce5':
			$fileStr = File::Read(OT_adminROOT .'tools/tinymce5/tinymce.min.js');
			if (strlen($fileStr)<=15){
				die(''.
				'alert("未检测到tinyMCE5编辑器，请确定存在【后台目录/tools/tinymce5/】该目录");'.
				'$id("editorMode1").checked=true;'.
				'');
			}
			break;

		case 'kindeditor4':
			$fileStr = File::Read(OT_adminROOT .'tools/kindeditor4/kindeditor-all-min.js');
			if (strlen($fileStr)<=15){
				die(''.
				'alert("未检测到KindEditor4编辑器，请确定存在【后台目录/tools/kindeditor4/】该目录");'.
				'$id("editorMode1").checked=true;'.
				'');
			}
			break;

		case 'kindeditor3':
			$fileStr = File::Read(OT_adminROOT .'tools/kindeditor3/kindeditor-min.js');
			if (strlen($fileStr)<=15){
				die(''.
				'alert("未检测到Kindeditor3编辑器，请确定存在【后台目录/tools/kindeditor3/】该目录");'.
				'$id("editorMode1").checked=true;'.
				'');
			}
			break;

		case 'ckeditor4':
			$fileStr = File::Read(OT_adminROOT .'tools/ckeditor4/ckeditor.js');
			if (strlen($fileStr)<=15){
				die(''.
				'alert("未检测到CKEditor4编辑器，请确定存在【后台目录/ckeditor4/】该目录");'.
				'$id("editorMode1").checked=true;'.
				'');
			}
			break;

		case 'ckeditor3':
			$fileStr = File::Read(OT_adminROOT .'tools/ckeditor3/ckeditor.js');
			if (strlen($fileStr)<=15){
				die(''.
				'alert("未检测到CKEditor3编辑器，请确定存在【后台目录/ckeditor3/】该目录");'.
				'$id("editorMode1").checked=true;'.
				'');
			}
			break;

		case 'fckeditor':
			$fileStr = File::Read(OT_adminROOT .'tools/fckeditor/fckeditor.js');
			if (strlen($fileStr)<=15){
				die(''.
				'alert("未检测到FCKeditor编辑器，请确定存在【后台目录/fckeditor/】该目录");'.
				'$id("editorMode1").checked=true;'.
				'');
			}
			break;

		case 'ueditor':
			$fileStr = File::Read(OT_adminROOT .'tools/ueditor/ueditor.config.js');
			if (strlen($fileStr)<=15){
				die(''.
				'alert("未检测到ueditor编辑器，请确定存在【后台目录/tools/ueditor/】该目录");'.
				'$id("editorMode1").checked=true;'.
				'');
			}
			break;

		default :
			die(''.
			'alert("未知编辑器.");'.
			'$id("editorMode1").checked=true;'.
			'');
	}
}


function ReadQrCode(){
	$dir = OT::GetStr('dir');
	$img = OT::GetStr('img');
	if (strlen($img) == 0){ die('二维码图片路径为空'); }
	if (! Is::HttpUrl($img)){
		$img = StrInfo::FilePath($dir, $img);
		if (! file_exists($img)){ die('二维码图片不存在('. $img .')'); }
	}

	include_once(OT_ROOT .'inc/QrReader/QrReader.php');
	$qrcode = new QrReader($img);	// 图片路径
	$text = $qrcode->text();		//返回识别后的文本
	if (strlen($text) == 0){ die('二维码图片识别不了'); }
	die($text);
}


function CheckHomeHtml(){
	global $systemArr;
	$beforeURL	= GetUrl::CurrDir(1);
	$webHtml = new WebHtml();
	$homeHtmlStr = $webHtml->GetCode($beforeURL);
	if (strpos($homeHtmlStr,'<!-- Html For') !== false){
		JS::AlertEnd('网站首页是静态页.');
	}else{
		JS::AlertEnd('网站首页不是静态页，您静态页名是 '. $systemArr['SYS_htmlHomeName'] .'.\n1、检查前台'. $systemArr['SYS_htmlHomeName'] .'文件是否存在。\n2、首页默认页'. $systemArr['SYS_htmlHomeName'] .'要优先于index.php');
	}
}

?>