<?php
define('PRO','1');
define('SCR','profile');
require_once('global.php');
!$winduid && Showmsg('not_login');

require_once(R_P.'require/bbscode.php');
require_once(R_P.'require/postfunc.php');
include_once(D_P.'data/bbscache/level.php');
require_once(R_P.'require/header.php');

InitGP(array('action'));

if (empty($action)) {

	$userdb = $db->get_one("SELECT m.groupid,m.memberid,m.icon,m.regdate,m.honor,md.postnum,md.digests,md.rvrc,md.money,md.credit,md.currency,md.starttime,md.lastvisit,md.onlinetime,mb.deposit,mb.ddeposit FROM pw_members m LEFT JOIN pw_memberdata md USING(uid) LEFT JOIN pw_memberinfo mb USING(uid) WHERE m.uid=".pwEscape($winduid));
	require_once(R_P.'require/showimg.php');
	require_once(R_P.'require/credit.php');
	$creditdb = $credit->get($winduid,'CUSTOM');
	$iconarray= explode('|',$userdb['icon']);
	$userface = showfacedesign($userdb['icon']);
	$systitle = $userdb['groupid']=='-1' ? '' : $ltitle[$userdb['groupid']];
	$memtitle = $ltitle[$userdb['memberid']];
	$userdb['rvrc'] = floor($userdb['rvrc']/10);
	if ($userdb['onlinetime']) {
		$userdb['onlinetime'] = floor($userdb['onlinetime']/3600);
	} else {
		$userdb['onlinetime'] = 0;
	}
	$userdb['regdate'] = get_date($userdb['regdate'],'Y-m-d');
	$userdb['lastvisit'] = get_date($userdb['lastvisit'],'Y-m-d');

	$msgdb = $favordb = $colonydb = array();
	$query = $db->query("SELECT m.mid,m.fromuid,m.touid,m.username,m.ifnew,m.mdate,mc.title FROM pw_msg m LEFT JOIN pw_msgc mc USING(mid) WHERE m.type='rebox' AND m.touid=".pwEscape($winduid)."ORDER BY m.mdate DESC LIMIT 5");
	while ($rt = $db->fetch_array($query)) {
		$rt['title'] = substrs($rt['title'],30,1);
		$rt['mdate'] = get_date($rt['mdate']);
		$msgdb[] = $rt;
	}

	$ftids = $db->get_value("SELECT tids FROM pw_favors WHERE uid=".pwEscape($winduid));
	if ($ftids) {
		$tids = array();
		$tids_a = explode(',',str_replace('|',',',$ftids));
		$num = 0;
		foreach ($tids_a as $value) {
			if (is_numeric($value)) {
				$num++;
				$tids[] = $value;
			}
			if ($num == 5) break;
		}
		if ($tids) {
			$tids = pwImplode($tids);
			include_once(D_P.'data/bbscache/forum_cache.php');
			$query = $db->query("SELECT fid,tid,subject,postdate,author,authorid,anonymous FROM pw_threads WHERE tid IN($tids) ORDER BY postdate DESC");
			while ($rt = $db->fetch_array($query)) {
				if ($rt['anonymous'] && $rt['author'] != $windid) {
					$rt['author'] = $db_anonymousname;
					$rt['authorid'] = 0;
				}
				$rt['subject'] = substrs($rt['subject'],30);
				$rt['postdate'] = get_date($rt['postdate']);
				$rt['forum'] = $forum[$rt['fid']]['name'];
				$favordb[] = $rt;
			}
		}
		unset($forum,$tids_a,$tids,$num);
	}

	$query = $db->query("SELECT cy.id,cy.cname FROM pw_cmembers c LEFT JOIN pw_colonys cy ON cy.id=c.colonyid WHERE c.uid=".pwEscape($winduid));
	while ($rt = $db->fetch_array($query)) {
		$colonydb[] = $rt;
	}
	$db->free_result($query);

	if ($_G['ifmemo']) {
		list($userdb['mmid'],$userdb['postdate'],$userdb['mcontent']) = $db->get_one("SELECT mid,postdate,content FROM pw_memo WHERE isuser='1' AND username=".pwEscape($windid),MYSQL_NUM);
		$userdb['mmid'] = (int)$userdb['mmid'];
		$userdb['postdate'] && $userdb['postdate'] = get_date($userdb['postdate'],'Y-m-d H:i:s');
		if ($userdb['mcontent']) {
			$userdb['mcontent'] = str_replace('<br />',"\n",$userdb['mcontent']);
			$SCR = 'post';
		}
	}
	require_once(PrintEot('profile'));footer();

} elseif ($action == 'show') {

	InitGP(array('uid','username'));
	ObHeader('u.php?action=show&'.($username ? 'username='.$username : 'uid='.$uid));

} elseif ($action == 'modify') {

	@include_once(D_P.'data/bbscache/customfield.php');
	require_once(R_P.'require/showimg.php');
	$ifppt = false;
	$madd = $mbadd = '';

	if (!$db_pptifopen || $db_ppttype == 'server') {
		$ifppt = true;
		$madd .= ',m.password';
	}
	!is_array($customfield) && $customfield = array();
	foreach ($customfield as $key => $value) {
		$customfield[$key]['id'] = $value['id'] = (int)$value['id'];
		$customfield[$key]['field'] = "field_$value[id]";
		if ($value['type'] == 3 && $_POST['step'] != 2) {
			$customfield[$key]['options'] = explode("\n",$value['options']);
		} elseif ($value['type'] == 2) {
			$SCR = 'post';
		}
		$mbadd .= ",mb.field_$value[id]";
	}
	$db_union[7] && $mbadd .= ',mb.customdata';

	$userdb = $db->get_one("SELECT m.email$madd,m.groupid,m.groups,m.icon,m.gender,m.signature,m.introduce,m.oicq,m.aliww,m.msn,m.yahoo,m.site,m.location,m.honor,m.bday,m.timedf,m.datefm,m.t_num,m.p_num,m.userstatus,md.currency,md.starttime,mb.tradeinfo{$mbadd} FROM pw_members m LEFT JOIN pw_memberdata md USING(uid) LEFT JOIN pw_memberinfo mb USING(uid) WHERE m.uid=".pwEscape($winduid));
	list($iconurl,$icontype,$iconwidth,$iconheight,$iconfile,$iconpig) = showfacedesign($userdb['icon'],true);

	if (empty($_POST['step'])) {

		unset($iconpig);
		include_once(D_P.'data/bbscache/dbreg.php');
		require_once(R_P.'require/forum.php');
		require_once(R_P.'require/header.php');
		$customdata = $custominfo = $sexselect = $yearslect = $monthslect = $dayslect = array();
		$ifpublic = $iconsize = $groupselect = $httpurl = '';
		$ifsign = false;

		InitGP(array('info_type'));
		!in_array($info_type,array('base','trade','link','face','safe','other')) && $info_type = 'base';

		getstatus($userdb['userstatus'],7) && $ifpublic = 'checked';

		if ($db_selectgroup && $userdb['groups']) {
			$groupselect = $userdb['groupid']=='-1' ? '<option></option>' : "<option value=\"$userdb[groupid]\">".$ltitle[$userdb['groupid']]."</option>";
			$groups = explode(',',$userdb['groups']);
			foreach ($groups as $value) {
				if ($value && array_key_exists($value,$ltitle)) {
					$groupselect .= "<option value=\"$value\">$ltitle[$value]</option>";
				}
			}
		}
		$db_union[7] && list($customdata,$custominfo) = Getcustom($userdb['customdata']);

		$sexselect[(int)$userdb['gender']] = 'checked';

		!$rg_timestart && $rg_timestart = 1960;
		!$rg_timeend && $rg_timeend = 2000;
		$getbirthday = explode('-',$userdb['bday']);
		$yearslect[(int)$getbirthday[0]] = $monthslect[(int)$getbirthday[1]] = $dayslect[(int)$getbirthday[2]] = 'selected';

		$width2 = $width3 = $iconwidth;
		$height2 = $height3 = $iconheight;
		$iconwidth && $iconsize = " width=\"$iconwidth\"";
		$iconheight && $iconsize .= " height=\"$iconheight\"";

		if ($icontype == 2) {
			$httpurl = $iconurl;
			$width3 = $height3 = '';
		} elseif ($icontype == 3) {
			$width2 = $height2 = '';
		}
		if ($userdb['signature'] || $userdb['introduce']) {
			$SCR = 'post';
		}
		if (!is_array($trade = unserialize($userdb['tradeinfo']))) {
			$trade = array();
		}
		//系統頭像
		$img = @opendir("$imgdir/face");
		while ($imgname = @readdir($img)) {
			if ($imgname != "." && $imgname != ".." && $imgname != "" && eregi("\.(gif|jpg|png|bmp)$",$imgname)) {
				$num++;
				$imgname_array[] = $imgname;
				if ($num >= 10) break;
			}
		}
		@closedir($img);
		require_once(PrintEot('profile'));footer();

	} else {

		PostCheck();
		Add_S($userdb);
		$ustatus = '';
		$upmembers = $upmemdata = $upmeminfo = array();

		if ($ifppt) {

			include_once(D_P.'data/bbscache/dbreg.php');
			InitGP(array('propwd','proemail'),'P');
			if ($propwd || $userdb['email'] != $proemail) {
				if ($_POST['oldpwd']) {
					if (strlen($userdb['password']) == 16) {
						$_POST['oldpwd'] = substr(md5($_POST['oldpwd']),8,16);//支持 16 位 md5截取密碼
					} else {
						$_POST['oldpwd'] = md5($_POST['oldpwd']);
					}
				}
				$userdb['password'] != $_POST['oldpwd'] && Showmsg('pwd_confirm_fail');
				if ($propwd) {
					CkInArray($windid,$manager) && Showmsg('pro_manager');
					$propwd != $_POST['check_pwd'] && Showmsg('password_confirm');
					if ($propwd != str_replace(array("\\",'&',' ',"'",'"','/','*',',','<','>',"\r","\t","\n",'#','%'),'',$propwd)) {
						Showmsg('illegal_password');
					}
					if ($rg_pwdcomplex) {
						$arr_rule = array();
						$arr_rule = explode(',',$rg_pwdcomplex);
						foreach ($arr_rule as $value) {
							$value = (int)$value;
							if (!$value) continue;
							switch ($value) {
								case 1:
									if (!preg_match('/[a-z]/',$propwd)) {
										Showmsg('reg_password_lowstring');
									}
									break;
								case 2:
									if (!preg_match('/[A-Z]/',$propwd)) {
										Showmsg('reg_password_upstring');
									}
									break;
								case 3:
									if (!preg_match('/[0-9]/',$propwd)) {
										Showmsg('reg_password_num');
									}
									break;
								case 4:
									if (!preg_match('/[^a-zA-Z0-9\\\/\&\'\"\*\,<>#\?% ]/',$propwd)) {
										Showmsg('reg_password_specialstring');
									}
									break;
							}
						}
					}
					$upmembers['password'] = md5($propwd);
					$upmemdata['pwdctime'] = $timestamp;
				}
				if ($userdb['email'] != $proemail) {
					include_once(D_P.'data/bbscache/dbreg.php');
					$rg_emailcheck && Showmsg('pro_emailcheck');

					$email_check = $db->get_one("SELECT COUNT(*) AS count FROM pw_members WHERE email=".pwEscape($proemail));
					if ($email_check['count'] > 1) {
						Showmsg('reg_email_have_same');
					} else {
						unset($email_check);
					}
				}
			}
			if ($_POST['propublicemail'] != getstatus($userdb['userstatus'],7)) {
				$ustatus .= ',userstatus=userstatus'.($_POST['propublicemail'] ? '|' : '&~') .'(1<<6)';
			}
		} else {
			$proemail = $userdb['email'];
		}
		if (!preg_match('/^[-a-zA-Z0-9_\.]+\@([0-9A-Za-z][0-9A-Za-z-]+\.)+[A-Za-z]{2,5}$/',$proemail)) {
			Showmsg('illegal_email');
		}
		InitGP(array('proicon','prosign','profrom','proyahoo','promsn','prohomepage','prohonor', 'prointroduce','customdata','prooicq','proaliww','proicq','alipay','tradetype','question'),'P');
		InitGP(array('newgroupid','progender','proyear','promonth','proday','facetype'), 'P', 2);

		if ($db_ifsafecv && $question != '-2') {
			$safecv = '';
			if ($db_ifsafecv) {
				require_once(R_P.'require/checkpass.php');
				$safecv = questcode($question,$_POST['customquest'],$_POST['answer']);
			}
			$upmembers['safecv'] = $safecv;
		}

		if ($db_selectgroup && $newgroupid && $newgroupid != $userdb['groupid'] && $userdb['groups']) {
			if (strpos($userdb['groups'],','.$newgroupid.',') === false) {
				Showmsg('undefined_action');
			} else {
				if ($userdb['groupid'] == '-1') {
					$groups = str_replace(",$newgroupid,",',',$userdb['groups']);
					$groups == ',' && $groups = '';
				} else {
					$groups = str_replace(",$newgroupid,",",$userdb[groupid],",$userdb['groups']);
				}
				$upmembers['groupid']	= $newgroupid;
				$upmembers['groups']	= $groups;
			}
		}
		$prooicq && !is_numeric($prooicq) && Showmsg('illegal_OICQ');
		$proicq && !is_numeric($proicq) && Showmsg('illegal_OICQ');

		strlen($prointroduce)>500 && Showmsg('introduce_limit');
		$_G['signnum'] && strlen($prosign) > $_G['signnum'] && Showmsg('sign_limit');
		if ($_G['allowhonor']) {
			$prohonor = substrs($prohonor,90);
			$upmembers['honor'] = $prohonor;
			if ($userdb['honor'] <> $prohonor) {
				pwAddFeed($winduid,'honor','',array('honor' => $prohonor));
			}
		}
		@include_once(D_P.'data/bbscache/wordsfb.php');
		if (!empty($wordsfb) || !empty($replace)) {
			$wordsfb = (array)$wordsfb + (array)$replace;
			foreach ($wordsfb as $key => $value) {
				$banword = (string)stripslashes($key);
				if ($banword && (lowerstrpos($prosign,$banword) || lowerstrpos($prointroduce,$banword) || lowerstrpos($prohonor,$banword))) {
					Showmsg('sign_wordsfb');
				}
			}
		}
		//upmeminfo
		if ($db_union[7]) {
			list($customdata) = Getcustom($customdata,false,true);
			!empty($customdata) && $upmeminfo['customdata'] = addslashes(serialize($customdata));
		}
		foreach ($customfield as $value) {
			$fieldvalue = Char_cv($_POST[$value['field']]);
			if ($value['required'] && !$userdb[$value['field']] && !$fieldvalue) {
				Showmsg('field_empty');
			}
			if ($fieldvalue && $userdb[$value['field']] != $fieldvalue) {
				if ($value['maxlen'] && strlen($fieldvalue) > $value['maxlen']) {
					Showmsg('field_lenlimit');
				}
				$upmeminfo[$value['field']] = $fieldvalue;
			}
		}
		$trade = array();
		if ($alipay && preg_match('/^[-a-zA-Z0-9_\.]+\@([0-9A-Za-z][0-9A-Za-z-]+\.)+[A-Za-z]{2,5}$/',$alipay)) {
			$trade['alipay'] = stripslashes($alipay);
		}
		/*
		if ($tenpay) {
			$trade['tenpay'] = stripslashes($tenpay);
		}
		*/
		if ($tradetype && is_array($tradetype)) {
			$i = 0;
			foreach ($tradetype as $key => $value) {
				if ($key > 0 && $value && is_string($value)) {
					$trade['tradetype'][$key] = stripslashes($value);
				}
				if (++$i > 100) break;
			}
		}
		$tradeinfo = $trade ? addslashes(serialize($trade)) : '';
		if ($tradeinfo <> $userdb['tradeinfo']) {
			$upmeminfo['tradeinfo'] = $tradeinfo;
		}

		//user icon
		$iconfile = addslashes($iconfile);
		if ($_G['allowportait'] && $facetype == 2) {
			$httpurl = $_POST['httpurl'];
			if (strncmp($httpurl[0],'http',4) != 0 || strrpos($httpurl[0],'|') !== false) {
				Showmsg('illegal_customimg');
			}
			$icontype == 3 && DelIcon($iconfile);
			$httpurl[1] = (int)$httpurl[1];
			$httpurl[2] = (int)$httpurl[2];
			$iconfile = $httpurl[0];
			if (empty($httpurl[1]) && empty($httpurl[2])) {
				list($iconwidth,$iconheight) = getimagesize($iconfile);
			} else {
				list($iconwidth,$iconheight) = getfacelen($httpurl[1],$httpurl[2]);
			}
			unset($httpurl);
		} elseif ($db_ifupload && $_G['upload'] && $facetype == 3 && is_array($_POST['uploadurl'])) {
			UploadIcon($_POST['uploadurl']);
		}
		$facetype != 1 && $facetype != 2 && $facetype != 3 && $facetype = $icontype;
		$usericon = GetIcon($proicon);
		pwFtpClose($ftp);
		//update memdata
		if ($upmemdata) {
			$pwSQL = pwSqlSingle($upmemdata);
			$db->update("UPDATE pw_memberdata SET $pwSQL WHERE uid=".pwEscape($winduid));
		}
		//update meminfo
		if ($upmeminfo) {
			$pwSQL = pwSqlSingle($upmeminfo);
			$db->pw_update(
				"SELECT uid FROM pw_memberinfo WHERE uid=".pwEscape($winduid),
				"UPDATE pw_memberinfo SET $pwSQL WHERE uid=".pwEscape($winduid),
				"INSERT INTO pw_memberinfo SET uid=".pwEscape($winduid).','.$pwSQL
			);
		}
		unset($upmemdata,$upmeminfo,$iconurl,$icontype,$iconwidth,$iconheight, $iconfile, $iconpig, $facetype, $customfield);
		//other
		$prohomepage && substr($prohomepage,0,4)!='http' && $prohomepage = "http://$prohomepage";

		$probday = '';
		if ($proyear || $promonth || $proday) {
			$probday = $proyear.'-'.$promonth.'-'.$proday;
		}
		$cksign = convert($prosign,$db_windpic,2);
		$signstatus = $cksign != $prosign ? 1 : 0;

		if ($signstatus != getstatus($userdb['userstatus'],9)) {
			$ustatus .= ',userstatus=userstatus'.($signstatus ? '|' : '&~') .'(1<<8)';
		}
		//update member
		$pwSQL = pwSqlSingle(array_merge($upmembers,array(
			'email' => $proemail, 'icon' => $usericon, 'gender' => $progender, 'signature' => $prosign, 'introduce' => $prointroduce, 'oicq' => $prooicq, 'aliww' => $proaliww, 'icq' => $proicq, 'yahoo' => $proyahoo, 'msn' => $promsn, 'site' => $prohomepage, 'location' => $profrom, 'bday' => $probday
		)));
		$db->update("UPDATE pw_members SET {$pwSQL}$ustatus WHERE uid=".pwEscape($winduid));

		refreshto("profile.php",'operate_success');
	}
} elseif ($action == 'bbsset') {

	$userdb = $db->get_one("SELECT style,timedf,datefm,t_num,p_num,banpm,msggroups,userstatus FROM pw_members WHERE uid=".pwEscape($winduid));

	$t_num = array(10,20,30,40);
	$p_num = array(10,20,30);
	if ($groupid && in_array($groupid,array(3,4,5))) {
		$t_num[] = 100;
		$p_num[] = 100;
	}
	if (empty($_POST['step'])) {

		require_once(R_P.'require/forum.php');
		InitGP(array('info_type'));
		!in_array($info_type,array('fancy','friend','msg')) && $info_type = 'fancy';

		$ifsign	  = false;
		$friend_0 = $friend_1 = $friend_2 = '';
		$editor_Y = $editor_N = $check_12 = $d_type_0 = $d_type_1 = $email_Y = $email_N = '';
		$check_24 = 'checked';
		${'friend_'.getstatus($userdb['userstatus'],3,3)} = 'checked';
		${'email_'.(getstatus($userdb['userstatus'],8) ? 'Y' : 'N')} = 'checked';
		${'editor_'.(getstatus($userdb['userstatus'],11) ? 'Y' : 'N')} = 'checked';
		$userdb['style'] == '' && $skin = '';
		$choseskin = getstyles($skin);

		$customstyles = $customname = '';
		$query = $db->query("SELECT sid,name,customname FROM pw_styles WHERE uid=".pwEscape($winduid));
		while ($rt = $db->fetch_array($query)) {
			$customname = $rt['customname'] ? $rt['customname'] : $rt['sid'];
			if ($rt['sid'] == $userdb['style'] && !$skinco) {
				$customstyles .= "<option value=\"".$rt['sid']."\" selected>$customname</option>";
			} else {
				$customstyles .= "<option value=\"".$rt['sid']."\">$customname</option>";
			}
		}
		$choseskin = $choseskin.$customstyles;

		if ($db_signmoney && strpos($db_signgroup,",$groupid,") !== false) {
			require_once(R_P.'require/credit.php');
			$cur = $credit->get($winduid,$db_signcurtype);
			$cur === false && Showmsg('numerics_checkfailed');
			$ifsign = true;
			$days = $cur < 0 ? 0 : floor($cur/$db_signmoney);
			if ($userdb['starttime'] && $userdb['starttime'] <= $tdtime) {
				$haveshow = floor(($tdtime-$userdb['starttime'])/86400)+1;
			} else {
				$haveshow = 0;
			}
			${'showsign_'.(getstatus($userdb['userstatus'],10) ? 'Y' : 'N')} = 'checked';
		}
		if ($userdb['timedf']) {
			$temptimedf = str_replace('.','_',abs($userdb['timedf']));
			$userdb['timedf'] < 0 ? ${'zone_0'.$temptimedf} = 'selected' : ${'zone_'.$temptimedf} = 'selected';
		}
		if ($userdb['datefm']) {
			if (strpos($userdb['datefm'],'h:i A') !== false) {
				$userdb['datefm'] = str_replace(' h:i A','',$userdb['datefm']);
				$check_12 = 'checked';
				$check_24 = '';
			} else {
				$userdb['datefm'] = str_replace(' H:i','',$userdb['datefm']);
			}
			$userdb['datefm'] = str_replace(array('m','n','d','j','y','Y'), array('mm','m','dd','d','yy','yyyy'), $userdb['datefm']);
			$d_type_1 = 'checked';
		} else {
			$userdb['datefm'] = 'yyyy-mm-dd';
			$d_type_0 = 'checked';
		}
		if ($_G['msggroup']) {
			include_once(D_P.'data/bbscache/level.php');
			$usergroup = '';
			foreach ($ltitle as $key => $value) {
				if ($key != 1 && $key != 2) {
					if ($userdb['msggroups'] && strpos($userdb['msggroups'],','.$key.',') !== false) {
						$checked = 'checked';
					} else {
						$checked = '';
					}
					$usergroup .= "<div style=\"width:32%;float:left\"><input type=\"checkbox\" name=\"msggroups[]\" value=\"$key\" $checked>$value</div>";
				}
			}
		}
		${'T_'.(int)$userdb['t_num']} = ${'P_'.(int)$userdb['p_num']} = 'selected';//p_num step2 bug

		require_once PrintEot('profile');
		footer();

	} else {

		PostCheck();
		InitGP(array('date_f','timedf','tpskin','banidinfo'),'P');
		InitGP(array('showsign','editor','proreceivemail','friendcheck','msggroups'),'P',2);

		$upmemdata = array();
		$ustatus = '';
		if ($editor != getstatus($userdb['userstatus'],11)) {
			$ustatus.= ',userstatus=userstatus'.($editor ? '|' : '&~') .'(1<<10)';
		}
		if ($proreceivemail != getstatus($userdb['userstatus'],8)) {
			$ustatus.= ',userstatus=userstatus'.($proreceivemail ? '|' : '&~') .'(1<<7)';
		}
		if ($friendcheck != getstatus($userdb['userstatus'],3,3)) {
			switch ($friendcheck) {
				case 0:
					$ustatus .= ',userstatus=userstatus&~(3<<2)';break;
				case 1:
					$ustatus .= ',userstatus=userstatus|(1<<2),userstatus=userstatus&~(1<<3)';break;
				case 2:
					$ustatus .= ',userstatus=userstatus&~(1<<2),userstatus=userstatus|(1<<3)';break;
			}
		}
		if (GetCookie('skinco') && $tpskin != GetCookie('skinco')) {
			Cookie('skinco','',0);
		}
		$showsign = $showsign ? 1 : 0;

		if ($db_signmoney && ($singstatus = getstatus($userdb['userstatus'],10)) != $showsign) {
			$ustatus .= ',userstatus=userstatus'.($showsign ? '|' : '&~').'(1<<9)';
			if ($singstatus && $showsign == 0) {
				$upmemdata['starttime'] = 0;
			} else {
				require_once(R_P.'require/credit.php');
				if (($cur = $credit->get($winduid,$db_signcurtype)) === false) {
					Showmsg('numerics_checkfailed');
				}
				if ($cur < $db_signmoney) {
					Showmsg('noenough_currency');
				}
				$credit->addLog('main_showsign',array($db_signcurtype => -$db_signmoney),array(
					'uid'		=> $winduid,
					'username'	=> $windid,
					'ip'		=> $onlineip
				));
				if (!$credit->set($winduid,$db_signcurtype,-$db_signmoney,false)) {
					Showmsg('numerics_checkfailed');
				}
				$upmemdata['starttime'] = $tdtime;
			}
		}
		if ($_POST['d_type'] && $date_f) {
			$date_f  = strpos($date_f,'mm') !== false ? str_replace('mm','m',$date_f) : str_replace('m','n',$date_f);
			$date_f  = strpos($date_f,'dd') !== false ? str_replace('dd','d',$date_f) : str_replace('d','j',$date_f);
			$date_f  = str_replace(array('yyyy','yy'),array('Y','y'),$date_f);
			$date_f .= $_POST['time_f']=='12' ? ' h:i A' :' H:i';
		} else {
			$date_f = '';
		}
		$t_num = $_POST['t_num'] && !in_array($_POST['t_num'],$t_num) ? 0 : $_POST['t_num'];
		$p_num = $_POST['p_num'] && !in_array($_POST['p_num'],$p_num) ? 0 : $_POST['p_num'];

		//update memdata
		if ($upmemdata) {
			$pwSQL = pwSqlSingle($upmemdata);
			if (is_object($credit) && $setsql = $credit->runsql($winduid)) {
				$pwSQL .= ','.$setsql;
			}
			$db->update("UPDATE pw_memberdata SET $pwSQL WHERE uid=".pwEscape($winduid));
		}
		$groups = '';
		if ($_G['msggroup'] && $msggroups) {
			foreach ($msggroups as $key => $val) {
				if ($val) {
					$groups .= $groups ? ','.$val : $val;
				}
			}
		}
		$groups && $groups = ",$groups,";

		$pwSQL = pwSqlSingle(array('style' => $tpskin, 'datefm' => $date_f, 'timedf' => $timedf, 't_num' => $t_num, 'p_num' => $p_num, 'banpm' => $banidinfo, 'msggroups' => $groups));

		$db->update("UPDATE pw_members SET {$pwSQL}{$ustatus} WHERE uid=".pwEscape($winduid));

		refreshto("profile.php?action=bbsset",'operate_success');
	}

} elseif ($action == 'permission') {

	InitGP(array('gid'),'G',2);
	$userdb = $db->get_one("SELECT m.groupid,m.groups,m.memberid,md.onlinetime,md.postnum,md.digests,md.rvrc,md.money,md.credit FROM pw_members m LEFT JOIN pw_memberdata md ON m.uid=md.uid WHERE m.uid='$winduid'");
	require_once(R_P.'require/credit.php');
	$creditdb = $credit->get($winduid,'CUSTOM');
	$usercredit = array(
		'postnum'	=> $userdb['postnum'],
		'digests'	=> $userdb['digests'],
		'rvrc'		=> $userdb['rvrc'],
		'money'		=> $userdb['money'],
		'credit'	=> $userdb['credit'],
		'onlinetime'=> $userdb['onlinetime']
	);
	foreach ($creditdb as $key => $value) {
		$usercredit[$key] = $value[1];
	}
	$upgradeset  = unserialize($db_upgrade);
	$totalcredit = CalculateCredit($usercredit,$upgradeset);
	$mygpdb = $_gmember = $_gspecial = $_gsystem = array();
	$winddb['groupid']!='-1' && $mygpdb[$winddb['groupid']] = $ltitle[$userdb['groupid']];
	if ($winddb['groups']) {
		$groups = explode(',',$winddb['groups']);
		foreach ($groups as $value) {
			$value && array_key_exists($value,$ltitle) && $mygpdb[$value] = $ltitle[$value];
		}
	}
	$mygpdb[$winddb['memberid']] = $ltitle[$winddb['memberid']];
	foreach (array_keys($mygpdb) as $value) {
		!$gid && $gid = $value;
		break;
	}
	$query = $db->query("SELECT gid,gptype,grouptitle,grouppost FROM pw_usergroups WHERE gptype!='default' ORDER BY grouppost,gid");
	while ($rt = $db->fetch_array($query)) {
		if (strpos(",$_G[pergroup],",",$rt[gptype],") !== false) {
			if ($rt['gptype'] == 'member') {
				${'_g'.$rt['gptype']}[$rt['gid']] = array('title' => $rt['grouptitle'],'post' => $rt['grouppost']);
			} else {
				${'_g'.$rt['gptype']}[$rt['gid']] = array('title' => $rt['grouptitle']);
			}
		} else {
			$gid == $rt['gid'] && !$mygpdb[$gid] && Showmsg('per_error');
		}
	}
	$gRight = array();
	$query = $db->query("SELECT rkey,rvalue FROM pw_permission WHERE uid='0' AND fid='0' AND gid=".pwEscape($gid)."AND type='basic'");
	while ($rt = $db->fetch_array($query)) {
		$gRight[$rt['rkey']] = $rt['rvalue'];
	}
	$db->free_result($query);
	//@include Pcv(D_P."data/groupdb/group_$gid.php");
	$per = array();
	$per['hide']	= $gRight['allowhide']		? 1 : 0;
	$per['read']	= $gRight['allowread']		? 1 : 0;
	$per['search']	= $gRight['allowsearch']	? 1 : 0;
	$per['member']	= $gRight['allowmember']	? 1 : 0;
	$per['profile']	= $gRight['allowprofile']	? 1 : 0;
	$per['show']	= $gRight['show']		? 1 : 0;
	$per['report']	= $gRight['allowreport']	? 1 : 0;
	$per['upload']	= $gRight['upload']		? 1 : 0;
	$per['portait']	= $gRight['allowportait']	? 1 : 0;
	$per['honor']	= $gRight['allowhonor']	? 1 : 0;
	$per['post']	= $gRight['allowpost']		? 1 : 0;
	$per['rp']		= $gRight['allowrp']		? 1 : 0;
	$per['newvote']	= $gRight['allownewvote']	? 1 : 0;
	$per['vote']	= $gRight['allowvote']		? 1 : 0;
	$per['vwvt']	= $gRight['viewvote']	? 1 : 0;
	$per['html']	= $gRight['htmlcode']		? 1 : 0;
	$per['hidden']	= $gRight['allowhidden']	? 1 : 0;
	$per['sell']	= $gRight['allowsell']		? 1 : 0;
	$per['mark']	= $gRight['markable']	? 1 : 0;
	$per['attach']	= $gRight['allowupload']	? 1 : 0;
	$per['down']	= $gRight['allowdownload']	? 1 : 0;
	$per['sort']	= $gRight['allowsort']	? 1 : 0;
	$per['messege']	= $gRight['allowmessege']	? 1 : 0;
	$per['maxmsg']	= (int)$gRight['maxmsg'];
	$per['maxfavor'] = (int)$gRight['maxfavor'];
	$per['maxgraft'] = !$gRight['maxgraft'] ? 0 : $gRight['maxgraft'];
	$per['signnum'] = (int)$gRight['signnum'];
	$per['active']	= $gRight['allowactive']	 ? 1 : 0;
	$per['reward']	= $gRight['allowreward'] ? 1 : 0;
	$per['anonymous'] = $gRight['anonymous'] ? 1 : 0;
	$per['leaveword'] = $gRight['leaveword'] ? 1 : 0;
	$per['allownum'] = (int)$gRight['allownum'];
	$per['uploadmaxsize'] = ceil(($gRight['uploadmaxsize'] ? $gRight['uploadmaxsize'] : $db_uploadmaxsize)/1024);
	!$gRight['uploadtype'] && $gRight['uploadtype'] = $db_uploadfiletype;
	$gRight['uploadtype'] = unserialize($gRight['uploadtype']);
	$per['uptype'] = '';
	foreach($gRight['uploadtype'] as $key => $value){
		$per['uptype'] .= ($per['uptype'] ? ', ' : '')."$key:$value";
	}
	unset($gRight);

	require_once(PrintEot('profile'));footer();

} elseif ($action == 'forumright') {

	require_once(R_P.'require/forum.php');
	require_once(R_P.'require/credit.php');

	$rt = $db->get_one("SELECT f.name,f.type,f.f_type,f.password,f.allowvisit,f.allowpost,f.allowrp,f.allowdownload,f.allowupload,f.cms,fe.creditset FROM pw_forums f LEFT JOIN pw_forumsextra fe USING(fid) WHERE f.fid=".pwEscape($fid));
	if (!$rt || $rt['type'] == 'category') {
		Showmsg('data_error');
	}
	wind_forumcheck($rt);
	$forumright = array();
	$creditset = $credit->creditset($rt['creditset'],$db_creditset);
	foreach ($creditset as $key=>$value) {
		foreach ($value as $k=>$v) {
			$forumright[$k][$key] = (int)$v;
		}
	}
	if ($rt['allowvisit'] && strpos($rt['allowvisit'],",$groupid,") === false) {
		$per['visit'] = 0;
	} else {
		$per['visit'] = 1;
	}
	if ($rt['allowpost'] && strpos($rt['allowpost'],",$groupid,") === false) {
		$per['post'] = 0;
	} elseif (!$rt['allowpost'] && $_G['allowpost'] == 0) {
		$per['post'] = 0;
	} else {
		$per['post'] = 1;
	}
	if ($rt['allowrp'] && strpos($rt['allowrp'],",$groupid,") === false) {
		$per['rp'] = 0;
	} elseif (!$rt['allowrp'] && $_G['allowpost'] == 0) {
		$per['rp'] = 0;
	} else {
		$per['rp'] = 1;
	}
	if ($rt['allowdownload'] && strpos($rt['allowdownload'],",$groupid,")===false) {
		$per['down'] = 0;
	} elseif (!$rt['allowdownload'] && $_G['allowpost'] == 0) {
		$per['down'] = 0;
	} else {
		$per['down'] = 1;
	}
	if ($rt['allowupload'] && strpos($rt['allowupload'],",$groupid,") === false) {
		$per['upload'] = 0;
	} elseif (!$rt['allowupload'] && $_G['allowpost'] == 0) {
		$per['upload'] = 0;
	} else {
		$per['upload'] = 1;
	}

	require_once(PrintEot('profile'));footer();

} elseif ($action == 'forumsell') {

	$f = $db->get_one("SELECT f.forumsell,fe.forumset FROM pw_forums f LEFT JOIN pw_forumsextra fe USING(fid) WHERE f.fid=" . pwEscape($fid));
	empty($f) && Showmsg('data_error');
	if (!$f['forumsell']) {
		Showmsg('forumsell_error');
	}
	$forumset = unserialize($f['forumset']);
	require_once(R_P.'require/credit.php');
	include_once(D_P.'data/bbscache/forum_cache.php');
	$fname = $forum[$fid]['name'];

	if (empty($_POST['step'])) {

		InitGP(array('page','date'));
		if ($date && isset($forumset['sellprice'][$date])) {

		} else {
			(!is_numeric($page) || $page < 1) && $page = 1;
			$limit = pwLimit(($page-1)*10, 10);
			$rt = $db->get_one("SELECT COUNT(*) AS sum FROM pw_forumsell WHERE uid=" . pwEscape($winduid));
			$pages = numofpage($rt['sum'],$page,ceil($rt['sum']/10), "profile.php?action=forumsell&fid=$fid&");
			$query = $db->query("SELECT * FROM pw_forumsell WHERE uid=" . pwEscape($winduid) . " ORDER BY overdate DESC $limit");
			$buydb = array();
			while ($rt = $db->fetch_array($query)) {
				$rt['buydate']	= get_date($rt['buydate']);
				$rt['overdate']	= get_date($rt['overdate']);
				$buydb[] = $rt;
			}
		}
		require_once(PrintEot('profile'));footer();

	} else {

		PostCheck();
		InitGP(array('date','buymethod'));
		$rt = $db->get_one("SELECT MAX(overdate) AS u FROM pw_forumsell WHERE uid=" . pwEscape($winduid) . " AND fid=" . pwEscape($fid));
		if ($rt['u'] > $timestamp) {
			Showmsg('forumsell_already');
		}
		if (!isset($forumset['sellprice'][$date])) {
			Showmsg('forumsell_date');
		}
		if ($buymethod) {
			if ($forumset['sellprice'][$date]['rprice'] <= 0) {
				Showmsg('undefined_action');
			}
			include_once(D_P.'data/bbscache/ol_config.php');
			if (!$ol_onlinepay) {
				Showmsg($ol_whycolse);
			}
			$order_no = '1'.str_pad($winduid,10, "0",STR_PAD_LEFT).get_date($timestamp,'YmdHis').num_rand(5);
			$db->update("INSERT INTO pw_clientorder SET " . pwSqlSingle(array(
				'order_no'	=> $order_no,
				'type'		=> 2,
				'uid'		=> $winduid,
				'paycredit'	=> $fid,
				'price'		=> $forumset['sellprice'][$date]['rprice'],
				'number'	=> 1,
				'date'		=> $timestamp,
				'state'		=> 0,
				'extra_1'	=> $date
			)));
			if (!$ol_payto) {
				Showmsg('olpay_alipayerror');
			}
			require_once(R_P.'require/onlinepay.php');
			$olpay = new OnlinePay($ol_payto);
			ObHeader($olpay->alipayurl($order_no, $forumset['sellprice'][$date]['rprice'], 2));
		}
		if ($forumset['sellprice'][$date]['cprice'] <= 0) {
			Showmsg('undefined_action');
		}
		if ($credit->get($winduid,$f['forumsell']) < $forumset['sellprice'][$date]['cprice']) {
			$creditname = pwCreditNames($f['forumsell']);
			Showmsg('forumsell_price');
		}
		$credit->addLog('main_forumsell',array($f['forumsell'] => -$forumset['sellprice'][$date]['cprice']),array(
			'uid'		=> $winduid,
			'username'	=> $windid,
			'ip'		=> $onlineip,
			'fname'		=> $forum[$fid]['name'],
			'days'		=> $date
		));
		$credit->set($winduid,$f['forumsell'],-$forumset['sellprice'][$date]['cprice']);

		$overdate = $timestamp + $date * 86400;
		$db->update("INSERT INTO pw_forumsell SET " . pwSqlSingle(array(
			'fid'		=> $fid,
			'uid'		=> $winduid,
			'buydate'	=> $timestamp,
			'overdate'	=> $overdate,
			'credit'	=> $f['forumsell'],
			'cost'		=> $forumset['sellprice'][$date]['cprice']
		),false));
		refreshto("thread.php?fid=$fid",'operate_success');
	}

} elseif ($action == 'log') {

	$_G['atclog'] || Showmsg('no_atclog_right');
	InitGP(array('page','type'));
	require_once GetLang('logtype');
	require_once(R_P.'require/forum.php');
	include_once(D_P.'data/bbscache/forum_cache.php');
	$sqladd = "WHERE username1=".pwEscape($windid,false);
	if ($type && $lang['logtype'][$type]) {
		$sqladd .= " AND type=".pwEscape($type);
		$type_sel[$type] = 'selected';
	} else {
		$type = '';$type_sel = array();
	}
	$db_perpage = 15;
	(!is_numeric($page) || $page < 1) && $page = 1;
	$limit = pwLimit(($page-1)*$db_perpage,$db_perpage);
	$count    = $db->get_value("SELECT COUNT(*) AS count FROM pw_adminlog $sqladd");
	$pages = numofpage($count,$page,ceil($count/$db_perpage),"profile.php?action=log&type=$type&");
	$logdb = array();
	$query = $db->query("SELECT * FROM pw_adminlog $sqladd ORDER BY id DESC $limit");
	while ($rt = $db->fetch_array($query)) {
		$rt['date']    = get_date($rt['timestamp']);
		$rt['descrip'] = descriplog($rt['descrip']);
		$logdb[] = $rt;
	}
	require_once PrintEot('profile');footer();

} elseif ($action == 'change') {

	require_once(R_P.'require/credit.php');
	$rt = $db->get_one("SELECT db_value FROM pw_config WHERE db_name='jf_A'");
	$jf_A = $rt['db_value'] ? unserialize($rt['db_value']) : array();

	if (empty($_POST['step'])) {

		$creditdb = $credit->get($winduid,'CUSTOM');
		$jf = array();
		foreach ($jf_A as $key => $value) {
			if ($value[2]) {
				list($j_1,$j_2) = explode('_',$key);
				$jf[$key] = array($credit->cType[$j_1],$credit->cType[$j_2],$value[0],$value[1]);
			}
		}
		!$jf && Showmsg('jfchange_empty');

		require_once PrintEot('profile');footer();

	} else {

		PostCheck();
		InitGP(array('type','change'));
		if (!$jf_A[$type] || !$jf_A[$type][2]) {
			Showmsg('bk_credit_type_error');
		}
		$change = (int)$change;
		if (!is_numeric($change) || $change <= 0) Showmsg('bk_credit_fillin_error');
		$change%$jf_A[$type][0] != 0 && Showmsg('change_error');

		list($sell,$buy) = explode('_',$type);
		$credit1 = $change;
		$credit2 = intval($change/$jf_A[$type][0]*$jf_A[$type][1]);
		/*
		$db->query("LOCK TABLES pw_memberdata WRITE,pw_membercredit WRITE");
		$lockfile = D_P.'data/bbscache/lock_profile.txt';
		$fp = fopen($lockfile,'wb+');
		flock($fp,LOCK_EX);
		*/
		if (procLock('credit_change',$winduid)) {

			if ($credit1 > $credit->get($winduid,$sell)) {
				Showmsg('bk_credit_change_error');
			}
			$credit->addLog('main_changereduce',array($sell => -$credit1),array(
				'uid'		=> $winduid,
				'username'	=> $windid,
				'ip'		=> $onlineip,
				'tocname'	=> $credit->cType[$buy]
			));
			$credit->addLog('main_changeadd',array($buy => $credit2),array(
				'uid'		=> $winduid,
				'username'	=> $windid,
				'ip'		=> $onlineip,
				'fromcname'	=> $credit->cType[$sell]
			));
			$credit->sets($winduid,array($sell => -$credit1, $buy => $credit2));

			procUnLock('credit_change',$winduid);
			//fclose($fp);
			//$db->query("UNLOCK TABLES");
		}

		refreshto('profile.php?action=change','bank_creditsuccess');
	}
} elseif ($action == 'buy') {

	require_once(R_P.'require/pw_func.php');
	require_once(R_P.'require/credit.php');
	InitGP(array('job','gid'));

	if (empty($job)) {

		$specialdb = $sright = $gids = array();
		$query = $db->query("SELECT gid,grouptitle FROM pw_usergroups WHERE gptype='special'");
		while ($rt = $db->fetch_array($query)) {
			$sright[$rt['gid']] = $rt;
			$gids[] = $rt['gid'];
		}
		if ($gids) {
			$query = $db->query("SELECT gid,rkey,rvalue FROM pw_permission WHERE uid='0' AND fid='0' AND gid IN(" . pwImplode($gids) . ") AND rkey IN ('sellinfo','sellprice','rmbprice','selltype', 'selllimit', 'allowbuy')");
			while ($rt = $db->fetch_array($query)) {
				$sright[$rt['gid']][$rt['rkey']] = $rt['rvalue'];
			}
			foreach ($sright as $key => $value) {
				if ($value['allowbuy']) {
					$value['enddate'] = '-';
					$value['selltype'] = $credit->cType[$value['selltype']];
					$specialdb[$key] = $value;
				}
			}
			$query = $db->query("SELECT gid,startdate,days FROM pw_extragroups WHERE uid=".pwEscape($winduid));
			while ($rt = $db->fetch_array($query)) {
				if (array_key_exists($rt['gid'],$specialdb)) {
					$specialdb[$rt['gid']]['days']		= $rt['days'];
					$specialdb[$rt['gid']]['startdate']	= $rt['startdate'];
					$specialdb[$rt['gid']]['enddate']	= get_date($rt['startdate'] + $rt['days']*86400,'Y-m-d');
				}
			}
		}
		require_once(PrintEot('profile'));footer();

	} elseif ($job == 'buy') {

		$rt = $db->get_one("SELECT uid,startdate,days FROM pw_extragroups WHERE uid=".pwEscape($winduid) . " AND gid=" . pwEscape($gid));
		if ($rt && $timestamp <= $rt['startdate'] + $rt['days']*86400) {
			$enddate = get_date($rt['startdate'] + $rt['days']*86400,'Y-m-d');
			Showmsg('specialgroup_exists');
		}
		$rt = $db->get_one("SELECT gid,grouptitle FROM pw_usergroups WHERE gptype='special' AND gid=" . pwEscape($gid));
		if (!$rt) {
			Showmsg('specialgroup_error');
		}
		$query = $db->query("SELECT gid,rkey,rvalue FROM pw_permission WHERE uid='0' AND fid='0' AND gid=" . pwEscape($gid) . " AND rkey IN ('sellinfo','sellprice','rmbprice','selltype','selllimit','allowbuy')");
		while ($permi = $db->fetch_array($query)) {
			$rt['sright'][$permi['rkey']] = $permi['rvalue'];
		}
		if (!$rt['sright']['allowbuy']) {
			Showmsg('special_allowbuy');
		}
		if (empty($_POST['step'])) {

			$rt['sright']['selltype'] = $credit->cType[$rt['sright']['selltype']];
			require_once(PrintEot('profile'));footer();

		} else {

			PostCheck();
			InitGP(array('pwpwd'), 'P');
			InitGP(array('days','buymethod','options'), null, 2);
			if (!is_numeric($days) || $days <= 0) {
				Showmsg('illegal_nums');
			}
			if ($days < $rt['sright']['selllimit']) {
				Showmsg('special_selllimit');
			}
			$mb = $db->get_one("SELECT password,groups FROM pw_members WHERE uid=" . pwEscape($winduid));

			if ($gid == $groupid || strpos($mb['groups'],",$gid,") !== false) {
				Showmsg('specialgroup_noneed');
			}
			if ($buymethod) {
				if ($rt['sright']['rmbprice'] <= 0) {
					Showmsg('undefined_action');
				}
				include_once(D_P.'data/bbscache/ol_config.php');
				if (!$ol_onlinepay) {
					Showmsg($ol_whycolse);
				}
				$grouptitle = $rt['grouptitle'];
				$order_no = '1'.str_pad($winduid,10, "0",STR_PAD_LEFT).get_date($timestamp,'YmdHis').num_rand(5);
				$db->update("INSERT INTO pw_clientorder SET " . pwSqlSingle(array(
					'order_no'	=> $order_no,
					'type'		=> 3,
					'uid'		=> $winduid,
					'paycredit'	=> $gid,
					'price'		=> $rt['sright']['rmbprice'],
					'number'	=> $days,
					'date'		=> $timestamp,
					'state'		=> 0,
					'extra_1'	=> $options
				)));
				if (!$ol_payto) {
					Showmsg('olpay_alipayerror');
				}
				require_once(R_P.'require/onlinepay.php');
				$olpay = new OnlinePay($ol_payto);
				ObHeader($olpay->alipayurl($order_no, round($rt['sright']['rmbprice'] * $days, 2), 3));
			}
			if (md5($pwpwd) != $mb['password']) {
				Showmsg('password_error');
			}
			if ($rt['sright']['sellprice'] <= 0) {
				Showmsg('undefined_action');
			}
			$needcur = $days * $rt['sright']['sellprice'];
			$cur = $credit->get($winduid,$rt['sright']['selltype']);
			if ($cur === false) {
				Showmsg('numerics_checkfailed');
			}
			if ($cur < $needcur) {
				Showmsg('noenough_currency');
			}
			$credit->addLog('main_buygroup',array($rt['sright']['selltype'] => -$needcur),array(
				'uid'		=> $winduid,
				'username'	=> $windid,
				'ip'		=> $onlineip,
				'gptitle'	=> $rt['grouptitle'],
				'days'		=> $days
			));
			if (!$credit->set($winduid,$rt['sright']['selltype'],-$needcur)) {
				Showmsg('numerics_checkfailed');
			}
			if ($options == 1) {
				if ($winddb['groupid'] == '-1') {
					$db->update("UPDATE pw_members SET groupid=".pwEscape($gid)."WHERE uid=".pwEscape($winduid));
				} else {
					$groups = $mb['groups'] ? $mb['groups'].$winddb['groupid'].',' : ",$winddb[groupid],";
					$db->update("UPDATE pw_members SET " . pwSqlSingle(array('groupid' => $gid, 'groups' => $groups)) . ' WHERE uid=' . pwEscape($winduid));
				}
			} else {
				$groups = $mb['groups'] ? $mb['groups'].$gid.',' : ",$gid,";
				$db->update("UPDATE pw_members SET groups=" . pwEscape($groups,false) . " WHERE uid=" . pwEscape($winduid));
			}
			$db->pw_update(
				"SELECT uid FROM pw_extragroups WHERE uid=" . pwEscape($winduid) . " AND gid=" . pwEscape($gid),
				"UPDATE pw_extragroups SET ". pwSqlSingle(array(
					'togid'		=> $winddb['groupid'],
					'startdate'	=> $timestamp,
					'days'		=> $days
				)) . " WHERE uid=".pwEscape($winduid)."AND gid=".pwEscape($gid)
				,
				"INSERT INTO pw_extragroups SET " . pwSqlSingle(array(
					'uid'		=> $winduid,
					'togid'		=> $winddb['groupid'],
					'gid'		=> $gid,
					'startdate'	=> $timestamp,
					'days'		=> $days
				))
			);
			refreshto("profile.php",'group_buy_success');
		}
	}

} elseif ($action == 'ajaxface') {

	require_once(R_P.'require/showimg.php');
	define('AJAX',true);
	$facetype = $_POST['facetype'];
	list($iconurl,$icontype,$iconwidth,$iconheight,$iconfile,$iconpig) = showfacedesign($winddb['icon'],true);
	$iconfile = addslashes($iconfile);
	if ($facetype == 3 && $db_ifupload && $_G['upload'] && is_array($_POST['uploadurl'])) {
		UploadIcon($_POST['uploadurl']);
		pwFtpClose($ftp);
		$usericon = GetIcon();
		$db->update("UPDATE pw_members SET icon=".pwEscape($usericon,false)."WHERE uid=".pwEscape($winduid));
		if ($iconpig) {
			$iconurl = "$imgpath/pig.gif";
		} elseif ($db_ftpweb && !file_exists("$attachdir/upload/$iconfile")) {
			$iconurl = "$db_ftpweb/upload/";
		} else {
			$iconurl = "$attachpath/upload/";
		}
		$showmsg = 'success';
	} else {
		$showmsg = 'undefined_action';
	}
	echo "<script language=\"JavaScript1.2\">parent.facepath('$iconurl','$iconfile','$showmsg','$iconwidth','$iconheight');</script>";exit;

} elseif ($action == 'memo' && $_G['ifmemo']) {

	PostCheck();
	list($mmid,$mcontent) = $db->get_one("SELECT mid,content FROM pw_memo WHERE isuser='1' AND username=".pwEscape($windid,false),MYSQL_NUM);
	$mmid = (int)$mmid;
	$mm_content = Char_cv($_POST['mm_content']);
	if (!$mmid) {
		$db->update("INSERT INTO pw_memo"
			. " SET " . pwSqlSingle(array(
				'username'	=> $windid,
				'postdate'	=> $timestamp,
				'content'	=> $mm_content,
				'isuser'	=> 1
		)));
	} elseif ($mmid==(int)$_POST['mm_mid'] && $mcontent!=$mm_content) {
		$db->update("UPDATE pw_memo SET postdate=".pwEscape($timestamp).",content=".pwEscape($mm_content)."WHERE mid=".pwEscape($mmid));
	}
	refreshto('profile.php','operate_success');

} elseif ($action == 'style') {
	if (defined('M_P')) {
		Showmsg('mode_cstyles_right');
	}
	!$_G['maxcstyles'] && Showmsg('no_cstyles_right');
	$job = GetGP('job');

	if (empty($job)) {
		$page = (int)GetGP('page');
		$page < 1 && $page = 1;
		$count		= $db->get_value("SELECT COUNT(*) AS count FROM pw_styles WHERE uid=".pwEscape($winduid,false));
		$numofpage	= ceil($count/$db_perpage);
		$pages		= numofpage($count,$page,$numofpage,"profile.php?action=style&");
		$stylelistdb = array();
		$query = $db->query("SELECT sid,uid,name,customname,createtime,lastmodify FROM pw_styles WHERE uid=".pwEscape($winduid,false).pwLimit(($page-1)*$db_perpage,$db_perpage));
		while ($rt = $db->fetch_array($query)){
			empty($rt['customname']) && $rt['customname'] = '--';
			$rt['createtime'] = get_date($rt['createtime']);
			$rt['lastmodify'] = get_date($rt['lastmodify']);
			empty($skinco) && $rt['sid'] == $winddb['style'] && $rt['useing'] = 1;
			$stylelistdb[] = $rt;
		}
		require_once(PrintEot('profile'));footer();
	} elseif ($job == 'add') {
		$count = $db->get_value("SELECT COUNT(*) AS count FROM pw_styles WHERE uid=".pwEscape($winduid,false));
		$count > $_G['maxcstyles'] && Showmsg('cstyles_num_limit');
		$selstyle = Char_cv(GetGP('selstyle'));
		empty($db_styledb) && $db_styledb['wind'] = array('0' => 'wind','1' => '1');
		(empty($selstyle) || empty($db_styledb[$selstyle])) && $selstyle = 'wind';
		foreach ($db_styledb as $key => $value) {
			if ($value['1']) {
				$cname = $value['0'] ? $value['0'] : $key;
				if ($key == $selstyle) {
					$opsystemstyle .= "<option value=\"$key\" selected>$cname</option>";
				} else{
					$opsystemstyle .= "<option value=\"$key\">$cname</option>";
				}
			}
		}
		$customdb = $db->get_one("SELECT * FROM pw_styles WHERE uid='0' AND name=".pwEscape($selstyle));
		list($bgcolor,$bgimg,$imgtype) = explode(' ',$customdb['bgcolor']);
		if ($bgimg) {
			preg_match("/url\((http:\/\/.+)\)/i",$bgimg, $matches);
			$bgimg = $matches[1];
		}
		$imgtype == 'repeat' ? $imgtype_2 = 'selected' : $imgtype_1 = 'selected';
		$customdb['yeyestyle'] ? $yes_Y = 'checked' : $yes_N = 'checked';
		$customdb['customname'] || $customdb['customname'] = $customdb['name'];
		require_once(PrintEot('profile'));footer();
	} elseif ($job == 'modify') {
		$sid = (int)GetGP('sid');
		$customdb = $db->get_one("SELECT * FROM pw_styles WHERE sid=".pwEscape($sid)."AND uid=".pwEscape($winduid,false));
		empty($customdb) && Showmsg('style_error');
		list($bgcolor,$bgimg,$imgtype) = explode(' ',$customdb['bgcolor']);
		if($bgimg){
			preg_match("/url\((http:\/\/.+)\)/i",$bgimg, $matches);
			$bgimg = $matches[1];
		}
		$imgtype == 'repeat' ? $imgtype_2 = 'selected' : $imgtype_1 = 'selected';
		$customdb['yeyestyle'] ? $yes_Y = 'checked' : $yes_N = 'checked';
		require_once(PrintEot('profile'));footer();
	} elseif ($job == 'save') {
		PostCheck();
		$colorcss = array('bgcolor','linkcolor','tablecolor','tdcolor','headcolor','headborder', 'headfontone','headfonttwo','cbgcolor','cbgborder','cbgfont','forumcolorone','forumcolortwo');
		InitGP(array('css','customname'),'P');
		$sid = (int)GetGP('sid');
		$do = GetGP('do');
		if ($do == 'add') {//add style
			$customdb = $db->get_one("SELECT * FROM pw_styles WHERE uid='0' AND sid=".pwEscape($sid));
			empty($customdb) && Showmsg('style_error');
			$count = $db->get_value("SELECT COUNT(*) AS count FROM pw_styles WHERE uid=".pwEscape($winduid,false));
			$count > $_G['maxcstyles'] && Showmsg('cstyles_num_limit');
			$pwCss = array('name'=>$customdb['name'],'createtime'=>$timestamp,'stylepath'=>$customdb['stylepath'],'tplpath'=>$customdb['tplpath']);
		} elseif ($do == 'modify') {//modify style
			$customdb = $db->get_one("SELECT * FROM pw_styles WHERE uid=".pwEscape($winduid)."AND sid=".pwEscape($sid));
			empty($customdb) && Showmsg('style_error');
			$pwCss = array();
		} else {
			Showmsg('undefined_action');
		}
		foreach ($colorcss as $c) {//color
			empty($css[$c]) && $css[$c] = $customdb[$c];
			!preg_match("/^#([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){3})?$/",$css[$c]) && Showmsg('style_color_error');
			$pwCss[$c] = $css[$c];
		}
		$pwCss['yeyestyle']		=  $css['yeyestyle'] ? 1 : 0;
		$pwCss['tablewidth']	= intval(trim($css['tablewidth'])).(strpos($css['tablewidth'],'px') !== false ? 'px' : '%');//tablewidth
		$pwCss['mtablewidth']	= intval(trim($css['mtablewidth'])).(strpos($css['mtablewidth'],'px') !== false ? 'px' : '%');//mtablewidth
		if ($css['bgimg']) {//backgroud image
			!preg_match('/^(http|ftp|https|telnet|mms|rtsp):\/\/([.a-zA-Z0-9-])+(:[0-9]+)*([+:%\/\?~=&;\\\(\),._a-zA-Z0-9-])*\.(gif|jpg|jpeg|png)$/is',$css['bgimg']) && Showmsg('style_bgimg_error');
			$css['imgtype'] = $css['imgtype'] == 'repeat' ? 'repeat' : 'no-repeat';
			$pwCss['bgcolor'] .= ' url('.$css['bgimg'].') '.$css['imgtype'];
		}

		$pwCss['customname'] = $customname ? substrs($customname,24) : $customdb['name'];
		$pwCss['lastmodify'] = $timestamp;
		if ($do == 'add') {
			$pwCss['uid'] = $winduid;
			$db->update("INSERT INTO pw_styles SET".pwSqlSingle($pwCss));
		} elseif ($do == 'modify') {
			$db->update("UPDATE pw_styles SET".pwSqlSingle($pwCss)."WHERE sid=".pwEscape($sid)."AND uid=".pwEscape($winduid));
		}
		refreshto('profile.php?action=style','operate_success');
	} elseif ($job == 'use'){
		$sid = (int)GetGP('sid');
		$ckid = $db->get_one("SELECT sid FROM pw_styles WHERE sid=".pwEscape($sid)."AND uid=".pwEscape($winduid));
		if ($ckid) {
			$db->update("UPDATE pw_members SET style=".pwEscape($ckid['sid'],false)."WHERE uid=".pwEscape($winduid));
			Cookie('skinco','',0);
			refreshto('profile.php?action=style','operate_success');
		} else {
			Showmsg('style_error');
		}
	} elseif ($job == 'del') {
		$sid = (int)GetGP('sid');
		$ckid = $db->get_one("SELECT sid FROM pw_styles WHERE sid=".pwEscape($sid)."AND uid=".pwEscape($winduid));
		if ($ckid) {
			$db->update("DELETE FROM pw_styles WHERE sid=".pwEscape($ckid['sid'],false)."AND uid=".pwEscape($winduid));
			$db->update("UPDATE pw_members SET style='' WHERE style=".pwEscape($sid)."AND uid=".pwEscape($winduid));
			Cookie('skinco','',0);
			refreshto('profile.php?action=style','operate_success');
		} else {
			Showmsg('style_error');
		}
	}
} elseif ($action == 'privacy' && $db_modes['o']['ifopen']) {//TODO 隱私設置擴展問題

	if (empty($_POST['step'])) {
		$userdb = $db->get_one("SELECT index_privacy,profile_privacy,info_privacy,credit_privacy,owrite_privacy,msgboard_privacy FROM pw_ouserdata WHERE uid=".pwEscape($winduid));
		${'index_'.$userdb['index_privacy']} = 'selected="selected"';
		${'profile_'.$userdb['profile_privacy']} = 'selected="selected"';
		${'info_'.$userdb['info_privacy']} = 'selected="selected"';
		${'credit_'.$userdb['credit_privacy']} = 'selected="selected"';
		${'owrite_'.$userdb['owrite_privacy']} = 'selected="selected"';
		${'msgboard_'.$userdb['msgboard_privacy']} = 'selected="selected"';

		require_once(PrintEot('profile'));footer();
	} elseif ($_POST['step'] == 2) {
		PostCheck();
		InitGP(array('privacy'),'P',2);
		$pwSQL = array('uid'=>$winduid);
		$pwSQL['index_privacy'] = $privacy['index'] < 0 || $privacy['index'] > 2 ? 0 : $privacy['index'];
		$pwSQL['profile_privacy'] = $privacy['profile'] < 0 || $privacy['profile'] > 2 ? 0 : $privacy['profile'];
		$pwSQL['info_privacy'] = $privacy['info'] < 0 || $privacy['info'] > 2 ? 0 : $privacy['info'];
		$pwSQL['credit_privacy'] = $privacy['credit'] < 0 || $privacy['credit'] > 2 ? 0 : $privacy['credit'];
		$pwSQL['owrite_privacy'] = $privacy['owrite'] < 0 || $privacy['owrite'] > 2 ? 0 : $privacy['owrite'];
		$pwSQL['msgboard_privacy'] = $privacy['msgboard'] < 0 || $privacy['msgboard'] > 2 ? 0 : $privacy['msgboard'];

		$db->update("REPLACE INTO pw_ouserdata SET ".pwSqlSingle($pwSQL));
		refreshto('profile.php?action=privacy','operate_success');
	}
} else {
	Showmsg('undefined_action');
}

function Getcustom($data,$unserialize=true,$strips=null){
	global $db_union;
	$customdata = array();
	if (!$data || ($unserialize ? !is_array($data=unserialize($data)) : !is_array($data))) {
		$data = array();
	} elseif (!is_array($custominfo = unserialize($db_union[7]))) {
		$custominfo = array();
	}
	if (!empty($data) && !empty($custominfo)) {
		foreach ($data as $key => $value) {
			if (!empty($strips)) {
				$customdata[stripslashes(Char_cv($key))] = stripslashes(Char_cv($value));
			} elseif ($custominfo[$key] && $value) {
				$customdata[$key] = $value;
			}
		}
	}
	return array($customdata,$custominfo);
}
function lowerstrpos($haystack,$needle) {
	$haystack && $haystack = strtolower($haystack);
	$needle = strtolower($needle);
	if ($haystack && strpos($haystack,$needle)!==false) {
		return true;
	}
	return false;
}
function UploadIcon($uploadurl) {
	global $db_uploadfiletype,$db_imgsize,$iconfile,$icontype,$iconwidth,$iconheight,$facetype,$winduid;
	$db_uploadfiletype = array();
	$db_uploadfiletype['gif'] = $db_uploadfiletype['jpg'] = $db_uploadfiletype['bmp'] = $db_uploadfiletype['png'] = $db_imgsize;
	$uploadurl[1] = (int)$uploadurl[1];
	$uploadurl[2] = (int)$uploadurl[2];
	$uploaddb = UploadFile($winduid,'face',"1\t1");
	if (!empty($uploaddb)) {
		$attachurl = str_replace('upload/','',$uploaddb[0]['attachurl']);
		if ($icontype == 3 && $iconfile != $attachurl) {
			DelIcon($iconfile);
		}
		$iconfile = $attachurl;
		$uploadurl[1] > $uploaddb[0]['img_w'] && $uploadurl[1] = $uploaddb[0]['img_w'];
		$uploadurl[2] > $uploaddb[0]['img_h'] && $uploadurl[2] = $uploaddb[0]['img_h'];
		if (!$uploadurl[1] && !$uploadurl[2]) {
			$uploadurl[1] = $uploaddb[0]['img_w'];
			$uploadurl[2] = $uploaddb[0]['img_h'];
		}
		list($iconwidth,$iconheight) = getfacelen($uploadurl[1],$uploadurl[2]);
	} elseif ($icontype != 3) {
		$facetype = 1;
	} else {
		if (!$uploadurl[1] || !$uploadurl[2]) {
			global $iconurl;
			require_once(R_P.'require/imgfunc.php');
			$srcdata = GetImgSize($iconurl);
			$iconwidth = $srcdata['width'];
			$iconheight = $srcdata['height'];
		} else {
			list($iconwidth,$iconheight) = getfacelen($uploadurl[1],$uploadurl[2]);
		}
	}
}
function GetIcon($proicon = null) {
	global $iconfile,$icontype,$iconwidth,$iconheight,$iconpig,$facetype,$db_imgheight,$db_imgwidth;
	if ($facetype == 1) {
		if ($icontype != 1) {
			global $imgdir;
			$icontype == 3 && DelIcon($iconfile);
			if (!file_exists("$imgdir/face/$proicon")) {
				$proicon = 'none.gif';
			}
		}
		if (!empty($proicon)) {
			if (strlen($proicon)>20 || !preg_match('/^[0-9A-Za-z]+\.[A-Za-z]{2,5}$/',$proicon)) {
				Showmsg('undefined_action');
			}
			$iconfile = $proicon;
		}
		$iconwidth = $iconheight = 0;
	}
	$iconwidth < 1 && $iconwidth = '';
	$iconheight < 1 && $iconheight = '';
	$usericon = "$iconfile|$facetype|$iconwidth|$iconheight";
	$iconpig && $usericon .= "|$iconpig";
	if ($iconpig) {
		$usericon .= "|$iconpig";
	} else {
		$usericon .= "|";
	}
	if ($facetype == 3) {
		$usericon .= "|1";
	}
	strlen($usericon)>255 && Showmsg('illegal_customimg');
	return $usericon;
}
function updatemedal_list() {
	global $db;
	$query = $db->query("SELECT uid FROM pw_medaluser GROUP BY uid");
	$medaldb = '<?php die;?>0';
	while ($rt = $db->fetch_array($query)) {
		$medaldb .= ','.$rt['uid'];
	}
	writeover(D_P.'data/bbscache/medals_list.php',$medaldb);
}
?>