<?php
/**
 * @version $Id: batch.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', 'batch');
allowdo('setbatch');
$baseurl = 'admincp.php?action=batch&type=';
require_once (PBDIGG_ROOT.'include/article.func.php');

if ($type == 'article' || empty($type))
{
	if ($submitted)
	{
		//search article
		$condition = '1';
		$pattern = array('%','_','*');
		$replace = array('\%','\_','%');
		$cid = (int)$cid;
		if ($cid)
		{
			$condition .= ' AND t.cid = '.$cid;
		}
		$author = strip_tags(trim(isset($_POST['author']) ? $_POST['author'] : $_GET['author']));
		$_author = array_filter(explode(',', $author));
		if ($_author)
		{
			$authorCondition = '';
			foreach ($_author as $value)
			{
				if ($value && (strlen($value) < 20))
				{
					$value = str_replace($pattern, $replace, preg_replace('/\*{2,}/i', '*', $value));
					$authorCondition .= " OR username LIKE '$value'";
				}
			}
			$authorCondition = substr_replace($authorCondition, '', 0, 3);
			$DB->db_query("SELECT uid FROM {$db_prefix}members WHERE $authorCondition");
			if ($DB->db_num())
			{
				$uids = '';
				while ($rs = $DB->db_fetch_array())
				{
					$uids .= ",".$rs['uid'];
				}
				$condition .= ' AND t.uid IN ('.substr($uids, 1).')';
			}
			else
			{
				$condition .= ' AND t.uid = -1';
			}
		}
		$later = trim($later);
		if ($later && preg_match('/^[0-9]{4}-[0-9]{2,4}-[0-9]{2,4}$/i', $later))
		{
			$condition .= ' AND t.postdate > '.strtotime($later.'0:0:0');
		}
		$earlier = trim($earlier);
		if ($earlier && preg_match('/^[0-9]{4}-[0-9]{2,4}-[0-9]{2,4}$/i', $earlier))
		{
			$condition .= ' AND t.postdate < '.strtotime($earlier.'23:59:59');
		}
		$views = (int)$views;
		if ($views != -1)
		{
			$condition .= ' AND t.views < '.$views;
		}
		$comments = (int)$comments;
		if ($comments != -1)
		{
			$condition .= ' AND t.comments < '.$comments;
		}
		$digg = (int)$digg;
		if ($digg != -1)
		{
			$condition .= ' AND t.digg < '.$digg;
		}
		$tags = strip_tags(trim(isset($_POST['tags']) ? $_POST['tags'] : $_GET['tags']));
		$_tags = array_filter(explode(',', $tags));
		$tagCondition = '';
		if ($_tags)
		{
			foreach ($_tags as $value)
			{
				if ($value && (strlen($value) < 30))
				{
					$value = str_replace($pattern, $replace, preg_replace('/\*{2,}/i', '*', $value));
					$tagCondition .= " OR tg.tagname LIKE '$value'";
				}
			}
			$tagCondition = substr_replace($tagCondition, '', 0, 3);
			$SQL = "SELECT DISTINCT t.tid FROM {$db_prefix}threads t 
					LEFT JOIN {$db_prefix}tagcache tc 
					ON t.tid = tc.tid 
					LEFT JOIN {$db_prefix}tags tg 
					ON tc.tagid = tg.tagid 
					WHERE $tagCondition";
			$DB->db_query($SQL);
			if ($DB->db_num())
			{
				$tids = '';
				while ($rs = $DB->db_fetch_array())
				{
					$tids .= ",".$rs['tid'];
				}
				$condition .= ' AND t.tid IN ('.substr($tids, 1).')';
			}
			else
			{
				$condition .= ' AND t.tid = -1';
			}
		}
		$linkhost = trim($linkhost);
		if ($linkhost)
		{
			$linkhost = preg_replace('/\*{2,}/i', '*', $linkhost);
			$_linkhost = str_replace($pattern, $replace, $linkhost);
			$condition .= " AND t.linkhost LIKE '$_linkhost'";
		}
		$ip = trim($ip);
		if ($ip && preg_match('/^[0-9\*\.]*?$/i', $ip))
		{
			$ip = preg_replace('/\*{2,}/i', '*', $ip);
			$_ip = str_replace('*', '%', $ip);
			$condition .= " AND t.postip LIKE '$_ip'";
		}
		if ($ddel)
		{
			$tidarray = array();
			$DB->db_query("SELECT t.tid FROM {$db_prefix}threads t WHERE $condition");
			while ($rs = $DB->db_fetch_array())
			{
				$tidarray[] = $rs['tid'];
			}
			delArticle($tidarray);
			redirect($a_message['del_success'], $actionurl);
		}
		$pagesize = 30;
		$rs = $DB->db_fetch_one_array("SELECT COUNT(*) num FROM {$db_prefix}threads t WHERE $condition");
		$totalRecords = (int)$rs['num'];
		$page = !isPage($page) ? 1 : $page;
		$start_limit = ($page -1) * $pagesize;
		$mult = cpmultLink($page, $totalRecords, 'admincp.php?action=batch&type=article&submitted=1&cid='.$cid.'&author='.rawurlencode($author).'&later='.$later.'&earlier='.$earlier.'&views='.$views.'&comments='.$comments.'&digg='.$digg.'&tags='.rawurlencode($tags).'&linkhost='.$linkhost.'&ip='.$ip.'&', $pagesize);
		$DB->db_query("SELECT t.tid, t.subject, t.author, t.postdate, t.postip FROM {$db_prefix}threads t WHERE $condition LIMIT $start_limit, $pagesize");
		$article = array();
		while ($rs = $DB->db_fetch_array())
		{
			$rs['postdate'] = gdate($rs['postdate'], 'Y-m-d H:i');
			if (!$rs['author'])
			{
				if ($pb_anonnick)
				{
					$rs['author'] = $pb_anonnick;
				}
				else
				{
					$rs['author'] = $pb_sitename.$cp_message['net_friend'];
				}
			}
			$article[] = $rs;
		}
		$type = 'article_list';
		$TPL->assign('article', $article);
		$TPL->assign('mult', $mult);
		$TPL->assign('total_records', $totalRecords);
	}
	elseif ($step == 'del')
	{
		if (!$tid)
		{
			showMsg($a_message['parameter_error'], $actionurl);
		}
		delArticle($tid);
		redirect($a_message['del_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>';
		$type = 'article';
		$TPL->assign('cate_option', $option);
		$TPL->assign('js_more', '<script type="text/javascript" src="../templates/admin/js/setday.js"></script>');
	}
}
elseif ($type == 'comment')
{
	if ($submitted)
	{
		//search comments
		$condition = '1';
		$pattern = array('%','_','*');
		$replace = array('\%','\_','%');
		$cid = (int)$cid;
		if ($cid)
		{
			$condition .= ' AND cm.cid = '.$cid;
		}
		$author = strip_tags(trim(isset($_POST['author']) ? $_POST['author'] : $_GET['author']));
		$_author = array_filter(explode(',', $author));
		if ($_author)
		{
			$authorCondition = '';
			foreach ($_author as $value)
			{
				if ($value && (strlen($value) < 20))
				{
					$value = str_replace($pattern, $replace, preg_replace('/\*{2,}/i', '*', $value));
					$authorCondition .= " OR username LIKE '$value'";
				}
			}
			$authorCondition = substr_replace($authorCondition, '', 0, 3);
			$DB->db_query("SELECT uid FROM {$db_prefix}members WHERE $authorCondition");
			if ($DB->db_num())
			{
				$uids = '';
				while ($rs = $DB->db_fetch_array())
				{
					$uids .= ",".$rs['uid'];
				}
				$condition .= ' AND cm.uid IN ('.substr($uids, 1).')';
			}
			else
			{
				$condition .= ' AND cm.uid = -1';
			}
		}
		$later = trim($later);
		if ($later && preg_match('/^[0-9]{4}-[0-9]{2,4}-[0-9]{2,4}$/i', $later))
		{
			$condition .= ' AND cm.postdate > '.strtotime($later.'0:0:0');
		}
		$earlier = trim($earlier);
		if ($earlier && preg_match('/^[0-9]{4}-[0-9]{2,4}-[0-9]{2,4}$/i', $earlier))
		{
			$condition .= ' AND cm.postdate < '.strtotime($earlier.'23:59:59');
		}
		$ip = trim($ip);
		if ($ip && preg_match('/^[0-9\*\.]*?$/i', $ip))
		{
			$ip = preg_replace('/\*{2,}/i', '*', $ip);
			$_ip = str_replace('*', '%', $ip);
			$condition .= " AND cm.postip LIKE '$_ip'";
		}
		if ($ddel)
		{
			$ridarray = array();
			$DB->db_query("SELECT cm.rid FROM {$db_prefix}comments cm WHERE $condition");
			while ($rs = $DB->db_fetch_array())
			{
				$ridarray[] = $rs['rid'];
			}
			delComment($ridarray);
			redirect($a_message['del_success'], $actionurl);
		}
		$pagesize = 30;
		$rs = $DB->db_fetch_one_array("SELECT COUNT(*) num FROM {$db_prefix}comments cm WHERE $condition");
		$totalRecords = (int)$rs['num'];
		$page = !isPage($page) ? 1 : $page;
		$start_limit = ($page -1) * $pagesize;
		$mult = cpmultLink($page, $totalRecords, 'admincp.php?action=batch&type=comment&submitted=1&cid='.$cid.'&author='.rawurlencode($author).'&later='.$later.'&earlier='.$earlier.'&ip='.$ip.'&', $pagesize);
		$DB->db_query("SELECT cm.rid, cm.content, cm.author, cm.postdate, cm.postip FROM {$db_prefix}comments cm WHERE $condition LIMIT $start_limit, $pagesize");
		$comment = array();
		while ($rs = $DB->db_fetch_array())
		{
			$rs['postdate'] = gdate($rs['postdate'], 'Y-m-d H:i');
			if (!$rs['author'])
			{
				if ($pb_anonnick)
				{
					$rs['author'] = $pb_anonnick;
				}
				else
				{
					$rs['author'] = $pb_sitename.$cp_message['net_friend'];
				}
			}
			$rs['content'] = PBSubstr($rs['content'], 35);
			$comment[] = $rs;
		}
		$type = 'comment_list';
		$TPL->assign('comment', $comment);
		$TPL->assign('mult', $mult);
		$TPL->assign('total_records', $totalRecords);
	}
	elseif ($step == 'del')
	{
		if (!$rid)
		{
			showMsg($a_message['parameter_error'], $actionurl);
		}
		delComment($rid);
		redirect($a_message['del_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>';
		$TPL->assign('cate_option', $option);
		$TPL->assign('js_more', '<script type="text/javascript" src="../templates/admin/js/setday.js"></script>');
	}
}
elseif ($type == 'attachment')
{
	if ($submitted)
	{
		//search attachmet
		$condition = '1';
		$pattern = array('%','_','*');
		$replace = array('\%','\_','%');
		$cid = (int)$cid;
		if ($cid)
		{
			$condition .= ' AND a.cid = '.$cid;
		}
		$author = strip_tags(trim(isset($_POST['author']) ? $_POST['author'] : $_GET['author']));
		$_author = array_filter(explode(',', $author));
		if ($_author)
		{
			$authorCondition = '';
			foreach ($_author as $value)
			{
				if ($value && (strlen($value) < 20))
				{
					$value = str_replace($pattern, $replace, preg_replace('/\*{2,}/i', '*', $value));
					$authorCondition .= " OR username LIKE '$value'";
				}
			}
			$authorCondition = substr_replace($authorCondition, '', 0, 3);
			$DB->db_query("SELECT uid FROM {$db_prefix}members WHERE $authorCondition");
			if ($DB->db_num())
			{
				$uids = '';
				while ($rs = $DB->db_fetch_array())
				{
					$uids .= ",".$rs['uid'];
				}
				$condition .= ' AND a.uid IN ('.substr($uids, 1).')';
			}
			else
			{
				$condition .= ' AND a.uid = -1';
			}
		}
		$later = trim($later);
		if ($later && preg_match('/^[0-9]{4}-[0-9]{2,4}-[0-9]{2,4}$/i', $later))
		{
			$condition .= ' AND a.uploaddate > '.strtotime($later.'0:0:0');
		}
		$earlier = trim($earlier);
		if ($earlier && preg_match('/^[0-9]{4}-[0-9]{2,4}-[0-9]{2,4}$/i', $earlier))
		{
			$condition .= ' AND a.uploaddate < '.strtotime($earlier.'23:59:59');
		}
		$sizelarger = trim($sizelarger);
		if ($sizelarger && is_numeric($sizelarger))
		{
			$condition .= ' AND a.filesize > '.($sizelarger * 1024);
		}
		$sizesmaller = trim($sizesmaller);
		if ($sizesmaller && is_numeric($sizesmaller))
		{
			$condition .= ' AND a.filesize < '.($sizesmaller * 1024);
		}
		$tidlarger = trim($tidlarger);
		if ($tidlarger && is_numeric($tidlarger))
		{
			$condition .= ' AND a.tid > '.$tidlarger;
		}
		$tidsmaller = trim($tidsmaller);
		if ($tidsmaller && is_numeric($tidsmaller))
		{
			$condition .= ' AND a.tid < '.$tidsmaller;
		}
		if ($onlyimg)
		{
			$condition .= ' AND a.isimg = 1';
		}
		$pagesize = 30;
		$rs = $DB->db_fetch_one_array("SELECT COUNT(*) num FROM {$db_prefix}attachments a WHERE $condition");
		$totalRecords = (int)$rs['num'];
		$page = !isPage($page) ? 1 : $page;
		$start_limit = ($page -1) * $pagesize;
		$mult = cpmultLink($page, $totalRecords, 'admincp.php?action=batch&type=attachment&submitted=1&cid='.$cid.'&author='.rawurlencode($author).'&later='.$later.'&earlier='.$earlier.'&sizelarger='.$sizelarger.'&sizesmaller='.$sizesmaller.'&tidlarger='.$tidlarger.'&tidsmaller='.$tidsmaller.'&onlyimg='.$onlyimg.'&', $pagesize);
		$SQL = "SELECT a.aid, a.filename, a.filesize, a.uploaddate, a.downloads, m.username, c.name catename FROM {$db_prefix}attachments a 
				LEFT JOIN {$db_prefix}categories c 
				ON a.cid = c.cid 
				LEFT JOIN {$db_prefix}members m 
				ON a.uid = m.uid 
				WHERE $condition LIMIT $start_limit, $pagesize";
		$attachment = array();
		$DB->db_query($SQL);
		while ($rs = $DB->db_fetch_array())
		{
			$rs['uploaddate'] = gdate($rs['uploaddate'], 'Y-m-d H:i');
			if (!$rs['username'])
			{
				if ($pb_anonnick)
				{
					$rs['username'] = $pb_anonnick;
				}
				else
				{
					$rs['username'] = $pb_sitename.$cp_message['net_friend'];
				}
			}
			$rs['filename'] = htmlspecialchars($rs['filename']);
			$rs['filesize'] = getRealSize($rs['filesize']);
			$attachment[] = $rs;
		}
		$type = 'attachment_list';
		$TPL->assign('attachment', $attachment);
		$TPL->assign('mult', $mult);
		$TPL->assign('total_records', $totalRecords);
	}
	elseif ($step == 'del')
	{
		require_once(PBDIGG_ROOT.'include/attachment.inc.php');
		if (!$aid)
		{
			showMsg($a_message['parameter_error'], $actionurl);
		}
		delAttachment(implode(',', $aid));
		redirect($a_message['del_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>';
		$TPL->assign('cate_option', $option);
		$TPL->assign('js_more', '<script type="text/javascript" src="../templates/admin/js/setday.js"></script>');
	}
}
elseif ($type == 'email')
{
	if ($step)
	{
		if (empty($mailto) || empty($title))
		{
			showMsg($a_message['email_empty'], $actionurl);
		}	
		if (is_array($mailto))
		{
			$mailto = implode(',', array_map('intval', $mailto));
		}
		$mailCache = PBDIGG_ROOT.'data/cache/'.md5($_SITECONFIG['pb_sitehash']).'_email.tmp';
		if ($step == 1)
		{
			PWriteFile($mailCache, $mail_content, 'wb');
		}
		else
		{
			$mail_content = PReadFile($mailCache);
		}
		$title = HConvert($title);
		$mail_content = stripslashes(SafeConvert($mail_content));
		if (empty($mail_content))
		{
			showMsg($a_message['email_empty'], $actionurl);
		}
		if (!$count)
		{
			$count = 100;
		}
		$count = (int)$count;
		$start = ($step - 1) * $count;
		$next = $start + $count;
		$step++;
		$jumpurl = 'admincp.php?action=batch&type=email&step='.$step.'&count='.$count.'&mailto='.$mailto.'&title='.rawurlencode($title).'&';
		$DB->db_query("SELECT uid, username, email FROM {$db_prefix}members WHERE groupid IN (".$mailto.") ORDER BY uid LIMIT $start, $count");
		if ($DB->db_num())
		{
			require_once (PBDIGG_ROOT.'include/mail.inc.php');
			while ($rs = $DB->db_fetch_array())
			{
				PMail($rs['email'], $title, str_replace('{!--username--}', $rs['username'], $mail_content));
			}
			redirect(sprintf($a_message['send_process'], $start, $next), $jumpurl);
		}
		else
		{
			PDel($mailCache);
			redirect($a_message['send_success'], $baseurl.'email');
		}
	}
	else
	{
		$group = array();
		foreach ($grouplevel as $key => $value)
		{
			if (($key == 5) || $key > 6) continue;
			$group[$key] = $value['grouptitle'];
		}
		$group['-1'] = $a_message['common_member'];
		$TPL->assign('mailto', html_checkbox($group, 'mailto[]', array(), 3));
	}
}
elseif ($type == 'msg')
{
	if ($step)
	{
		if (empty($msgto) || empty($title))
		{
			showMsg($a_message['email_empty'], $actionurl);
		}	
		if (is_array($msgto))
		{
			$msgto = implode(',', array_map('intval', $msgto));
		}
		$msgCache = PBDIGG_ROOT.'data/cache/'.md5($_SITECONFIG['pb_sitehash']).'_msg.tmp';
		if ($step == 1)
		{
			PWriteFile($msgCache, $msg_content, 'wb');
		}
		else
		{
			$msg_content = PReadFile($msgCache);
		}
		$title = HConvert($title);
		$msg_content = HConvert($msg_content);
		if (empty($msg_content))
		{
			showMsg($a_message['email_empty'], $actionurl);
		}
		if (!$count)
		{
			$count = 100;
		}
		$count = (int)$count;
		$start = ($step - 1) * $count;
		$next = $start + $count;
		$step++;
		$jumpurl = 'admincp.php?action=batch&type=msg&step='.$step.'&count='.$count.'&msgto='.$msgto.'&title='.rawurlencode($title).'&';
		$DB->db_query("SELECT uid, username FROM {$db_prefix}members WHERE groupid IN (".$msgto.") ORDER BY uid LIMIT $start, $count");
		if ($DB->db_num())
		{
			$insert = $uids = '';
			while ($rs = $DB->db_fetch_array())
			{
				$insert .= "(0, ".$rs['uid'].", '$title', '".str_replace('{!--username--}', $rs['username'], $msg_content)."', 'r', $timestamp, 0, 1),";
				$uids .= $rs['uid'].',';
			}
			$DB->db_query("INSERT INTO {$db_prefix}message (fuid, tuid, title, content, type, postdate, ifread, ifsys) 
							VALUES ".substr($insert, 0, -1));
			$DB->db_query("UPDATE {$db_prefix}memberdata SET newmsg = newmsg + 1 WHERE uid IN (".substr($uids, 0, -1).")");
			redirect(sprintf($a_message['send_process'], $start, $next), $jumpurl);
		}
		else
		{
			PDel($msgCache);
			redirect($a_message['send_success'], $baseurl.'msg');
		}
	}
	else
	{
		$group = array();
		foreach ($grouplevel as $key => $value)
		{
			if (($key == 5) || $key > 6) continue;
			$group[$key] = $value['grouptitle'];
		}
		$group['-1'] = $a_message['common_member'];
		$TPL->assign('msgto', html_checkbox($group, 'msgto[]', array(), 3));
	}
}
elseif ($type == 'invitecode')
{
	if (!$step || $step == 'apply')
	{
		if ($submitted)
		{
			if (!$id || !is_array($id)) showMsg('参数错误');
			switch ($feedback)
			{
				case '1':
					$endtime = $timestamp + 1296000;
					$insertstr = $msg = '';
					foreach ($id as $v)
					{
						$rs = $DB->db_fetch_one_array("SELECT uid, applynum FROM {$db_prefix}applyinvite WHERE id = '$v'");
						$id = $rs['applynum'];
						while ($id)
						{
							$insertstr .= "(".$rs['uid'].", '".substr(md5($timestamp.random(8).$pb_sitehash), 8, 18)."', '".$timestamp."', '".$endtime."'),";
							$id--;
						}
						if ($insertstr)
						{
							$DB->db_query("INSERT INTO {$db_prefix}invitecode (uid, invitecode, createtime, endtime) VALUES ".substr($insertstr, 0, -1));
							$DB->db_query("DELETE FROM {$db_prefix}applyinvite WHERE id = $v");
							$DB->db_query("INSERT INTO {$db_prefix}message (fuid, tuid, title, content, type, postdate, ifread, ifsys) VALUES (0, ".$rs['uid'].", '邀请码申请审核通过', '您申请的".$rs['applynum']."个注册邀请码已经通过审核。<br />请您在15天内使用。逾期将自动失效。', 'r', $timestamp, 0, 1)");
						}
					}
					break;

				default:
						$id = implode(',', $id);
						$id && $DB->db_query("DELETE FROM {$db_prefix}applyinvite WHERE id IN ($id)");
					break;
			}
			redirect('操作成功', $actionurl.'&amp;step=apply');
		}
		else
		{
			!in_array($ad, array('ASC', 'DESC')) && $ad = 'ASC';
			$newad = ($ad == 'ASC') ? 'DESC' : 'ASC';
			if ($orderby && in_array($orderby, array('id', 'uid', 'applydate')))
			{
				$sql = $orderby.' '.$ad;
			}
			else
			{
				$sql = 'applydate';
			}
			$apply = array();
			$pagesize = 30;
			$page = !isPage($page) ? 1 : $page;
			$start_limit = ($page -1) * $pagesize;
			$rs = $DB->db_fetch_one_array("SELECT COUNT(*) num FROM {$db_prefix}applyinvite");
			$totalRecords = $rs['num'] ? $rs['num'] : 0;
			$mult = cpmultLink($page, $totalRecords, 'admincp.php?action=batch&amp;type=invitecode&amp;step=apply&amp;', $pagesize);
			$SQL = "SELECT * FROM {$db_prefix}applyinvite ORDER BY $sql LIMIT $start_limit, $pagesize";
			$DB->db_query($SQL);
			if ($DB->db_num())
			{
				while ($rt = $DB->db_fetch_array())
				{
					$rt['applydate'] = gdate($rt['applydate'], 'm-d H:i');
					$apply[] = $rt;
				}
			}
			$TPL->assign('step', 'apply');
			$TPL->assign('newad', $newad);
			$TPL->assign('mult', $mult);
			$TPL->assign('total_records', $totalRecords);
			$TPL->assign('apply', $apply);
		}
	}
	elseif ($step == 'manage')
	{
		$invitecode = array();
		$pagesize = 20;
		$page = !isPage($page) ? 1 : $page;
		$start_limit = ($page -1) * $pagesize;
		$rs = $DB->db_fetch_one_array("SELECT COUNT(*) num FROM {$db_prefix}invitecode");
		$totalRecords = $rs['num'] ? $rs['num'] : 0;
		$mult = cpmultLink($page, $totalRecords, 'admincp.php?action=batch&amp;type=invitecode&amp;step=manage&amp;', $pagesize);
		$SQL = "SELECT i.*, m.username FROM {$db_prefix}invitecode i 
				LEFT JOIN {$db_prefix}members m 
				ON i.uid = m.uid 
				ORDER BY i.id DESC 
				LIMIT $start_limit, $pagesize";
		$DB->db_query($SQL);
		if ($DB->db_num())
		{
			while ($rt = $DB->db_fetch_array())
			{
				$rt['createtime'] = gdate($rt['createtime'], 'Y-m-d H:i');
				if (!$rt['endtime'])
				{
					$rt['endtime'] = $cp_message['notimelimit'];
				}
				elseif ($rt['endtime'] < $timestamp)
				{
					$rt['endtime'] = '<span class="r">'.gdate($rt['endtime'], 'Y-m-d H:i').'</span>';
				}
				else
				{
					$rt['endtime'] = gdate($rt['endtime'], 'Y-m-d H:i');
				}
				if (!$rt['username'])
				{
					$rt['username'] = '系统生成';
				}
				$invitecode[] = $rt;
			}
		}
		$actionurl .= '&amp;step=del';
		$TPL->assign('step', 'manage');
		$TPL->assign('mult', $mult);
		$TPL->assign('total_records', $totalRecords);
		$TPL->assign('invitecode', $invitecode);
	}
	elseif ($step == 'del')
	{
		if (empty ($id) || !is_array($id))
		{
			showMsg($a_message['parameter_error'], $actionurl.'&amp;step=manage');
		}
		$id = implode(',', $id);
		if ($id)
		{
			$DB->db_query("DELETE FROM {$db_prefix}invitecode WHERE id IN ($id)");
		}
		redirect($a_message['del_success'], $actionurl.'&amp;step=manage');
	}
	elseif ($step == 'make')
	{
		if ($submitted)
		{
			$num = intval($num);
			$matchs = array();
			if (!$num)
			{
				$num = 100;
			}
			if (!$endtime || ($endtime != '-1' && !preg_match('/^(\d{4})-(\d{1,2})-(\d{1,2})$/i', $endtime, $matchs)))
			{
				showMsg($a_message['invitecode_illegal_endtime'], $actionurl.'&amp;step=make');
			}
			$endtime = ($endtime == '-1') ? '' : mktime(0,0,0,$matchs[2],$matchs[3],$matchs[1]);
			$endtime != '-1' && $endtime <= $timestamp && showMsg('过期时间不能小于当前时间');
			$insertstr = '';
			while ($num)
			{
				$insertstr .= "(0, '".substr(md5($timestamp.random(8).$pb_sitehash), 8, 18)."', '".$timestamp."', '".$endtime."'),";
				$num --;
			}
			if ($insertstr)
			{
				$DB->db_query("INSERT INTO {$db_prefix}invitecode (uid, invitecode, createtime, endtime) VALUES ".substr($insertstr, 0, -1));
			}
			showMsg($a_message['invitecode_make_success'], $actionurl.'&amp;step=make');
		}
		else
		{
			$actionurl .= '&amp;step=make&amp;submitted=1';
			$TPL->assign('js_more', '<script type="text/javascript" src="../templates/admin/js/setday.js"></script>');
			$TPL->assign('step', 'make');
		}
	}
	elseif ($step == 'extend')
	{
		if ($submitted)
		{
			if (!$extendto || !$extendnum || !is_numeric($extendnum) || !$endtime || ($endtime != '-1' && !preg_match('/^(\d{4})-(\d{1,2})-(\d{1,2})$/i', $endtime, $matchs)))
			{
				showMsg($a_message['parameter_error'], $actionurl.'&amp;step=extend');
			}
			$sqlendtime = ($endtime == '-1') ? '' : mktime(0,0,0,$matchs[2],$matchs[3],$matchs[1]);
			$sqlendtime && $sqlendtime <= $timestamp && showMsg('过期时间不能小于当前时间');
			$extendnum = (int)$extendnum;
			if (is_array($extendto) && array_map('intval', $extendto))
			{
				$extendto = implode(',', $extendto);
			}
			if (!preg_match('/[0-9,]/i', $extendto))
			{
				showMsg($a_message['parameter_error'], $actionurl.'&amp;step=extend');
			}
			$count = 100;
			$page = !isPage($page) ? 1 : $page;
			$start = ($page - 1) * $count;
			$next = $start + $count;
			$page++;
			$jumpurl = 'admincp.php?action=batch&type=invitecode&step=extend&submitted=1&page='.$page.'&extendto='.$extendto.'&extendnum='.$extendnum.'&endtime='.$endtime;
			$DB->db_query("SELECT uid FROM {$db_prefix}members WHERE groupid IN ($extendto) LIMIT $start, $count");
			if ($DB->db_num())
			{
				$uids = array();
				while ($rs = $DB->db_fetch_array())
				{
					$invitecodeinsert = '';
					$i = $extendnum;
					while ($i)
					{
						$invitecodeinsert .= "(".$rs['uid'].", '".substr(md5($timestamp.random(8).$pb_sitehash), 8, 18)."', '$timestamp', '$sqlendtime'),";
						$i--;
					}
					if ($invitecodeinsert)
					{
						$uids[$rs['uid']] = substr($invitecodeinsert, 0, -1);
					}
				}
				foreach ($uids as $key => $value)
				{
					$DB->db_query("INSERT INTO {$db_prefix}invitecode (uid, invitecode, createtime, endtime) VALUES ".$value);
					$DB->db_query("INSERT INTO {$db_prefix}message (fuid, tuid, title, content, type, postdate, ifread, ifsys) VALUES (0, $key, '".$a_message['invitecode_msgtitle']."', '".$a_message['invitecode_extend_intro']."', 'r', $timestamp, 0, 1)");
				}
				redirect(sprintf($a_message['send_process'], $start, $next), $jumpurl);
			}
			else
			{
				redirect($a_message['send_success'], $actionurl.'&amp;step=extend');
			}
		}
		else
		{
			$group = array();
			foreach ($grouplevel as $key => $value)
			{
				if (($key == 5) || $key > 6) continue;
				$group[$key] = $value['grouptitle'];
			}
			$group['-1'] = $a_message['common_member'];
			$TPL->assign('extendto', html_checkbox($group, 'extendto[]', array('1','2','-1'), 3));
			$TPL->assign('js_more', '<script type="text/javascript" src="../templates/admin/js/setday.js"></script>');
			$actionurl .= '&amp;step=extend&amp;submitted=1';
			$TPL->assign('step', 'extend');
		}
	}
	elseif ($step == 'tidy')
	{
		if ($submitted)
		{
			$sql = '';
			if ($createtime != '-1')
			{
				$sql .= " WHERE endtime <> 0 AND endtime < $timestamp";
				if ($createtime && preg_match('/^(\d{4})-(\d{1,2})-(\d{1,2})$/i', $createtime, $matchs))
				{
					$createtime = mktime(0,0,0,$matchs[2],$matchs[3],$matchs[1]);
					if ($createtime && $createtime != '-1')
					{
						$sql .= ' OR createtime < '.$createtime;
					}
				}
			}
			$DB->db_query("DELETE FROM {$db_prefix}invitecode".$sql);
			redirect($a_message['invitecode_tidy_success'], $actionurl.'&amp;step=tidy');
		}
		else
		{
			$actionurl .= '&amp;step=tidy&amp;submitted=1';
			$TPL->assign('js_more', '<script type="text/javascript" src="../templates/admin/js/setday.js"></script>');
		}
	}
}
else
{
	redirect($a_message['unknow_operate'], 'admincp.php?action=main');
}

$TPL->assign('menu', $m_batch);

?>
