<?php
/**
 * @version $Id: tool.inc.php v2.0 $
 * @package PBDigg
 * @copyright Copyright (C) 2007 - 2008 PBDigg.com. All Rights Reserved.
 * @license PBDigg is free software and use is subject to license terms
 */

if(!defined('IN_ADMIN') || !isset($_PBDEV['PHP_SELF']) || !preg_match('/[\/\\\\]admincp\.php$/i', $_PBDEV['PHP_SELF']))
{
	exit('Access Denied');
}
define('PB_CSCRIPT', 'tool');
allowdo('settool');
$baseurl = 'admincp.php?action=tool&amp;type=';

if ($type == 'cache' || empty($type))
{
	if ($submitted)
	{
		if ($config)
		{
			$Cache->config();
		}
		if ($cate)
		{
			$Cache->categories();
			$Cache->singlecate();
		}
		if ($article || $comment || $member)
		{
			$Cache->mktrantpl();
			$Cache->mktran();
			$Cache->toparticle();
			$Cache->commendarticle();
			$Cache->firstarticle();
		}
		if ($tag)
		{
			$Cache->tags();
		}
		if ($link)
		{
			$Cache->flink();
		}
		if ($announce)
		{
			$Cache->announce();
		}
		if ($stat)
		{
			$Cache->sitestat();
			$Cache->reg();
			$Cache->grouplevel();
			$Cache->userGroupCache();
			$Cache->adminGroupCache();
			$Cache->pluginsmenu();
			$Cache->plugins();
		}
		if ($count)
		{
			$recount = array();
			$query = $DB->db_query("SELECT cid, COUNT(*) num FROM {$db_prefix}threads GROUP BY cid");
			while ($a = $DB->db_fetch_array())
			{
				$recount[$a['cid']][0] = $a['num'];
			}
			$query = $DB->db_query("SELECT cid, COUNT(*) num FROM {$db_prefix}comments GROUP BY cid");
			while ($c = $DB->db_fetch_array())
			{
				$recount[$c['cid']][1] = $c['num'];
			}
			$tnum = $cnum = 0;
			foreach ($recount as $k => $v)
			{
				if (!@include (PBDIGG_ROOT.'data/cache/cache_singlecate_'.$k.'.php')) continue;
				$ta = (int)$v[0];
				$tc = (int)$v[1];
				$tnum += $ta;
				$cnum += $tc;
				if ($singlecate['subcids'])
				{
					$subcids = explode(',', substr($singlecate['subcids'],0,-1));
					foreach ($subcids as $cid)
					{
						$tc += (int)$recount[$cid][1];
						$ta += (int)$recount[$cid][0];
					}
				}
				$DB->db_query("UPDATE {$db_prefix}categories SET tnum = ".$ta.", cnum = ".$tc." WHERE cid = ".$k);
			}
			$pnum = $DB->db_fetch_one_array("SELECT COUNT(*) num FROM {$db_prefix}categories");
			$mnum = $DB->db_fetch_one_array("SELECT COUNT(*) num FROM {$db_prefix}members");
			$mname = $DB->db_fetch_one_array("SELECT username FROM {$db_prefix}members ORDER BY uid DESC LIMIT 1");
			$DB->db_query("UPDATE {$db_prefix}sitestat SET newmember = '".$mname['username']."', membernum = '".$mnum['num']."', catenum = '".$pnum['num']."', artnum = '".$tnum."', comnum = '".$cnum."' WHERE id = 1");
		}
		redirect($a_message['cache_refresh_success'], $actionurl);
	}
	else
	{
		$type = 'cache';
		$log_description = $cp_message['cache_tool'];
	}
}
elseif ($type == 'fileperms')
{
	$dirarray = array (
		'./admin/dbak',
		'./attachments',
		'./cache',
		'./compile/admin',
		'./data/cache',
		'./data/log',
		'./images/avatars',
		'./images/cate',
		'./debug'
	);
	$TPL->assign('perm', checkPerm($dirarray));
	$log_description = $cp_message['fileperms_tool'];
}
elseif ($type == 'announcement')
{
	if ($step == 'add' || empty($step))
	{
		//add announcement
		if ($submitted)
		{
			$cid = (int)$cid;
			$displayorder = (int)$displayorder;
			$url = trim($_POST['url']);
			$enddate = trim($_POST['enddate']);
			$title = SafeConvert(trim($_POST['title']));
			$content = SafeConvert(trim($_POST['content']));
			if (empty($title) || (empty($content) && empty($url)))
			{
				showMsg($a_message['annou_empty'], $actionurl);	
			}
			if ($cid < 0)
			{
				$cid = 0;
			}
			if ($displayorder < 0)
			{
				$displayorder = 0;
			}
			if ($url && $ck = checkURL($url))
			{
				showMsg($ck, $actionurl);
			}
			if ($enddate && preg_match('/^[\d]{4}-[\d]{2}-[\d]{2}$/', $enddate))
			{
				list($year, $month, $day) = explode('-', $enddate);
				$enddate = mktime(0, 0, 0, $month, $day, $year);
				if (($enddate === FALSE) || ($enddate == -1))
				{
					$enddate = 0;
				}
			}
			else
			{
				$enddate = 0;
			}
			$DB->db_query("INSERT INTO {$db_prefix}announcements (cid,author,subject,url,content,postdate,enddate,displayorder) 
			VALUES ($cid,'".addslashes($customer['username'])."','$title','$url','$content','$timestamp','$enddate','$displayorder')");
			$Cache->announce();
			redirect($a_message['add_annou_success'], $actionurl);
		}
		else
		{
			$option = '<select name="cid">'."\r\n".'<option value="0" selected="selected">'.$cp_message['all_cate'].'</option>'."\r\n";
			$cate_option = '';
			if (@include(PBDIGG_ROOT.'data/cache/cache_cate_option.php'))
			{
				$option .= $cate_option;
			}
			else
			{
				cateOption($categories, $cate_option);
				$Cache->writeCache('cate_option', 'return $cate_option = \''.addcslashes($cate_option, '\\\'').'\'');
				$option .= $cate_option;
			}
			$option .= '</select>';
			$actionurl .= '&step=add';
			$TPL->assign('cate_optioin', $option);
			$TPL->assign('step', 'add');
			$TPL->assign('js_more', '<script type="text/javascript" src="../templates/admin/js/setday.js"></script>');
		}
	}
	elseif ($step == 'list')
	{
		if ($submitted)
		{
			if ($displayorder && is_array($displayorder))
			{
				positiveInteger($displayorder);
				foreach ($displayorder as $key => $value)
				{
					$DB->db_query("UPDATE {$db_prefix}announcements SET displayorder = $value WHERE aid = $key");
				}
				$Cache->announce();
				redirect($a_message['update_order_success'], $actionurl.'&step=list');
			}
			else
			{
				showMsg($a_message['parameter_error'], $actionurl.'&step=list');
			}
		}
		else
		{
			$DB->db_query("SELECT aid, subject, enddate, displayorder FROM {$db_prefix}announcements ORDER BY postdate DESC");
			$announce = $rt = array();
			if ($DB->db_num())
			{
				while ($rt = $DB->db_fetch_array())
				{
					if ($rt['enddate'])
					{
						if ($rt['enddate'] < $timestamp)
						{
							$rt['enddate'] = '<span class="r">'.$a_message['expire_annou'].'</span>';
						}
						else
						{
							$rt['enddate'] = gdate($rt['enddate'], 'Y-m-d');
						}
					}
					else
					{
						$rt['enddate'] = $a_message['date_unlimited'];
					}
					$announce[] = $rt;
				}
			}
			$actionurl .= '&amp;step=list';
			$TPL->assign('announce', $announce);
			$TPL->assign('step', 'list');
		}
	}
	elseif ($step == 'mod')
	{
		if ($submitted)
		{
			$cid = (int)$cid;
			$displayorder = (int)$displayorder;
			$url = trim($_POST['url']);
			$enddate = trim($_POST['enddate']);
			$title = SafeConvert(Hentities(trim($_POST['title'])));
			$content = SafeConvert(trim($_POST['content']));
			if (empty($title) || (empty($content) && empty($url)))
			{
				showMsg($a_message['annou_empty'], $actionurl);	
			}
			if ($cid < 0)
			{
				$cid = 0;
			}
			if ($displayorder < 0)
			{
				$displayorder = 0;
			}
			if ($url && checkURL($url))
			{
				showMsg($a_message['url_error'], $actionurl);
			}
			if ($enddate && preg_match('/^[\d]{4}-[\d]{2}-[\d]{2}$/', $enddate))
			{
				list($year, $month, $day) = explode('-', $enddate);
				$enddate = mktime(0, 0, 0, $month, $day, $year);
				if (($enddate === FALSE) || ($enddate == -1))
				{
					$enddate = 0;
				}
			}
			else
			{
				$enddate = 0;
			}
			$DB->db_query("UPDATE {$db_prefix}announcements SET cid = $cid, subject = '$title', url = '$url', content = '$content', enddate = '$enddate', displayorder = $displayorder WHERE aid = $aid");
			$Cache->announce();
			redirect($a_message['mod_annou_success'], $actionurl.'&amp;step=list');
		}
		else
		{
			$aid = (int)$aid;
			$rt = $DB->db_fetch_one_array("SELECT cid, author, subject, url, content, enddate, displayorder FROM {$db_prefix}announcements WHERE aid = $aid");
			if ($rt)
			{
				$rt['enddate'] = $rt['enddate'] ? gdate($rt['enddate'], 'Y-m-d') : '';
				$rt['subject'] = htmlspecialchars($rt['subject']);
				$option = '<select name="cid">'."\r\n".'<option value="0">'.$cp_message['all_cate'].'</option>'."\r\n";
				$cate_option = '';
				cateOption($categories, $cate_option, 0, $rt['cid']);
				$option .= $cate_option;
				$option .= '</select>';
				$actionurl .= "&amp;step=mod&amp;aid=$aid";
				$TPL->assign('cate_optioin', $option);
				$TPL->assign('announce', $rt);
				$TPL->assign('js_more', '<script type="text/javascript" src="../templates/admin/js/setday.js"></script>');
			}
			else
			{
				showMsg($a_message['parameter_error'], $actionurl.'&amp;step=list');
			}
		}
	}
	elseif ($step == 'del')
	{
		$aid = (int)$aid;
		if ($aid)
		{
			$DB->db_query("DELETE FROM {$db_prefix}announcements WHERE aid = $aid LIMIT 1");
			$Cache->announce();
			redirect($a_message['del_annou_success'], $actionurl.'&step=list');
		}
		else
		{
			showMsg($a_message['parameter_error'], $actionurl.'&step=list');
		}
	}

}
elseif ($type == 'link')
{
	if (empty($step) || $step == 'add')
	{
		if ($submitted)
		{
			$status = (int)$status;
			$displayorder = (int)$displayorder;
			$sitename = HConvert(trim($_POST['sitename']));
			$siteurl = trim($_POST['siteurl']);
			$logo = trim($_POST['logo']);
			$description = HConvert(trim($_POST['description']));
			if (empty($sitename) || empty($siteurl))
			{
				showMsg($a_message['link_empty'], $actionurl);
			}
			if ($displayorder < 0)
			{
				$displayorder = 0;
			}
			if (checkURL($siteurl))
			{
				showMsg($a_message['siteurl_error'], $actionurl);
			}
			if ($logo && checkURL($siteurl))
			{
				showMsg($a_message['logourl_error'], $actionurl);
			}
			$rt = $DB->db_fetch_one_array("SELECT COUNT(*) num FROM {$db_prefix}links WHERE sitename = '$sitename' AND siteurl = '$siteurl'");
			if ($rt['num'])
			{
				showMsg($a_message['link_exist'], $actionurl);
			}
			$DB->db_query("INSERT INTO {$db_prefix}links (displayorder,ifshow,sitename,siteurl,description,logo) VALUES ($displayorder,$status,'$sitename','$siteurl','$description','$logo')");
			$Cache->flink();
			redirect($a_message['add_link_success'], $actionurl);
		}
		else
		{
			$actionurl .= '&step=add';
			$TPL->assign('step', 'add');
		}
	}
	elseif ($step == 'list')
	{
		if ($submitted)
		{
			if ($displayorder && is_array($displayorder))
			{
				positiveInteger($displayorder);
				foreach ($displayorder as $key => $value)
				{
					$DB->db_query("UPDATE {$db_prefix}links SET displayorder = $value WHERE lid = $key");
				}
				$Cache->flink();
				redirect($a_message['update_order_success'], $actionurl.'&step=list');
			}
			else
			{
				showMsg($a_message['parameter_error'], $actionurl.'&step=list');
			}
		}
		else
		{
			$link = $rt = array();
			$DB->db_query("SELECT lid, displayorder, ifshow, sitename, siteurl FROM {$db_prefix}links");
			if ($DB->db_num())
			{
				while ($rt = $DB->db_fetch_array())
				{
					if ($rt['ifshow'])
					{
						$rt['ifshow'] = $a_message['yes'];
					}
					else
					{
						$rt['ifshow'] = $a_message['not'];
					}
					$link[] = $rt;
				}
			}
			$actionurl .= '&step=list';
			$TPL->assign('link', $link);
			$TPL->assign('step', 'list');
		}
	}
	elseif ($step == 'del')
	{
		$lid = (int)$lid;
		$rt = countRecords('links', "lid = $lid");
		$actionurl .= '&step=list';
		if ($rt)
		{
			delRecords('links', "lid = $lid");
			$Cache->flink();
			redirect($a_message['del_link_success'], $actionurl);
		}
		else
		{
			showMsg($a_message['link_not_exist'], $actionurl);
		}
	}
	elseif ($step == 'mod')
	{
		if ($submitted)
		{
			if (empty($lid) || !is_numeric($lid))
			{
				showMsg($a_message['parameter_error'], $actionurl.'&step=list');
			}
			$errorurl = 'admincp.php?action=tool&type=link&step=mod&lid='.$lid;
			$lid = (int)$lid;
			$status = (int)$status;
			$displayorder = (int)$displayorder;
			$sitename = HConvert(trim($_POST['sitename']));
			$siteurl = trim($_POST['siteurl']);
			$logo = trim($_POST['logo']);
			$description = HConvert(trim($_POST['description']));
			if (empty($sitename) || empty($siteurl))
			{
				showMsg($a_message['link_empty'], $errorurl);
			}
			if ($displayorder < 0 || $displayorder > 255)
			{
				$displayorder = 0;
			}
			if (checkURL($siteurl))
			{
				showMsg($a_message['siteurl_error'], $errorurl);
			}
			if ($logo && checkURL($siteurl))
			{
				showMsg($a_message['logourl_error'], $errorurl);
			}
			if (countRecords('links', "sitename = '$sitename' AND siteurl = '$siteurl' AND lid <> $lid"))
			{
				showMsg($a_message['link_exist'], $errorurl);
			}
			updateRecords(array('displayorder'=>$displayorder, 'ifshow'=>$status, 'sitename'=>$sitename, 'siteurl'=>$siteurl, 'description'=>$description, 'logo'=>$logo), 'links', "lid = $lid");
			$Cache->flink();
			redirect($a_message['mod_link_success'], $actionurl.'&step=list');
		}
		else
		{
			$lid = (int)$lid;
			$rt = getFiledValues('', 'links', "lid = $lid");
			if ($rt)
			{
				radioChecked('status_', $rt[0]['ifshow']);
				$TPL->assign('status_0', $status_0);
				$TPL->assign('status_1', $status_1);
				unset($status_0, $status_1);
				$actionurl .= '&step=mod&lid='.$lid;
				$TPL->assign('link', $rt[0]);
			}
			else
			{
				showMsg($a_message['parameter_error'], $actionurl.'&step=list');
			}
		}
	}
}
else
{
	redirect($a_message['unknow_operate'], 'admincp.php?action=main');
}

$TPL->assign('menu', $m_tool);
?>
