<?php

/*
	[Discuz!] (C)2001-2006 Comsenz Inc.
	This is NOT a freeware, use is subject to license terms

	$RCSfile: global.func.php,v $
	$Revision: 1.90.2.3 $
	$Date: 2006/09/30 01:56:56 $
*/

if(!defined('IN_DISCUZ') || !isset($PHP_SELF) || !preg_match("/[\/\\\\]admincp\.php$/", $PHP_SELF)) {
        exit('Access Denied');
}

@set_time_limit(600);

function cpmsg($message, $url_forward = '', $msgtype = 'message', $extra = '') {
	extract($GLOBALS, EXTR_SKIP);
	eval("\$message = \"".(isset($msglang[$message]) ? $msglang[$message] : $message)."\";");

	if($msgtype == 'form') {
			$message = "<form method=\"post\" action=\"$url_forward\"><input type=\"hidden\" name=\"formhash\" value=\"".FORMHASH."\">".
				"<br><br><br>$message$extra<br><br><br><br>\n".
        			"<input class=\"button\" type=\"submit\" name=\"confirmed\" value=\"$lang[ok]\"> &nbsp; \n".
       				"<input class=\"button\" type=\"button\" value=\"$lang[cancel]\" onClick=\"history.go(-1);\"></form><br>";
	} else {
		if($url_forward) {
			$message .= "<br><br><br><a href=\"$url_forward\">$lang[message_redirect]</a>";
			$url_forward = transsid($url_forward);
			$message .= "<script>setTimeout(\"redirect('$url_forward');\", 1250);</script>";
		} elseif(strpos($message, $lang['return'])) {
			$message .= "<br><br><br><a href=\"javascript:history.go(-1);\" class=\"mediumtxt\">$lang[message_return]</a>";
		}
		$message = "<br><br><br>$message$extra<br><br>";
	}

?>
<br><br><br><br><br><br>
<table width="500" border="0" cellpadding="0" cellspacing="0" align="center" class="tableborder">
<tr class="header"><td><?=$lang['discuz_message']?></td></tr><tr><td class="altbg2"><div align="center">
<?=$message?></div><br><br>
</td></tr></table>
<br><br><br>
<?

	cpfooter();
	dexit();
}

function istpldir($dir) {
	return is_dir(DISCUZ_ROOT.'./'.$dir) && !in_array(substr($dir, -1, 1), array('/', '\\')) &&
		 strpos(realpath(DISCUZ_ROOT.'./'.$dir), realpath(DISCUZ_ROOT.'./templates')) === 0;
}

function isplugindir($dir) {
	return !$dir || (!preg_match("/(\.\.|[\\\\]+$)/", $dir) && substr($dir, -1) =='/');
}

function ispluginkey($key) {
	return preg_match("/^[a-z]+[a-z0-9_]*$/i", $key);
}

function dir_writeable($dir) {
	if(!is_dir($dir)) {
		@mkdir($dir, 0777);
	}
	if(is_dir($dir)) {
		if($fp = @fopen("$dir/test.test", 'w')) {
			@fclose($fp);
			@unlink("$dir/test.test");
			$writeable = 1;
		} else {
			$writeable = 0;
		}
	}
	return $writeable;
}

function hookselect($hooksarray, $title = '') {
	$hookselect = '';
	foreach($hooksarray as $group => $hooks) {
		$hookselect .= "<optgroup label=\"$group\">";
		foreach($hooks as $hook) {
			$hookselect .= "<option value=\"$hook\" ".($title && $title == $hook ? 'selected' : '').">$hook</option>";
		}
		$hookselect .= "</optgroup>";
	}
	return $hookselect;
}

function showforum($key, $type = '') {
	global $forums, $showedforums, $lang, $indexname;

	$forum = $forums[$key];
	$showedforums[] = $key;

	return '<li><a href="'.($type == 'group' ? './'.$indexname.'?gid='.$forum['fid'] : './forumdisplay.php?fid='.$forum['fid']).'" target="_blank"><b>'.$forum['name'].'</b><span class="smalltxt">'.
		($forum['status'] ? '' : ' ('.$lang['forums_hidden'].')').'</span></a> - '.
		$lang['display_order'].': <input type="text" name="order['.$forum['fid'].']" value="'.$forum['displayorder'].'" size="1"> - '.
		($type != 'sub' ? '<a href="admincp.php?action=forumadd&fupid='.$forum['fid'].'" title="'.$lang['forums_add_comment'].'">['.$lang['forums_add'].']</a> ' : '').
		'<a href="admincp.php?action=forumdetail&fid='.$forum['fid'].'" title="'.$lang['forums_edit_comment'].'">['.$lang['edit'].']</a>'.
		($type != 'group' ? ' <a href="admincp.php?action=forumcopy&source='.$forum['fid'].'" title="'.$lang['forums_copy_comment'].'">['.$lang['forums_copy'].']</a> ' : ' ').
		'<a href="admincp.php?action=forumdelete&fid='.$forum['fid'].'" title="'.$lang['forums_delete_comment'].'">['.$lang['delete'].']</a> - '.
		'<a href="admincp.php?action=moderators&fid='.$forum['fid'].'" title="'.$lang['forums_moderators_comment'].'">['.$lang['forums_moderators'].($forum['moderators'] ? ': '.str_replace("\t", ', ', $forum['inheritedmod'] ? '<b>'.$forum['moderators'].'</b>' : $forum['moderators']) : '').']</a>'.
		'<br></li>';
}

function showtype($name, $type = '', $submit = '') {
	$name = $GLOBALS['lang'][$name] ? $GLOBALS['lang'][$name] : $name;
	$id = substr(md5($name), 16);
	$submithtml = $submit ? '<center><input class="button" type="submit" name="'.$submit.'" value="'.$GLOBALS['lang']['submit'].'"></center>' : '';
	if($type != 'bottom') {
		if(!$type) {
			echo '</table><br>';
		}
		if(!$type || $type == 'top') {

?>
<a name="<?=$id?>"></a>
<table width="100%" border="0" cellpadding="0" cellspacing="0" class="tableborder">
<tr class="header">
<td colspan="2"><?=$name?>
<a href="###" onclick="collapse_change('<?=$id?>')"><img id="menuimg_<?=$id?>" src="./images/admincp/menu_reduce.gif" border="0"/ style="float: right; margin-top: -12px; margin-right: 8px;"></a>
</td>
</tr>
<tbody id="menu_<?=$id?>" style="display: yes">
<?

		}
	} else {
		echo '</tbody></table>'.$submithtml;
	}
}

function showsetting($setname, $varname, $value, $type = 'radio', $width = '60%') {
	$check = array();
	$comment = $GLOBALS['lang'][$setname.'_comment'];

	$aligntop = $type == "textarea" || $width != "60%" ?  "valign=\"top\"" : NULL;
	echo "<tr><td width=\"$width\" class=\"altbg1\" $aligntop>".
		'<b>'.(isset($GLOBALS['lang'][$setname]) ? $GLOBALS['lang'][$setname] : $setname).'</b>'.($comment ? '<br><span class="smalltxt">'.$comment.'</span>' : NULL).'</td>'.
		'<td class="altbg2">';

	if($type == 'radio') {
		$value ? $check['true'] = "checked" : $check['false'] = "checked";
		echo "<input class=\"radio\" class=\"radio\" type=\"radio\" name=\"$varname\" value=\"1\" $check[true]> {$GLOBALS[lang][yes]} &nbsp; &nbsp; \n".
			"<input class=\"radio\" class=\"radio\" type=\"radio\" name=\"$varname\" value=\"0\" $check[false]> {$GLOBALS[lang][no]}\n";
	} elseif($type == 'radioplus') {
		$value == -1 ? $check['default'] = 'checked' : ($value ? $check['true'] = 'checked' : $check['false'] = 'checked');
		echo "<input class=\"radio\" class=\"radio\" type=\"radio\" name=\"$varname\" value=\"-1\" $check[default]> ".$GLOBALS['lang']['default']." &nbsp; &nbsp; \n".
			"<input class=\"radio\" class=\"radio\" type=\"radio\" name=\"$varname\" value=\"1\" $check[true]> {$GLOBALS[lang][yes]} &nbsp; &nbsp; \n".
			"<input class=\"radio\" class=\"radio\" type=\"radio\" name=\"$varname\" value=\"0\" $check[false]> {$GLOBALS[lang][no]}\n";
	} elseif($type == 'color') {
		global $stylestuff;
		$preview_varname = str_replace('[', '_', str_replace(']', '', $varname));
		$background = strexists($value, '.') ? "url('".$stylestuff['imgdir']['subst']."/$value')" : $value;
		echo "<input type=\"text\" size=\"30\" value=\"$value\" name=\"$varname\" onchange=\"if (this.value.indexOf('.')==-1) this.form.$preview_varname.style.background=this.value; else this.form.$preview_varname.style.background='url(".$stylestuff['imgdir']['subst']."/'+this.value+')'\">\n".
			"<input type=\"button\" id=\"$preview_varname\" value=\"\" style=\"width: 20px;background: $background\" disabled>\n";
	} elseif($type == 'text' || $type == 'password') {
		echo "<input type=\"$type\" size=\"30\" name=\"$varname\" value=\"".dhtmlspecialchars($value)."\">\n";
	} elseif($type == 'calendar') {
		echo "<input type=\"$type\" size=\"30\" name=\"$varname\" value=\"".dhtmlspecialchars($value)."\" onclick=\"showcalendar(event, this)\">\n";
	} elseif($type == 'textarea') {
		echo "<img src=\"images/admincp/zoomin.gif\" onmouseover=\"this.style.cursor='hand'\" onclick=\"zoomtextarea('$varname', 1)\"> <img src=\"images/admincp/zoomout.gif\" onmouseover=\"this.style.cursor='hand'\" onclick=\"zoomtextarea('$varname', 0)\"><br><textarea rows=\"5\" name=\"$varname\" id=\"$varname\" cols=\"30\">".dhtmlspecialchars($value)."</textarea>";
	} else {
		echo $type;
	}
	echo '</td></tr>';
}

function showmenu($title, $menus = array()) {
	global $menucount, $collapse;

	echo '<table width="146" border="0" cellspacing="0" align="center" cellpadding="0" class="leftmenulist" style="margin-bottom: 5px;">';
	if(is_array($menus)) {
		$menucount++;
		$collapsed = preg_match("/\[$menucount\]/", $collapse);

		echo 	'<tr class="leftmenutext"><td><a href="###" onclick="collapse_change('.$menucount.')"><img id="menuimg_'.$menucount.'" src="./images/admincp/menu_'.($collapsed ? 'add' : 'reduce').'.gif" border="0"/></a>&nbsp;'.
			'<a href="###" onclick="collapse_change('.$menucount.')">'.$title.'</a></td></tr>'.
			'<tbody id="menu_'.$menucount.'" style="display:'.($collapsed ? 'none' : '').'">'.
		 	'<tr class="leftmenutd"><td><table border="0" cellspacing="0" cellpadding="0" class="leftmenuinfo">';

		foreach($menus as $menudata) {
			echo '<tr><td><a href="'.$menudata['url'].'" target="main">'.$menudata['name'].'</a></td></tr>';
		}
		echo '</table></td></tr></tbody>';
	} else {
		echo "<tr class=\"leftmenutext\"><td><img src=\"./images/admincp/menu_reduce.gif\" />&nbsp;<a href=\"$menus\" target=\"main\">$title</a></td></tr>\n";
	}
	echo "</table>\n";
}

function showtips($tips) {
	global $_DCOOKIE;

	$tips = isset($GLOBALS['lang'][$tips]) ? $GLOBALS['lang'][$tips] : $tips;
	$collapsed = preg_match("/\[tip\]/", $_DCOOKIE['collapse']);

	echo 	'<table width="100%" border="0" cellpadding="0" cellspacing="0" class="tableborder">'.
		'<tr class="header"><td><div style="float:left; margin-left:0px; padding-top:8px"><a href="###" onclick="collapse_change(\'tip\')">'.$GLOBALS['lang']['tips'].'</a></div><div style="float:right; margin-right:4px; padding-bottom:9px">'.
		'<a href="###" onclick="collapse_change(\'tip\')"><img id="menuimg_tip" src="./images/admincp/menu_'.($collapsed ? 'add' : 'reduce').'.gif" border="0"/></a></div>'.
		'</td></tr><tbody id="menu_tip" style="display:'.($collapsed ? 'none' : '').'"><tr><td>'.$tips.'</td></tr></tbody></table><br />';
}

function shownav($navs) {
	$navs = isset($GLOBALS['lang'][$navs]) ? $GLOBALS['lang'][$navs] : $navs;
	echo 	'<table width="100%" border="0" cellpadding="0" cellspacing="0" class="guide">'.
		'<tr><td><a href="#" onClick="parent.menu.location=\'admincp.php?action=menu\'; parent.main.location=\'admincp.php?action=home\';return false;">'.$GLOBALS['lang']['header_system'].'</a>&nbsp;&raquo;&nbsp;'.$navs.'</td></tr></table><br />';
}

function sqldumptable($table, $startfrom = 0, $currsize = 0) {
	global $db, $sizelimit, $startrow, $extendins, $sqlcompat, $sqlcharset, $dumpcharset, $usehex;

	$offset = 300;
	$tabledump = '';

	if(!$startfrom) {

		$tabledump = "DROP TABLE IF EXISTS $table;\n";

		$createtable = $db->query("SHOW CREATE TABLE $table");
		$create = $db->fetch_row($createtable);

		$tabledump .= $create[1];

		if($sqlcompat == 'MYSQL41' && $db->version() < '4.1') {
			$tabledump = preg_replace("/TYPE\=(.+)/", "ENGINE=\\1 DEFAULT CHARSET=".$dumpcharset, $tabledump);
		}
		if($db->version() > '4.1' && $sqlcharset) {
			$tabledump = preg_replace("/(DEFAULT)*\s*CHARSET=.+/", "DEFAULT CHARSET=".$sqlcharset, $tabledump);
		}

		$query = $db->query("SHOW TABLE STATUS LIKE '$table'");
		$tablestatus = $db->fetch_array($query);
		$tabledump .= ($tablestatus['Auto_increment'] ? " AUTO_INCREMENT=$tablestatus[Auto_increment]" : '').";\n\n";
		if($sqlcompat == 'MYSQL40' && $db->version() >= '4.1') {
			if($tablestatus['Auto_increment'] <> '') {
				$temppos = strpos($tabledump, ',');
				$tabledump = substr($tabledump, 0, $temppos).' auto_increment'.substr($tabledump, $temppos);
			}
			if($tablestatus['Engine'] == 'MEMORY') {
				$tabledump = str_replace('TYPE=MEMORY', 'TYPE=HEAP', $tabledump);
			}
		}
	}

	$tabledumped = 0;
	$numrows = $offset;
	if($extendins =='0') {
		while($currsize + strlen($tabledump) < $sizelimit * 1000 && $numrows == $offset) {
			$tabledumped = 1;
			$rows = $db->query("SELECT * FROM $table LIMIT $startfrom, $offset");
			$numfields = $db->num_fields($rows);
			if($usehex) {
				$fields=$db->query("SHOW FIELDS FROM $table");
				while ($fieldrows = $db->fetch_row($fields)) {
					$stringfield[] = preg_match('/char|text/i', $fieldrows[1]);
				}
			}
			$numrows = $db->num_rows($rows);
			while($row = $db->fetch_row($rows)) {
				$comma = '';
				$tabledump .= "INSERT INTO $table VALUES (";
				for($i = 0; $i < $numfields; $i++) {
					$tabledump .= $comma.($usehex ? ($row[$i] != '' && $stringfield[$i] ? '0x'.bin2hex($row[$i]) : '\''.$row[$i].'\'') : '\''.mysql_escape_string($row[$i]).'\'');
					$comma = ',';
				}
				$tabledump .= ");\n";
			}
			$startfrom += $offset;
		}
	} else {
		while($currsize + strlen($tabledump) < $sizelimit * 1000 && $numrows == $offset) {
			$tabledumped = 1;
			$rows = $db->query("SELECT * FROM $table LIMIT $startfrom, $offset");
			$numfields = $db->num_fields($rows);
			if($usehex) {
				$fields=$db->query("SHOW FIELDS FROM $table");
				while ($fieldrows = $db->fetch_row($fields)) {
					$stringfield[] = preg_match('/char|text/i', $fieldrows[1]);
				}
			}
			if($numrows = $db->num_rows($rows)) {
				$tabledump .= "INSERT INTO $table VALUES";
				$commas = '';
				while($row = $db->fetch_row($rows)) {
					$comma = '';
					$tabledump .= $commas." (";
					for($i = 0; $i < $numfields; $i++) {
						$tabledump .= $comma.($usehex ? ($row[$i] != '' && $stringfield[$i] ? '0x'.bin2hex($row[$i]) : '\''.$row[$i].'\'') : '\''.mysql_escape_string($row[$i]).'\'');
						$comma = ',';
					}
					$tabledump .= ')';
					$commas = ',';
				}
				$tabledump .= ";\n";
			}
			$startfrom += $offset;
		}
	}

	$startrow = $startfrom;
	$tabledump .= "\n";
	return $tabledump;
}

function splitsql($sql) {
	$sql = str_replace("\r", "\n", $sql);
	$ret = array();
	$num = 0;
	$queriesarray = explode(";\n", trim($sql));
	unset($sql);
	foreach($queriesarray as $query) {
		$queries = explode("\n", trim($query));
		foreach($queries as $query) {
			$ret[$num] .= $query[0] == "#" ? NULL : $query;
		}
		$num++;
	}
	return($ret);
}

function cpheader() {
	extract($GLOBALS, EXTR_SKIP);

	echo 	'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'.
		'<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset='.$charset.'">'.
		'<link href="./images/admincp/admincp.css" rel="stylesheet" type="text/css" />'.
		'<script language="JavaScript" src="include/common.js"></script>';

?>

<script language="JavaScript">
var is_ie = document.all ? true : false;
var is_ff = window.addEventListener ? true : false;
function refreshmainframe(e) {
	e = e ? e : window.event;
	actualCode = e.keyCode ? e.keyCode : e.charCode;
	if(parent.main && actualCode == 116) {
		parent.main.location.reload();
		if(is_ie) {
			e.keyCode = 0;
			e.returnValue = false;
		} else {
			e.preventDefault();
		}
	}
}

function checkalloption(form, value) {
	for(var i = 0; i < form.elements.length; i++) {
		var e = form.elements[i];
		if(e.value == value && e.type == 'radio' && e.disabled != true) {
			e.checked = true;
		}
	}
}

function zoomtextarea(objname, zoom) {
	zoomsize = zoom ? 10 : -10;
	obj = $(objname);
	if(obj.rows + zoomsize > 0 && obj.cols + zoomsize * 3 > 0) {
		obj.rows += zoomsize;
		obj.cols += zoomsize * 3;
	}
}

function redirect(url) {
	window.location.replace(url);
}

function get_cookie(name) {
	cookiename = name + '=';
	cookiepos = document.cookie.indexOf(cookiename);
	if(cookiepos != -1) {
		cookiestart =cookiepos+cookiename.length;
		cookieend = document.cookie.indexOf(';', cookiestart);
		if(cookieend == -1) {
			cookieend = document.cookie.length;
		}
		return unescape(document.cookie.substring(cookiestart, cookieend));
	}
	return '';
}

function set_cookie(name, value) {
	expires = new Date();
	expires.setTime(expires.getTime() + 2592000);
	document.cookie = name + "=" + value + "; path=<?=$cookiepath?>; expires=" + expires.toGMTString();
}

function $(id) {
	return document.getElementById(id);
}

var collapsed = get_cookie('<?=$tablepre?>collapse');
function collapse_change(menucount) {
	if($('menu_' + menucount).style.display == 'none') {
		$('menu_' + menucount).style.display = '';collapsed = collapsed.replace('[' + menucount + ']' , '');
		$('menuimg_' + menucount).src = './images/admincp/menu_reduce.gif';
	} else {
		$('menu_' + menucount).style.display = 'none';collapsed += '[' + menucount + ']';
		$('menuimg_' + menucount).src = './images/admincp/menu_add.gif';
	}
	set_cookie('<?=$tablepre?>collapse', collapsed);
}
</script>
</head>

<body leftmargin="10" topmargin="10" onkeydown="refreshmainframe(event)">
<table width="100%" border="0" cellpadding="2" cellspacing="6"><tr><td>
<?

}

function cpfooter() {
	global $version, $adminid, $db, $tablepre, $action, $bbname, $charset;
	global $_COOKIE, $_SESSION, $_DCOOKIE, $_DCACHE, $_DSESSION, $_DCACHE, $_DPLUGIN, $sqldebug, $debuginfo;
	debuginfo();

?>
</td></tr></table>
<br><br><div class="footer"><hr size="0" noshade color="<?=BORDERCOLOR?>" width="80%">
Powered by <a href="http://www.discuz.net" target="_blank" style="color: <?=TEXT?>"><b>Discuz!</b> <?=$version?></a> &nbsp;&copy; 2001-2006, <b>
<a href="http://www.comsenz.com" target="_blank" style="color: <?=TEXT?>">Comsenz Inc.</a></b></div><br>
</body>
</html>
<?
	if($adminid == 1 && $action == 'home') {
		$members = $db->result($db->query("SELECT COUNT(*) FROM {$tablepre}members"), 0);
		$threads = $db->result($db->query("SELECT COUNT(*) FROM {$tablepre}threads"), 0);
		$posts = $db->result($db->query("SELECT COUNT(*) FROM {$tablepre}posts"), 0);
		echo '<script language="JavaScript" src="http://customer.discuz.net/news.php?version='.rawurlencode(DISCUZ_VERSION).'&release='.rawurlencode(DISCUZ_RELEASE).'&php='.PHP_VERSION.'&mysql='.$dbversion.'&charset='.rawurlencode($charset).'&bbname='.rawurlencode($bbname).'&members='.$members.'&threads='.$threads.'&posts='.$posts.'&md5hash='.md5(preg_replace("/http:\/\/(.+?)\/.*/i", "\\1", $_SERVER['HTTP_REFERER']).$_SERVER['HTTP_USER_AGENT'].DISCUZ_VERSION.DISCUZ_RELEASE.$bbname.$members.$threads.$posts).'"></script>';
	}
	updatesession();
}

function dirsize($dir) {
	$dh = opendir($dir);
	$size = 0;
	while($file = readdir($dh)) {
		if($file != '.' and $file != '..') {
			$path = $dir."/".$file;
			if(@is_dir($path)) {
				$size += dirsize($path);
			} else {
				$size += filesize($path);
			}
		}
	}
	@closedir($dh);
	return $size;
}

function isfounder($user = '') {
	$user = empty($user) ? array('uid' => $GLOBALS['discuz_uid'], 'adminid' => $GLOBALS['adminid']) : $user;
	$founders = str_replace(' ', '', $GLOBALS['forumfounders']);
	if($user['adminid'] <> 1) {
		return FALSE;
	} elseif(empty($founders)) {
		return TRUE;
	} else {
		return strexists(",$founders,", ",$user[uid],");
	}
}

?>