<?php
/**
 * @version $Id: member.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', 'member');
allowdo('setmember');
$baseurl = 'admincp.php?action=member&type=';
require_once (PBDIGG_ROOT.'include/member.class.php');
$Member = new Member();

if ($type == 'add' || empty($type)) 
{
	//add new member
	if ($submitted)
	{
		$Member->Action('add', array('username'=>trim($_POST['username']), 'password'=>trim($_POST['password']), 'email'=>trim($_POST['email']), 'groupid'=>(int)$_POST['groupid'], 'ignore'=>'1', 'exp'=>array('ctsig'=>0)));
		redirect($a_message['add_member_success'], $actionurl);
	}
	else
	{
		$group_option = array();
		foreach ($grouplevel as $key => $value)
		{
			$group_option[$key] = $value['grouptitle'];
		}
		//default add common user
		$group_option = html_select($group_option, 'groupid', 7, 'id="groupid"');
		$TPL->assign('group_option', $group_option);
		$type = 'add';
	}
}
elseif ($type == 'manage')
{
	if ($submitted)
	{
		//search member
		$sql = '1';
		$pattern = array('%','_','*');
		$replace = array('\%','\_','%');
		$username = strip_tags(trim(isset($_POST['username']) ? $_POST['username'] : $_GET['username']));
		if ($username && (strlen($username) < 20))
		{
			$username = preg_replace('/\*{2,}/i', '', $username);
			$username = str_replace($pattern, $replace, $username);
			$sql .= " AND m.username LIKE '$username'";
		}
		$email = trim(isset($_POST['email']) ? $_POST['email'] : $_GET['email']);
		if ($email && isEMAIL($email) && (strlen($email) < 100))
		{
			$email = preg_replace('/\*{2,}/i', '', $email);
			$email = str_replace($pattern, $replace, $email);
			$sql .= " AND m.email LIKE '$email'";
		}
		$groupid = (int)$groupid;
		if ($groupid)
		{
			$groupid = ($groupid == 7) ? -1 : $groupid;
			$sql .= " AND m.groupid = $groupid";
		}
		//register time
		$later = trim($later);
		if (preg_match('/^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})/i', $later))
		{
			$later = strtotime($later.' 0:0:0');
			$sql .= " AND m.regdate > '$later'";
		}
		$earlier = trim($earlier);
		if (preg_match('/^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})/i', $earlier))
		{
			$earlier = strtotime($earlier.' 23:59:59');
			$sql .= " AND m.regdate < '$earlier'";
		}
		//last login date
		$logdate = trim($logdate);
		if (preg_match('/^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})/i', $logdate))
		{
			$logdate = strtotime($logdate);
			$sql .= " AND md.lastvisit < '$logdate'";
		}
		exchange($articlemore, $articleless);
		if ($articleless === '0' && $articlemore === '0')
		{
			$sql .= " AND md.postnum = 0";
		}
		else
		{
			if (is_numeric($articleless))
			{
				$articleless = (int)$articleless;
				$sql .= " AND md.postnum < $articleless";
			}
			if (is_numeric($articlemore))
			{
				$articlemore = (int)$articlemore;
				$sql .= " AND md.postnum > $articlemore";
			}
		}
		exchange($currencymore, $currencyless);
		if ($currencyless === '0' && $currencymore === '0')
		{
			$sql .= " AND md.currency = 0";
		}
		else
		{
			if (is_numeric($currencyless))
			{
				$currencyless = (int)$currencyless;
				$sql .= " AND md.currency < $currencyless";
			}
			if (is_numeric($currencymore))
			{
				$currencymore = (int)$currencymore;
				$sql .= " AND md.currency > $currencymore";
			}
		}
		if (!in_array($orderby, array('m.username','m.email','m.regdate','md.lastvisit','md.postnum','md.currency')))
		{
			$orderby = 'm.username';
		}
		$sql .= " ORDER BY $orderby";
		if (!in_array($ordertype, array('ASC','DESC')))
		{
			$ordertype = 'ASC';
		}
		$sql .= " $ordertype";
		$pagesize = (int)$pagesize;
		if (!$pagesize || ($pagesize < 0))
		{
			$pagesize = 30;
		}
		$rs = $DB->db_fetch_one_array("SELECT COUNT(*) num FROM {$db_prefix}members m INNER JOIN {$db_prefix}memberdata md USING (uid) WHERE $sql");
		$totalRecords = (int)$rs['num'];
		$page = !isPage($page) ? 1 : $page;
		$start_limit = ($page -1) * $pagesize;
		$mult = cpmultLink($page, $totalRecords, 'admincp.php?action=member&type=manage&submitted=1&username='.rawurlencode($username).'&email='.$email.'&groupid='.$groupid.'&later='.$later.'&earlier='.$earlier.'&logdate='.$logdate.'&articleless='.$articleless.'&articlemore='.$articlemore.'&currencyless='.$currencyless.'&currencymore='.$currencymore.'&orderby='.$orderby.'&ordertype='.$ordertype.'&pagesize='.$pagesize.'&', $pagesize);
		$SQL = "SELECT m.uid, m.username, m.email, m.groupid, m.regdate, md.lastvisit FROM {$db_prefix}members m 
				LEFT JOIN {$db_prefix}memberdata md 
				USING(uid) 
				WHERE $sql LIMIT $start_limit, $pagesize";
		$DB->db_query($SQL);
		$member = $rs = array();
		while ($rs = $DB->db_fetch_array())
		{
			if ($rs['groupid'] == '-1')
			{
				$rs['group'] = $grouplevel['7']['grouptitle'];
			}
			else
			{
				$rs['group'] = $grouplevel[$rs['groupid']]['grouptitle'];
			}
			$rs['regdate'] = gdate($rs['regdate'], 'Y-m-d H:i');
			$rs['lastvisit'] = gdate($rs['lastvisit'], 'Y-m-d H:i');
			$member[] = $rs;
		}
		$type = 'list';
		$TPL->assign('member', $member);
		$TPL->assign('mult', $mult);
		$TPL->assign('total_records', $totalRecords);
	}
	elseif ($find)
	{
		//shortcut search
		$sql = '1';
		switch ($find)
		{
			case 'newest':
				$numsql = "SELECT COUNT(*) num FROM {$db_prefix}members WHERE regdate > $timestamp - 259200";
				$sql .= ' AND m.regdate >'.($timestamp - 259200);
				break;
			
			case 'currency':
				$numsql = "SELECT COUNT(*) num FROM {$db_prefix}memberdata WHERE currency < 0";
				$sql .= ' AND md.currency < 0';
				break;
			
			case 'article':
				$numsql = "SELECT COUNT(*) num FROM {$db_prefix}memberdata WHERE postnum = 0";
				$sql .= ' AND md.postnum = 0';
				break;
			
			default:
				$numsql = "SELECT COUNT(*) num FROM {$db_prefix}members";
				break;
		}
		$pagesize = 30;
		$rs = $DB->db_fetch_one_array($numsql);
		$totalRecords = (int)$rs['num'];
		$page = !isPage($page) ? 1 : $page;
		$start_limit = ($page -1) * $pagesize;
		$mult = cpmultLink($page, $totalRecords, 'admincp.php?action=member&type=manage&find='.$find.'&', $pagesize);
		$SQL = "SELECT m.uid, m.username, m.email, m.groupid, m.regdate, md.lastvisit FROM {$db_prefix}members m 
				LEFT JOIN {$db_prefix}memberdata md 
				USING(uid) 
				WHERE $sql LIMIT $start_limit, $pagesize";
		$DB->db_query($SQL);
		$member = $rs = array();
		while ($rs = $DB->db_fetch_array())
		{
			if ($rs['groupid'] == '-1')
			{
				$rs['group'] = $grouplevel['7']['grouptitle'];
			}
			else
			{
				$rs['group'] = $grouplevel[$rs['groupid']]['grouptitle'];
			}
			$rs['regdate'] = gdate($rs['regdate'], 'Y-m-d H:i');
			$rs['lastvisit'] = gdate($rs['lastvisit'], 'Y-m-d H:i');
			$member[] = $rs;
		}
		$type = 'list';
		$TPL->assign('member', $member);
		$TPL->assign('mult', $mult);
		$TPL->assign('total_records', $totalRecords);
	}
	else
	{
		$group_option = array('0'=>$cp_message['all_group']);
		foreach ($grouplevel as $key => $value)
		{
			$group_option[$key] = $value['grouptitle'];
		}
		//default add common user
		$group_option = html_select($group_option, 'groupid', 0, 'id="groupid"');
		$TPL->assign('group_option', $group_option);
	}
}
elseif ($type == 'del')
{
	if ($uid)
	{
		$Member->setUID($_POST['uid']);
		$Member->Action('del');
		redirect($a_message['del_member_success'], 'admincp.php?action=member&type=manage');
	}
}
elseif ($type == 'check')
{
	if ($checktype)
	{
		//del or pass
		$Member->setUID($_POST['uid']);
		switch ($checktype)
		{
			case 'del':
				$Member->Action('del');
				redirect($a_message['del_member_success'], $actionurl);
			
			case 'pass':
				$Member->Action('check', TRUE);
				redirect($a_message['check_member_success'], $actionurl);
			default:
				redirect($a_message['parameter_error'], $actionurl);
		}
	}
	//ready for check
	$rs = $DB->db_fetch_one_array("SELECT COUNT(*) num FROM {$db_prefix}members m WHERE groupid = 6");
	$totalRecords = (int)$rs['num'];
	$pagesize = 30;
	$page = !isPage($page) ? 1 : $page;
	$start_limit = ($page -1) * $pagesize;
	$mult = cpmultLink($page, $totalRecords, 'admincp.php?action=member&type=check&', $pagesize);
	$SQL = "SELECT m.uid, m.username, m.email, m.regdate FROM {$db_prefix}members m 
			WHERE groupid = 6 LIMIT $start_limit, $pagesize";
	$DB->db_query($SQL);
	$member = $rs = array();
	while ($rs = $DB->db_fetch_array())
	{
		$rs['regdate'] = gdate($rs['regdate'], 'Y-m-d H:i');
		$member[] = $rs;
	}
	$TPL->assign('member', $member);
	$TPL->assign('mult', $mult);
	$TPL->assign('total_records', $totalRecords);
}
elseif ($type == 'mod')
{
	if ($submitted)
	{
		if (empty($uid) || !is_numeric($uid))
		{
			redirect($a_message['parameter_error'], $baseurl.'search');
		}
		$actionurl .= "&uid=$uid";
		$exp = array('qq'=>'','msn'=>'','site'=>'','location'=>'','gender'=>'','birthday'=>'','signature'=>'','showsign'=>'');
		$updatedata = array('uid'=>(int)$uid, 'username'=>$_POST['username'], 'password'=>$_POST['password'], 'rpassword'=>$_POST['rpassword'], 'email'=>$_POST['email'], 'publicemail'=>(isset($ifpublicemail) ? '1': '0'), 'groupid'=>(int)$_POST['groupid'], 'ignore'=>'1');
		if ($qq && checkQQ($qq))
		{
			$exp['qq'] = $qq;
		}
		if ($msn && checkMSN($msn))
		{
			$exp['msn'] = $msn;
		}
		if ($site && !checkURL($site))
		{
			$exp['site'] = $site;
		}
		if ($location && !checkLocation($location))
		{
			$exp['location'] = $location;
		}
		$exp['gender'] = (int)$gender;

		$birthday = $year.'-'.$month.'-'.$day;
		if (preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}/i', $birthday))
		{
			$exp['birthday'] = $birthday;
		}
		$exp['signature'] = HConvert($_POST['signature']);
		$exp['showsign'] = (isset($showsign) ? '1': '0');
		$updatedata['exp'] = $exp;
		$Member->Action('mod', $updatedata);
		redirect($a_message['mod_member_success'], $actionurl);
	}
	else
	{
		if (empty($uid))
		{
			redirect($a_message['parameter_error'], $baseurl.'search');
		}
		$uid = (int)$_GET['uid'];
		$SQL = "SELECT m.*, mx.* FROM {$db_prefix}members m 
				LEFT JOIN {$db_prefix}memberexp mx USING(uid) WHERE m.uid = $uid";
		$member = $DB->db_fetch_one_array($SQL);
		if ($member)
		{
			radioChecked('gender_', $member['gender'], 4);
			$TPL->assign('gender_0', $gender_0);
			$TPL->assign('gender_1', $gender_1);
			$TPL->assign('gender_3', $gender_3);
			unset($gender_0, $gender_1, $gender_3);
			$ifpublicemail = ($member['publicemail']) ? 'checked="checked"' : '';
			$ifshowsign = ($member['showsign']) ? 'checked="checked"' : '';
		}
		else
		{
			redirect($a_message['member_not_exist'], $baseurl.'search');
		}
		list($year, $month, $day) = explode('-', $member['birthday']);
		require_once (PBDIGG_ROOT.'include/DateTime.php');
		$year_option = html_select($_YEAR, 'year', $year, 'id="year"');
		$month_option = html_select($_MONTH, 'month', $month, 'id="month"');
		$day_option = html_select($_DAY, 'day', $day, 'id="day"');
		$group_option = array();
		foreach ($grouplevel as $key => $value)
		{
			$group_option[$key] = $value['grouptitle'];
		}
		//default add common user
		$groupid = ($member['groupid'] == -1) ? 7 : $member['groupid'];
		$group_option = html_select($group_option, 'groupid', $groupid, 'id="groupid"');
		$TPL->assign('group_option', $group_option);
		$TPL->assign('year_option', $year_option);
		$TPL->assign('month_option', $month_option);
		$TPL->assign('day_option', $day_option);
		$TPL->assign('member', $member);
		$TPL->assign('ifshowsign', $ifshowsign);
		$actionurl .= '&uid='.$uid;
		if ($pb_ucenable) $TPL->assign('modusername', 'disabled="disabled"');
		$TPL->assign('ifpublicemail', $ifpublicemail);
	}
}
elseif ($type == 'tidy')
{
	if ($step)
	{
		$count = (int)$count;
		$start = ($step - 1) * $count;
		$next = $start + $count;
		$step++;
		$jumpurl = 'admincp.php?action=member&type=tidy&step='.$step.'&count='.$count;
		$uid = array();
		$DB->db_query("SELECT uid FROM {$db_prefix}members LIMIT $start, $count");
		while ($rs = $DB->db_fetch_array())
		{
			$uid[] = $rs['uid'];
		}
		if ($uid)
		{
			foreach ($uid as $value)
			{
				//update user's article
				$rs = $DB->db_fetch_one_array("SELECT COUNT(*) num FROM {$db_prefix}threads WHERE uid = ".$value['uid']);
				$postnum = $rs['num'];
				$rs = $DB->db_fetch_one_array("SELECT COUNT(*) num FROM {$db_prefix}comments WHERE uid = ".$value['uid']);
				$commentnum = $rs['num'];
				$rs = $DB->db_fetch_one_array("SELECT COUNT(*) num FROM {$db_prefix}attachments WHERE uid = ".$value['uid']);
				$uploadnum = $rs['num'];
				$rs = $DB->db_fetch_one_array("SELECT COUNT(*) num FROM {$db_prefix}tdata td, {$db_prefix}threads t WHERE td.type = 'digg' AND td.uid = t.uid AND td.tid = t.tid AND td.uid = ".$value['uid']);
				$diggnum = $rs['num'];
				$rs = $DB->db_fetch_one_array("SELECT COUNT(*) num FROM {$db_prefix}tdata td, {$db_prefix}threads t WHERE td.type = 'bury' AND td.uid = t.uid AND td.tid = t.tid AND td.uid = ".$value['uid']);
				$burynum = $rs['num'];
				$DB->db_query("UPDATE {$db_prefix}memberdata SET postnum = $postnum, commentnum = $commentnum, diggnum = $diggnum, burynum = $burynum, uploadnum = $uploadnum WHERE uid = ".$value['uid']);
			}
			redirect(sprintf($a_message['tidy_member_process'], $start, $next), $jumpurl);
		}
		$Cache->tags();
		redirect($a_message['tidy_member_success'], $baseurl.'tidy');
	}
}
else
{
	redirect($a_message['unknow_operate'], 'admincp.php?action=main');
}

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

?>