<?php

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

	$RCSfile: cache.func.php,v $
	$Revision: 1.130.2.18 $
	$Date: 2007/03/09 21:20:38 $
*/

define('DISCUZ_KERNEL_VERSION', '5.5.0');
define('DISCUZ_KERNEL_RELEASE', '20070301');

if(isset($_GET['kernel_version'])) {
	exit('Crossday Discuz! Board<br>Developed by Comsenz Inc.<br><br>Version: '.DISCUZ_KERNEL_VERSION.'<br>Release: '.DISCUZ_KERNEL_RELEASE);
} elseif(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

function arrayeval($array, $level = 0) {
	$space = '';
	for($i = 0; $i <= $level; $i++) {
		$space .= "\t";
	}
	$evaluate = "Array\n$space(\n";
	$comma = $space;
	if(is_array($array)) {
		foreach($array as $key => $val) {
			$key = is_string($key) ? '\''.addcslashes($key, '\'\\').'\'' : $key;
			$val = !is_array($val) && (!preg_match("/^\-?[1-9]\d*$/", $val) || strlen($val) > 12) ? '\''.addcslashes($val, '\'\\').'\'' : $val;
			if(is_array($val)) {
				$evaluate .= "$comma$key => ".arrayeval($val, $level + 1);
			} else {
				$evaluate .= "$comma$key => $val";
			}
			$comma = ",\n$space";
		}
	}
	$evaluate .= "\n$space)";
	return $evaluate;
}

function updatecache($cachename = '') {
	global $db, $bbname, $tablepre, $maxbdays;

	$cachescript = array
		(
		'settings'	=> array('settings'),
		'jswizard'	=> array('jswizard'),
		'index'		=> array('announcements', 'onlinelist', 'forumlinks', 'advs', 'supe_updateusers', 'supe_updateitems'),
		'forumdisplay'	=> array('announcements_forum', 'pmlist', 'globalstick', 'forums', 'icons', 'onlinelist', 'smiliestable', 'advs'),
		'viewthread'	=> array('forums', 'pmlist', 'usergroups', 'ranks', 'bbcodes', 'smilies', 'fields_thread', 'smiliestable', 'advs'),
		'pm'		=> array('smiliestable'),
		'post'		=> array('bbcodes_display', 'bbcodes', 'smilies_display', 'smilies', 'icons'),
		'blog'		=> array('usergroups', 'ranks', 'bbcodes', 'smilies'),
		'forums'	=> array('forums'),
		'profilefields'	=> array('fields_required', 'fields_optional'),
		'censor'	=> array('censor'),
		'ipbanned'	=> array('ipbanned'),
		'bbcodes'	=> array('bbcodes', 'smilies'),
		'medals'	=> array('medals'),
		'magics'	=> array('magics'),
		'usergroups'	=> array('usergroups'),
		'topicadmin'	=> array('modreasons'),
		'archiver'      => array('advs'),
		'register'      => array('advs'),
		'faqs'		=> array('faqs'),
		'secqaa'	=> array('secqaa'),
		'updatecircles'	=> array('supe_updatecircles')
		);
	if($maxbdays) {
		$cachescript['birthdays'] = array('birthdays');
		$cachescript['index'][]   = 'birthdays_index';
	}

	foreach($cachescript as $script => $cachenames) {
		if(!$cachename || (!is_array($cachename) && in_array($cachename, $cachenames)) || (is_array($cachename) && array_intersect($cachename, $cachenames))) {
			writetocache($script, $cachenames);
		}
	}

	if(!$cachename || $cachename == 'styles') {
		$stylevars = array();
		$query = $db->query("SELECT * FROM {$tablepre}stylevars");
		while($var = $db->fetch_array($query)) {
			$stylevars[$var['styleid']][$var['variable']] = $var['substitute'];
		}
		$query = $db->query("SELECT s.*, t.directory AS tpldir FROM {$tablepre}styles s LEFT JOIN {$tablepre}templates t ON s.templateid=t.templateid");
		while($data = $db->fetch_array($query)) {
			$data = array_merge($data, $stylevars[$data['styleid']]);

			$data['bgcode'] = strpos($data['bgcolor'], '.') ? (preg_match('/^http:\/\//i', $data['bgcolor']) ? "background-image: url(\"$data[bgcolor]\")" : "background-image: url(\"$data[imgdir]/$data[bgcolor]\")") : "background-color: $data[bgcolor]";
			$data['catbgcode'] = strpos($data['catcolor'], '.') ? (preg_match('/^http:\/\//i', $data['catcolor']) ? "background-image: url(\"$data[catcolor]\")" : "background-image: url(\"$data[imgdir]/$data[catcolor]\")") : "background-color: $data[catcolor]";
			$data['headerbgcode'] = strpos($data['headercolor'], '.') ? (preg_match('/^http:\/\//i', $data['headercolor']) ? "background-image: url(\"$data[headercolor]\")" : "background-image: url(\"$data[imgdir]/$data[headercolor]\")") : "background-color: $data[headercolor]";
			$data['headermenubgcode'] = strpos($data['headermenu'], '.') ? (preg_match('/^http:\/\//i', $data['headermenu']) ? "background-image: url(\"$data[headermenu]\")" : "background-image: url(\"$data[imgdir]/$data[headermenu]\")") : "background-color: $data[headermenu]";
			$data['framebg'] = preg_match('/^http:\/\//i', $data['framebg']) ? $data['framebg'] : $data['imgdir'].'/'.$data['framebg'];
			$data['frameswitch'] = preg_match('/^http:\/\//i', $data['frameswitch']) ? $data['frameswitch'] : $data['imgdir'].'/'.$data['frameswitch'];
			if(strstr($data['boardimg'], ',')) {
				$flash = explode(",", $data['boardimg']);
				$flash[0] = trim($flash[0]);
				$flash[0] = preg_match('/^http:\/\//i', $flash[0]) ? $flash[0] : $data['imgdir'].'/'.$flash[0];
				$data['boardlogo'] = "<embed src=\"".$flash[0]."\" width=\"".trim($flash[1])."\" height=\"".trim($flash[2])."\" type=\"application/x-shockwave-flash\"></embed>";
			} else {
				$data['boardimg'] = preg_match('/^http:\/\//i', $data['boardimg']) ? $data['boardimg'] : $data['imgdir'].'/'.$data['boardimg'];
				$data['boardlogo'] = "<img src=\"$data[boardimg]\" alt=\"$bbname\" border=\"0\" />";
			}
			$data['bold'] = $data['nobold'] ? 'normal' : 'bold';
			writetocache($data['styleid'], '', getcachevars($data, 'CONST'), 'style_');
			writetocsscache($data);
		}
	}

	if(!$cachename || $cachename == 'usergroups') {
		$query = $db->query("SELECT * FROM {$tablepre}usergroups u
					LEFT JOIN {$tablepre}admingroups a ON u.groupid=a.admingid");
		while($data = $db->fetch_array($query)) {
			$ratearray = array();
			if($data['raterange']) {
				foreach(explode("\n", $data['raterange']) as $rating) {
					$rating = explode("\t", $rating);
					$ratearray[$rating[0]] = array('min' => $rating[1], 'max' => $rating[2], 'mrpd' => $rating[3]);
				}
			}
			$data['raterange'] = $ratearray;
			$data['grouptitle'] = $data['color'] ? '<font color="'.$data['color'].'">'.$data['grouptitle'].'</font>' : $data['grouptitle'];
			$data['grouptype'] = $data['type'];
			$data['grouppublic'] = $data['system'] != 'private';
			$data['groupcreditshigher'] = $data['creditshigher'];
			$data['groupcreditslower'] = $data['creditslower'];
			unset($data['type'], $data['system'], $data['creditshigher'], $data['creditslower'], $data['color'], $data['groupavatar'], $data['admingid']);
			foreach($data as $key => $val) {
				if(!isset($data[$key])) {
					unset($data[$key]);
				}
			}
			writetocache($data['groupid'], '', getcachevars($data), 'usergroup_');
		}
	}

	if(!$cachename || $cachename == 'admingroups') {
		$query = $db->query("SELECT * FROM {$tablepre}admingroups");
		while($data = $db->fetch_array($query)) {
			writetocache($data['admingid'], '', getcachevars($data), 'admingroup_');
		}
	}

	if(!$cachename || $cachename == 'plugins') {
		$query = $db->query("SELECT pluginid, available, adminid, name, identifier, datatables, directory, copyright, modules FROM {$tablepre}plugins");
		while($plugin = $db->fetch_array($query)) {
			$data = array_merge($plugin, array('modules' => array()), array('vars' => array()));
			$plugin['modules'] = unserialize($plugin['modules']);
			if(is_array($plugin['modules'])) {
				foreach($plugin['modules'] as $module) {
					$data['modules'][$module['name']] = $module;
				}
			}
			$queryvars = $db->query("SELECT variable, value FROM {$tablepre}pluginvars WHERE pluginid='$plugin[pluginid]'");
			while($var = $db->fetch_array($queryvars)) {
				$data['vars'][$var['variable']] = $var['value'];
			}
			writetocache($plugin['identifier'], '', "\$_DPLUGIN['$plugin[identifier]'] = ".arrayeval($data), 'plugin_');
		}
	}

	if(empty($cachename) || in_array($cachename, array('forums', 'usergroups', 'settings'))) {
		updatespacesettings();
	}
}

function updatespacesettings() {
	global $db, $tablepre, $initcredits;

	$query = $db->query("SELECT groupid, readaccess FROM {$tablepre}usergroups WHERE creditshigher<=".intval($initcredits)." AND ".intval($initcredits)."<creditslower LIMIT 1");
	$groupinfo = $db->fetch_array($query);
	$fids = 0;
	$query = $db->query("SELECT fid, viewperm FROM {$tablepre}forumfields");
	while($forum = $db->fetch_array($query)) {
		if(empty($forum['viewperm']) || in_array($groupinfo['groupid'], explode("\t", $forum['viewperm']))) {
			$fids .= ','.$forum['fid'];
		}
	}
	$spacesettings = array('parms' => array('infids' => $fids, 'groupid' => $groupinfo['groupid'], 'readaccess' => $groupinfo['readaccess']));
	writetocache('spacesettings', '', getcachevars($spacesettings));
}

function updatesettings() {
	global $_DCACHE;
	if(isset($_DCACHE['settings']) && is_array($_DCACHE['settings'])) {
		writetocache('settings', '', '$_DCACHE[\'settings\'] = '.arrayeval($_DCACHE['settings']));
	}
}

function writetocache($script, $cachenames, $cachedata = '', $prefix = 'cache_') {
	global $authkey, $timestamp;
	if(is_array($cachenames) && !$cachedata) {
		foreach($cachenames as $name) {
			$cachedata .= getcachearray($name, $script);
		}
	}

	$dir = DISCUZ_ROOT.'./forumdata/cache/';
	if(!is_dir($dir)) {
		@mkdir($dir, 0777);
	}
	if(@$fp = fopen("$dir$prefix$script.php", 'wb')) {
		fwrite($fp, "<?php\n//Discuz! cache file, DO NOT modify me!".
			"\n//Created: ".date("M j, Y, G:i").
			"\n//Identify: ".md5($prefix.$script.'.php'.$cachedata.$authkey)."\n\n$cachedata?>");
		fclose($fp);
	} else {
		dexit('Can not write to cache files, please check directory ./forumdata/ and ./forumdata/cache/ .');
	}
}

function writetocsscache($data) {
	$csstemplates = array('css', 'css_editor');
	$styleid = $data['styleid'];
	include_once DISCUZ_ROOT.'./forumdata/cache/style_'.$styleid.'.php';
	$cachedir = DISCUZ_ROOT.'./forumdata/cache/';
	foreach($csstemplates as $css) {
		$cssfile = template($css, $styleid, $data['tpldir']);
		$cssfile = !file_exists($cssfile) ? template($css, 1, './templates/default/') : $cssfile;
		$fp = fopen($cssfile, 'r');
		$cssdata = fread($fp, filesize($cssfile));
		fclose($fp);
		$cssdata = preg_replace("/<\?=([A-Z0-9]+)\?>/e", '\$data[strtolower(\'\1\')]', $cssdata);
		$cssdata = preg_replace("/<\?.+?\?>\s*/", '', $cssdata);
		$cssdata = str_replace("url(\"$data[imgdir]", "url(\"../../$data[imgdir]", $cssdata);
		$cssdata = str_replace("url($data[imgdir]", "url(../../$data[imgdir]", $cssdata);
		$extra = substr($css, 3);
		if(@$fp = fopen($cachedir.'style_'.$styleid.$extra.'.css', 'w')) {
			fwrite($fp, $cssdata);
			fclose($fp);
		} else {
			dexit('Can not write to cache files, please check directory ./forumdata/ and ./forumdata/cache/ .');
		}
	}
}

function getcachearray($cachename, $script = '') {
	global $db, $timestamp, $tablepre, $timeoffset, $maxbdays, $smcols, $smrows;

	$cols = '*';
	$conditions = '';
	switch($cachename) {
		case 'settings':
			$table = 'settings';
			$conditions = "WHERE variable NOT IN ('bbrules', 'bbrulestxt', 'closedreason', 'creditsnotify', 'backupdir', 'custombackup', 'jswizard', 'maxonlines', 'modreasons', 'newsletter', 'welcomemsg', 'welcomemsgtxt') AND variable NOT LIKE 'jswizard_%'";
			break;
		case 'jswizard':
			$table = 'settings';
			$conditions = "WHERE variable LIKE 'jswizard_%'";
			break;
		case 'usergroups':
			$table = 'usergroups';
			$cols = 'groupid, type, grouptitle, creditshigher, creditslower, stars, color, groupavatar, readaccess, allowavatar, allowcusbbcode, allowuseblog';
			$conditions = "ORDER BY creditslower";
			break;
		case 'ranks':
			$table = 'ranks';
			$cols = 'ranktitle, postshigher, stars, color';
			$conditions = "ORDER BY postshigher DESC";
			break;
		case 'announcements':
			$table = 'announcements';
			$cols = 'id, subject, type, starttime, endtime, message, displayorder, groups';
			$conditions = "WHERE starttime<='$timestamp' AND (endtime>='$timestamp' OR endtime='0') ORDER BY displayorder, starttime DESC, id DESC";
			break;
		case 'announcements_forum':
			$table = 'announcements a';
			$cols = 'a.id, a.author, a.message, m.uid AS authorid, a.subject, a.type, a.starttime, a.displayorder';
			$conditions = "LEFT JOIN {$tablepre}members m ON m.username=a.author WHERE a.type!=2 AND a.groups = '' AND a.starttime<='$timestamp' ORDER BY a.displayorder, a.starttime DESC, a.id DESC LIMIT 1";
			break;
		case 'pmlist':
			$table = 'announcements a';
			$cols = 'id, subject, starttime, endtime, message, groups';
			$conditions = "WHERE type=2 AND starttime<='$timestamp' AND (endtime>='$timestamp' OR endtime='0') ORDER BY displayorder, starttime DESC, id DESC";
			break;
		case 'globalstick':
			$table = 'forums';
			$cols = 'fid, type, fup';
			$conditions = "WHERE status>0 AND type IN ('forum', 'sub') ORDER BY type";
			break;
		case 'forums':
			$table = 'forums f';
			$cols = 'f.fid, f.type, f.name, f.fup, ff.viewperm, a.uid';
			$conditions = "LEFT JOIN {$tablepre}forumfields ff ON ff.fid=f.fid LEFT JOIN {$tablepre}access a ON a.fid=f.fid AND a.allowview='1' WHERE f.status>0 ORDER BY f.type, f.displayorder";
			break;
		case 'onlinelist':
			$table = 'onlinelist';
			$conditions = "ORDER BY displayorder";
			break;
		case 'forumlinks':
			$table = 'forumlinks';
			$conditions = "ORDER BY displayorder";
			break;
		case 'bbcodes':
			$table = 'bbcodes';
			$conditions = "WHERE available='1'";
			break;
		case 'bbcodes_display':
			$table = 'bbcodes';
			$cols = 'tag, icon, example, explanation, params, prompt';
			$conditions = "WHERE available='1' AND icon!=''";
			break;
		case 'smilies':
			$table = 'smilies';
			$cols = 'id, code, url';
			$conditions = "WHERE type='smiley' ORDER BY LENGTH(code) DESC";
			break;
		case in_array($cachename, array('smilies_display', 'smiliestable')):
			$table = 'smilies';
			$cols = 'id, code, url';
			$limit = in_array($script, array('forumdisplay', 'viewthread', 'pm')) ? 'LIMIT '.($smcols * $smrows) : '';
			$conditions = "WHERE type='smiley' ORDER BY displayorder $limit";
			break;
		case 'icons':
			$table = 'smilies';
			$cols = 'id, url';
			$conditions = "WHERE type='icon' ORDER BY displayorder";
			break;
		case 'fields_required':
			$table = 'profilefields';
			$cols = 'fieldid, invisible, title, description, required, unchangeable, selective, choices';
			$conditions = "WHERE available='1' AND required='1' ORDER BY displayorder";
			break;
		case 'fields_optional':
			$table = 'profilefields';
			$cols = 'fieldid, invisible, title, description, required, unchangeable, selective, choices';
			$conditions = "WHERE available='1' AND required='0' ORDER BY displayorder";
			break;
		case 'fields_thread':
			$table = 'profilefields';
			$cols = 'fieldid, title, selective, choices';
			$conditions = "WHERE available='1' AND invisible='0' AND showinthread='1' ORDER BY displayorder";
			break;
		case 'ipbanned':
			$db->query("DELETE FROM {$tablepre}banned WHERE expiration<'$timestamp'");
			$table = 'banned';
			$cols = 'ip1, ip2, ip3, ip4, expiration';
			break;
		case 'censor':
			$table = 'words';
			$cols = 'find, replacement';
			break;
		case 'medals':
			$table = 'medals';
			$cols = 'medalid, name, image';
			$conditions = "WHERE available='1'";
			break;
		case 'magics':
			$table = 'magics';
			$cols = 'magicid, available, identifier, name, description, weight, price';
			break;
		case 'birthdays_index':
			$table = 'members';
			$cols = 'uid, username, email, bday';
			$conditions = "WHERE RIGHT(bday, 5)='".gmdate('m-d', $timestamp + $timeoffset * 3600)."' ORDER BY bday LIMIT $maxbdays";
			break;
		case 'birthdays':
			$table = 'members';
			$cols = 'uid';
			$conditions = "WHERE RIGHT(bday, 5)='".gmdate('m-d', $timestamp + $timeoffset * 3600)."' ORDER BY bday";
			break;
		case 'modreasons':
			$table = 'settings';
			$cols = 'value';
			$conditions = "WHERE variable='modreasons'";
			break;
		case 'faqs':
			$table = 'faqs';
			$cols = 'id, identifier, keyword';
			$conditions = "WHERE identifier!='' AND keyword!=''";
			break;
		case 'secqaa':
			$table = 'itempool';
			$cols = 'question, answer';
			$conditions = "ORDER BY rand() LIMIT 10";
			break;
	}

	$data = array();
	if(!in_array($cachename, array('advs', 'supe_updateusers', 'supe_updateitems', 'supe_updatecircles'))) {
		$query = $db->query("SELECT $cols FROM {$tablepre}$table $conditions");
	}
	switch($cachename) {
		case 'settings':
			$data['qihoo_links'] = array();
			while($setting = $db->fetch_array($query)) {
				if($setting['variable'] == 'extcredits') {
					if(is_array($setting['value'] = unserialize($setting['value']))) {
						foreach($setting['value'] as $key => $value) {
							if($value['available']) {
								unset($setting['value'][$key]['available']);
							} else {
								unset($setting['value'][$key]);
							}
						}
					}
				} elseif($setting['variable'] == 'qihoo_keywords') {
					foreach(explode("\n", trim($setting['value'])) as $keyword) {
						if($keyword = trim($keyword)) {
							$data['qihoo_links']['keywords'][] = '<a href="search.php?srchtype=qihoo&amp;srchtxt='.rawurlencode($keyword).'&amp;searchsubmit=yes" target="_blank">'.dhtmlspecialchars(trim($keyword)).'</a>';
						}
					}
				} elseif($setting['variable'] == 'qihoo_topics') {
					if(is_array($topics = unserialize($setting['value']))) {
						foreach($topics as $topic) {
							if($topic['topic'] = trim($topic['topic'])) {
								$data['qihoo_links']['topics'][] = '<a href="topic.php?topic='.rawurlencode($topic['topic']).'&amp;keyword='.rawurlencode($topic['keyword']).'&amp;stype='.$topic['stype'].'&amp;length='.$topic['length'].'&amp;relate='.$topic['relate'].'" target="_blank">'.dhtmlspecialchars(trim($topic['topic'])).'</a>';
							}
						}
					}
				} elseif(in_array($setting['variable'], array('creditspolicy', 'ftp', 'secqaa', 'supe'))) {
					$setting['value'] = unserialize($setting['value']);
				} elseif($setting['variable'] == 'creditsformula') {
					if(!preg_match("/^([\+\-\*\/\.\d\(\)]|((extcredits[1-8]|digestposts|posts|pageviews|oltime)([\+\-\*\/\(\)]|$)+))+$/", $setting['value']) || !is_null(@eval(preg_replace("/(digestposts|posts|pageviews|oltime|extcredits[1-8])/", "\$\\1", $setting['value']).';'))) {
						$setting['value'] = '$member[\'extcredits1\']';
					} else {
						$setting['value'] = preg_replace("/(digestposts|posts|pageviews|oltime|extcredits[1-8])/", "\$member['\\1']", $setting['value']);
					}
				} elseif($setting['variable'] == 'maxsmilies') {
					$setting['value'] = $setting['value'] <= 0 ? -1 : $setting['value'];
				} elseif($setting['variable'] == 'threadsticky') {
					$setting['value'] = explode(',', $setting['value']);
				} elseif($setting['variable'] == 'attachdir') {
					$setting['value'] = str_replace('\\', '/', substr($setting['value'], 0, 2) == './' ? DISCUZ_ROOT.$setting['value'] : $setting['value']);
				} elseif($setting['variable'] == 'onlinehold') {
					$setting['value'] = $setting['value'] * 60;
				}

				if(!in_array($setting['variable'], array('qihoo_keywords', 'qihoo_topics'))) {
					$GLOBALS[$setting['variable']] = $data[$setting['variable']] = $setting['value'];
				}

				if(in_array($setting['variable'], array('supe_status', 'supe_tablepre', 'supe_siteurl', 'supe_sitename', 'supe_circlestatus'))) {
					$data['supe'][substr($setting['variable'], 5)] = $setting['value'];
					unset($data[$setting['variable']]);
				}
			}

			$data['ftp']['connid'] = 0;
			$data['indexname'] = empty($data['indexname']) ? 'index.php' : $data['indexname'];
			$data['seccodedata'] = $data['seccodedata'] ? unserialize($data['seccodedata']) : array();

			if(!$data['supe']['status']) {
				$data['supe'] = array('status' => 0);
			} else {
				if(!$data['supe']['items']['status']) {
					$data['supe']['items'] = array('status' => 0);
				}
				global $supe;
				if(!isset($data['supe']['attachurl']) && isset($supe['tablepre'])) {
					supe_dbconnect();
					$query = $supe['db']->query("SELECT * FROM {$supe[tablepre]}settings WHERE variable IN ('attachmentdir', 'attachmenturl')");
					$supe_settings = array();
					while($supe_setting = $supe['db']->fetch_array($query)) {
						$supe_settings[$supe_setting['variable']] = $supe_setting['value'];
					}
					if(substr($supe_settings['attachmentdir'], 0, 2) == './' && empty($supe_settings['attachmenturl'])) {
						$supe_settings['attachmenturl'] = $supe['siteurl'].substr($supe_settings['attachmentdir'], 1);
					}
					$data['supe']['attachurl'] = $supe_settings['attachmenturl'];
					$db->query("UPDATE {$tablepre}settings SET value='".addslashes(serialize($data['supe']))."' WHERE variable='supe'");
				}
				if(!$data['supe']['dbmode']) {
					unset($data['supe']['dbhost'], $data['supe']['dbuser'], $data['supe']['dbpw'], $data['supe']['dbname']);
				}
			}

			$secqaacheck = sprintf('%03b', $data['secqaa']['status']);
			$data['secqaa']['status'] = array(
				1 => $secqaacheck{0},
				2 => $secqaacheck{1},
				3 => $secqaacheck{2}
			);
			if(!$data['secqaa']['status'][2] && !$data['secqaa']['status'][3]) {
				unset($data['secqaa']['minposts']);
			}

			$data['jsmenustatus'] = sprintf('%b', $data['jsmenustatus']);
			for($i = 1; $i <= strlen($data['jsmenustatus']); $i++) {
				if(substr($data['jsmenustatus'], -$i, 1)) $data['jsmenu'][$i] = TRUE;
			}
			unset($data['jsmenustatus']);

			$data['stylejumpstatus'] = $data['stylejump'];
			$data['stylejump'] = array();
			$query = $db->query("SELECT styleid, name FROM {$tablepre}styles WHERE available='1'");
			while($style = $db->fetch_array($query)) {
				$data['stylejump'][$style['styleid']] = dhtmlspecialchars($style['name']);
			}

			$query = $db->query("SELECT COUNT(*) FROM {$tablepre}forums WHERE status>0 AND threadcaches>0");
			$data['cachethreadon'] = $db->result($query, 0) ? 1 : 0;

			$query = $db->query("SELECT COUNT(*) FROM {$tablepre}members");
			$GLOBALS['totlamembers'] = $data['totalmembers'] = $db->result($query, 0);
			$query = $db->query("SELECT username FROM {$tablepre}members ORDER BY uid DESC LIMIT 1");
			$GLOBALS['lastmember'] = $data['lastmember'] = $db->result($query, 0);
			$GLOBALS['version'] = $data['version'] = DISCUZ_KERNEL_VERSION;

			$query = $db->query("SELECT nextrun FROM {$tablepre}crons WHERE available>'0' AND nextrun>'$timestamp' ORDER BY nextrun LIMIT 1");
			$data['cronnextrun'] = $db->result($query, 0);
			$globaladvs = advertisement('all');
			$data['globaladvs'] = $globaladvs['all'] ? $globaladvs['all'] : array();
			$data['redirectadvs'] = $globaladvs['redirect'] ? $globaladvs['redirect'] : array();

			$data['plugins'] = $data['pluginlinks'] = array();
			$query = $db->query("SELECT available, name, identifier, directory, datatables, modules FROM {$tablepre}plugins");
			while($plugin = $db->fetch_array($query)) {
				$plugin['modules'] = unserialize($plugin['modules']);
				if(is_array($plugin['modules'])) {
					foreach($plugin['modules'] as $module) {
						if($plugin['available'] && isset($module['name'])) {

							switch($module['type']) {
								case 1:
									$data['plugins']['links'][] = array('displayorder' => $module['displayorder'], 'adminid' => $module['adminid'], 'url' => "<a href=\"$module[url]\">$module[menu]</a>");
									break;
								case 2:
									$data['plugins']['links'][] = array('displayorder' => $module['displayorder'], 'adminid' => $module['adminid'], 'url' => "<a href=\"plugin.php?identifier=$plugin[identifier]&module=$module[name]\">$module[menu]</a>");
									$data['pluginlinks'][$plugin['identifier']][$module['name']] = array('adminid' => $module['adminid'], 'directory' => $plugin['directory']);
									break;
								case 4:
									$data['plugins']['include'][] = array('displayorder' => $module['displayorder'], 'adminid' => $module['adminid'], 'script' => $plugin['directory'].$module['name']);
									break;
								case 5:
									$data['plugins']['jsmenu'][] = array('displayorder' => $module['displayorder'], 'adminid' => $module['adminid'], 'url' => "<a href=\"$module[url]\">$module[menu]</a>");
									break;
								case 6:
									$data['plugins']['jsmenu'][] = array('displayorder' => $module['displayorder'], 'adminid' => $module['adminid'], 'url' => "<a href=\"plugin.php?identifier=$plugin[identifier]&module=$module[name]\">$module[menu]</a>");
									$data['pluginlinks'][$plugin['identifier']][$module['name']] = array('adminid' => $module['adminid'], 'directory' => $plugin['directory']);
									break;
							}
						}
					}
				}
			}

			if(is_array($data['plugins']['links'])) {
				usort($data['plugins']['links'], 'pluginmodulecmp');
				foreach($data['plugins']['links'] as $key => $module) {
					unset($data['plugins']['links'][$key]['displayorder']);
				}
			}
			if(is_array($data['plugins']['include'])) {
				usort($data['plugins']['include'], 'pluginmodulecmp');
				foreach($data['plugins']['include'] as $key => $module) {
					unset($data['plugins']['include'][$key]['displayorder']);
				}
			}
			if(is_array($data['plugins']['jsmenu'])) {
				usort($data['plugins']['jsmenu'], 'pluginmodulecmp');
				foreach($data['plugins']['jsmenu'] as $key => $module) {
					unset($data['plugins']['jsmenu'][$key]['displayorder']);
				}
			}

			$data['hooks'] = array();
			$query = $db->query("SELECT ph.title, ph.code, p.identifier FROM {$tablepre}plugins p
				LEFT JOIN {$tablepre}pluginhooks ph ON ph.pluginid=p.pluginid AND ph.available='1'
				WHERE p.available='1' ORDER BY p.identifier");
			while($hook = $db->fetch_array($query)) {
				if($hook['title'] && $hook['code']) {
					$data['hooks'][$hook['identifier'].'_'.$hook['title']] = $hook['code'];
				}
			}
			break;
		case 'jswizard':
			while($jswizard = $db->fetch_array($query)) {
				$key = substr($jswizard['variable'], 9);
				$data[$key] = unserialize($jswizard['value']);
				unset($data[$key]['type']);
				unset($data[$key]['parameter']);
			}
			break;
		case 'usergroups':
			global $userstatusby;
			while($group = $db->fetch_array($query)) {
				$groupid = $group['groupid'];
				$group['grouptitle'] = $group['color'] ? '<font color="'.$group['color'].'">'.$group['grouptitle'].'</font>' : $group['grouptitle'];
				if($userstatusby == 2) {
					$group['byrank'] = $group['type'] == 'member' ? 1 : 0;
				}
				if($userstatusby == 0 || ($userstatusby == 2 && $group['type'] == 'member')) {
					unset($group['grouptitle'], $group['stars']);
				}
				if($group['type'] != 'member') {
					unset($group['creditshigher'], $group['creditslower']);
				}
				unset($group['groupid'], $group['color']);
				$data[$groupid] = $group;
			}
			break;
		case 'ranks':
			global $userstatusby;
			if($userstatusby == 2) {
				while($rank = $db->fetch_array($query)) {
					$rank['ranktitle'] = $rank['color'] ? '<font color="'.$rank['color'].'">'.$rank['ranktitle'].'</font>' : $rank['ranktitle'];
					unset($rank['color']);
					$data[] = $rank;
				}
			}
			break;
		case 'announcements':
			$data = array();
			while($datarow = $db->fetch_array($query)) {
				if(empty($datarow['type'])) {
					unset($datarow['message']);
				} elseif($datarow['type'] == 2) {
					$datarow['message'] = dhtmlspecialchars(cutstr(strip_tags($datarow['message']), 70));
				}
				$datarow['groups'] = empty($datarow['groups']) ? array() : explode(',', $datarow['groups']);
				$data[] = $datarow;
			}
			break;
		case 'announcements_forum':
			if($data = $db->fetch_array($query)) {
				$data['authorid'] = intval($data['authorid']);
				$data['message'] = cutstr(strip_tags($data['message']), ($data['type'] ? 250 : 18));
			} else {
				$data = array();
			}
			break;
		case 'pmlist':
			$data = array();
			while($datarow = $db->fetch_array($query)) {
				$datarow['message'] = dhtmlspecialchars(cutstr(strip_tags($datarow['message']), 70));
				$datarow['groups'] = empty($datarow['groups']) ? array() : explode(',', $datarow['groups']);
				$data[] = $datarow;
			}
			break;
		case 'globalstick':
			$fuparray = $threadarray = array();
			while($forum = $db->fetch_array($query)) {
				switch($forum['type']) {
					case 'forum':
						$fuparray[$forum['fid']] = $forum['fup'];
						break;
					case 'sub':
						$fuparray[$forum['fid']] = $fuparray[$forum['fup']];
						break;
				}
			}
			$query = $db->query("SELECT tid, fid, displayorder FROM {$tablepre}threads WHERE displayorder IN (2, 3)");
			while($thread = $db->fetch_array($query)) {
				switch($thread['displayorder']) {
					case 2:
						$threadarray[$fuparray[$thread['fid']]][] = $thread['tid'];
						break;
					case 3:
						$threadarray['global'][] = $thread['tid'];
						break;
				}
			}
			foreach(array_unique($fuparray) as $gid) {
				if(!empty($threadarray[$gid])) {
					$data['categories'][$gid] = array(
						'tids'	=> implode(',', $threadarray[$gid]),
						'count'	=> intval(@count($threadarray[$gid]))
					);
				}
			}
			$data['global'] = array(
				'tids'	=> empty($threadarray['global']) ? 0 : implode(',', $threadarray['global']),
				'count'	=> intval(@count($threadarray['global']))
			);
			break;
		case 'censor':
			$banned = $mod = array();
			$data = array('filter' => array(), 'banned' => '', 'mod' => '');
			while($censor = $db->fetch_array($query)) {
				$censor['find'] = preg_replace("/\\\{(\d+)\\\}/", ".{0,\\1}", preg_quote($censor['find'], '/'));
				switch($censor['replacement']) {
					case '{BANNED}':
						$banned[] = $censor['find'];
						break;
					case '{MOD}':
						$mod[] = $censor['find'];
						break;
					default:
						$data['filter']['find'][] = '/'.$censor['find'].'/i';
						$data['filter']['replace'][] = $censor['replacement'];
						break;
				}
			}
			if($banned) {
				$data['banned'] = '/('.implode('|', $banned).')/i';
			}
			if($mod) {
				$data['mod'] = '/('.implode('|', $mod).')/i';
			}
			break;
		case 'forums':
			while($forum = $db->fetch_array($query)) {
				if(!isset($forumlist[$forum['fid']])) {
					$forum['name'] = strip_tags($forum['name']);
					if($forum['uid']) {
						$forum['users'] = "\t$forum[uid]\t";
					}
					unset($forum['uid']);
					if($forum['fup']) {
						$forumlist[$forum['fup']]['count']++;
					}
					$forumlist[$forum['fid']] = $forum;
				} elseif($forum['uid']) {
					if(!$forumlist[$forum['fid']]['users']) {
						$forumlist[$forum['fid']]['users'] = "\t";
					}
					$forumlist[$forum['fid']]['users'] .= "$forum[uid]\t";
				}
			}

			if(!empty($forumlist)) {
				foreach($forumlist as $fid1 => $forum1) {
					if(($forum1['type'] == 'group' && $forum1['count'])) {
						$data[$fid1]['fid'] = $forum1['fid'];
						$data[$fid1]['type'] = $forum1['type'];
						$data[$fid1]['name'] = $forum1['name'];
						$data[$fid1]['fup'] = $forum1['fup'];
						$data[$fid1]['viewperm'] = $forum1['viewperm'];
						foreach($forumlist as $fid2 => $forum2) {
							if($forum2['fup'] == $fid1 && $forum2['type'] == 'forum') {
								$data[$fid2]['fid'] = $forum2['fid'];
								$data[$fid2]['type'] = $forum2['type'];
								$data[$fid2]['name'] = $forum2['name'];
								$data[$fid2]['fup'] = $forum2['fup'];
								$data[$fid2]['viewperm'] = $forum2['viewperm'];
								foreach($forumlist as $fid3 => $forum3) {
									if($forum3['fup'] == $fid2 && $forum3['type'] == 'sub') {
										$data[$fid3]['fid'] = $forum3['fid'];
										$data[$fid3]['type'] = $forum3['type'];
										$data[$fid3]['name'] = $forum3['name'];
										$data[$fid3]['fup'] = $forum3['fup'];
										$data[$fid3]['viewperm'] = $forum3['viewperm'];
									}
								}
							}
						}
					}
				}
			}
			break;
		case 'onlinelist':
			$data['legend'] = '';
			while($list = $db->fetch_array($query)) {
				$data[$list['groupid']] = $list['url'];
				$data['legend'] .= "<img src=\"images/common/$list[url]\" alt=\"\" /> $list[title] &nbsp; &nbsp; &nbsp; ";
			}
			break;
		case 'forumlinks':
			global $forumlinkstatus;
			if($forumlinkstatus) {
				$tightlink_text = $tightlink_logo = '';
				while($flink = $db->fetch_array($query)) {
					if($flink['description']) {
						$forumlink['content'] = "<a href=\"$flink[url]\" target=\"_blank\"><span class=\"bold\">$flink[name]</span></a><br>$flink[description]";
						if($flink['logo']) {
							$forumlink['type'] = 1;
							$forumlink['logo'] = $flink['logo'];
						} else {
							$forumlink['type'] = 2;
						}
						$data[] = $forumlink;
					} else {
						if($flink['logo']) {
							$tightlink_logo .= "<a href=\"$flink[url]\" target=\"_blank\"><img src=\"$flink[logo]\" border=\"0\" alt=\"$flink[name]\" /></a> ";
						} else {
							$tightlink_text .= "<a href=\"$flink[url]\" target=\"_blank\">[$flink[name]]</a> ";
						}
					}
				}
				if($tightlink_logo || $tightlink_text) {
					$tightlink_logo .= $tightlink_logo ? '<br>' : '';
					$data[] = array('type' => 3, 'content' => $tightlink_logo.$tightlink_text);
				}
			} else {
				$data = array();
			}
			break;
		case 'bbcodes':
			$regexp = array	(
						1 => "/\[{bbtag}](.+?)\[\/{bbtag}\]/is",
						2 => "/\[{bbtag}=(['\"]?)(.+?)(['\"]?)\](.+?)\[\/{bbtag}\]/is",
						3 => "/\[{bbtag}=(['\"]?)(.+?)(['\"]?),(['\"]?)(.+?)(['\"]?)\](.+?)\[\/{bbtag}\]/is"
					);

			while($bbcode = $db->fetch_array($query)) {
				$search = str_replace('{bbtag}', $bbcode['tag'], $regexp[$bbcode['params']]);
				$bbcode['replacement'] = preg_replace("/([\r\n])/", '', $bbcode['replacement']);
				switch($bbcode['params']) {
					case 2:
						$bbcode['replacement'] = str_replace('{1}', '\\2', $bbcode['replacement']);
						$bbcode['replacement'] = str_replace('{2}', '\\4', $bbcode['replacement']);
						break;
					case 3:
						$bbcode['replacement'] = str_replace('{1}', '\\2', $bbcode['replacement']);
						$bbcode['replacement'] = str_replace('{2}', '\\5', $bbcode['replacement']);
						$bbcode['replacement'] = str_replace('{3}', '\\7', $bbcode['replacement']);
						break;
					default:
						$bbcode['replacement'] = str_replace('{1}', '\\1', $bbcode['replacement']);
						break;
				}
				if(preg_match("/\{(RANDOM|MD5)\}/", $bbcode['replacement'])) {
					$search = str_replace('is', 'ies', $search);
					$replace = '\''.str_replace('{RANDOM}', '_\'.random(6).\'', str_replace('{MD5}', '_\'.md5("\\1").\'', $bbcode['replacement'])).'\'';
				} else {
					$replace = $bbcode['replacement'];
				}

				for($i = 0; $i < $bbcode['nest']; $i++) {
					$data['searcharray'][] = $search;
					$data['replacearray'][] = $replace;
				}
			}

			break;
		case 'bbcodes_display':
			while($bbcode = $db->fetch_array($query)) {
				$tag = $bbcode['tag'];
				$bbcode['example'] = dhtmlspecialchars(trim($bbcode['example']));
				if(!$bbcode['example']) {
					switch($bbcode['params']) {
						case 2:
							$bbcode['example'] = '['.$bbcode['tag'].'=][/'.$bbcode['tag'].']';
							break;
						case 3:
							$bbcode['example'] = '['.$bbcode['tag'].'=,][/'.$bbcode['tag'].']';
							break;
						default:
							$bbcode['example'] = '['.$bbcode['tag'].'][/'.$bbcode['tag'].']';
							break;
					}
				}
				$bbcode['explanation'] = dhtmlspecialchars(trim($bbcode['explanation']));
				$bbcode['example'] = addcslashes($bbcode['example'], '\\\'');
				$bbcode['prompt'] = addcslashes($bbcode['prompt'], '\\\'');
				unset($bbcode['tag']);
				$data[$tag] = $bbcode;
			}
			break;
		case 'smilies':
			$data = array('searcharray' => array(), 'replacearray' => array());
			while($smiley = $db->fetch_array($query)) {
				$data['searcharray'][$smiley['id']] = '/'.preg_quote(dhtmlspecialchars($smiley['code']), '/').'/';
				$data['replacearray'][$smiley['id']] = $smiley['url'];
			}
			break;
		case 'smilies_display':
			$smdir = defined('SMDIR') ? SMDIR : './images/smilies';
			while($smiley = $db->fetch_array($query)) {
				if($size = @getimagesize($smdir.'/'.$smiley['url'])) {
					$smiley['code'] = dhtmlspecialchars($smiley['code']);
					$smileyid = $smiley['id'];
					$s = smthumb($size, $GLOBALS['smthumb']);
					$smiley['w'] = $s['w'];
					$smiley['h'] = $s['h'];
					$l = smthumb($size);
					$smiley['lw'] = $l['w'];
					unset($smiley['id']);
					$data[$smileyid] = $smiley;
				}
			}
			break;
		case 'smiliestable':
			$smdir = defined('SMDIR') ? SMDIR : './images/smilies';
			$smilies = '';
			$i = 0;
			while($smiley = $db->fetch_array($query)) {
				if($i < $smcols * $smrows) {
					$size = @getimagesize($smdir.'/'.$smiley['url']);
					$s = smthumb($size, $GLOBALS['smthumb']);
					$smiley['w'] = $s['w'];
					$smiley['h'] = $s['h'];
					$l = smthumb($size);
					$smiley['lw'] = $l['w'];
					$smiley['code'] = addcslashes(addslashes(dhtmlspecialchars($smiley['code'])), '\\\'');
					$smilies .= !($i % $smcols) && $i ? '</tr>' : '';
					$smilies .= !($i % $smcols) ? '<tr align="center" height="'.($GLOBALS['smthumb'] + 6).'">' : '';
					$smilies .= '<td valign="middle"><img src="\\\'+SMDIR+\\\'/'.$smiley['url'].'" id="smilie_'.$smiley['id'].'" alt="'.$smiley['code'].'" border="0" onClick="insertSmiley('.$smiley['id'].')" onMouseover="smileyMenu(this)" width="'.$smiley['w'].'" height="'.$smiley['h'].'" title="'.$smiley['lw'].'" /></td>';
				}
				$i++;
			}
			$smilies = $i ? $smilies.'</tr>' : '';
			$smiliesnum = $db->result($db->query("SELECT COUNT(*) FROM {$tablepre}smilies WHERE type='smiley'"), 0);
			return "\$_DCACHE['$cachename'] = '".$smilies."';\n\$_DCACHE['smiliesnum'] = '".$smiliesnum."';\n";
		case 'icons':
			while($icon = $db->fetch_array($query)) {
				$data[$icon['id']] = $icon['url'];
			}
			break;
		case (in_array($cachename, array('fields_required', 'fields_optional', 'fields_thread'))):
			while($field = $db->fetch_array($query)) {
				$choices = array();
				if($field['selective']) {
					foreach(explode("\n", $field['choices']) as $item) {
						list($index, $choice) = explode('=', $item);
						$choices[trim($index)] = trim($choice);
					}
					$field['choices'] = $choices;
				} else {
					unset($field['choices']);
				}
				$data[] = $field;
			}
			break;
		case 'ipbanned':
			if($db->num_rows($query)) {
				$data['expiration'] = 0;
				$data['regexp'] = $separator = '';
			}
			while($banned = $db->fetch_array($query)) {
				$data['expiration'] = !$data['expiration'] || $banned['expiration'] < $data['expiration'] ? $banned['expiration'] : $data['expiration'];
				$data['regexp'] .=	$separator.
							($banned['ip1'] == '-1' ? '\\d+\\.' : $banned['ip1'].'\\.').
							($banned['ip2'] == '-1' ? '\\d+\\.' : $banned['ip2'].'\\.').
							($banned['ip3'] == '-1' ? '\\d+\\.' : $banned['ip3'].'\\.').
							($banned['ip4'] == '-1' ? '\\d+' : $banned['ip4']);
				$separator = '|';
			}
			break;
		case 'medals':
			while($medal = $db->fetch_array($query)) {
				$data[$medal['medalid']] = array('name' => $medal['name'], 'image' => $medal['image']);
			}
			break;
		case 'magics':
			while($magic = $db->fetch_array($query)) {
				$data[$magic['magicid']]['identifier'] = $magic['identifier'];
				$data[$magic['magicid']]['available'] = $magic['available'];
				$data[$magic['magicid']]['name'] = $magic['name'];
				$data[$magic['magicid']]['description'] = $magic['description'];
				$data[$magic['magicid']]['weight'] = $magic['weight'];
				$data[$magic['magicid']]['price'] = $magic['price'];
			}
			break;
		case 'birthdays_index':
			$bdaymembers = array();
			while($bdaymember = $db->fetch_array($query)) {
				$birthyear = intval($bdaymember['bday']);
				$bdaymembers[] = '<a href="space.php?uid='.$bdaymember['uid'].'" target="_blank" '.($birthyear ? 'title="'.$bdaymember['bday'].'"' : '').'>'.$bdaymember['username'].'</a>';
			}
			$data['todaysbdays'] = implode(', ', $bdaymembers);
			break;
		case 'birthdays':
			$data['uids'] = $comma = '';
			$data['num'] = 0;
			while($bdaymember = $db->fetch_array($query)) {
				$data['uids'] .= $comma.$bdaymember['uid'];
				$comma = ',';
				$data['num'] ++;
			}
			break;
		case 'modreasons':
			$modreasons = $db->result($query, 0);
			$modreasons = str_replace(array("\r\n", "\r"), array("\n", "\n"), $modreasons);
			$data = explode("\n", trim($modreasons));
			break;
		case 'advs':
			$data = advertisement($script);
			break;
		case 'faqs':
			while($faqs = $db->fetch_array($query)) {
				$data[$faqs['identifier']]['id'] = $faqs['id'];
				$data[$faqs['identifier']]['keyword'] = $faqs['keyword'];
			}
			break;
		case 'secqaa':
			while($secqaa = $db->fetch_array($query)) {
				$secqaa['answer'] = md5($secqaa['answer']);
				$data[] = $secqaa;
			}
			break;
		case 'supe_updateusers':
			global $supe;
			supe_dbconnect();
			if($supe['status'] && $supe['maxupdateusers']) {
				$query = $supe['db']->query("SELECT uid, username FROM {$supe[tablepre]}userspaces WHERE islock=0 ORDER BY lastpost DESC LIMIT $supe[maxupdateusers]");
				while($datarow = $supe['db']->fetch_array($query)) {
					$data[$datarow['uid']] = $datarow;
				}
			}
			break;
		case 'supe_updateitems':
			global $supe;
			supe_dbconnect();
			if($supe['status'] && $supe['items']['status']) {
				$limit = $supe['items']['rows'] * $supe['items']['columns'];
				switch($supe['items']['orderby']) {
					case '1':
						$orderby = 'viewnum';
						break;
					case '2':
						$orderby = 'replynum';
						break;
					case '3':
						$orderby = 'dateline';
						break;
					case '4':
						$orderby = 'lastpost';
						break;
					default:
						$orderby = 'itemid';
				}
				$supe['items']['hours'] = $supe['items']['hours'] > 0 ? $supe['items']['hours'] : 24;
				$conditions = !in_array($orderby, array('dateline', 'lastpost')) ? 'WHERE folder=1 AND type<>\'news\' AND dateline >='.($timestamp - $supe['items']['hours'] * 86400) : 'WHERE folder=1 AND type<>\'news\'';
				$query = $supe['db']->query("SELECT itemid, uid, username, type, subject FROM {$supe[tablepre]}spaceitems $conditions ORDER BY $orderby DESC LIMIT $limit");
				$itemtable = '';
				$items = array();
				include language('templates');
				while($item = $supe['db']->fetch_array($query)) {
					$typename = $language['supe_'.$item['type']];
					$items[] = '<a href="\'.$supe[\'siteurl\'].\'?action/viewspace/itemid/'.$item['itemid'].'.html" target="_blank"><img src="\\\'+IMGDIR+\\\'/menu_collapsed_yes.gif" align="absmiddle" border="0"></a> [<a href="\'.$supe[\'siteurl\'].\'?action/'.$item['type'].'" target="_blank">'.$typename.'</a>] <a href="\'.$supe[\'siteurl\'].\'?uid/'.$item['uid'].'" target="_blank"><strong>'.addcslashes(addslashes($item['username']), '\\\'').'</strong></a>: <a href="\'.$supe[\'siteurl\'].\'?action/viewspace/itemid/'.$item['itemid'].'.html" target="_blank">'.addcslashes(addslashes(cutstr($item['subject'], 35)), '\\\'').'</a>';
				}
				for($i = 0; $i < $limit; $i++) {
					$itemtable .= (($i + 1) % $supe['items']['columns'] == 1 || $supe['items']['columns'] == 1 ? '<tr align="left" class="altbg2">' : '').
					'<td width="'.intval(100 / $supe['items']['columns']).'%" nowrap>'.(isset($items[$i]) ? $items[$i] : '&nbsp;').'</td>'.
					(($i + 1) % $supe['items']['columns'] == 0 ? "</tr>" : '');
				}
				return "\$_DCACHE['$cachename'] = '".$itemtable."';\n\n";
			}
		case 'supe_updatecircles':
			global $supe;
			supe_dbconnect();
			if($supe['status'] && $supe['circlestatus']) {
				$query = $supe['db']->query("SELECT gid, uid, username, groupname, logo, usernum, lastpost FROM {$supe[tablepre]}groups WHERE catid>0 AND flag=1 ORDER BY lastpost DESC LIMIT 8");
				while($datarow = $supe['db']->fetch_array($query)) {
					$datarow['groupname'] = cutstr($datarow['groupname'], 30);
					$data[] = $datarow;
				}
			}
			break;
		default:
			while($datarow = $db->fetch_array($query)) {
				$data[] = $datarow;
			}
	}

	return "\$_DCACHE['$cachename'] = ".arrayeval($data).";\n\n";
}

function getcachevars($data, $type = 'VAR') {
	$evaluate = '';
	foreach($data as $key => $val) {
		if(is_array($val)) {
			$evaluate .= "\$$key = ".arrayeval($val).";\n";
		} else {
			$val = addcslashes($val, '\'\\');
			$evaluate .= $type == 'VAR' ? "\$$key = '$val';\n" : "define('".strtoupper($key)."', '$val');\n";
		}
	}
	return $evaluate;
}

function advertisement($range) {
	global $db, $tablepre, $timestamp;
	$advs = array();
	$query = $db->query("SELECT * FROM {$tablepre}advertisements WHERE available>'0' AND starttime<='$timestamp' ORDER BY displayorder");
	if($db->num_rows($query)) {
		while($adv = $db->fetch_array($query)) {
			if(in_array($adv['type'], array('footerbanner', 'thread'))) {
				$parameters = unserialize($adv['parameters']);
				$position = isset($parameters['position']) && in_array($parameters['position'], array(2, 3)) ? $parameters['position'] : 1;
				$type = $adv['type'].$position;
			} else {
				$type = $adv['type'];
			}
			$adv['targets'] = $adv['targets'] == '' ? 'all' : $adv['targets'];
			foreach(explode("\t", $adv['targets']) as $target) {
				$target = $target == '0' ? 'index' : (in_array($target, array('all', 'register', 'redirect', 'archiver')) ? $target : ($target == 'forum' ? 'forum_all' : 'forum_'.$target));
				if((($range == 'forumdisplay' && !in_array($adv['type'], array('thread', 'interthread'))) || $range == 'viewthread') &&  substr($target, 0, 6) == 'forum_') {
					if($adv['type'] == 'thread') {
						foreach(isset($parameters['displayorder']) ? explode("\t", $parameters['displayorder']) : array('0') as $postcount) {
							$advs[$type.'_'.$postcount][$target][] = $adv['code'];
						}
					} else {
						$advs[$type][$target][] = $adv['code'];
					}
				} elseif($range == 'all' && in_array($target, array('all', 'redirect'))) {
					$advs[$target][$type][] = $adv['code'];
				} elseif($target == $range) {
					$advs[$type][] = $adv['code'];
				}
			}
		}
	}
	return $advs;
}

function pluginmodulecmp($a, $b) {
	return $a['displayorder'] > $b['displayorder'] ? 1 : -1;
}

function smthumb($size, $smthumb = 50) {
	if($size[0] <= $smthumb && $size[1] <= $smthumb) {
		return array('w' => $size[0], 'h' => $size[1]);
	}
	$sm = array();
	$x_ratio = $smthumb / $size[0];
	$y_ratio = $smthumb / $size[1];
	if(($x_ratio * $size[1]) < $smthumb) {
		$sm['h'] = ceil($x_ratio * $size[1]);
		$sm['w'] = $smthumb;
	} else {
		$sm['w'] = ceil($y_ratio * $size[0]);
		$sm['h'] = $smthumb;
	}
	return $sm;
}

?>