<?php
!defined('P_W') && exit('Forbidden');

$updatecache = false;
$query = $db->query("SELECT db_name,db_value FROM pw_config WHERE db_name='db_siteid' OR db_name='db_siteownerid' OR db_name='db_sitehash'");
while ($rt = $db->fetch_array($query)) {
	if (($rt['db_name']=='db_siteid' && $rt['db_value']!=$db_siteid) || ($rt['db_name']=='db_siteownerid' && $rt['db_value']!=$db_siteownerid) || ($rt['db_name']=='db_sitehash' && $rt['db_value']!=$db_sitehash)) {
		${$rt['db_name']} = preg_replace('/[^\d\w\_]/is','',$rt['db_value']);
		$updatecache = true;
	}
}
$db->free_result($query);
if (!$db_siteid) {
	$db_siteid = generatestr(16);
	$db->update("REPLACE INTO pw_config SET db_name='db_siteid',db_value=".pwEscape($db_siteid,false));

	$db_siteownerid = generatestr(18);
	$db->update("REPLACE INTO pw_config SET db_name='db_siteownerid',db_value=".pwEscape($db_siteownerid,false));

	$db_sitehash = '10'.SitStrCode(md5($db_siteid.$db_siteownerid),md5($db_siteownerid.$db_siteid));
	$db->update("REPLACE INTO pw_config SET db_name='db_sitehash',db_value=".pwEscape($db_sitehash,false));
	$updatecache = true;
}
$updatecache && updatecache_c();

!$action && $action='info';
${'cls_'.$action} = 'class="two"';
if ($action=='modify') {
	if ($_POST['step']==2) {
		InitGP(array('siteid','siteownerid','sitehash'));
		if (!$siteid || !$siteownerid || !$sitehash) {
			adminmsg('adcode_error');
		}
		if ($sitehash != '10'.SitStrCode(md5($siteid.$siteownerid),md5($siteownerid.$siteid))) {
			adminmsg('adcode_error');
		}
		$db->update("REPLACE INTO pw_config SET db_name='db_siteid',db_value=".pwEscape($siteid));
		$db->update("REPLACE INTO pw_config SET db_name='db_siteownerid',db_value=".pwEscape($siteownerid));
		$db->update("REPLACE INTO pw_config SET db_name='db_sitehash',db_value=".pwEscape($sitehash));
		updatecache_c();
		adminmsg('operate_success');
	}
} elseif (!in_array($action,array('key','info'))) {
	ObHeader($basename);
}
include PrintEot('code');exit;
function generatestr($len) {
	mt_srand((double)microtime()*1000000);
    $keychars = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWYXZ";
	$maxlen = strlen($keychars)-1;
	$str = '';
	for ($i=0;$i<$len;$i++){
		$str .= $keychars[mt_rand(0,$maxlen)];
	}
	return substr(md5($str.time().$GLOBALS['pwServer']["HTTP_USER_AGENT"].$GLOBALS['db_hash']),0,$len);
}
function SitStrCode($string,$key,$action='ENCODE'){
	$string	= $action == 'ENCODE' ? $string : base64_decode($string);
	$len	= strlen($key);
	$code	= '';
	for($i=0; $i<strlen($string); $i++){
		$k		= $i % $len;
		$code  .= $string[$i] ^ $key[$k];
	}
	$code = $action == 'DECODE' ? $code : str_replace('=','',base64_encode($code));
	return $code;
}
?>